Files
image2api/backend/internal/service/concurrency.go
T
chiyiandClaude Opus 4.8 5cf6206ee9 feat: 并发分组系统 + 品牌/Logo 上传 + 兑换码开关 + 文档分辨率表
并发分组(新功能):
- 新表 concurrency_groups(名称/上限/默认),用户加 concurrency_group_id
- 启动自动建「默认并发」组(上限10、默认),老用户回填、新注册自动绑定
- 并发计数改用 Redis(自愈 sorted-set + TTL + fail-open):
  · 用户并发(画图台 + API key 合计)受其分组上限限制,0=不限制 → 超返回 429
  · 账号级并发也从内存 gate 换成同一套 Redis(6 处调用点)
  · 移除旧的「已有正在生成的任务」单任务锁
- 后台「并发分组」新菜单:增删改、设默认、用户数;默认组不可删(删别的组成员转默认)
- 用户管理:并发列 + 新建/编辑可选分组
- 个人设置页:账户信息卡(用户名/邮箱/角色/余额/并发);/me 暴露 concurrency_group/limit

品牌 / Logo(上传到 RustFS):
- Logo 改成拖拽/点击上传,点保存才上传;替换自动删旧;branding/ 设为公开且被清理任务 pin 住(永不删)
- 有自定义就用:前台左侧 nav + 后台侧栏 + favicon(浏览器标签);没有则默认 V 图标
- 前台页头还原成文字;首页 Hero 子标题用 site.subtitle(默认那句宣传语,设置页预填)
- 邮件验证码标题用站点名;新增 POST/DELETE /settings/logo + POST /settings/asset(首页底图上传)

兑换码开关:
- 系统设置→积分 新增「开启兑换码」(默认开);关闭后后端拒绝兑换、前台隐藏兑换入口(/site 暴露 cdk_redeem_enabled)

文档 / 分辨率:
- 去掉 quality 参数:size(宽x高)同时决定比例 + 分辨率档(长边映射 1K/2K/4K)
- 文档加「分辨率对照表」(14 个比例 × 1K/2K/4K → size 该传的值);guessRatio 与自定义模型 RATIO_OPTS 对齐到 14 个

其它:
- 删模型时同步清掉各上游账号「支持模型」里的该 id
- 首页设置/兑换码弹窗去固定高度滚动条;展示位弹窗浅色主题适配

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:52:31 +08:00

104 lines
3.4 KiB
Go

package service
import (
"context"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
// ConcurrencyService is a Redis-backed, self-healing concurrency limiter shared
// by the per-user gate (画图台 + API key) and the per-account upstream gate.
//
// Each slot is a member of a sorted set keyed by the subject (user/account),
// scored with its expiry time. Acquire prunes expired members first, so a slot
// whose Release was lost (crash / missed defer) auto-frees after the TTL — the
// count can never leak forever. It's intentionally lossy-tolerant: if Redis is
// unavailable it FAILS OPEN (allows the work) rather than blocking generation.
type ConcurrencyService struct {
redis *redis.Client
// ttl is the max lifetime of a slot — the longest a generation can run
// (video ~3min) plus head-room, after which a stuck slot self-heals.
ttl int
}
func NewConcurrencyService(rdb *redis.Client) *ConcurrencyService {
return &ConcurrencyService{redis: rdb, ttl: 900} // 15 min
}
// acquireScript: KEYS[1]=set, ARGV[1]=max (0=unlimited), ARGV[2]=ttl secs,
// ARGV[3]=token. Prunes expired members, then admits the token iff under max.
// Returns 1 on success, 0 when full.
var acquireScript = redis.NewScript(`
local t = redis.call('TIME')
local now = tonumber(t[1])
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
local n = redis.call('ZCARD', KEYS[1])
local max = tonumber(ARGV[1])
if max > 0 and n >= max then return 0 end
redis.call('ZADD', KEYS[1], now + tonumber(ARGV[2]), ARGV[3])
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[2]))
return 1
`)
// Acquire takes one slot under `key` (capped at max; 0 = unlimited), tagged with
// `token`. Returns true if admitted. Fail-open when Redis is down/unset.
func (c *ConcurrencyService) Acquire(ctx context.Context, key string, max int, token string) bool {
if c == nil || c.redis == nil {
return true
}
res, err := acquireScript.Run(ctx, c.redis, []string{key}, max, c.ttl, token).Int()
if err != nil {
return true // fail open — never block a generation on Redis trouble
}
return res == 1
}
// Release frees the slot held by `token` under `key`. Safe to call even if the
// slot already expired.
func (c *ConcurrencyService) Release(ctx context.Context, key, token string) {
if c == nil || c.redis == nil {
return
}
_ = c.redis.ZRem(ctx, key, token).Err()
}
// Count returns the live (non-expired) slot count under `key` — for display.
func (c *ConcurrencyService) Count(ctx context.Context, key string) int {
if c == nil || c.redis == nil {
return 0
}
now := time.Now().Unix()
_ = c.redis.ZRemRangeByScore(ctx, key, "-inf", strconv.FormatInt(now, 10)).Err()
n, err := c.redis.ZCard(ctx, key).Result()
if err != nil {
return 0
}
return int(n)
}
// CountUsers returns live concurrency for many users in one round-trip
// (group_id display etc. don't need this, but the user list does). Keyed by the
// raw subject id passed in.
func (c *ConcurrencyService) CountMany(ctx context.Context, prefix string, ids []string) map[string]int {
out := make(map[string]int, len(ids))
if c == nil || c.redis == nil || len(ids) == 0 {
return out
}
pipe := c.redis.Pipeline()
cmds := make(map[string]*redis.IntCmd, len(ids))
for _, id := range ids {
cmds[id] = pipe.ZCard(ctx, prefix+id)
}
if _, err := pipe.Exec(ctx); err != nil {
return out
}
for id, cmd := range cmds {
if n, err := cmd.Result(); err == nil && n > 0 {
out[id] = int(n)
}
}
return out
}