gateway_cache.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package repository
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/Wei-Shaw/sub2api/internal/service"
  12. "github.com/redis/go-redis/v9"
  13. )
  14. const stickySessionPrefix = "sticky_session:"
  15. const openAIResponsesSessionWindowPrefix = "openai_responses_session_window:"
  16. const liveCallPrefix = "live:call:"
  17. type gatewayCache struct {
  18. rdb *redis.Client
  19. }
  20. func NewGatewayCache(rdb *redis.Client) service.GatewayCache {
  21. return &gatewayCache{rdb: rdb}
  22. }
  23. // buildSessionKey 构建 session key,包含 groupID 实现分组隔离
  24. // 格式: sticky_session:{groupID}:{sessionHash}
  25. func buildSessionKey(groupID int64, sessionHash string) string {
  26. return fmt.Sprintf("%s%d:%s", stickySessionPrefix, groupID, sessionHash)
  27. }
  28. func buildOpenAIResponsesSessionWindowKey(groupID int64, sessionHash string) string {
  29. return fmt.Sprintf("%s%d:%s", openAIResponsesSessionWindowPrefix, groupID, sessionHash)
  30. }
  31. func (c *gatewayCache) GetSessionAccountID(ctx context.Context, groupID int64, sessionHash string) (int64, error) {
  32. key := buildSessionKey(groupID, sessionHash)
  33. accountID, err := c.rdb.Get(ctx, key).Int64()
  34. if err != nil {
  35. if errors.Is(err, redis.Nil) {
  36. return 0, service.ErrStickySessionNotFound
  37. }
  38. return 0, err
  39. }
  40. return accountID, nil
  41. }
  42. func (c *gatewayCache) SetSessionAccountID(ctx context.Context, groupID int64, sessionHash string, accountID int64, ttl time.Duration) error {
  43. key := buildSessionKey(groupID, sessionHash)
  44. return c.rdb.Set(ctx, key, accountID, ttl).Err()
  45. }
  46. func (c *gatewayCache) RefreshSessionTTL(ctx context.Context, groupID int64, sessionHash string, ttl time.Duration) error {
  47. key := buildSessionKey(groupID, sessionHash)
  48. return c.rdb.Expire(ctx, key, ttl).Err()
  49. }
  50. // DeleteSessionAccountID 删除粘性会话与账号的绑定关系。
  51. // 当检测到绑定的账号不可用(如状态错误、禁用、不可调度等)时调用,
  52. // 以便下次请求能够重新选择可用账号。
  53. //
  54. // DeleteSessionAccountID removes the sticky session binding for the given session.
  55. // Called when the bound account becomes unavailable (e.g., error status, disabled,
  56. // or unschedulable), allowing subsequent requests to select a new available account.
  57. func (c *gatewayCache) DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error {
  58. key := buildSessionKey(groupID, sessionHash)
  59. return c.rdb.Del(ctx, key).Err()
  60. }
  61. var claimOpenAIResponsesSessionWindowScript = redis.NewScript(`
  62. local previous = redis.call('GET', KEYS[1])
  63. redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])
  64. return previous
  65. `)
  66. var compareAndRefreshOpenAIResponsesSessionWindowScript = redis.NewScript(`
  67. local current = redis.call('GET', KEYS[1])
  68. if current == false or current ~= ARGV[1] then
  69. return 0
  70. end
  71. redis.call('PEXPIRE', KEYS[1], ARGV[2])
  72. return 1
  73. `)
  74. var compareAndDeleteOpenAIResponsesSessionWindowScript = redis.NewScript(`
  75. local current = redis.call('GET', KEYS[1])
  76. if current == false or current ~= ARGV[1] then
  77. return 0
  78. end
  79. redis.call('DEL', KEYS[1])
  80. return 1
  81. `)
  82. func (c *gatewayCache) ClaimOpenAIResponsesSessionWindow(ctx context.Context, groupID int64, sessionHash string, owner []byte, ttl time.Duration) ([]byte, error) {
  83. if c == nil || c.rdb == nil {
  84. return nil, errors.New("gateway cache unavailable")
  85. }
  86. if len(owner) == 0 || strings.TrimSpace(sessionHash) == "" || ttl <= 0 {
  87. return nil, errors.New("invalid OpenAI Responses session-window claim")
  88. }
  89. result, err := claimOpenAIResponsesSessionWindowScript.Run(
  90. ctx,
  91. c.rdb,
  92. []string{buildOpenAIResponsesSessionWindowKey(groupID, sessionHash)},
  93. owner,
  94. ttl.Milliseconds(),
  95. ).Result()
  96. if errors.Is(err, redis.Nil) {
  97. return nil, nil
  98. }
  99. if err != nil {
  100. return nil, err
  101. }
  102. switch value := result.(type) {
  103. case nil:
  104. return nil, nil
  105. case string:
  106. return []byte(value), nil
  107. case []byte:
  108. return append([]byte(nil), value...), nil
  109. default:
  110. return nil, fmt.Errorf("unexpected OpenAI Responses session-window claim result %T", result)
  111. }
  112. }
  113. func (c *gatewayCache) CompareAndRefreshOpenAIResponsesSessionWindow(ctx context.Context, groupID int64, sessionHash string, expected []byte, ttl time.Duration) (bool, error) {
  114. if c == nil || c.rdb == nil {
  115. return false, errors.New("gateway cache unavailable")
  116. }
  117. if len(expected) == 0 || strings.TrimSpace(sessionHash) == "" || ttl <= 0 {
  118. return false, errors.New("invalid OpenAI Responses session-window refresh")
  119. }
  120. n, err := compareAndRefreshOpenAIResponsesSessionWindowScript.Run(
  121. ctx,
  122. c.rdb,
  123. []string{buildOpenAIResponsesSessionWindowKey(groupID, sessionHash)},
  124. expected,
  125. ttl.Milliseconds(),
  126. ).Int()
  127. return n == 1, err
  128. }
  129. func (c *gatewayCache) CompareAndDeleteOpenAIResponsesSessionWindow(ctx context.Context, groupID int64, sessionHash string, expected []byte) (bool, error) {
  130. if c == nil || c.rdb == nil {
  131. return false, errors.New("gateway cache unavailable")
  132. }
  133. if len(expected) == 0 || strings.TrimSpace(sessionHash) == "" {
  134. return false, errors.New("invalid OpenAI Responses session-window delete")
  135. }
  136. n, err := compareAndDeleteOpenAIResponsesSessionWindowScript.Run(
  137. ctx,
  138. c.rdb,
  139. []string{buildOpenAIResponsesSessionWindowKey(groupID, sessionHash)},
  140. expected,
  141. ).Int()
  142. return n == 1, err
  143. }
  144. var _ service.OpenAIWSSessionPreemptionCache = (*gatewayCache)(nil)
  145. const (
  146. grokVideoPendingBillingPrefix = "grok_video_pending:"
  147. grokVideoBilledPrefix = "grok_video_billed:"
  148. )
  149. func (c *gatewayCache) SetGrokVideoPendingBilling(ctx context.Context, key string, payload []byte, ttl time.Duration) error {
  150. if c == nil || c.rdb == nil {
  151. return errors.New("gateway cache unavailable")
  152. }
  153. key = strings.TrimSpace(key)
  154. if key == "" || len(payload) == 0 {
  155. return errors.New("invalid grok video pending billing payload")
  156. }
  157. if ttl <= 0 {
  158. ttl = 24 * time.Hour
  159. }
  160. return c.rdb.Set(ctx, grokVideoPendingBillingPrefix+key, payload, ttl).Err()
  161. }
  162. func (c *gatewayCache) GetGrokVideoPendingBilling(ctx context.Context, key string) ([]byte, error) {
  163. if c == nil || c.rdb == nil {
  164. return nil, errors.New("gateway cache unavailable")
  165. }
  166. key = strings.TrimSpace(key)
  167. if key == "" {
  168. return nil, errors.New("invalid grok video pending billing key")
  169. }
  170. val, err := c.rdb.Get(ctx, grokVideoPendingBillingPrefix+key).Bytes()
  171. if err != nil {
  172. if errors.Is(err, redis.Nil) {
  173. return nil, nil
  174. }
  175. return nil, err
  176. }
  177. return val, nil
  178. }
  179. func (c *gatewayCache) ClaimGrokVideoBilled(ctx context.Context, key string, ttl time.Duration) (bool, error) {
  180. if c == nil || c.rdb == nil {
  181. return false, errors.New("gateway cache unavailable")
  182. }
  183. key = strings.TrimSpace(key)
  184. if key == "" {
  185. return false, errors.New("invalid grok video billed key")
  186. }
  187. if ttl <= 0 {
  188. ttl = 48 * time.Hour
  189. }
  190. return c.rdb.SetNX(ctx, grokVideoBilledPrefix+key, "1", ttl).Result()
  191. }
  192. func (c *gatewayCache) ReleaseGrokVideoBilled(ctx context.Context, key string) error {
  193. if c == nil || c.rdb == nil {
  194. return errors.New("gateway cache unavailable")
  195. }
  196. key = strings.TrimSpace(key)
  197. if key == "" {
  198. return errors.New("invalid grok video billed key")
  199. }
  200. return c.rdb.Del(ctx, grokVideoBilledPrefix+key).Err()
  201. }
  202. // Compile-time assertion: gatewayCache must implement CyberSessionBlockStore.
  203. var _ service.CyberSessionBlockStore = (*gatewayCache)(nil)
  204. var _ service.LiveCallStore = (*gatewayCache)(nil)
  205. const reasoningContentPrefix = "reasoning_content:"
  206. // reasoningContentDefaultTTL 是 reasoning 缓存的默认过期时间。Codex 会话可能
  207. // 跨多天恢复,取 7 天;调用方传入非正 TTL 时兜底。
  208. const reasoningContentDefaultTTL = 7 * 24 * time.Hour
  209. // SetReasoningContent 按 reasoning item id 缓存 reasoning 全文。
  210. // itemID 或 content 为空时直接返回 nil(无可缓存内容,属正常情况而非错误)。
  211. func (c *gatewayCache) SetReasoningContent(ctx context.Context, itemID string, content string, ttl time.Duration) error {
  212. if c == nil || c.rdb == nil {
  213. return errors.New("gateway cache unavailable")
  214. }
  215. itemID = strings.TrimSpace(itemID)
  216. if itemID == "" || content == "" {
  217. return nil
  218. }
  219. if ttl <= 0 {
  220. ttl = reasoningContentDefaultTTL
  221. }
  222. return c.rdb.Set(ctx, reasoningContentPrefix+itemID, content, ttl).Err()
  223. }
  224. // GetReasoningContent 返回缓存的 reasoning 全文;未命中返回
  225. // service.ErrReasoningContentNotFound。
  226. func (c *gatewayCache) GetReasoningContent(ctx context.Context, itemID string) (string, error) {
  227. if c == nil || c.rdb == nil {
  228. return "", errors.New("gateway cache unavailable")
  229. }
  230. itemID = strings.TrimSpace(itemID)
  231. if itemID == "" {
  232. return "", service.ErrReasoningContentNotFound
  233. }
  234. val, err := c.rdb.Get(ctx, reasoningContentPrefix+itemID).Result()
  235. if err != nil {
  236. if errors.Is(err, redis.Nil) {
  237. return "", service.ErrReasoningContentNotFound
  238. }
  239. return "", err
  240. }
  241. return val, nil
  242. }
  243. const (
  244. cyberSessionBlockPrefix = "cyber_session_block:"
  245. cyberSessionScopePrefix = "cyber_session_scope:"
  246. cyberSessionRedisCommandMaxKeys = 128
  247. )
  248. // SetCyberSessionBlocked writes exact blocks in bounded transactions. The
  249. // coarse scope is activated only after all exact blocks have been stored.
  250. func (c *gatewayCache) SetCyberSessionBlocked(ctx context.Context, scopeKey string, keys []string, ttl time.Duration) error {
  251. if len(keys) == 0 {
  252. return nil
  253. }
  254. exactKeys := make([]string, 0, cyberSessionRedisCommandMaxKeys)
  255. flush := func() error {
  256. if len(exactKeys) == 0 {
  257. return nil
  258. }
  259. pipe := c.rdb.TxPipeline()
  260. for _, key := range exactKeys {
  261. pipe.Set(ctx, cyberSessionBlockPrefix+key, "1", ttl)
  262. }
  263. _, err := pipe.Exec(ctx)
  264. exactKeys = exactKeys[:0]
  265. return err
  266. }
  267. for _, key := range keys {
  268. if key != "" {
  269. exactKeys = append(exactKeys, key)
  270. if len(exactKeys) == cyberSessionRedisCommandMaxKeys {
  271. if err := flush(); err != nil {
  272. return err
  273. }
  274. }
  275. }
  276. }
  277. if err := flush(); err != nil {
  278. return err
  279. }
  280. if scopeKey != "" {
  281. return c.rdb.Set(ctx, cyberSessionScopePrefix+scopeKey, "1", ttl).Err()
  282. }
  283. return nil
  284. }
  285. func (c *gatewayCache) IsCyberSessionScopeActive(ctx context.Context, scopeKey string) (bool, error) {
  286. n, err := c.rdb.Exists(ctx, cyberSessionScopePrefix+scopeKey).Result()
  287. if err != nil {
  288. return false, err
  289. }
  290. return n > 0, nil
  291. }
  292. // FindCyberSessionBlocked checks bounded batches in caller order and stops at
  293. // the first blocked key, preserving the original earliest-match behavior.
  294. func (c *gatewayCache) FindCyberSessionBlocked(ctx context.Context, keys []string) (string, error) {
  295. if len(keys) == 0 {
  296. return "", nil
  297. }
  298. for start := 0; start < len(keys); start += cyberSessionRedisCommandMaxKeys {
  299. end := start + cyberSessionRedisCommandMaxKeys
  300. if end > len(keys) {
  301. end = len(keys)
  302. }
  303. redisKeys := make([]string, end-start)
  304. for i, key := range keys[start:end] {
  305. redisKeys[i] = cyberSessionBlockPrefix + key
  306. }
  307. values, err := c.rdb.MGet(ctx, redisKeys...).Result()
  308. if err != nil {
  309. return "", err
  310. }
  311. for i, value := range values {
  312. if value != nil {
  313. return keys[start+i], nil
  314. }
  315. }
  316. }
  317. return "", nil
  318. }
  319. var claimLiveControllerScript = redis.NewScript(`
  320. local key = KEYS[1]
  321. local target = ARGV[1]
  322. local owner = ARGV[2]
  323. local current = redis.call('HGET', key, 'controller')
  324. if current == false or current == 'closed' then
  325. return 0
  326. end
  327. if target == 'observer' and current ~= 'pending' then
  328. return 0
  329. end
  330. if target == 'proxy' and current ~= 'pending' and current ~= 'observer' and
  331. (current ~= 'proxy' or redis.call('HGET', key, 'controller_owner') ~= owner) then
  332. return 0
  333. end
  334. redis.call('HSET', key, 'controller', target, 'controller_owner', owner)
  335. return 1
  336. `)
  337. var markLiveCallClosedScript = redis.NewScript(`
  338. local key = KEYS[1]
  339. if redis.call('EXISTS', key) == 0 then
  340. return 0
  341. end
  342. if redis.call('HGET', key, 'controller') == 'closed' then
  343. return 0
  344. end
  345. redis.call('HSET', key, 'controller', 'closed', 'controller_owner', '')
  346. redis.call('EXPIRE', key, ARGV[1])
  347. return 1
  348. `)
  349. var releaseLiveControllerScript = redis.NewScript(`
  350. local key = KEYS[1]
  351. if redis.call('HGET', key, 'controller') ~= 'proxy' or
  352. redis.call('HGET', key, 'controller_owner') ~= ARGV[1] then
  353. return 0
  354. end
  355. redis.call('HSET', key, 'controller', 'pending', 'controller_owner', '')
  356. return 1
  357. `)
  358. func liveCallKey(callHash string) string {
  359. return liveCallPrefix + callHash
  360. }
  361. func HashLiveCallID(callID string) string {
  362. sum := sha256.Sum256([]byte(callID))
  363. return hex.EncodeToString(sum[:])
  364. }
  365. func (c *gatewayCache) SaveLiveCall(ctx context.Context, record *service.LiveCallRecord, ttl time.Duration) error {
  366. if record == nil || record.CallHash == "" || record.CallID == "" {
  367. return fmt.Errorf("invalid live call record")
  368. }
  369. values := map[string]any{
  370. "call_id": record.CallID,
  371. "account_id": record.AccountID,
  372. "api_key_id": record.APIKeyID,
  373. "user_id": record.UserID,
  374. "group_id": record.GroupID,
  375. "subscription_id": record.SubscriptionID,
  376. "lease_id": record.LeaseID,
  377. "model": record.Model,
  378. "created_at": record.CreatedAt.UnixMilli(),
  379. "expires_at": record.ExpiresAt.UnixMilli(),
  380. "controller": record.Controller,
  381. "controller_owner": record.ControllerOwner,
  382. "user_agent": record.UserAgent,
  383. "ip_address": record.IPAddress,
  384. "inbound_endpoint": record.InboundEndpoint,
  385. "attestation": record.AttestationCiphertext,
  386. }
  387. key := liveCallKey(record.CallHash)
  388. pipe := c.rdb.TxPipeline()
  389. pipe.HSet(ctx, key, values)
  390. pipe.Expire(ctx, key, ttl)
  391. _, err := pipe.Exec(ctx)
  392. return err
  393. }
  394. func (c *gatewayCache) GetLiveCall(ctx context.Context, callHash string) (*service.LiveCallRecord, error) {
  395. values, err := c.rdb.HGetAll(ctx, liveCallKey(callHash)).Result()
  396. if err != nil {
  397. return nil, err
  398. }
  399. if len(values) == 0 {
  400. return nil, service.ErrLiveCallNotFound
  401. }
  402. parseInt := func(field string) int64 {
  403. value, _ := strconv.ParseInt(values[field], 10, 64)
  404. return value
  405. }
  406. createdAt := time.UnixMilli(parseInt("created_at"))
  407. expiresAt := time.UnixMilli(parseInt("expires_at"))
  408. return &service.LiveCallRecord{
  409. CallID: values["call_id"],
  410. CallHash: callHash,
  411. AccountID: parseInt("account_id"),
  412. APIKeyID: parseInt("api_key_id"),
  413. UserID: parseInt("user_id"),
  414. GroupID: parseInt("group_id"),
  415. SubscriptionID: parseInt("subscription_id"),
  416. LeaseID: values["lease_id"],
  417. Model: values["model"],
  418. CreatedAt: createdAt,
  419. ExpiresAt: expiresAt,
  420. Controller: values["controller"],
  421. ControllerOwner: values["controller_owner"],
  422. UserAgent: values["user_agent"],
  423. IPAddress: values["ip_address"],
  424. InboundEndpoint: values["inbound_endpoint"],
  425. AttestationCiphertext: values["attestation"],
  426. }, nil
  427. }
  428. func (c *gatewayCache) ClaimLiveController(ctx context.Context, callHash, controller, owner string) (bool, error) {
  429. result, err := claimLiveControllerScript.Run(ctx, c.rdb, []string{liveCallKey(callHash)}, controller, owner).Int()
  430. return result == 1, err
  431. }
  432. func (c *gatewayCache) GetLiveController(ctx context.Context, callHash string) (string, error) {
  433. value, err := c.rdb.HGet(ctx, liveCallKey(callHash), "controller").Result()
  434. if err == redis.Nil {
  435. return "", service.ErrLiveCallNotFound
  436. }
  437. return value, err
  438. }
  439. func (c *gatewayCache) ReleaseLiveController(ctx context.Context, callHash, owner string) (bool, error) {
  440. result, err := releaseLiveControllerScript.Run(ctx, c.rdb, []string{liveCallKey(callHash)}, owner).Int()
  441. return result == 1, err
  442. }
  443. func (c *gatewayCache) MarkLiveCallClosed(ctx context.Context, callHash string, ttl time.Duration) (bool, error) {
  444. result, err := markLiveCallClosedScript.Run(ctx, c.rdb, []string{liveCallKey(callHash)}, int64(ttl.Seconds())).Int()
  445. return result == 1, err
  446. }