新增删除分享码功能

This commit is contained in:
eafonyang
2026-06-17 16:50:39 +08:00
parent 4b903f39e1
commit 7ed7183f1a
6 changed files with 239 additions and 0 deletions
+34
View File
@@ -28,6 +28,7 @@
// 创建: Lua 原子写入 hash + SADD pending + ZADD mac 索引
// 查询: ZREMRANGEBYSCORE 清过期索引 → ZRANGE 取剩余 → HGETALL 兆底校验
// 导入: HGETALL hash → HSET import:pending (幂等)
// 删除: 校验 mac+code → DEL hash + SREM pending + ZREM mac 索引
// 持久化: 每 5 分钟任务 SMEMBERS/HGETALL pending → INSERT DB → 移除 pending 条目
package cache
@@ -84,6 +85,27 @@ redis.call('EXPIRE', KEYS[3], tonumber(ARGV[9]))
return 1
`)
var shareDeleteScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[1]) == 0 then
return 0
end
if redis.call('HGET', KEYS[1], 'mac_addr') ~= ARGV[1] then
return -1
end
redis.call('DEL', KEYS[1])
redis.call('SREM', KEYS[2], ARGV[2])
redis.call('ZREM', KEYS[3], ARGV[2])
return 1
`)
type ShareDeleteResult int
const (
ShareDeleteNotFound ShareDeleteResult = 0
ShareDeleteForbidden ShareDeleteResult = -1
ShareDeleteOK ShareDeleteResult = 1
)
type ShareImportPendingLog struct {
MacAddr string `json:"mac_addr"`
ShareCode string `json:"share_code"`
@@ -296,6 +318,18 @@ func (c *ShareCodeCache) ListByMac(ctx context.Context, macAddr string) ([]*Shar
return result, nil
}
func (c *ShareCodeCache) Delete(ctx context.Context, macAddr, shareCode string) (ShareDeleteResult, error) {
key := shareCodeKey(shareCode)
macIdxKey := shareMacIndexKey(macAddr)
ok, err := shareDeleteScript.Run(ctx, c.rdb, []string{key, sharePendingSet, macIdxKey},
macAddr, shareCode,
).Int()
if err != nil {
return ShareDeleteNotFound, fmt.Errorf("delete share code in redis: %w", err)
}
return ShareDeleteResult(ok), nil
}
func shareMacIndexKey(macAddr string) string {
return shareMacIndexPrefix + macAddr
}