feat(share): 新增 shareList 接口 + 分享码模块全链路优化

- 新增 GET /audio/shareList?mac=xx 查询未过期分享码(纯 Redis,ZSET 索引)
- share:mac:{mac} 从 SET 改为 ZSET(score=expire_at),支持 ZREMRANGEBYSCORE 精确过期清理
- 空 ZSET 自动 DEL,避免 key 累积
- share:import:pending 增加 12h 兜底 TTL,防止 DB 不可用时内存泄漏
- 导入日志 field 改为 mac:code(去掉 nanotime),同 MAC+code 多次导入幂等去重
- MarkPersisted 保存/恢复 PTTL,防御性编程
- shareCreate 改为 POST + JSON body
- 全量 handler 补充 Swagger 注释,集成 swag 文档生成
- Makefile 使用 $(go env GOPATH)/bin/swag 解决 PATH 问题
This commit is contained in:
eafonyang
2026-06-12 17:07:59 +08:00
parent 8010cbd32f
commit b2aed2a6b5
12 changed files with 315 additions and 77 deletions
+3 -1
View File
@@ -1,3 +1,5 @@
SWAG := $(shell go env GOPATH)/bin/swag
.PHONY: run build test tidy swag
run:
@@ -13,4 +15,4 @@ tidy:
go mod tidy
swag:
swag init -g cmd/server/main.go -o docs --parseDependency --parseGoList
$(SWAG) init -g cmd/server/main.go -o docs --parseDependency --parseGoList
+44
View File
@@ -571,6 +571,50 @@ const docTemplate = `{
}
}
}
},
"/audio/shareList": {
"get": {
"description": "根据设备 MAC 地址查询该设备尚未过期的所有分享码(仅查询 Redis,依赖 TTL 自动过期)",
"produces": [
"application/json"
],
"tags": [
"ShareCode"
],
"summary": "查询未过期分享码",
"parameters": [
{
"type": "string",
"description": "设备 MAC 地址",
"name": "mac",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "成功返回 share_codes 列表",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"400": {
"description": "参数校验失败",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"500": {
"description": "系统错误",
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}`
+44
View File
@@ -564,6 +564,50 @@
}
}
}
},
"/audio/shareList": {
"get": {
"description": "根据设备 MAC 地址查询该设备尚未过期的所有分享码(仅查询 Redis,依赖 TTL 自动过期)",
"produces": [
"application/json"
],
"tags": [
"ShareCode"
],
"summary": "查询未过期分享码",
"parameters": [
{
"type": "string",
"description": "设备 MAC 地址",
"name": "mac",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": "成功返回 share_codes 列表",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"400": {
"description": "参数校验失败",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"500": {
"description": "系统错误",
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}
+30
View File
@@ -376,4 +376,34 @@ paths:
summary: 创建 EQ 分享码
tags:
- ShareCode
/audio/shareList:
get:
description: 根据设备 MAC 地址查询该设备尚未过期的所有分享码(仅查询 Redis,依赖 TTL 自动过期)
parameters:
- description: 设备 MAC 地址
in: query
name: mac
required: true
type: string
produces:
- application/json
responses:
"200":
description: 成功返回 share_codes 列表
schema:
additionalProperties: true
type: object
"400":
description: 参数校验失败
schema:
additionalProperties: true
type: object
"500":
description: 系统错误
schema:
additionalProperties: true
type: object
summary: 查询未过期分享码
tags:
- ShareCode
swagger: "2.0"
+68 -3
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"math/big"
"strings"
"time"
"github.com/redis/go-redis/v9"
@@ -18,8 +19,10 @@ const (
shareImportPendingHash = "share:import:pending"
shareFlushLockPref = "share:flush:lock:"
shareImportFlushLockPref = "share:import:flush:lock:"
shareMacIndexPrefix = "share:mac:"
shareCodeLength = 5
shareCodeTTL = 30 * time.Minute
shareImportPendingTTL = 12 * time.Hour
shareCodeCharset = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
shareCodeMaxRetries = 20
@@ -43,6 +46,8 @@ redis.call('HSET', KEYS[1],
)
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[5]))
redis.call('SADD', KEYS[2], ARGV[6])
-- ZSET: score = expire_at unix timestamp, member = share code
redis.call('ZADD', KEYS[3], tonumber(ARGV[7]), ARGV[6])
return 1
`)
@@ -86,8 +91,9 @@ func (c *ShareCodeCache) Create(ctx context.Context, macAddr, ipAddr string, eqD
}
key := shareCodeKey(code)
ok, err := shareCreateScript.Run(ctx, c.rdb, []string{key, sharePendingSet},
macAddr, ipAddr, eqJSON, expireAt.Format(time.RFC3339), int(shareCodeTTL.Seconds()), code,
macIdxKey := shareMacIndexKey(macAddr)
ok, err := shareCreateScript.Run(ctx, c.rdb, []string{key, sharePendingSet, macIdxKey},
macAddr, ipAddr, eqJSON, expireAt.Format(time.RFC3339), int(shareCodeTTL.Seconds()), code, expireAt.Unix(),
).Int()
if err != nil {
return nil, fmt.Errorf("create share code in redis: %w", err)
@@ -151,14 +157,27 @@ func (c *ShareCodeCache) ReleaseFlushLock(ctx context.Context, shareCode string)
func (c *ShareCodeCache) MarkPersisted(ctx context.Context, shareCode string) error {
key := shareCodeKey(shareCode)
// preserve remaining TTL before HSET (HSET clears TTL in some Redis versions)
remainTTL, err := c.rdb.PTTL(ctx, key).Result()
if err != nil {
return fmt.Errorf("get share code ttl: %w", err)
}
if err := c.rdb.HSet(ctx, key, fieldPersisted, "1").Err(); err != nil {
return fmt.Errorf("mark share code persisted: %w", err)
}
// restore TTL
if remainTTL > 0 {
_ = c.rdb.PExpire(ctx, key, remainTTL).Err()
}
return c.rdb.SRem(ctx, sharePendingSet, shareCode).Err()
}
func (c *ShareCodeCache) EnqueueImportLog(ctx context.Context, macAddr, shareCode, ipAddr, eqData string, expireAt time.Time) error {
field := fmt.Sprintf("%s:%s:%d", macAddr, shareCode, time.Now().UnixNano())
field := fmt.Sprintf("%s:%s", macAddr, shareCode) // 同 MAC+code 幂等,避免重复导入产生多条记录
payload, err := json.Marshal(ShareImportPendingLog{
MacAddr: macAddr,
ShareCode: shareCode,
@@ -172,6 +191,8 @@ func (c *ShareCodeCache) EnqueueImportLog(ctx context.Context, macAddr, shareCod
if err := c.rdb.HSet(ctx, shareImportPendingHash, field, payload).Err(); err != nil {
return fmt.Errorf("enqueue import log: %w", err)
}
// Fallback TTL: prevent unbounded growth if persist task is disabled or DB is down
c.rdb.Expire(ctx, shareImportPendingHash, shareImportPendingTTL)
return nil
}
@@ -195,6 +216,50 @@ func (c *ShareCodeCache) ReleaseImportFlushLock(ctx context.Context, field strin
return c.rdb.Del(ctx, shareImportFlushLockPref+field).Err()
}
func (c *ShareCodeCache) ListByMac(ctx context.Context, macAddr string) ([]*ShareCodeData, error) {
key := shareMacIndexKey(macAddr)
now := time.Now()
// Remove expired entries from ZSET (score = expire_at unix timestamp)
_, err := c.rdb.ZRemRangeByScore(ctx, key, "-inf", fmt.Sprintf("%d", now.Unix())).Result()
if err != nil && strings.Contains(err.Error(), "WRONGTYPE") {
// Old SET-type key from previous version, delete it
_ = c.rdb.Del(ctx, key).Err()
return nil, nil
}
// Get remaining (unexpired) codes
codes, err := c.rdb.ZRange(ctx, key, 0, -1).Result()
if err != nil {
return nil, fmt.Errorf("zrange mac index: %w", err)
}
if len(codes) == 0 {
// ZSET is empty, remove the key to avoid accumulating empty keys
_ = c.rdb.Del(ctx, key).Err()
return nil, nil
}
var result []*ShareCodeData
for _, code := range codes {
data, err := c.Get(ctx, code)
if err != nil {
return nil, err
}
if data == nil {
// hash already expired/removed, clean from ZSET
_ = c.rdb.ZRem(ctx, key, code).Err()
continue
}
result = append(result, data)
}
return result, nil
}
func shareMacIndexKey(macAddr string) string {
return shareMacIndexPrefix + macAddr
}
func shareCodeKey(code string) string {
return shareCodeKeyPrefix + code
}
+52
View File
@@ -93,6 +93,58 @@ func (h *ShareCodeHandler) ExportShareCode(c *gin.Context) {
})
}
// ListShareCodesByMac 查询某 MAC 尚未过期的分享码
//
// @Summary 查询未过期分享码
// @Description 根据设备 MAC 地址查询该设备尚未过期的所有分享码(仅查询 Redis,依赖 TTL 自动过期)
// @Tags ShareCode
// @Produce json
// @Param mac query string true "设备 MAC 地址"
// @Success 200 {object} map[string]any "成功返回 share_codes 列表"
// @Failure 400 {object} map[string]any "参数校验失败"
// @Failure 500 {object} map[string]any "系统错误"
// @Router /audio/shareList [get]
func (h *ShareCodeHandler) ListShareCodesByMac(c *gin.Context) {
mac := strings.TrimSpace(c.Query("mac"))
if mac == "" {
c.JSON(http.StatusOK, gin.H{"code": 400, "msg": "参数校验失败"})
return
}
ctx := c.Request.Context()
items, err := h.cache.ListByMac(ctx, mac)
if err != nil {
h.log.Error("list share codes by mac failed", zap.String("mac", mac), zap.Error(err))
c.JSON(http.StatusOK, gin.H{"code": 500, "msg": "系统错误"})
return
}
type shareItem struct {
ShareCode string `json:"share_code"`
ExpireAt string `json:"expire_at"`
EqData any `json:"eq_data"`
}
list := make([]shareItem, 0, len(items))
for _, item := range items {
var eqData any
if err := json.Unmarshal([]byte(item.EqData), &eqData); err != nil {
eqData = item.EqData
}
list = append(list, shareItem{
ShareCode: item.ShareCode,
ExpireAt: item.ExpireAt.Format("2006-01-02 15:04:05"),
EqData: eqData,
})
}
c.JSON(http.StatusOK, gin.H{
"code": 200,
"msg": "操作成功",
"share_codes": list,
})
}
// ImportShareCode 导入分享码
//
// @Summary 导入 EQ 分享码
+1
View File
@@ -68,6 +68,7 @@ func New(log *zap.Logger, db *sql.DB, searchClient *search.Client, rdb *redis.Cl
audio.GET("/modelCurve", curve.ModelCurve)
audio.GET("/getModelCSV", modelCSV.GetModelCSV)
audio.POST("/shareCreate", shareCode.ExportShareCode)
audio.GET("/shareList", shareCode.ListShareCodesByMac)
audio.GET("/shareAccept", shareCode.ImportShareCode)
}