Compare commits

..
405 Commits
Author SHA1 Message Date
Wesley Liddick 3fa08aa930 Merge pull request #3749 from moonfunjohn/codex/easypay-custom-methods
EasyPay custom visible payment methods
2026-07-06 16:06:59 +08:00
Albert Coady 27cb485d55 fix: share built-in payment method matching 2026-07-06 15:00:29 +08:00
Albert Coady 22ec77b570 fix: match built-in payment methods exactly 2026-07-06 15:00:29 +08:00
Albert Coady b197ba61ce test: align antigravity mapping preset label 2026-07-06 15:00:29 +08:00
Albert Coady a5a2fea045 Polish EasyPay custom method UI 2026-07-06 15:00:29 +08:00
Albert Coady 0dc6e56aae fix: harden easypay custom method validation 2026-07-06 15:00:29 +08:00
Albert Coady bf76168ba5 feat: add custom easypay payment methods 2026-07-06 15:00:29 +08:00
Wesley Liddick 2854ab2ace Merge pull request #3744 from Wei-Shaw/fix/subscription-cny-optin-rate
fix(payment): 订阅 CNY 换算改为独立汇率配置的显式 opt-in(含 #3738)
2026-07-06 14:58:20 +08:00
Wesley Liddick e95c909ee5 Merge pull request #3747 from Wei-Shaw/revert-3738-fix/subscription-confirm-amount-and-affiliate-base
Revert "fix(payment): 订阅确认页显示换算后 CNY 金额 + 邀请返利按 USD price 计算"
2026-07-06 14:58:00 +08:00
Wesley Liddick ba1bb0a3d3 Revert "fix(payment): 订阅确认页显示换算后 CNY 金额 + 邀请返利按 USD price 计算" 2026-07-06 14:55:04 +08:00
Wesley Liddick 11fd61458c Merge pull request #3738 from wucm667/fix/subscription-confirm-amount-and-affiliate-base
fix(payment): 订阅确认页显示换算后 CNY 金额 + 邀请返利按 USD price 计算
2026-07-06 14:53:59 +08:00
shaw d56e94b875 feat(payment): 订阅 CNY 换算改为独立汇率配置的显式 opt-in
- 新增 SUBSCRIPTION_USD_TO_CNY_RATE 配置(1 USD = X CNY,默认 0=关闭),
  替代复用 balance_recharge_multiplier 的隐式换算,促销倍率与订阅定价解耦
- 未配置汇率时订阅保持 price 直付的存量行为,存量部署升级零影响
- 前端确认页/原价/手续费/方式限额与后端换算条件严格镜像(rate>0 且币种为 CNY)
- 管理后台新增汇率配置输入(zh/en 文案),checkout-info 透出 subscription_usd_to_cny_rate
- 单测锁定:汇率未配置时不换算、换算使用汇率而非余额倍率、余额订单不受影响、返利仍按 USD price
2026-07-06 14:34:17 +08:00
shaw d089c5789c Merge branch 'pr-3738' into fix/subscription-cny-optin-rate 2026-07-06 14:14:19 +08:00
Wesley Liddick 9fac6f15ce Merge pull request #3739 from Wei-Shaw/fix/openai-advanced-scheduler-audit-fixes
fix(scheduler): 修复 OpenAI 高级调度器审计发现的正确性与性能问题
2026-07-06 13:45:15 +08:00
shaw 0fd2e9216d fix(scheduler): 修复 OpenAI 高级调度器审计发现的正确性与性能问题
针对 #3692 合并后审计发现的问题集中修复:

- previous_response_id 剥离条件改为按 call_id 全覆盖校验,
  部分可重建的工具续链不再被误剥离(不受开关门控的行为回归)
- 粘性加权回退路径补分组归属校验并清理失效绑定,杜绝跨分组账号泄漏
- 账号列表页:无 OpenAI 账号时跳过分数计算、过滤池限定 openai 平台、
  负载批查合并为账号并集一次查询,消除全表扫描与 Redis N+1
- 订阅优先模式下常规池不可用时回退订阅池等待计划,
  busy-but-waitable 的订阅账号不再导致请求硬失败
- TopK/权重 DB 覆盖显式受总开关门控,与兄弟子开关语义一致
- 前端未分组 OpenAI 账号回退展示基础分,不再显示 "-"
- ListAllWithFilters 等能力正式进入 AccountRepository/AdminService 接口,
  移除匿名接口断言与静默降级;负载批查失败补 warn 日志
- SelectAccountWithSchedulerForCapability 增加显式 previousResponseCanMove
  参数,移除 "previous_response_can_move" 魔法字符串哨兵
- 设置写入路径补"基础权重不得全为零"聚合校验;
  运行时设置批量读取失败的降级路径覆盖全部键并留痕
2026-07-06 11:43:16 +08:00
Wesley Liddick 759332aa92 Merge pull request #3692 from linshuboy/codex/openai-advanced-scheduler-controls-squashed
[codex] add OpenAI advanced scheduler controls
2026-07-06 10:59:23 +08:00
wucm667 b408edf97b fix(payment): convert subscription CNY pay amount 2026-07-06 10:56:43 +08:00
Wesley Liddick f0f1f59a44 Merge pull request #3716 from wucm667/fix/antigravity-refresh-server-invalidated-token
fix(antigravity): 401 服务端失效的 token 触发主动刷新,修复 NeedsRefresh 仅看 expires_at 的死循环
2026-07-06 10:18:49 +08:00
Wesley Liddick ac68d73f0c Merge pull request #3717 from wucm667/fix/anthropic-models-honor-group-config
fix(gateway): Anthropic /v1/models 返回分组 models_list_config 自定义模型列表
2026-07-06 10:18:36 +08:00
Wesley Liddick 2e70ec0a15 Merge pull request #3714 from MoRanHuiShou-pug/fix-payment-nul-bytes
fix: sanitize payment response NUL bytes
2026-07-06 10:18:18 +08:00
Wesley Liddick de15f29d1f Merge pull request #3718 from wucm667/fix/usage-csv-export-utf8-bom
fix(usage): CSV 导出补 UTF-8 BOM,修复 Excel 打开中文列乱码
2026-07-06 10:12:27 +08:00
Wesley Liddick 809e1cf8ee Merge pull request #3704 from feitianbubu/feat/sidebar-logo-home-link
feat: 点击侧边栏 Logo/站点名返回首页
2026-07-06 10:12:15 +08:00
Wesley Liddick c9dda3c01f Merge pull request #3734 from Yinr/patch-1
fix(i18n): correct misleading "irreversible" description for revoke action
2026-07-06 10:12:04 +08:00
shaw 6752cdc826 fix(i18n): 用量页费用明细提示将面向用户的"成本"措辞统一为"费用"
用户 /usage 页费用列悬浮提示中的成本明细/输入成本/输出成本/
缓存创建成本/缓存读取成本/图片输出成本 改为对应的"费用"表述;
成本是运营方视角的词,面向用户应称费用。管理端真正的账号成本
词条(accountCost 等)保持不变。
2026-07-06 09:36:21 +08:00
Yeyin Hu ee90246aa5 Modify revokeDesc for subscription termination
Updated revokeDesc to indicate restoration option.
2026-07-06 08:23:43 +08:00
Yeyin Hu 2d2b6f0325 Update revokeDesc to allow subscription recovery 2026-07-06 08:12:09 +08:00
linshuboy f26ca5661e feat: add OpenAI advanced scheduler controls
Related: #1089, #408, #123
2026-07-05 17:24:38 +08:00
wucm667 aee9a7ba98 fix(usage): add UTF-8 BOM to CSV export 2026-07-05 08:36:15 +08:00
wucm667 41cdd438d7 fix(gateway): honor Anthropic custom models list 2026-07-05 08:35:34 +08:00
wucm667 b23475ac0c fix(antigravity): refresh server-invalidated tokens 2026-07-05 08:34:34 +08:00
MoRanHuiShou-pug e76e0499d7 fix: sanitize payment response NUL bytes 2026-07-05 03:55:40 +08:00
shaw 498f010ec3 fix(部署): 统一 Docker 部署 URL 安全默认值为开发友好模式
docker-compose.yml / docker-compose.local.yml 中
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP 与
SECURITY_URL_ALLOWLIST_ALLOW_PRIVATE_HOSTS 的兜底值由 false 改为 true,
与代码默认值(0c7a58fc)保持一致,避免未配置 .env 的 Docker 部署
在测试账号连接时因 http base URL 报 "invalid url scheme: http"。

同步更新 README(三语)、.env.example、config.example.yaml 中
过时的"默认拒绝 HTTP"描述,改为默认允许并指导生产环境显式收紧。
2026-07-04 13:51:37 +08:00
feitianbubu 20008264fe feat: 点击侧边栏 Logo/站点名返回首页 2026-07-04 13:33:53 +08:00
github-actions[bot] b650bdd68d chore: sync VERSION to 0.1.144 [skip ci] 2026-07-04 03:49:44 +00:00
Wesley Liddick 41def4ba03 Merge pull request #3699 from wucm667/fix/responses-billing-use-mapped-model
fix(openai): /v1/responses 计费使用映射后模型,修复按原始模型价格误计费
2026-07-04 10:40:53 +08:00
Wesley Liddick 707b87a96f Merge pull request #3676 from wucm667/fix/codex-import-refresh-token-missing-collision
fix(admin): Codex Session 导入 refresh_token 缺失时不再合并同 workspace 不同账号
2026-07-04 10:29:47 +08:00
shaw cbe0c4665f chore: update readme 2026-07-04 10:18:41 +08:00
shaw dec709fb3a chore: update sponsors 2026-07-04 10:06:11 +08:00
wucm667 4dd3aee5c2 fix(openai): use mapped billing model for responses 2026-07-04 10:04:42 +08:00
wucm667 6bd248fd1f fix(admin): avoid merging Codex access-only imports 2026-07-04 09:53:01 +08:00
shaw be297b90ce refactor(frontend): merge Codex image bridge and tool policy into one four-state control
Replace the two adjacent account-level controls (3-state injection bridge
+ 2-state explicit tool policy) in EditAccountModal with a single
four-state selector: follow channel / force inject / no injection /
block all. The four states map onto the existing extra keys
(codex_image_generation_bridge, codex_image_generation_explicit_tool_policy)
with no backend change; strip already disables the bridge upstream, so
the effective decision space is exactly these four states.

- load: strip takes precedence and reads as "block all"; legacy
  bridge_enabled key still recognized and cleaned up on save
- save: block writes policy=strip and drops the bridge override;
  inherit clears both keys
- semantic accent colors per state (sky/emerald/amber/rose) with dark
  mode support; state badge follows the same palette
- replace account-scope i18n keys in zh/en (channel-scope keys untouched)
- rewrite specs to cover all four states (25/25 passing)
2026-07-04 09:49:37 +08:00
Wesley Liddick dfdb838ce4 Merge pull request #3690 from AndersonBY/feature/codex-image-tool-policy
feat: add Codex image tool strip policy
2026-07-04 09:27:37 +08:00
Wesley Liddick be3aee1a4b Merge pull request #3694 from zhaoteng45/fix/antigravity-gemini31-pro-agent
fix: normalize Antigravity Gemini 3.1 Pro routing
2026-07-04 09:23:46 +08:00
Wesley Liddick 588e02b29e Merge pull request #3673 from heathermhuang/codex/grok-admin-issues-3545-3649
fix: preserve configured Grok OAuth concurrency
2026-07-04 09:22:18 +08:00
Wesley Liddick 659086861d Merge pull request #3670 from weiness/feat/configurable-migration-timeout
feat: make setup migration timeout configurable
2026-07-04 09:21:14 +08:00
Wesley Liddick 0c53d4f334 Merge pull request #3661 from jianjianai/fix/group-capacity-batch-hotpath
fix: 优化用户组容量汇总批量统计性能
2026-07-04 09:20:02 +08:00
Wesley Liddick 8e07ec55db Merge pull request #3685 from jianjianai/fix/optimize-slot-cleanup
fix: 优化并发槽位定时清理性能
2026-07-04 09:19:34 +08:00
Wesley Liddick 129d05258a Merge pull request #3696 from jianjianai/codex/token-expired-nonretryable
fix:添加 token_expired 刷新不可重试判断
2026-07-04 09:18:43 +08:00
Wesley Liddick 46ef146225 Merge pull request #3689 from DaydreamCoding/feat/usage-error-requests-alignment
feat(usage): 错误请求对齐用量明细(UI/排序/筛选/列设置)
2026-07-04 09:18:08 +08:00
Wesley Liddick 35df02aeac Merge pull request #3698 from Wei-Shaw/feat/anthropic-7d-oi-fable-model-rate-limit
feat(anthropic): 7d_oi(Fable 专属 7d 窗口)429 仅做模型级限流 + 用量窗口新增 7d F 进度条
2026-07-04 08:49:08 +08:00
shaw b3f796972e feat(anthropic): treat 7d_oi (Fable) window 429 as model-level rate limit
Anthropic OAuth/setup-token accounts now expose a Fable-only 7d window in
429 responses (anthropic-ratelimit-unified-7d_oi-*). Previously, a 429
triggered solely by this window fell through to the legacy path and marked
the whole account rate limited (picking the sooner 5h/7d reset) even though
5h/7d were still "allowed".

Backend:
- HandleUpstreamError: when only 7d_oi is rejected/exceeded, set a
  model-level rate limit (scope "claude-fable-5") and skip account-level
  SetRateLimited / session-window rewrite / temp-unsched entirely.
  Real 5h/7d exhaustion keeps the exact legacy account-level behavior.
- modelRateLimitKeysForRequest: append the Fable family scope for any
  mapped Anthropic model containing "fable", so claude-fable-5[1m] and
  other variants are excluded from scheduling together.
- Passive sampling: collect 7d_oi utilization/reset into Extra
  (passive_usage_7d_oi_*), including from the 429 response itself so the
  usage bar doesn't freeze at a stale value during the limit window;
  cleared on 5h window reset like the existing 7d keys.
- Usage API: new seven_day_fable window in UsageInfo. GetPassiveUsage
  builds it from passive samples; active queries parse the upstream
  seven_day_overage_included field (claim name from the
  representative-claim header) and fall back to passive data when the
  upstream usage API doesn't return it, so the active-query button keeps
  the bar populated. seven_day_sonnet handling is preserved unchanged.

Frontend:
- /admin/accounts usage cell renders a "7d F" (amber) progress bar next to
  the existing 5h / 7d / 7d S bars for Anthropic OAuth/setup-token accounts.
2026-07-04 08:28:30 +08:00
jjaw e5dc1f5972 添加 token_expired 刷新不可重试判断 2026-07-04 04:30:15 +08:00
zhaoteng45 df2cedeead fix: normalize antigravity gemini 3.1 pro routing 2026-07-03 17:22:49 +00:00
DaydreamCoding ebbdc70311 feat(usage): 错误请求对齐用量明细(UI/排序/筛选/列设置)
错误请求列表(/admin/usage 错误 tab、Ops 弹窗、用户端 /usage 错误 tab)
对齐用量明细的交互与信息密度。Squash of:

- feat(usage): 错误请求全面对齐用量明细(UI/列序/排序/筛选/列设置/新列)
- refactor(usage): 错误表提取共享徽章工具与 IP 批量工具条,后端排序解析归并 SetSort
- feat(usage): /admin/usage 错误请求新增分类过滤
- fix(ops): 错误列表 phase=upstream 过滤生效,守卫豁免改为显式 opt-in
- fix(ops): 错误列表用户列回退显示已删除 KEY 所有者
- fix(usage): 错误请求状态码排序对齐展示/过滤,筛选项改固定常用码
2026-07-03 23:02:27 +08:00
Anderson f385cdceb7 feat: add Codex image tool strip policy 2026-07-03 22:36:39 +08:00
Wesley Liddick 2649573b99 Merge pull request #3684 from Wei-Shaw/fix/usage-log-queue-silent-drop
fix: prevent silent usage_logs drops under queue overflow
2026-07-03 22:17:24 +08:00
shaw a1b2b32e08 fix: prevent silent usage_logs drops under queue overflow (#3656)
高并发下扣费成功但 usage_logs 被双层异步队列静默丢弃(单用户实测丢失 49%),
导致消费排行与对账缺口。根因是 6a685727 为避免溢出时单行 INSERT 踩踏数据库,
把三处"队列满"改成了立即终态丢弃。

改为有界阻塞背压,兼顾数据不丢与批量写入模式不变:

- CreateBestEffort/createBatched 入队移除 default 立即丢弃分支,
  队列满时阻塞等待(受 detached 15s ctx 期限约束)
- writeUsageLogBestEffort 收到 dropped 不再直接放弃,统一走
  repo.Create 同步兜底(仍经批处理器;ctx 耗尽时换新 detached 窗口),
  重复写入由 ON CONFLICT DO NOTHING 幂等防护
- worker 池默认溢出策略 sample→sync(viper 默认 + 池常量),
  溢出时提交方内联执行(提交点在响应写出后,不阻塞客户端),
  显式配置 sample/drop 的部署不受影响
- 附带修复 ensure*Batcher 的存量数据竞争:channel nil 检查移入 sync.Once

正常负载零行为变化;突发时短暂等待替代永久丢失;数据库只见批量 INSERT。
2026-07-03 21:02:32 +08:00
jjaw f3a3a0869d 优化并发槽位清理 2026-07-03 21:02:31 +08:00
Heatherm Huang b2687b2258 fix(frontend): edit grok oauth model mapping 2026-07-03 19:43:54 +08:00
Wesley Liddick 28c2d20d9f Merge pull request #3675 from wucm667/fix/antigravity-401-auto-recover
fix(antigravity): 401 认证失败可自动恢复,不再永久卡在 error 状态
2026-07-03 16:58:37 +08:00
jianjian c620ad6a36 fix: align group capacity SQL with target schema 2026-07-03 08:44:39 +00:00
wucm667 d0a1443a41 fix(antigravity): allow oauth 401 auto recovery 2026-07-03 15:21:53 +08:00
Heatherm Huang 2b462b07de fix: preserve configured Grok OAuth concurrency 2026-07-03 14:41:18 +08:00
Wesley Liddick 87dfc66132 Merge pull request #3659 from jianjianai/fix/ops-realtime-stats-performance
fix: 优化运维实时账号统计接口性能
2026-07-03 10:45:24 +08:00
Wesley Liddick 5d7f213cbf Merge pull request #3657 from jianjianai/fix/redeem-invitation-bad-request
修复邀请码误走普通兑换接口时返回 500
2026-07-03 10:44:22 +08:00
weiness 36d5f4e4ca feat: make setup migration timeout configurable 2026-07-03 10:29:33 +08:00
shaw a5638a4e54 fix: match Codex session imports by chatgpt_user_id before shared account id
Members of the same ChatGPT team share chatgpt_account_id, so matching
imports by the account key first could overwrite another member's
account credentials. Identity keys are now ordered by strength
(user > email > access > account), and an account-key hit is rejected
when both sides carry different chatgpt_user_id values.

- Keep the account-key fallback when either side lacks a user id, so
  legacy accounts without chatgpt_user_id are updated and backfilled
  instead of duplicated
- Index all candidate accounts per shared key so a teammate's row can
  no longer shadow a legacy account depending on row order
- Apply the same conflict check to in-batch dedup and emit a warning
  when a legacy account is claimed via the shared account key
- Scope a 120s timeout to the Codex session import request instead of
  raising the global client timeout
2026-07-03 10:13:51 +08:00
jianjian 72ccd1b111 fix: batch group capacity summaries 2026-07-02 20:22:17 +00:00
jianjian 3f2ef60468 fix: optimize ops realtime account stats 2026-07-02 20:04:47 +00:00
jianjian 372436323a 修复邀请码普通兑换错误 2026-07-02 16:38:42 +00:00
github-actions[bot] 0b8e5eec32 chore: sync VERSION to 0.1.143 [skip ci] 2026-07-02 11:48:20 +00:00
Wesley Liddick 9caa3c9c5e Merge pull request #3635 from JRBaggins/hotfix/openai-oauth-count-tokens-latest
fix: handle OpenAI OAuth count_tokens scope errors
2026-07-02 17:41:43 +08:00
Wesley Liddick 3020652fa1 Merge pull request #3565 from zy6p/zy6p/pr-openai-ws-http-bridge
feat(openai-ws): 支持 http_bridge ingress 模式
2026-07-02 17:40:32 +08:00
Wesley Liddick 537bd50469 Merge pull request #3638 from infinityf4p/show-reset-credit-expiration
feat(openai): show reset credit expiration
2026-07-02 17:39:17 +08:00
Wesley Liddick 6bc6998b0e Merge pull request #3627 from alfadb/fix/ollama-anthropic-bearer-auth
fix(anthropic): 支持 API Key Bearer 认证方式
2026-07-02 17:37:30 +08:00
Wesley Liddick 4e23c77ece Merge pull request #3626 from DanisJiang/fix/claude-code-stream-keepalive
fix: prevent Claude Code stream keepalive stalls
2026-07-02 17:35:48 +08:00
Wesley Liddick 821399ade1 Merge pull request #3622 from deqiying/feat/subscription-revoke-restore
支持恢复已撤销订阅
2026-07-02 17:34:20 +08:00
Wesley Liddick 441b8ec2e2 Merge pull request #3614 from heathermhuang/codex/grok-media-group-gate-fix
fix: enable Grok media generation groups
2026-07-02 17:34:09 +08:00
Wesley Liddick fafdd8342f Merge pull request #3641 from infinityf4p/fix/openai-plan-type-workspace
fix(openai): avoid inactive workspace plan type overrides
2026-07-02 17:33:59 +08:00
Wesley Liddick 50dff6762c Merge pull request #3630 from seng1e/fix/codex-image-bridge-skip-compact
fix(openai): skip Codex image bridge injections for /responses/compact
2026-07-02 17:32:43 +08:00
Wesley Liddick e63492090a Merge pull request #3609 from phoenixikkifullstack/fix/antigravity-gemini-3.1-pro-high
fix: Handle invalid arguments correctly for Gemini reasoning models
2026-07-02 17:32:32 +08:00
Wesley Liddick 51b5142af7 Merge pull request #3612 from StarryKira/codex/fix-user-model-stats-requested-model
[codex] fix user model stats requested aggregation
2026-07-02 17:32:19 +08:00
Wesley Liddick 634b0eee48 Merge pull request #3430 from chaochaoweb3/codex/remove-claude-oauth-expires-in
fix: omit expires_in from Claude OAuth token exchange
2026-07-02 17:32:09 +08:00
Wesley Liddick fd66ae1ecb Merge pull request #3642 from infinityf4p/fix/openai-subscription-expiry-save
fix(openai): persist subscription expiration from OAuth
2026-07-02 17:31:58 +08:00
Wesley Liddick a32196eedd Merge pull request #3615 from DaydreamCoding/feat/usage-ip-geolocation
feat(usage): add IP geolocation lookup to usage tables
2026-07-02 16:42:06 +08:00
Wesley Liddick 3302146759 Merge pull request #3643 from bestony/feat/admin-group-column-settings
feat(admin): add group column settings
2026-07-02 16:40:59 +08:00
shaw 41af8e8e11 chore: update sponsors 2026-07-02 16:29:34 +08:00
shaw 11a3da65c0 fix(group): harden peak-rate config handling and label peak windows with server timezone
Follow-up fixes to #3569 based on code audit:

- Expose server_timezone / server_utc_offset in public settings (and the
  __APP_CONFIG__ injection payload) and label every peak-window display
  with the server UTC offset, so users don't misread the billing window
  as browser-local time
- Unify CreateGroup/UpdateGroup peak-config sanitization via a single
  NormalizePeakRateConfig chokepoint: non-subscription groups always get
  peak fields cleared; unparseable window strings and negative
  multipliers are scrubbed when peak is disabled
- Replace hot-path time.Parse in PeakMultiplierAt with a manual HH:MM
  parser (accept set verified byte-for-byte identical to
  time.Parse("15:04") by exhaustive fuzzing) and reuse it in validation
- Revert the zero-behavior CalculateCost indirection churn in
  billing_service/gateway_service introduced by #3569
- Remove dead GetGroupPlatformMap and the duplicate deref helper in the
  admin handler package
- Share frontend peak formatting via utils/peak-rate.ts, unify the ×N
  label format, and move hardcoded Chinese tooltips to i18n keys
2026-07-02 16:11:07 +08:00
Heatherm Huang 99a8d8ad28 fix: normalize grok imagine image alias 2026-07-02 15:04:40 +08:00
Bestony@Homelab 5436d0bf10 feat(admin): add group column settings 2026-07-02 15:04:36 +08:00
Wesley Liddick a632cb0050 Merge pull request #3569 from xueshiji/main
feat(group): 订阅分组新增可选的高峰时段倍率,以支持智谱等coding plan的高峰时段
2026-07-02 14:55:34 +08:00
infinityf4p df59b8b966 fix: persist OpenAI subscription expiration 2026-07-02 14:38:08 +08:00
infinityf4p d0b8760eb9 fix: preserve OpenAI plan type from inactive workspaces 2026-07-02 14:37:30 +08:00
zy6p 5fe4ee1da1 style(test): gofmt oauth passthrough tests 2026-07-02 14:33:55 +08:00
infinityf4p dfb36e45f1 show reset credit expiration 2026-07-02 13:27:58 +08:00
JRBaggins c4128580f2 fix: handle OpenAI OAuth count_tokens scope errors 2026-07-02 11:42:10 +08:00
seng1e c797159bf5 fix(openai): skip Codex image bridge injections for /responses/compact
The Codex image_generation bridge block in Forward injects
tools:[image_generation] and tool_choice:"auto" (since #3498) into every
Codex request, including /responses/compact. The upstream compact endpoint
rejects tool_choice with 400 "Unknown parameter: 'tool_choice'", so every
remote compaction fails once the bridge is enabled. Guard the whole image
generation block with !isCompactRequest.

Fixes #3629
2026-07-02 11:09:50 +08:00
alfadb 7869b7fe38 fix(anthropic): 支持 API Key Bearer 认证方式 2026-07-02 10:43:08 +08:00
Yuhao Jiang a5781fe31d fix Claude Code stream keepalive stalls 2026-07-01 21:01:11 -05:00
deqiying b26dcc3da2 feat(subscription): 支持恢复已撤销订阅 2026-07-01 22:19:21 +08:00
DaydreamCoding 0ff93aca7a feat: add usage IP geolocation lookup 2026-07-01 21:49:49 +08:00
Heatherm Huang 9934bd2572 fix: default grok group media generation 2026-07-01 20:55:53 +08:00
Heatherm Huang 0435417f43 fix: enable grok media generation groups 2026-07-01 20:31:32 +08:00
github-actions[bot] 7dc7cfce1d chore: sync VERSION to 0.1.142 [skip ci] 2026-07-01 11:06:15 +00:00
shaw 98be187d56 chore: update sponsors 2026-07-01 19:04:40 +08:00
Haruka e236bff1ed fix: aggregate user model stats by requested model 2026-07-01 19:01:30 +08:00
phoenix 45be32b254 fix: remove space lines 2026-07-01 18:51:33 +08:00
shaw 60da9ba178 fix(frontend): refine grok icon, palette and i18n 2026-07-01 18:49:33 +08:00
xueshiji be26e6ff2c fix: test 2026-07-01 18:09:20 +08:00
phoenix f5b2961270 fix: Handle invalid arguments correctly for Gemini reasoning models 2026-07-01 18:08:25 +08:00
xueshiji a0eaf12a01 fix: test 2026-07-01 17:54:39 +08:00
Wesley Liddick 5eb9da9c93 Merge pull request #3593 from heathermhuang/codex/grok-media-routing
fix: route Grok media endpoints
2026-07-01 17:49:27 +08:00
xueshiji 5e99561d6e Merge branch 'Wei-Shaw:main' into main 2026-07-01 17:48:42 +08:00
xueshiji 1034f576d7 fix: 高峰倍率全链路透传、计费术语修正与边界处理
- 高峰倍率信息透传至可用渠道、支付计划、结算信息等 API,前端
  GroupBadge / GroupOptionItem / SubscriptionPlanCard / PaymentView /
  SubscriptionsView 统一展示高峰时段与倍率标签
- 修正计费术语:"文本倍率" → "token 倍率",明确高峰倍率同时作用于
  token 计费的图片 token,图片按次计费不受高峰影响
- 允许高峰倍率 multiplier=0,支持高峰时段免费策略
- 切换分组类型为 standard 时自动清除高峰倍率配置
- 长上下文计费与标准计费路径改用内部实现,移除冗余中间调用
- 前端高峰倍率相关控件文案改为 i18n
- 新增多组高峰倍率相关单元测试
2026-07-01 17:46:12 +08:00
zy6p 71c16b7230 fix(test): correct passthrough failover assertions 2026-07-01 17:20:55 +08:00
Heatherm Huang aac3261c69 fix: convert grok image edit uploads 2026-07-01 16:31:33 +08:00
Heatherm Huang f77cf6b477 Revert "feat: add LLM media tester"
This reverts commit a34d4967e6.
2026-07-01 16:08:21 +08:00
shaw 8c2d9b9a12 chore(openai): remove gpt-5.3-codex from OpenAI default model list
移除 OpenAI OAuth 账号默认模型列表中的 gpt-5.3-codex(后端 DefaultModels、前端 openai 白名单及 UseKeyModal 目录),保留 gpt-5.3-codex-spark 与计费/别名/messages-dispatch 相关逻辑不变。
2026-07-01 15:54:34 +08:00
Heatherm Huang c9fb221a31 fix: satisfy grok media lint 2026-07-01 15:42:00 +08:00
Wesley Liddick 0a9146c3d1 Merge pull request #3586 from deqiying/codex/fix-subscription-revoke-soft-delete
修复订阅撤销操作实际上是软删除的bug
2026-07-01 15:38:45 +08:00
Heatherm Huang 42e471f59a fix: harden grok media routing 2026-07-01 15:36:08 +08:00
Heatherm Huang a34d4967e6 feat: add LLM media tester 2026-07-01 15:12:48 +08:00
Wesley Liddick d679ee3c29 Merge pull request #3596 from JRBaggins/fix/tag-version-resolution
fix: source-build version resolution for release tags
2026-07-01 14:45:11 +08:00
xueshiji ebd83dc0f9 fix: 触发ci 2026-07-01 14:43:22 +08:00
shaw fd004bdd88 fix(account-repo): Clone query before Count to prevent state pollution
ListWithFilters reused the Ent query builder across Count() and All(),
so interceptor-appended predicates (SoftDeleteMixin's deleted_at IS NULL)
accumulated on the shared builder — the same pattern already fixed in
group_repo/promo_code_repo/user_repo by commit 2588fa6a (P1-03 audit).

The integration test now asserts pagination.Total matches len(items) on a
single page, guarding the total-vs-items invariant reported in #3601.

Fixes #3601
2026-07-01 14:35:49 +08:00
xueshiji e998f8044b fix: ci 2026-07-01 14:34:57 +08:00
JRBaggins de64b02612 fix: resolve build version from release tag 2026-07-01 14:25:46 +08:00
Wesley Liddick 3812e627a8 Merge pull request #3546 from nslogx/fix/platform-quota-five-platforms
fix: allow five platform quota updates
2026-07-01 14:07:08 +08:00
xueshiji 8b46994dc2 Merge branch 'Wei-Shaw:main' into main 2026-07-01 14:01:03 +08:00
Wesley Liddick 9817d5d5bf Merge pull request #3598 from DaydreamCoding/feat/openai-spark-shadow-account
feat(spark-shadow): OpenAI Spark 链接型影子账号
2026-07-01 14:00:52 +08:00
xueshiji 5e9529bb88 Merge branch 'Wei-Shaw:main' into main 2026-07-01 14:00:51 +08:00
shaw 96c9166b0e fix(usage): 用户使用记录默认显示推理强度列 2026-07-01 14:00:27 +08:00
DaydreamCodingandClaude Sonnet 5 bdf7ead157 feat(spark-shadow): OpenAI Spark 链接型影子账号
背景:gpt-5.3-codex-spark 使用独立于 codex 全局(5h/7d)的配额窗口(数据源是
/wham/usage 响应体的 codex_bengalfox,而非 codex 全局用的 x-codex-* 响应头),且
只能挂在已完成 OAuth 授权的 OpenAI 账号下复用其登录态,不能作为独立账号单独接入。
为此新增“链接型影子账号”(spark shadow account):影子账号本身不持有任何凭据,
通过 parent_account_id 指向母账号,凭据/token/代理透传自母账号并共享母账号的刷新
周期,仅在配额维度(quota_dimension=spark)和用量窗口上与母账号完全独立调度、互不
连坐。

实现:
- 数据模型:migration 154(+154a)给 accounts 表加 parent_account_id /
  quota_dimension 列 + 4 条约束(维度合法 / parent⟺非 global 维度一致 / 禁自指 /
  FK)+ 2 个 CONCURRENTLY 索引(母账号索引 + 每母账号至多一个影子的唯一索引)。
- 创建:POST /api/v1/admin/accounts/:id/shadow(CreateShadow)—— 一母一影(唯一
  索引兜底并发竞态),继承母账号 proxy/分组/并发/优先级(显式传参可覆盖),默认
  model_mapping 恒等映射到 spark(拒绝非 spark 模型),母账号必须是真实的 OpenAI
  OAuth 账号(非影子)。
- 凭据透传:resolveCredentialAccount 把影子解析回母账号,GetAccessToken / 请求头
  / WS 三条路径统一走此函数;影子自身 Credentials 恒为空(仅允许写 model_mapping),
  凭据写入的汇聚点 persistAccountCredentials 对影子早返 no-op,防止误写。
- 调度:parentHealthyForShadow 只看母账号是否仍是 OpenAI OAuth + 凭据/传输是否
  可用(active、token 未过期、未处于 401/刷新失败/传输故障导致的临时不可调度冷却),
  刻意不看母账号的 global 限流窗口——两条 429 道互不连坐。
- 用量:影子的 codex_5h/7d 走 OpenAIQuotaService.QueryUsage(/wham/usage 的
  codex_bengalfox),与母账号走的 WSv2 探测(/responses 头)完全独立的数据源、
  刷新节流与 staleness 判定。
- 备份:ExportData 显式排除影子账号(影子不持凭据,通用凭据型导入强制
  credentials 非空、无法表达父子链接),按 skipped_shadows 计数提示前端。
- 前端:账号操作菜单新增“创建 Spark 影子”入口,影子行展示回填的母账号信息
  (邮箱 / plan / 隐私模式 / 订阅到期 / chatgpt_account_id),批量操作自动跳过
  影子账号。

说明:migrations 目录用完整文件名(而非纯数字前缀)标识迁移,故本次新增的
154_account_spark_shadow.sql / 154a_..._notx.sql 与已有的
154_add_ops_system_logs_api_key_id.sql 按序号共存,与目录里 145/151 已有的
先例一致。

测试:新增约 20 个测试文件,覆盖 handler(CreateShadow 校验 / 母账号信息回填)、
repository(影子 round-trip / 一母一影唯一索引 / 迁移 schema)、service(凭据
透传三路径 / 调度母健康门 / 用量窗口来源与刷新节流 / CRS 母账号不变量 / 各类
早返与 fail-closed 场景)及前端组件(账号列表 / 操作菜单 / 用量重置)。

验证(镜像 CI;golangci-lint 首次全量分析耗时过长被跳过,其余全部实测):
- gofmt -l:干净
- go build ./... / go vet ./...:通过
- go test ./... -count=1:全绿(全部包 ok,含 internal/service、
  internal/repository、migrations)
- go test -tags integration ./internal/repository/... ./internal/service/...
  (真实 Postgres,testcontainers):全绿,含迁移幂等性
  (TestMigrationsRunner_IsIdempotent_AndSchemaIsUpToDate)与影子相关全部用例
- pnpm lint:check / pnpm typecheck / pnpm build(真实 vite 构建)/
  pnpm vitest run:全绿(124 文件 760 用例)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-01 12:21:45 +08:00
zy6p e28b11ad75 fix(test): align compact passthrough expectation 2026-07-01 11:49:43 +08:00
Heatherm Huang c3e860607d fix: include official grok media model ids 2026-07-01 11:43:35 +08:00
Heatherm Huang 2fe756e4be fix: recognize grok media models 2026-07-01 11:43:35 +08:00
Heatherm Huang 3b5d812f7a fix: route grok media endpoints 2026-07-01 11:43:35 +08:00
Wesley Liddick 5f62625ae6 Merge pull request #3577 from heathermhuang/codex/fix-english-ui-cjk
fix: remove Chinese strings from English UI
2026-07-01 11:35:04 +08:00
zy6p 605b6f6632 fix(test): resolve oauth passthrough unit build errors 2026-07-01 11:34:16 +08:00
shaw db0414233c feat: 适配 sonnet5 2026-07-01 11:32:22 +08:00
Wesley Liddick e2d21c35af Merge pull request #3587 from alfadb/fix/openai-gpt-55-pro-codex-model
fix(openai): 保留 GPT-5.5 Pro Codex 模型名
2026-07-01 10:54:51 +08:00
shaw 59e9356c51 feat: 抹除 Anthropic OAuth 请求中客户端 dateline 隐写指纹
对 /v1/messages 转发到 Anthropic OAuth/setup-token 账号的请求做 dateline
归一化,将 system prompt 与 <system-reminder> 块中 "Today's date is …"
语句里的 4 种撇号变体与 "/" 日期分隔符还原为 ASCII 撇号 + "-",抹除某些
客户端在检测到非官方 base URL 时注入的 3 bit 隐写指纹。API Key 账号不受
影响。新增系统设置开关 enable_client_dateline_normalization,默认开启。
2026-07-01 10:54:18 +08:00
Wesley Liddick c1335bae12 Merge pull request #3588 from Ogannesson/fix/openai-codex-preserve-encrypted-reasoning
fix(openai): preserve encrypted reasoning across turns on codex OAuth path
2026-07-01 09:11:35 +08:00
alfadb b28a223337 fix(openai): 保留 GPT-5.5 Pro Codex 模型名
避免 Codex OAuth 模型归一化把 gpt-5.5-pro 降级为 gpt-5.5。\n\n同时补充 GPT-5.5 Pro 的计费回退与长上下文计费策略,保证保留上游模型名后仍使用现有 GPT-5.5/GPT-5.4 计费规则。\n\n验证:\n- go test ./internal/service/...\n- go build ./cmd/server/
2026-07-01 01:30:42 +08:00
deqiying 03727ac363 fix(subscription): 修复订阅撤销软删除失效
总: 增加明确的订阅撤销接口,修复撤销后的缓存失效和管理端 revoked 展示。

分: 同步失效订阅 L1 与 billing cache,补跨实例失效通知、soft-delete-aware 列表查询、revoked_at DTO 字段和回归测试。
2026-07-01 00:37:51 +08:00
Heatherm Huang 1158cf31bc fix: require localized interval validation 2026-06-30 22:31:21 +08:00
Heatherm Huang 41bb15d302 fix: remove remaining English fallbacks 2026-06-30 22:27:37 +08:00
Heatherm Huang b4f38b092f fix: preserve zh locale in i18n cleanup 2026-06-30 22:06:27 +08:00
Oganneson 73de2ea7f0 fix(openai): preserve encrypted reasoning across turns on codex OAuth path
PR #2068 dropped every reasoning item from input[] on the OAuth/codex path
(store=false). That silently discards encrypted_content -- the out-of-band
channel that carries reasoning context across turns under store=false --
degrading multi-turn agent reasoning with no visible error. Reported by
@neteroster on PR #2068.

The 404 that #2068 worked around ("Item with id 'rs_...' not found") is
triggered by the rs_* id lookup under store=false, not by the reasoning item
itself -- so the correct fix is to strip the id, not delete the item.

Verified end-to-end against the live chatgpt.com codex backend (gpt-5.5) and
a real OpenClaw container (api: openai-responses):
  - bare rs_ id, no encrypted_content  -> 404
  - id stripped                        -> 200
  - encrypted_content + id stripped    -> 200, reasoning context preserved
  - reasoning items require a summary field (missing -> 400)
  - real OpenClaw multi-turn agent loop -> all /v1/responses 200, zero 404

Fix: keep the reasoning item, strip only the rs_* id (always, independent of
PreserveReferences), preserve encrypted_content/content/summary verbatim, and
backfill an empty summary when absent. Tool-call call_id pairing is untouched.

Also verified compaction_summary items (cmp_*, the other encrypted_content
carrier): they require encrypted_content (missing -> 400) and their id does not
404 when present (kept or stripped), so the existing generic path already
handles them safely -- no special-casing needed.

Adds regression tests for each verified reasoning contract.

Refs #1957, #2068
2026-06-30 21:08:40 +08:00
Heatherm Huang 6e54776509 fix: localize English UI strings 2026-06-30 20:05:23 +08:00
github-actions[bot] dc1bc15457 chore: sync VERSION to 0.1.141 [skip ci] 2026-06-30 09:29:40 +00:00
Wesley Liddick 7cb98e5bdc Merge pull request #2007 from PMExtra/feature/user-usage-admin-parity
feat: align user usage analytics with admin
2026-06-30 17:10:09 +08:00
shaw 930326116e fix: 修复订阅支付金额显示错误 2026-06-30 16:26:22 +08:00
PMExtra cafc95c3e2 feat: align user usage analytics with admin 2026-06-30 15:31:28 +08:00
github-actions[bot] 89b2d63ef2 chore: sync VERSION to 0.1.140 [skip ci] 2026-06-30 06:26:55 +00:00
xueshiji 915c60b150 feat(group): 订阅分组新增可选的高峰时段倍率,以支持智谱等coding plan的高峰时段 2026-06-30 14:17:05 +08:00
shaw 345d5c6b56 chore: update sponsors 2026-06-30 14:11:14 +08:00
nslogx 6c46c2cb7d test: update platform quota contract for grok 2026-06-30 14:03:33 +08:00
Wesley Liddick 76e0d90736 Merge pull request #3509 from wucm667/fix/refund-pending-not-success
fix(payment): 退款 pending 不再当成最终成功,避免站内账务与网关状态不一致
2026-06-30 13:38:04 +08:00
Wesley Liddick 56ca027a0f Merge pull request #3568 from DaydreamCoding/fix/auth-signup-grok-platform-quota
fix(auth-signup): 平台配额快照脱离注册事务 + grok 补入 CHECK 约束
2026-06-30 13:37:54 +08:00
shaw bf4f006736 fix: 修复用户列表使用时间排序冲突 2026-06-30 13:36:36 +08:00
DaydreamCodingandClaude Opus 4.8 185f9c9920 fix(auth-signup): 平台配额快照脱离注册事务 + grok 补入 CHECK 约束
自助注册(含钉钉/OAuth)报 500→404 的根因:grok 自 2026-06 进入默认平台配额
(default_platform_quotas / auth_source_*),但 user_platform_quotas 的 CHECK
约束(迁移 142)仅允许 anthropic/openai/gemini/antigravity。注册时
snapshotPlatformQuotaDefaults 写 grok 行违反约束 → 整个注册事务被 Postgres 标记
aborted → consumePendingOAuthBrowserSessionTx 撞 "transaction aborted" → 500 →
clearCookies → 用户重试拿到 404(PENDING_AUTH_SESSION_NOT_FOUND)。
影响面:所有新自助注册(不限钉钉)。

修复(两层):
- 事务隔离(fix①):snapshotPlatformQuotaDefaults 用 ent.WithoutTx 剥离调用方事务,
  在基础连接 autocommit 执行。best-effort 快照失败永不毒化注册主事务,从根上消除
  "事务内 fail-open 形同虚设"陷阱——今后任何平台/约束漂移都不会再连累注册。
- 迁移 157:把 grok 加入 user_platform_quotas.platform 的 CHECK 约束,与代码平台
  列表(domain/constants.go PlatformGrok)对齐(DROP IF EXISTS + ADD,可重入)。

新增 ent.WithoutTx(ctx) helper(手写文件,不动生成代码)。

测试:
- 单测 TestSnapshotPlatformQuotaDefaults_DetachesCallerTransaction(RED→GREEN):
  快照即便在事务 ctx 中也必须用脱离事务的 ctx 调 repo。
- 集成测试 TestUserPlatformQuotaRepository_BulkInsertInitial_GrokAllowed:
  迁移 157 后 grok 可写入(真实 postgres 容器验证)。

验证:go build ./... / go vet -tags unit ./... / 全量单测(-tags unit,45 包) /
平台配额+迁移集成测试 全绿。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:22:27 +08:00
Wesley Liddick dcd8689d78 Merge pull request #3548 from dftian478/codex/中文-上下文窗口不切号
修复 OpenAI 上下文窗口错误误触发账号切换
2026-06-30 10:57:26 +08:00
Wesley Liddick efb8b45876 Merge pull request #3560 from StarryKira/feat/issue-3557-oauth-email
feat: fix OAuth email completion flow
2026-06-30 10:55:00 +08:00
Wesley Liddick ac6d4ccf09 Merge pull request #3549 from dftian478/codex/中文-gpt55-codex-instructions
修复 OpenAI GPT-5.5 的 Codex 指令选择
2026-06-30 10:53:35 +08:00
Wesley Liddick ac6f2e9693 Merge pull request #3559 from 315944211/fix/privacy-toast-result
fix: show privacy setting result accurately
2026-06-30 10:50:17 +08:00
zy6p 906be3f742 fix(openai-ws): honor explicit http_bridge ingress mode
(cherry picked from commit 9c0498a873f31472c94922a4115adab4587cd3e7)
2026-06-30 10:42:32 +08:00
zy6p 5654321380 fix(frontend): enable ws mode editing for openai setup-token accounts
(cherry picked from commit 73031d1ba8079b2f369a11b3de9542f27bd61405)
(cherry picked from commit acdbb9ce0471e5ab1009dc25e171a6497222347c)
2026-06-30 10:41:41 +08:00
zy6p 0476b5c97a fix(openai-ws): allow http_bridge accounts in ws ingress selection
(cherry picked from commit f0d215ec522e05043f5012a5f1e7aba2bfb57fcc)
(cherry picked from commit 7b14846a65e16570cb7b472b0ed06c6dcb190e0d)
2026-06-30 10:41:41 +08:00
Wesley Liddick e70e36e4d2 Merge pull request #3484 from bwliangc/feat/risk-control-matched-keyword
feat(risk-control): record matched keyword in keyword-block logs
2026-06-30 10:40:30 +08:00
zy6p 901958ba1b feat(openai-ws): add http_bridge ingress mode and account ws selector
(cherry picked from commit 58647ff63d7ff994c7c14c84c4913a8d3ed6be05)
(cherry picked from commit 9f18fb7c24e187fb20e90d1d9e89fcec91c56937)
2026-06-30 10:40:05 +08:00
wucm667 93a3bf3077 Fix refund pending finalization gaps 2026-06-30 10:19:50 +08:00
wucm667 7316d83027 fix(payment): 区分退款 pending 并收敛匿名查单 2026-06-30 10:00:48 +08:00
Wesley Liddick 55902d8548 Merge pull request #3558 from heathermhuang/codex/grok-cli-compat
fix: support Grok admin test and CLI compatibility
2026-06-30 08:42:59 +08:00
haruka 260fda19b3 feat: fix OAuth email completion flow 2026-06-30 01:11:51 +08:00
315944211 a0a3d0c33e fix: show privacy setting result accurately 2026-06-30 00:37:21 +08:00
Heatherm Huang 438510d298 fix: sanitize grok codex responses payloads 2026-06-29 21:37:30 +08:00
Heatherm Huang 10e623f674 fix: allow grok messages compatibility 2026-06-29 18:33:37 +08:00
Heatherm Huang 4a7148e203 fix: support grok cli compatibility routes 2026-06-29 17:53:19 +08:00
Wesley Liddick d3acd8e96e Merge pull request #3497 from JRBaggins/fix/openai-count-tokens-bridge
Bridge OpenAI count_tokens to responses input_tokens
2026-06-29 15:23:11 +08:00
dftian478 7cbf82ed65 修复 OpenAI 上下文窗口错误误触发账号切换 2026-06-29 10:29:23 +08:00
dftian478 709cf61853 修复 OpenAI GPT-5.5 的 Codex 指令选择 2026-06-29 10:25:43 +08:00
nslogx d86e83259e fix: allow five platform quota updates 2026-06-29 09:40:04 +08:00
Wesley Liddick c99112a9e9 Merge pull request #3515 from bestony/feat/ops-system-log-key-id
feat(ops): add key id filter to system logs
2026-06-29 09:24:40 +08:00
Wesley Liddick a22b12677f Merge pull request #3517 from bestony/feat/keys-column-settings
feat(keys): add API key column settings
2026-06-29 09:24:20 +08:00
Wesley Liddick b0dbc22fe5 Merge pull request #3510 from wucm667/fix/subscription-confirm-show-converted-amount
fix(payment): 订阅订单确认页显示换算后的 CNY 实付金额,而非 USD 套餐价
2026-06-29 09:24:01 +08:00
Wesley Liddick 7c857bd080 Merge pull request #3441 from deqiying/feature/openai-quota-headroom-scheduler
新增 OpenAI 剩余额度调度权重
2026-06-29 09:23:32 +08:00
Wesley Liddick bebafe7697 Merge pull request #3437 from imfangwenjie/fix/api-base-fetch
fix(frontend): use configured API base for direct requests
2026-06-29 09:23:13 +08:00
Wesley Liddick fc1e5a94a9 Merge pull request #3534 from mxyhi/fix/openai-quota-platform-post-billing
fix(openai): preserve quota platform in usage billing
2026-06-29 09:21:44 +08:00
Wesley Liddick 61f735a667 Merge pull request #3498 from liuaho6-commits/fix/codex-image-bridge-tool-choice
fix(openai): set tool_choice auto for Codex image bridge
2026-06-29 09:21:25 +08:00
Wesley Liddick b105cc0fd5 Merge pull request #3337 from ddnio/codex/openai-json-mode-developer-input
fix(openai): preserve JSON instructions in Codex OAuth input
2026-06-29 09:21:05 +08:00
Wesley Liddick 38577c6ca0 Merge pull request #3533 from Pluviobyte/codex/fix-api-key-unlimited-quota
fix(keys): reactivate exhausted keys set to unlimited
2026-06-29 09:19:53 +08:00
Wesley Liddick 47598462f5 Merge pull request #3401 from StarryKira/fix/issue-3394-fallback-pricing-log-spam
fix: stop per-request fallback-pricing log spam for unknown models (#3394)
2026-06-29 09:19:44 +08:00
Wesley Liddick 753c5e255c Merge pull request #3215 from fchange/fix/image-billing-false-positive
fix(openai): prevent false image billing on text-only /v1/responses requests
2026-06-29 09:19:34 +08:00
Wesley Liddick 3b18d1fa3d Merge pull request #3532 from smartcmd/fix/subscription-direct-pay-price
fix(payment): keep subscription price as direct pay amount
2026-06-29 09:19:24 +08:00
Wesley Liddick a822972d80 Merge pull request #3494 from devnomad-byte/docs/source-compile-admin-setup
docs: note admin account wizard requirement in source-compile install
2026-06-29 09:19:14 +08:00
mxyhi 82553c4dca fix(openai): preserve quota platform in usage billing 2026-06-28 11:13:09 +08:00
Pluviobyte da810c3b43 fix(keys): reactivate exhausted keys set to unlimited 2026-06-28 09:05:28 +08:00
daoge_cmd b1403e8b29 fix(payment): keep subscription price as direct pay amount 2026-06-28 06:29:01 +08:00
Bestony b244f850e7 feat(keys): add column settings 2026-06-27 15:14:13 +08:00
Bestony bad87ff533 feat(ops): add api key filter to system logs 2026-06-27 14:35:19 +08:00
wucm667 88ca0c1d13 fix(payment): 显示订阅 CNY 换算实付金额 2026-06-27 12:15:39 +08:00
Hao Liu e5f7836bf3 fix(openai): set tool_choice auto for Codex image bridge 2026-06-26 19:10:37 +08:00
JRBaggins 7a38c66214 Bridge OpenAI count_tokens to responses input_tokens 2026-06-26 17:59:26 +08:00
github-actions[bot] c275422251 chore: sync VERSION to 0.1.139 [skip ci] 2026-06-26 09:55:00 +00:00
shaw 9a0fbcc87d chore: update sponsors 2026-06-26 17:32:50 +08:00
Wesley Liddick df99b9417c Merge pull request #3495 from DaydreamCoding/feat/codex-detect-cli-only-engine-fingerprint
feat(codex-detect): codex_cli_only 检测加固 + 引擎指纹统一信号列表 + 账号级 app-server
2026-06-26 16:41:23 +08:00
DaydreamCodingandClaude Opus 4.8 819fda34d9 feat(codex-detect): codex_cli_only 检测加固 + 引擎指纹统一信号列表 + 账号级 app-server
将 codex_cli_only 客户端识别从「单一 strict 开关 + 固定 OR 头集合」重构为
可逐项管理的引擎指纹信号列表,加固整条判定链,并补齐账号级 app-server 控制、
对齐前端设置文案。

判定链(每步可短路):
- 账号未开 codex_cli_only → 不限制;gateway.force_codex_cli → 旁路放行
- 全局黑名单命中(OR 宽 deny)→ 立即拒
- 身份候选:官方 UA(strict,仅前缀)/ 官方 originator(OR)/ 全局白名单(双因子 AND)
  / 全局 app-server 开关 OR 账号 app-server 开关;均不命中 → 拒
- 版本门(仅官方候选):UA 须可解析引擎版本,再校验 [min,max] 区间
- 引擎指纹 AND 硬门:按信号列表逐条勾选 AND、每条行内变体 OR;无 Required 信号 → 放行

引擎指纹信号列表(唯一真源)
- 新增 openai.EngineFingerprintSignal 类型 + EvaluateEngineFingerprint 求值器
  (勾选 AND / 行内变体 OR / 无勾选 → 放行)
- CodexRestrictionPolicy 增 EngineFingerprintSignals;信号列表单一决定是否启用指纹门,
  不再保留独立「要求引擎指纹」总开关(与「信号全不选」语义重复)
- 新设置键 codex_cli_only_engine_fingerprint_signals(默认只勾 x-codex- 前缀);
  旧 body 指纹开关幂等迁移并入信号列表;wire 接线
- 黑/白名单自由条目、命名预设、版本区间 全局设置管线
- gateway 缺 settingService(仅测试/误配可达)时指纹门回退默认种子信号、失败关闭,
  不再因零值 policy(nil 信号)失败开放

账号级 Codex app-server(替换已失效的 ClaudeCode 放行机制)
- account.IsCodexCLIOnlyAppServerAllowed() 读 extra.codex_cli_only_allow_app_server,
  仅在 codex_cli_only 开启时生效;候选身份门「全局 OR 账号」,与旧系统双层控制对齐
- 移除已无入口的 claude_code 预设机制(allowedClientRegistry / MatchAllowedClients /
  账号 GetCodexCLIOnlyAllowedClients / reason);白名单 AllowedClientEntry / IsAllowedClientMatch 保留

门加固(反伪 + 写入校验)
- 官方 UA 访问门改 strict:IsCodexOfficialClientRequestStrict 仅前缀匹配,收窄「浏览器前缀 +
  中段 codex token」伪造面(strict 仍保留 Codex 家族前缀与 UA 尾部兜底,故对「任意前缀 +
  官方尾部 (name;ver)」仍放行——与 UA 可伪造、真正反伪靠引擎指纹门的设计一致)
- 官方客户端识别扩展:新增 codex-tui/、codex_vscode_copilot/ 前缀 + UA 尾部 (name;ver) 兜底
  (恢复 CODEX_INTERNAL_ORIGINATOR_OVERRIDE 的真实 client,如 cccc→codex-tui),originator 改
  精确集。该识别经 IsCodexOfficialClientByHeaders 被 passthrough 复用,故透传的官方判定一并
  修正(codex-tui 等不再被误改写 UA)——非「行为不变」,属有意修正
- 白名单写入校验 ValidateCodexWhitelistEntriesJSON + AllowedClientEntry.IsWhitelistable:
  双因子 AND 条目须可命中(非空 originator + 非空 ua_contains),拒绝写入会静默失效的死规则;
  黑名单(OR 宽 deny,允许 originator-only)不受约束

管理端 / 前端
- handler / DTO / settings_view / 契约测试;gateway 接入判定链
- 信号列表编辑器(替换 body 开关)、api 类型、SettingsView;无勾选给常驻警告
- Create/Edit/Bulk 三弹窗「Codex Only」下新增 app-server 开关(OR 合并全局)
- 文案:UA/Originator → User-Agent/Originator;黑/白名单重命名为 User-Agent/Originator 黑/白名单;
  「允许 App Server 第三方客户端」→「Codex app-server」+ 简介示例;i18n zh/en 同步
- 移除死代码 HasCodex*Fingerprint helper

测试:引擎指纹求值器 / 账号 app-server(OR 语义)/ detector(含 N1 strict、失败关闭)/
白名单写入校验 / BulkEdit spec 等;后端 build + service/openai/admin 单测全绿,前端 vue-tsc + vitest 全绿。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 16:19:41 +08:00
shaw f93a6c50ce fix: repair CI build & lint regressions on main
- openai_gateway_model_availability.go: pass platform through to
  listSchedulableAccounts so OpenAI/Grok diagnosis scopes to the
  correct candidate pool (build break introduced by Grok subscription
  PR #3310).
- no_account_error.go: drop redundant context.Context type on
  ctx := context.Background() to satisfy staticcheck ST1023.
2026-06-26 16:06:01 +08:00
Wesley Liddick a8cfafa02c Merge pull request #3489 from wucm667/fix/responses-anthropic-custom-tool-schema
fix(apicompat): Responses custom/freeform 工具转 Anthropic 时规范化 schema,修复 apply_patch 报错
2026-06-26 15:42:57 +08:00
Wesley Liddick d57106a56f Merge pull request #3490 from wucm667/feat/admin-cli-jwt-auth-fallback
feat(cli): sub2api-admin 支持 SUB2API_JWT 作为认证回退
2026-06-26 15:42:33 +08:00
Wesley Liddick 2fc4fef847 Merge pull request #3310 from heathermhuang/codex/grok-subscription-support
feat: add grok subscription support
2026-06-26 15:41:52 +08:00
shaw fcd3bc1272 fix: return 404 model_not_found instead of 503 when no account supports the model 2026-06-26 15:38:06 +08:00
devnomad-byteandClaude Opus 4.6 98feeccbe1 docs: note admin account wizard requirement in source-compile install
Method 3 (source compile) instructs users to pre-create config.yaml,
but does not mention that doing so disables the setup wizard — the
only code path that creates the initial admin account. Users following
the README end up with a running server and an empty users table, and
login fails with "invalid email or password".

The default.admin_email / default.admin_password fields in config.yaml
are loaded into the config struct but never read by any code path
(setup.SetupConfig.Admin is tagged yaml:"-"), so they cannot serve as
an alternative way to seed the admin.

Add a "Creating the Admin Account" subsection to Method 3 in all three
language READMEs (EN/CN/JA), explaining the wizard dependency and two
workarounds: let the wizard generate config.yaml, or temporarily move
config.yaml aside to trigger the wizard on first run.

Related: #521 (docker variant of the same symptom), #2617, #2350.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-26 15:19:58 +08:00
Heatherm Huang 44f502bab8 fix: address grok review feedback 2026-06-26 14:26:43 +08:00
wucm667 ac6e36f96b feat(cli): sub2api-admin 支持 SUB2API_JWT 认证回退 2026-06-26 14:11:25 +08:00
wucm667 40c8252734 fix(apicompat): 规范化 custom 工具 schema 2026-06-26 14:08:03 +08:00
Wesley Liddick 5f022663ac Merge pull request #3487 from lyen1688/fix/openai-response-failed-sanitize
fix: 修复 OpenAI response.failed 事件透传过长内容
2026-06-26 13:56:18 +08:00
lyen1688 8a7269f539 fix: sanitize verbose OpenAI response failed events 2026-06-26 12:29:58 +08:00
Wesley Liddick 683a8d8096 Merge pull request #3421 from syx0310/fork/openai-codex-pat-auth-upstream
feat: add codex personal access token auth
2026-06-26 11:15:38 +08:00
Wesley Liddick 54ef446c1d Merge pull request #3469 from wucm667/fix/responses-passthrough-duplicate-function-args
fix(openai): Responses passthrough 不再重复发出 function_call arguments,修复 Codex CLI 解析失败
2026-06-26 10:58:36 +08:00
bwlcandClaude Opus 4.8 815bc6c9b5 feat(risk-control): record matched keyword in keyword-block logs
The risk control center's moderation log records had no field for the
keyword that triggered a keyword block, so the admin UI couldn't show
which keyword was hit (only the application slog logged it).

- migration 156: add matched_keyword column to content_moderation_logs
- ContentModerationLog gains MatchedKeyword; set it on keyword block
- repo CreateLog/ListLogs persist and read the column
- frontend: show "命中关键词" inline in the log table and detail modal
- i18n: add matchedKeyword (zh/en)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 10:43:05 +08:00
Heatherm Huang 720db8983f test: harden grok quota readiness 2026-06-26 10:42:21 +08:00
Heatherm Huang 2a80495880 docs: clarify grok public route scope 2026-06-26 10:37:37 +08:00
Heatherm Huang 8a87a658ad test: cover grok readiness paths 2026-06-26 10:37:37 +08:00
Heatherm Huang 939905b8c7 fix: refine grok quota pause behavior 2026-06-26 10:37:37 +08:00
Heatherm Huang 0d28642181 feat: add grok quota probe parity 2026-06-26 10:37:37 +08:00
Heatherm Huang 1b9645ca32 fix: allow grok scheduler capability routing 2026-06-26 10:36:09 +08:00
Heatherm Huang e7a4f3f465 test: fix grok oauth validation suite 2026-06-26 10:36:09 +08:00
Heatherm Huang f29ccc7dfb fix: reduce grok oauth account-risk paths 2026-06-26 10:36:09 +08:00
Heatherm Huang b2e2c7e69c fix: harden grok oauth gateway paths 2026-06-26 10:36:09 +08:00
Heatherm Huang b3a07aeae7 fix: align grok oauth exchange with xai 2026-06-26 10:36:09 +08:00
Heatherm Huang 39be1ec97f feat: add grok subscription support 2026-06-26 10:36:09 +08:00
Wesley Liddick fd9c945fab Merge pull request #3470 from wucm667/fix/order-currency-symbol-from-field
fix(admin): 订单金额币种符号读取 currency 字段,修复 USD 渠道显示为 ¥
2026-06-26 09:46:02 +08:00
Wesley Liddick 94c059c99e Merge pull request #3471 from wucm667/fix/antigravity-standard-tier-empty-project-fallback
fix(antigravity): standard-tier 账号 project_id 为空时兜底,避免全部请求 500
2026-06-26 09:45:54 +08:00
Wesley Liddick 1721b2b2d1 Merge pull request #3404 from wucm667/fix/balance-preflight-prevent-overdraft
fix(billing): 余额扣减增加充足性校验,防止余额透支为负
2026-06-26 09:45:46 +08:00
Wesley Liddick 32ddd5c60b Merge pull request #3405 from wucm667/fix/subscription-order-apply-recharge-multiplier
fix(payment): 订阅套餐订单应用 BALANCE_RECHARGE_MULTIPLIER 汇率换算
2026-06-26 09:45:38 +08:00
Wesley Liddick d53dd112ce Merge pull request #3442 from hsn8086/fix/openai-chat-transport-failover
fix(openai): fail over on chat completions transport errors
2026-06-26 09:43:00 +08:00
Wesley Liddick 36a352f5eb Merge pull request #3429 from 404QAQ/fix/images-content-refusal-passthrough
fix(images): pass content-moderation refusals through as 400 instead of retrying
2026-06-26 09:42:50 +08:00
Wesley Liddick 9983f5b80a Merge pull request #3428 from Milesians/codex/fix-subscription-plan-validity-unit
fix(payment): support plural subscription validity units
2026-06-26 09:42:42 +08:00
Wesley Liddick 0bff6f9ac5 Merge pull request #3482 from SMGoro/fix/payment
fix(payment): 修复后端返回空supported_types时支付提供商卡片消失的问题
2026-06-26 09:42:33 +08:00
Wesley Liddick 6db9e42352 Merge pull request #3476 from zeyugao/main
Detect OpenAI overloaded errors by structured code
2026-06-26 09:42:22 +08:00
Wesley Liddick fd0da2570d Merge pull request #3481 from visa2/fix/gateway-glm-codex-tool-args-doubled
fix(apicompat): avoid doubling tool_call arguments from single-chunk upstreams (Codex + GLM)
2026-06-26 09:42:13 +08:00
Wesley Liddick 50c3e52799 Merge pull request #3460 from StarryKira/codex/fix-responses-cache-input
[codex] fix responses cache input for chat completions bridge
2026-06-26 09:42:04 +08:00
Wesley Liddick db1813f7a3 Merge pull request #3434 from feitianbubu/fix/codex-cli-only-chat-completions
fix(gateway): enforce codex_cli_only restriction on /v1/chat/completions
2026-06-26 09:41:46 +08:00
Wesley Liddick 6d50934de6 Merge pull request #3457 from feitianbubu/fix/admin-usage-cache-breakdown
fix(admin/usage): populate cache creation/read token breakdown in stats
2026-06-26 09:41:36 +08:00
Wesley Liddick 27278f62ed Merge pull request #3467 from jianjianai/fix/invalid-refresh-token-nonretryable
fix(token-refresh): treat refresh_token_invalidated as non-retryable / 添加 refresh_token_invalidated 到不可重试列表
2026-06-26 09:40:04 +08:00
Wesley Liddick d65b4c90ad Merge pull request #3435 from zichuanwangcloud-gif/fix/ops-dashboard-chart-infinite-height
fix(ops): prevent monitoring trend cards from growing unbounded
2026-06-26 09:39:06 +08:00
Wesley Liddick e89f4b43c0 Merge pull request #3433 from feitianbubu/fix/cc-terminal-attribution-header
fix(keys): add CLAUDE_CODE_ATTRIBUTION_HEADER=0 to Claude Code terminal templates
2026-06-26 09:38:57 +08:00
Wesley Liddick 38355ed204 Merge pull request #3436 from feitianbubu/fix/email-identity-error-shadowing
fix(auth): stop swallowing email auth identity create error via shadowed err
2026-06-26 09:38:49 +08:00
Wesley Liddick 03f6a28096 Merge pull request #3395 from 404QAQ/fix/errcheck-writestring
fix(lint): check WriteString return value to fix errcheck failure on main
2026-06-26 09:38:37 +08:00
shaw c9f42e1f77 fix(lint): gofmt token_refresh_service.go after refresh_token_invalidated addition 2026-06-26 09:34:20 +08:00
imfangwenjie 2a58a57a7c fix(frontend): use configured API base for direct requests
Route direct fetch calls, setup requests, gateway usage checks, and ops WebSocket connections through the configured API base instead of assuming same-origin backend paths.

Also derive OAuth callback suggestions from the configured API base so split frontend/API deployments show usable redirect URLs.
2026-06-26 02:42:44 +08:00
visa2andClaude Opus 4.8 29122e3051 fix(apicompat): avoid doubling tool_call arguments from single-chunk upstreams
When converting a Chat Completions stream into Responses events, the first
tool_call delta chunk was copied wholesale into stream state (including
function.arguments), then the same chunk's arguments were accumulated again by
the shared `+=` block. For OpenAI this is harmless because its first tool_call
chunk carries empty arguments, but upstreams that pack id+name+arguments into a
single chunk (e.g. GLM/Zhipu) end up with doubled arguments such as
{"cmd":"ls"}{"cmd":"ls"}. Codex then fails to parse the tool call with
"trailing characters", breaking every tool invocation.

Reset the copied arguments so the shared accumulator counts them exactly once,
keeping the emitted delta and the final done/arguments consistent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 00:58:38 +08:00
SMGDev 65ad7df4f4 fix(payment): 修复后端返回空supported_types时支付提供商卡片消失的问题
统一处理后端返回的null类型supported_types,将其标准化为空数组,避免调用includes()时报错导致卡片无法显示,同时修复多处相关的类型判断逻辑
2026-06-26 00:50:22 +08:00
chaochaoweb3 5bd9368ab4 fix claude oauth token exchange payload 2026-06-25 23:41:00 +08:00
Elsa cc7612bdbd Detect OpenAI overloaded error codes 2026-06-25 21:18:39 +08:00
Wesley Liddick ce6af41357 Merge pull request #3473 from DaydreamCoding/fix/gateway-openai-codex-spark-strip-image-tool
fix(gateway-openai): codex spark 剥离 image_generation 工具,修复 502
2026-06-25 17:43:24 +08:00
DaydreamCodingandClaude Opus 4.8 0112782049 fix(gateway-openai): codex spark 剥离 image_generation 工具,修复 502
gpt-5.3-codex-spark 为 text-only,不支持 image_generation 工具;codex CLI 默认
在 /responses 的 tools[] 携带该工具,导致 ChatGPT 后端返回 400
invalid_request_error(param=tools),被 mapUpstreamError 兜底成 502
"Upstream request failed"(真实 400 见 ops_error_logs.upstream_errors)。

新增 stripCodexSparkImageGenerationTools,对 spark 剥离客户端携带的
image_generation 工具(tools 清空则删键),接入三条路径:
- applyCodexOAuthTransformWithOptions:OAuth 全入口(responses/messages/chat-completions)
- buildUpstreamRequestOpenAIPassthrough 无条件 spark 块:覆盖 OAuth+APIKey
  /responses,不受 image-generation 开关影响
- WS stripCodexSparkImageGenerationToolFromRawPayload:覆盖 WebSocket /responses

bridge 注入(ensureOpenAIResponsesImageGenerationTool)本就跳过 spark;真正的缺口
在 normalizeOpenAIResponsesImageGenerationTools 会规范化并保留客户端工具。
临时绕过=换非 spark 模型;关 bridge/allow_image_generation 无效(工具是客户端带的)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 17:27:19 +08:00
wucm667 650c50e34b fix(antigravity): add project fallback for standard tier 2026-06-25 16:29:33 +08:00
wucm667 55242ffac1 fix(admin): 订单金额币种符号读取 currency 字段 2026-06-25 16:23:45 +08:00
wucm667 2b49d662cc fix(openai): dedupe passthrough function call args 2026-06-25 16:18:11 +08:00
简简aw 0a97a5f461 fix(token-refresh): treat refresh_token_invalidated as non-retryable 2026-06-25 15:12:21 +08:00
shaw 00d68ff6df feat(openai): add GPT-5.5 codex instructions and use as latest fallback 2026-06-25 11:44:42 +08:00
haruka dbdbfb1122 fix: avoid default codex instructions for chat bridge 2026-06-25 02:32:15 +08:00
feitianbubu 4567f6582b test(admin/usage): update sqlmock rows for cache breakdown columns 2026-06-24 23:59:22 +08:00
feitianbubu 063454ae96 fix(admin/usage): populate cache creation/read token breakdown in stats 2026-06-24 23:43:03 +08:00
shaw a1560ae77c chore: update sponsors 2026-06-24 22:14:47 +08:00
shaw 30adee43bc feat(admin/accounts): confirm before OpenAI weekly limit reset 2026-06-24 21:56:03 +08:00
deqiying a2cf297d90 feat: 新增 OpenAI quota headroom 调度权重 2026-06-24 00:13:22 +08:00
hsn 65fa728921 fix(openai): fail over on chat transport errors 2026-06-23 22:53:20 +08:00
feitianbubu 82576e0a38 fix(auth): stop swallowing email auth identity create error via shadowed err 2026-06-23 19:29:17 +08:00
zichuanwangcloud-gifandClaude Opus 4.8 9707dedca2 fix(ops): prevent monitoring trend cards from growing unbounded
The concurrency / switch-rate / throughput cards on the ops dashboard
sit in grid cells that only set `min-h-[360px]` (no definite height).
Their inner card uses `h-full`, which resolves to `auto` when the parent
height is `auto`. Combined with the Chart.js `responsive` +
`maintainAspectRatio: false` charts, this forms a height feedback loop:
the canvas reads the parent height to size itself, the content then grows,
the next ResizeObserver tick reads an even larger height, and the cards
stretch downward without bound.

On wide screens (`lg:grid-cols-4`) a sibling card usually fixes the row
height via `align-items: stretch`, masking the issue. It surfaces when no
sibling bounds the row height — e.g. the single-column (`grid-cols-1`)
stacked layout on narrow viewports, or when the concurrency card collapses
to little content. `min-h` only sets a floor, not a ceiling.

Fix: give the two Chart.js canvas cells a definite height (`h-[360px]`) so
the responsive resize has a fixed reference and the loop cannot run. The
concurrency card is not a responsive canvas, so it keeps `min-h-[360px]`
to avoid clipping its content.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 10:46:17 +00:00
feitianbubu ae5e980dd1 fix(gateway): enforce codex_cli_only restriction on /v1/chat/completions 2026-06-23 18:38:52 +08:00
feitianbubu 28e7adef09 fix(keys): add CLAUDE_CODE_ATTRIBUTION_HEADER=0 to Claude Code terminal templates 2026-06-23 18:27:49 +08:00
404QAQ 9491de0a39 fix(images): pass content-moderation refusals through as 400 instead of retrying
When gpt-image upstream returns response.completed with no image but a text
refusal (content moderation, e.g. the model replies "this request was judged
unsafe to generate"), the soft-failure path treated it as a probabilistic
upstream failure and returned a retryable UpstreamFailoverError (502). Retrying
or switching accounts is futile for a content-policy block — it just burns
other accounts' quota and still surfaces an opaque 502 to the client.

Distinguish the two no-image cases:
  (A) model text refusal  -> 400 content_policy_violation, no retry, refusal
      reason passed through to the client.
  (B) truly empty response -> unchanged: retryable UpstreamFailoverError (502).

Adds extractOpenAIImagesModelRefusal (extracts the refusal text from
output_text.delta / message output_text, capped at 600 chars) and two unit
tests; the existing empty-response retry test is unaffected.
2026-06-23 16:57:16 +08:00
milesians 147c1879d9 fix(payment): support plural subscription validity units 2026-06-23 15:22:55 +08:00
syx0310 32df33a1c3 feat: add codex personal access token auth 2026-06-22 16:07:41 +00:00
shaw 85a3b12254 chore: update sponsors 2026-06-22 16:37:56 +08:00
wucm667 c6f375d3ab fix(payment): 订阅订单应用充值汇率换算 2026-06-22 10:33:26 +08:00
wucm667 9f5b57fc96 fix(billing): 防止余额计费持续透支 2026-06-22 10:30:27 +08:00
shaw e5f38a6f60 chore: update sponsors 2026-06-22 09:55:31 +08:00
github-actions[bot] d430343f51 chore: sync VERSION to 0.1.138 [skip ci] 2026-06-22 01:24:13 +00:00
harukaandClaude Opus 4.8 6239e395b8 i18n(channel): explain case-insensitive matching in pricing conflict messages (#3394)
Update the modelConflict / mappingConflict strings (en + zh) to state that
model names are matched case-insensitively, so an existing entry (e.g.
"GLM-5.2") already covers all case variants and the lowercase variant does not
need to be added. This addresses the confusion in #3394 where the rejection of
a case-only duplicate looked like inconsistent behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 07:47:49 -07:00
harukaandClaude Opus 4.8 7c2fee6c99 fix(billing): dedup fallback pricing warn to stop per-request log spam (#3394)
The "[Billing] Using fallback pricing for model: X" warn was emitted on
every request for any model not in LiteLLM but matched by getFallbackPricing
(e.g. "glm-5.2" substring-matches the "glm-5" fallback price). Via the stdlib
log bridge it is inferred as WARN and persisted to ops_system_logs, producing
tens of thousands of rows/day. It fired even when channel pricing already
overrides the price, and from several call sites (resolver, account-stats
pricing, non-channel billing, admin lookup).

Dedup the warn at the source (BillingService.GetModelPricing) via a sync.Map
keyed by the already-lowercased model name, so each model logs at most once
per process while keeping one audit line. Billing amounts are unchanged.

Also clarify the model/mapping pattern conflict error to state that names are
matched case-insensitively, so an existing entry (e.g. "GLM-5.2") already
covers all case variants and the lowercase variant need not be added — the
behavior the issue mistook for a case-sensitivity bug.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 07:46:52 -07:00
shaw 6936687870 fix(lint): check WriteString return in summarizeOpenAIImagesNoOutputBody
修复 PR #3381 引入的 errcheck lint 错误,satisfy golangci-lint
对 strings.Builder.WriteString 返回值的检查要求。
2026-06-21 21:43:58 +08:00
404QAQ f4b51b0f2b fix(lint): check WriteString return value in summarizeOpenAIImagesNoOutputBody
golangci-lint (errcheck) flagged the unchecked (*strings.Builder).WriteString
return value at openai_images_responses.go:632. Align with the existing
convention used elsewhere in the package (e.g. gateway_service.go) by
explicitly discarding the return values with `_, _ =`.
2026-06-21 21:39:44 +08:00
Wesley Liddick 8105846f33 Merge pull request #3326 from tairan/fix/selinux-bind-mount-labels
fix(deploy): add :Z SELinux labels to bind mounts in compose files
2026-06-21 21:23:27 +08:00
Wesley Liddick f079742bab Merge pull request #3371 from cugxuan/feat/subscription-affiliate-rebate
feat: apply affiliate rebate to subscription payments
2026-06-21 21:18:50 +08:00
Wesley Liddick a560d2f91e Merge pull request #3363 from kangjwme/feat/prefer-soonest-reset-scheduling
feat(scheduling): opt-in "prefer soonest reset" account selection
2026-06-21 21:17:44 +08:00
Wesley Liddick d2ff9c0c4c Merge pull request #3369 from skyswordw/codex/default-ccswitch-openai-gpt-55
fix(ccswitch): default OpenAI import model to gpt-5.5
2026-06-21 21:16:07 +08:00
Wesley Liddick 92ce5bfe24 Merge pull request #3347 from SavitarC/fix/usage-cache-token-tooltip
fix(usage): 显示缓存 Token 明细
2026-06-21 21:15:45 +08:00
Wesley Liddick febfe538b7 Merge pull request #3344 from Milesians/main
fix(frontend): refresh custom page document title
2026-06-21 21:15:17 +08:00
Wesley Liddick 6e27b82335 Merge pull request #3381 from 404QAQ/fix/images-incomplete-failover
fix(images): 识别 response.incomplete 触发 failover + 记录软失败上游响应
2026-06-21 21:14:48 +08:00
Wesley Liddick f6d734ec23 Merge pull request #3308 from a0yark/fix/gemini-tool-schema-cleanup
fix(gemini): clean unsupported tool schema fields
2026-06-21 21:14:09 +08:00
Wesley Liddick af1a032d35 Merge pull request #3375 from StarryKira/fix/3358-vertex-beta-and-cch
fix(gateway): filter anthropic-beta on the Vertex Anthropic path + drop cch sign (#3358)
2026-06-21 21:13:14 +08:00
Wesley Liddick 93de19665b Merge pull request #3359 from alfadb/fix/glm-effort-mapping
修复 GLM 推理强度映射
2026-06-21 21:12:46 +08:00
Wesley Liddick bed12b7016 Merge pull request #3360 from feitianbubu/fix/auto-mode-cc-entrypoint-ide
fix(gateway): in auto mode recognize Claude Code IDE clients via any cc_entrypoint
2026-06-21 21:12:33 +08:00
Wesley Liddick f597e926da Merge pull request #3335 from FjlI5/fix/openai-upstream-endpoint-logging
fix: 修正 chat-only API-key 账号上游端点被误记为 /v1/responses
2026-06-21 21:12:15 +08:00
Wesley Liddick 7b5fbe5197 Merge pull request #3364 from feitianbubu/fix/promo-clear-expiry
fix(promo): allow clearing promo code expiry on edit
2026-06-21 21:12:02 +08:00
Wesley Liddick 04494fd0d9 Merge pull request #3312 from 315944211/codex/update-pnpm-action-setup-node24
chore: update pnpm action setup
2026-06-21 21:11:43 +08:00
Wesley Liddick 945b9b208b Merge pull request #3374 from wucm667/fix/email-binding-enforce-suffix-whitelist
fix(auth): 邮箱身份绑定流程同样校验注册后缀白名单,堵住绕过
2026-06-21 12:56:53 +08:00
404QAQ b0d5592ae2 fix(images): 识别 response.incomplete + 记录软失败上游响应
修复 gpt-image-2 大图/编辑请求 502 报错(社区 issue #2232/#3135/#2516,
现象:upstream did not return image output)。根因是上游生成超时/截断时返回
response.incomplete,旧逻辑只认 error/response.failed,导致:
1) 软失败报成模糊 502 且不触发 failover 换账号重试
2) 上游真实响应未记录,ops_error_logs 里上游信息全空,无法排查

- openAIImagesUpstreamErrorFromSSEPayload 增加 response.incomplete 识别:
  生成超时/截断(max_output_tokens 等) → 可重试 502 触发 failover;
  content_filter/moderation → 400 不重试
- 软失败兜底(无图无标准错误)记录上游诊断摘要到 ops(last_event/status/
  incomplete_reason/body 片段),非流式+流式两条路径一致
- summarizeOpenAIImagesNoOutputBody 提取诊断信息,body 截断上限 1KB

基于官方 v0.1.137 净分支。测试: 5 个新单测 + 图片回归通过 (-tags unit)
2026-06-21 08:34:12 +08:00
harukaandClaude Opus 4.8 5cb8cdd36c test(claude-code): detection recognizes the new-CLI billing block (no cch)
Locks in that Claude Code detection keys on the billing block prefix +
cc_entrypoint=cli, not on the cch field that the new CLI (and now our own
mimicry) no longer sends:

- BillingBlockRecognizedWithoutCCH: an identity-prose-less sub-request whose
  system block is `x-anthropic-billing-header: cc_version=...; cc_entrypoint=cli;`
  (no cch) is still detected as Claude Code.
- NoCCHBlockStillRequiresClaudeCodeUA: dropping cch did not loosen detection —
  a non-claude-cli UA is still rejected, so ClaudeCodeOnly groups can't be spoofed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 08:02:44 -07:00
harukaandClaude Opus 4.8 6cfb7898df fix(claude-mimicry): drop the cch sign to match new Claude Code CLI
Recent Claude Code CLI versions no longer emit the cch=... signature field in
their x-anthropic-billing-header system block (issue #3358). sub2api still
injected cch=00000 when mimicking Claude Code for OAuth accounts and optionally
signed it, so mimicked requests now diverge from real CLI traffic — the opposite
of what the mimicry is for.

- buildBillingAttributionText emits the block without the cch=00000 segment;
  cc_version + cc_entrypoint=cli are kept (detection and Anthropic's first-party
  signal rely on the block, not on cch).
- Retire signing: remove the two enableCCH signBillingHeaderCCH call sites in
  buildUpstreamRequest / buildCountTokensRequest and delete the now-dead
  signBillingHeaderCCH, cchPlaceholderRe, cchSeed, xxHash64Seeded helpers.
- enable_cch_signing is now a documented no-op (kept for backward compat).
- Drop the obsolete signing tests (TestSignBillingHeaderCCH, TestXXHash64Seeded,
  TestSanitizeMustBeBeforeCCHSigning_HashConsistency) and update the prompt test
  to assert the injected block no longer carries cch=.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 08:01:29 -07:00
harukaandClaude Opus 4.8 efffd5d791 test(gateway): Vertex anthropic-beta filtering
Covers the #3358 fix:
- StripsUnsupportedClaudeCodeTokens reproduces the prod 400 — the four Vertex-
  rejected tokens (advisor-tool, prompt-caching-scope, redact-thinking,
  thinking-token-count) plus the identity betas are stripped while whitelisted
  tokens survive. Fails before the builder fix, passes after.
- DropsHeaderWhenAllUnsupported: no anthropic-beta header is sent when every
  client token is filtered out.
- BodySanitizeKeysOnFinalBeta: body.context_management is stripped based on the
  final beta, not the raw client value.
- BlocksViaBetaPolicy: an admin block rule on a Vertex account returns BetaBlockedError.
- TestFilterVertexBetaTokens unit-tests whitelist/drop-set/dedupe/empty.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 07:53:32 -07:00
harukaandClaude Opus 4.8 40e1cc14b3 fix(gateway): filter anthropic-beta on the Vertex Anthropic path (#3358)
Vertex AI's Anthropic endpoint rejects unknown anthropic-beta tokens with
HTTP 400. buildUpstreamRequestAnthropicVertex forwarded the client header
verbatim via the allowedHeaders whitelist, so recent Claude Code CLIs that
send advisor-tool-2026-03-01, prompt-caching-scope-2026-01-05,
redact-thinking-2026-02-12 and thinking-token-count-2026-05-13 broke every
Vertex service_account request, even though plain account-test requests passed.

This is the only upstream builder that bypassed beta filtering: the
OAuth/API-key path uses computeFinalAnthropicBeta and the Bedrock path uses
filterBedrockBetaTokens. Close the gap with a Vertex-specific whitelist
(vertexSupportedBetaTokens) mirroring bedrockSupportedBetaTokens, plus the
existing BetaPolicy block check:

- evaluateBetaPolicy block check (symmetric to resolveBedrockBetaTokensForRequest)
- filterVertexBetaTokens strips policy-filtered + non-whitelisted tokens
- body context_management sanitize now keys on the final beta, not the raw client value
- overwrite the anthropic-beta header after the whitelist copy loop with the final value

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 07:51:24 -07:00
wucm667 ecedc7c8d3 fix(auth): enforce email bind suffix whitelist 2026-06-19 21:17:45 +08:00
cugxuan 0fa604ba71 feat: apply affiliate rebate to subscription payments 2026-06-19 17:47:10 +08:00
skywalker d3dfa28f8e Update CC Switch OpenAI default model 2026-06-19 17:11:25 +08:00
feitianbubu 2dc1387b59 fix(promo): allow clearing promo code expiry on edit 2026-06-18 23:07:25 +08:00
kangjwme 510adf703c feat(scheduling): add opt-in "prefer soonest reset" account selection
Adds a use-it-or-lose-it scheduling strategy: prefer accounts whose
session window resets soonest, so near-reset accounts get drained first
instead of accounts whose reset is still far away.

Both schedulers, opt-in, default behavior unchanged:

- Anthropic (gateway_service.go): new GatewaySchedulingConfig
  .PreferSoonestReset flag. When on, the layered load-aware selection
  inserts a filterBySoonestReset stage (priority -> soonest-reset ->
  load -> LRU). Accounts with no active SessionWindowEnd are treated as
  lowest priority; ties fall through to LRU.

- OpenAI/Codex (openai_account_scheduler.go): new "reset" score weight
  in GatewayOpenAIWSSchedulerScoreWeights. Soonest-reset accounts score
  higher; weight defaults to 0 (no effect).

SessionWindowEnd (upstream 5h/quota ResetsAt) is already carried in the
scheduler snapshot, so no snapshot changes are needed.

Documented in deploy/config.example.yaml. Adds unit tests for the
Anthropic filter and the OpenAI reset factor.
2026-06-18 22:50:46 +08:00
feitianbubu e3e31bd4c5 fix(gateway): auto mode recognize Claude Code IDE clients via any cc_entrypoint 2026-06-18 19:22:10 +08:00
alfadb 89cfe24a0c fix(openai): normalize glm reasoning effort 2026-06-18 19:07:08 +08:00
SavitarC 51d722906c fix(usage): 显示缓存 Token 明细 2026-06-18 14:34:13 +08:00
milesians 952be8711b fix(frontend): refresh custom page document title 2026-06-18 12:30:21 +08:00
欧阳丹 df51edfb06 Preserve OAuth instructions while keeping developer input 2026-06-18 03:15:31 +08:00
FjlI5 bab8a9a93e fix(openai): log /v1/chat/completions upstream endpoint for chat-only API-key accounts
DeriveUpstreamEndpoint maps every OpenAI-platform request to /v1/responses, but
API-key accounts whose upstream only speaks Chat Completions
(!ShouldUseResponsesAPI) are forwarded directly to /v1/chat/completions. The
messages, responses and cyber-policy recording sites derived the endpoint via the
bare GetUpstreamEndpoint, so usage/ops records mislabeled those requests as
/v1/responses. Generalize the existing resolveRawCCUpstreamEndpoint into
resolveOpenAIUpstreamEndpoint and use it at every OpenAI recording site, matching
the already-correct chat-completions client path.
2026-06-18 00:29:04 +08:00
WANG TAIRAN 31640363fc fix(deploy): add :Z SELinux labels to bind mounts
Add the :Z (private unshared) SELinux label to all bind-mounted
directories in docker-compose.local.yml and docker-compose.dev.yml.

On systems with SELinux in Enforcing mode (e.g. Fedora, RHEL, CentOS),
containers using bind mounts are denied access to host directories
because the default 'user_home_t' context is not accessible to
container processes. The :Z label tells the container runtime to
relabel the mount point with 'container_file_t' so the container
can read/write it.

Named volumes in docker-compose.yml are not affected because the
runtime already handles their labels automatically.

Fixes permission-denied errors on:
- ./data:/app/data
- ./postgres_data:/var/lib/postgresql/data
- ./redis_data:/data
2026-06-17 12:38:40 +08:00
a0yarkandCursor 8c4a43cf72 fix(gemini): satisfy schema cleanup test lint
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-16 23:19:45 +08:00
315944211 369f53a7a4 chore: force node24 for cla action 2026-06-16 21:12:09 +08:00
315944211 abc203a37b chore: update pnpm action setup 2026-06-16 21:12:09 +08:00
github-actions[bot] 4a5665da5b chore: sync VERSION to 0.1.137 [skip ci] 2026-06-16 12:59:59 +00:00
Wesley Liddick eba9bea959 Merge pull request #3278 from 315944211/feat/show-account-id-in-admin-list
feat: show account id in account list
2026-06-16 20:35:55 +08:00
Wesley Liddick de38d62360 Merge pull request #3250 from WesleyZiwen/codex/anthropic-429-window-reset
fix: preserve Anthropic window cooldowns
2026-06-16 20:34:36 +08:00
Wesley Liddick 9e9e154f57 Merge pull request #3306 from bestony/fix/ip-acl-denial-message
fix(auth): include client ip in acl denial message
2026-06-16 20:32:50 +08:00
Wesley Liddick 7fb3e1aacd Merge pull request #3247 from alfadb/fix/reasoning-and-thinking-protocol
fix(gateway): 整合推理强度与思考协议处理(替代 #2155 / #2136 / #3246)
2026-06-16 20:29:21 +08:00
Wesley Liddick f204216918 Merge pull request #3243 from alfadb/feature/chinese-llm-fallback-pricing
feat(billing): 国产 LLM 兜底定价 (GLM / Kimi / MiniMax) + 收编 DeepSeek V4
2026-06-16 20:28:49 +08:00
Wesley Liddick 03ec90a25a Merge pull request #3223 from feitianbubu/fix/intercept-streaming-haiku-probe
fix: 修复CC Switch改为流式测试后请求失败的问题
2026-06-16 20:27:33 +08:00
shaw 6c7203d83b fix(gateway): preserve SSE event:error body so ops logs reflect real upstream errors
When an Anthropic upstream returned HTTP 200 but then emitted an SSE
`event: error` frame (overloaded_error / rate_limit_error / api_error /
etc.), Forward's stream branch matched on `err.Error() == "have error in
stream"` and returned `UpstreamFailoverError{StatusCode: 403}` with no
ResponseBody. That dropped three pieces of evidence:

- handleFailoverExhausted → ExtractUpstreamErrorMessage(nil) = "" →
  ops_error_logs.upstream_error_message was empty.
- errorPassthroughService.MatchRule(_, 403, nil) could only match rules
  without keywords, so keyword-based passthrough rules silently never
  fired.
- upstream_errors carried no stream_error record, leaving ops looking at
  a generic 403 with no clue whether the upstream was throttled,
  overloaded, or rejecting the request. ping-during-slot-wait amplified
  this by skipping failover (writerSizeBeforeForward guard), so 403s
  ballooned in the ops view well past the upstream's actual rate.

Fix:
- Introduce *sseStreamErrorEventError that carries the SSE data line.
  Error() still returns "have error in stream" so existing log searches
  keep working.
- Forward extracts via errors.As, appends an OpsUpstreamErrorEvent
  (kind="stream_error", with the sanitized message and a truncated raw
  body honoring LogUpstreamErrorBody*), and returns
  UpstreamFailoverError{StatusCode: 403, ResponseBody: rawJSON}.

StatusCode 403 is preserved verbatim: mapUpstreamError, failover
decisions (shouldFailoverUpstreamError(403)=true), client-visible message,
RetryableOnSameAccount, and rateLimitService side-effects (this path
already didn't invoke them) all match prior behavior. OAuth and API Key
accounts share this path; the API-Key passthrough branch is independent
and already forwards SSE error frames untouched, so it's unaffected.

Adds four unit tests: typed-error contract + RawData, empty data line,
event:error after partial stream output (streamStarted=true), and
non-JSON data line.
2026-06-16 20:25:09 +08:00
alfadb a05d9e87c0 feat(billing): 国产模型 thinking-enabled 自动填充 reasoning_effort 默认值
问题:Kimi/GLM/MiniMax 等国产 LLM 协议层只有 thinking on/off 开关,没有
reasoning_effort 档位概念。客户端启用 thinking 后 usage_log.reasoning_effort
长期为 NULL,无法在用量分析里区分 'thinking 开启' 与 'thinking 关闭'。

方案:仅在 'thinking 启用 + 上游属于 passback-required 国产模型 + 客户端
未明确指定 effort' 三者同时成立时,给 usage_log.reasoning_effort 写默认值
'high'(与 DeepSeek thinking-enabled 默认 effort 一致)。

设计原则:
1. **白名单**:仅 ResolveThinkingProtocol == PassbackRequired 集合内,
   且排除原生支持 effort 的 DeepSeek(避免覆盖客户端意图)。
2. **fail-open**:客户端显式传 effort 时永远不覆盖。
3. **未来兼容**:如 Kimi 后续加入真 effort 档位,客户端开始发 effort,
   guard (3) 自动让出,本逻辑变 no-op。

实现:
- gateway_request.go: 加 DefaultEffortForThinkingEnabled (按模型白名单)
  + OpenAIBodyHasThinkingEnabled (检测 OpenAI 协议 body 里的 thinking.type)
  + ApplyThinkingEnabledFallback (包装现有 extractor 的 nil-then-default 逻辑)
- gateway_handler.go: Anthropic 路径两处(主 + retry)对称补充
- OpenAI 路径全覆盖:openai_gateway_service.go (passthrough + non-passthrough)
  + openai_gateway_chat_completions_raw.go + openai_gateway_responses_chat_fallback.go
  + openai_ws_http_bridge.go + openai_ws_forwarder.go
- 跨协议路径:gateway_forward_as_chat_completions.go (CC client → Anthropic upstream)
  + gateway_forward_as_responses.go (Responses client → Anthropic upstream)
  + gemini_chat_completions_compat_service.go (一致性保持)

未覆盖:openai_ws_v2_passthrough_adapter.go 两处。原因:该 adapter 持有的是
session-level 客户端原始 model,没有 *Account 句柄无法走 GetMappedModel。
WS v2 当前对国产模型场景不重要(pi 调用 Kimi/GLM/MiniMax 走 sync HTTP),
留待后续如果出现 WS v2 + 国产模型用例时单独处理。

测试:
- TestDefaultEffortForThinkingEnabled (14 用例):覆盖 Kimi/GLM/MiniMax 大小写、
  Qwen thinking 变体、DeepSeek 排除、Claude/GPT/Gemini 不命中。
- TestOpenAIBodyHasThinkingEnabled (8 用例):covers enabled/adaptive/disabled、
  大小写、空 body、缺字段、invalid JSON fail-safe。
- TestApplyThinkingEnabledFallback (9 用例):现有 effort 不覆盖、nil + 启用 +
  passback → high、nil + disabled → nil、nil + 启用 + 排除模型 → nil。
2026-06-16 19:37:31 +08:00
alfadb 5c5283979b doc(thinking-protocol): clarify mappedModel vs originalModel semantics per call path
回应 PR #3247 Copilot review:

1. NormalizeChineseLLMThinking 文档写 'MiniMax M3 / M3.x' 但实现覆盖
   minimax-m* (M2.x 也命中)。改成 'MiniMax M-series (M2.x/M3.x)'。

2. Copilot 质疑 gemini_messages_compat 传 originalModel 不是
   mappedModel 是误用。实际是有意为之的跨协议场景:
   - 上游是 Gemini,但被剥离的 body 是 Anthropic 格式
   - 剥离逻辑要按客户端请求的 Anthropic 子协议族判定
   - 传 mappedModel (gemini-3.1-pro) 会被判为 Unknown→不剥离→retry 死循环

   未改代码逻辑,改为更新文档:
   - thinking_protocol.go ResolveThinkingProtocol 添加「调用路径语义」
     说明 Anthropic gateway 与 Gemini compat 两条路径的参数语义差异。
   - gemini_messages_compat_service.go 调用点加 inline 注释解释
     路径语义为什么该传 originalModel。
2026-06-16 19:37:31 +08:00
alfadb 56c6325d15 fix(gateway): rewrite thinking.type=enabled to adaptive for MiniMax M-series
\u95ee\u9898\uff1aAnthropic-SDK \u5ba2\u6237\u7aef\uff08\u5982 pi-ai\uff09\u5728 budget-based thinking \u8def\u5f84\u4e0a\u9ed8\u8ba4\u53d1
`thinking: { type: 'enabled', budget_tokens: ... }` \u7ed9\u4efb\u4f55 Anthropic \u517c\u5bb9\u4e0a\u6e38\uff0c\u5305\u62ec
MiniMax M3 / M2.x \u3002\u4f46 MiniMax \u5b98\u65b9\u6587\u6863\u660e\u786e\u5217\u51fa\uff1athinking.type \u53ea\u63a5\u53d7
"adaptive" \u6216 "disabled"\uff0c\u4e0d\u63a5\u53d7 "enabled"\u3002\u9020\u6210\u4e0a\u6e38\u53ef\u80fd 400 / \u9759\u9ed8\u5ffd\u7565\u3002

\u4fee\u590d\uff1a\u5728 Anthropic forward \u8def\u5f84\u4e0a\u3001StripEmptyTextBlocks \u4e4b\u540e\u3001\u91cd\u8bd5\u5faa\u73af\u4e4b\u524d\uff0c
\u52a0\u4e00\u4e2a NormalizeChineseLLMThinking \u9884\u6539\u5199\u6b65\u9aa4\uff1a
- \u4ec5\u5bf9 ResolveThinkingProtocol == PassbackRequired \u4e0a\u6e38\u751f\u6548\uff08claude-* \u4e0d\u4f1a\u8fdb\u6765\uff09
- \u4ec5\u5339\u914d minimax-m* \u524d\u7f00\u7684\u6620\u5c04\u540e\u6a21\u578b ID
- \u4ec5\u5f53 thinking.type == "enabled" \u65f6\u6539\u5199\u4e3a "adaptive"
- Kimi/GLM/DeepSeek \u7684 enabled \u4e0d\u53d7\u5f71\u54cd\uff08\u8fd9\u4e9b\u4e0a\u6e38\u63a5\u53d7 enabled\uff09

\u8bbe\u8ba1\u539f\u5219\uff1a
1. "\u767d\u540d\u5355\u8bed\u4e49"\uff1a\u53ea\u5bf9\u5df2\u77e5\u9700\u8981\u5904\u7406\u7684\u4e0a\u6e38\u6539\u5199\uff0c\u4e0d\u505a\u9690\u5f0f\u5e7f\u8c31\u8865\u4e01\u3002
2. "\u4f4e\u4fb5\u5165\u6027"\uff1aMiniMax \u4e4b\u5916\u7684\u6a21\u578b\u96f6\u6539\u52a8\uff0c\u73b0\u6709 4 \u4e2a\u4e0a\u6e38\u7684\u884c\u4e3a\u4e0d\u53d8\u3002
3. "\u53ef\u8bca\u65ad"\uff1a\u6539\u5199\u65f6 LegacyPrintf \u8f93\u51fa\u4e00\u884c\u65e5\u5fd7\uff0c\u4fbf\u4e8e\u8c03\u8bd5\u3002

\u6d4b\u8bd5\uff1a9 \u4e2a\u65b0\u7528\u4f8b\u8986\u76d6 MiniMax M3/M2.7\u3001adaptive/disabled \u4e0d\u53d8\u3001\u65e0 thinking
\u5b57\u6bb5\u3001Kimi/GLM/DeepSeek/Claude \u4e0d\u53d7\u5f71\u54cd\u3001invalid JSON fail-safe\u3002

\u4f9d\u8d56\uff1a\u672c\u5206\u652f\u57fa\u4e8e fix/thinking-block-protocol-aware-filter\uff0c\u7528\u5176
ResolveThinkingProtocol \u4f5c\u4e3a passback-required \u5224\u522b\u6e90\u3002\u4e0a\u6e38 PR \u987a\u5e8f\u9700\u5148\u5408
fix/thinking-block-protocol-aware-filter\uff08PR #2136\uff09\u518d\u5408\u672c PR\u3002
2026-06-16 19:37:31 +08:00
alfadb efbf6d2092 fix(test): update FilterThinkingBlocksForRetry call to use mappedModel param
The function signature was changed to require a mappedModel parameter
for protocol-aware thinking-block filtering, but this test call site
was not updated. Without the fix, the unit test build fails on CI.
2026-06-16 19:37:31 +08:00
alfadbandClaude Opus 4.7 6baf00d784 fix(gateway): protocol-aware thinking-block filtering for Anthropic-compatible upstreams
The gateway's thinking-block handling was designed for Anthropic's strict
semantics (drop blocks with missing/invalid signature), but third-party
Anthropic-compatible upstreams have INVERTED semantics:

  * DeepSeek `/anthropic`, Kimi `/coding`, GLM, Moonshot, qwen-*-thinking
    require ALL historical thinking blocks to round-trip verbatim.
  * Stripping any of them produces:
    400 "The content[].thinking in the thinking mode must be passed back
    to the API"

Without this fix, every multi-turn request from a thinking-capable client
(Claude Code, pi, etc.) to such upstreams loses its thinking blocks and
fails. This becomes especially painful when an account's model_mapping
maps `claude-sonnet-4-6 → deepseek-v4-pro` — `reqModel` looks Anthropic
but the upstream contract is the opposite.

Approach
--------

Branch all thinking-block transforms by the *mapped* model id (after
account model_mapping is applied), classifying into three families:

  * `anthropic-strict`     claude-/opus-/sonnet-/haiku-      → existing behaviour
  * `passback-required`    deepseek-/kimi-/moonshot-/glm-/   → preserve verbatim
                           qwen-*-thinking
  * `unknown`              other models                       → conservative
                                                               (preserve, no retry)

Affected entry points (all guarded):

  * Pre-filter on outbound:   `FilterThinkingBlocks`
    Previously dropped blocks with missing/invalid signature; now skips
    entirely for non-strict families. Pre-filter is needed because the
    post-error retry path can run out of budget on long conversations
    (maxRetryElapsed = 10 s).
  * 400 retry rectifier:      `FilterThinkingBlocksForRetry`
    Disables top-level thinking and converts thinking → text. Now skips
    for passback-required (those 400s aren't signature errors and any
    transformation breaks the round-trip contract).
  * 400 retry rectifier (tools): `FilterSignatureSensitiveBlocksForRetry`
    Same family-aware short-circuit.
  * 400 detector:             `shouldRectifySignatureError`
    Returns false for passback-required, so the retry path doesn't even
    fire.

Tests
-----

  * `thinking_protocol_test.go` — classifier across all known vendor
    prefixes plus edge cases (empty, case, qwen non-thinking).
  * `thinking_protocol_filter_integration_test.go` — locks in that the
    three filter entry points return the body byte-for-byte unchanged
    when the model id is passback-required or unknown, and still strip
    invalid blocks for anthropic-strict.

This PR supersedes #1350 (which only added the pre-filter without the
upstream-family awareness, and would have made third-party upstreams
worse). Once merged, please close #1350.

Reference issues:
  - NousResearch/hermes-agent#16748 — DeepSeek /anthropic strip behaviour
  - NousResearch/hermes-agent#15700 — DeepSeek thinking:disabled requirement

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-16 19:37:31 +08:00
alfadb 34b1e56e29 test: add 'max' → 'xhigh' test cases for reasoning effort normalization
Cover the DeepSeek reasoning_effort 'max' alias in:
- TestExtractOpenAIReasoningEffortFromBody
- TestExtractCCReasoningEffortFromBody
- TestExtractResponsesReasoningEffortFromBody
2026-06-16 19:37:31 +08:00
alfadb 142d8c3618 fix(gateway): normalize DeepSeek reasoning_effort 'max' to 'xhigh'
pi maps defaultThinkingLevel 'xhigh' → 'max' for deepseek-v4-pro via
thinkingLevelMap, but normalizeOpenAIReasoningEffort did not recognize
'max', causing all reasoning_effort to be dropped (0% fill rate since
traffic switched from claude to deepseek on May 1).

Add 'max' → 'xhigh' mapping to match Claude's NormalizeClaudeOutputEffort
behavior.
2026-06-16 19:37:31 +08:00
alfadb 262fe1230d feat(billing): 为 doubao-embedding-vision 添加图文差别兜底定价
火山方舟 doubao-embedding-vision 多模态向量化按量付费官方价为文本 ¥0.7/MTok、图片 ¥1.8/MTok,二者不同价。原计费引擎对 embedding 仅记单一 input token、无图片输入档位,无法表达该差别。

变更:
- ModelPricing 新增 ImageInputPricePerToken 字段
- OpenAIUsage / UsageTokens 新增 ImageInputTokens 字段
- extractOpenAIEmbeddingsUsage 解析 usage.prompt_tokens_details.image_tokens
- CalculateCost 拆分文本/图片输入计费;ImageInputTokens 为 0 时走原单价路径,存量 chat/vision 流量行为不变
- getFallbackPricing 新增 doubao-embedding-vision 分支(most-specific-first,覆盖带版本后缀别名),fallback 表填入 $0.098/$0.252 per MTok(汇率 ÷7.14)

测试:新增图文混合/纯文本/图片 token 超额三类用例及定价回退断言;service 包单测与 golangci-lint 全通过。
2026-06-16 19:37:02 +08:00
alfadb 4f5f2788e1 fix(billing): add kimi-for-coding fallback pricing 2026-06-16 19:37:02 +08:00
alfadb c90089c814 fix(billing): address Copilot review feedback
应 PR #3243 review 修正三项问题:

1. 删除 DeepSeek V4 fallback 定价的重复块(cherry-pick 时
   的旧位置 + 新国产 LLM 分段都写了一遍,后写覆盖前写,
   当前值相同所以无 bug,但冗余,未来改一处易漏另一处)。
2. 删除 minimax-m3 匹配中的死代码——modelLower 已经
   strings.ToLower(),'MiniMax-M3' 字面量永远不可能匹中。
3. 测试结构改 *float64 替代 0 sentinel,让 free-tier
   模型(GLM-4.5-Flash / GLM-4.7-Flash)的 0 价能被
   真正断言而非默默跳过;定义内联 floatPtr 辅助函数。
2026-06-16 19:37:02 +08:00
alfadb a4ce73391b feat(billing): add GLM / Kimi / MiniMax fallback pricing for Chinese LLM providers
将 fix/deepseek-fallback-pricing 的 DeepSeek V4 Pro/Flash 定价收编,
并扩展国产 LLM 兜底定价覆盖:

- 智谱 GLM (z.ai 公开 SKU 13 个): glm-5.1 / glm-5 / glm-5-turbo / glm-4.7 /
  glm-4.7-flashx / glm-4.6 / glm-4.5 / glm-4.5-x / glm-4.5-air / glm-4.5-airx /
  glm-4-32b-0414-128k / glm-4.5-flash / glm-4.7-flash
- 月之暗面 Kimi K 系列 4 个: kimi-k2.6 / kimi-k2.5 / kimi-k2-thinking /
  kimi-k2 (K2-0905/K2-0711 官方未保留定价,隐性回退到 kimi-k2)
- MiniMax M 系列 6 个: minimax-m3 (≤512K) / minimax-m2.7 / minimax-m2.7-highspeed /
  minimax-m2.5 / minimax-m2.1 / minimax-m2
- DeepSeek V4 沿用原 fix/deepseek-fallback-pricing 的 entry 移植过来

所有定价数据来自各家官方定价页 (USD/MTok 口径),与现有
Claude/GPT 风格保持一致 (硬编码在 Go 代码里,admin channel 优先)。

匹配策略:长 key 优先 (glm-5.1 优先于 glm-5, k2.6 优先于 k2);
未列出的国产厂商 alias (qwen/doubao/hunyuan) 一律不返回兜底价,
避免误计价——这与 fix/deepseek-fallback-pricing 的白名单语义一致。

数据源注释 (Source URL) 内嵌在每个 initFallbackPricing 分组开头,
便于后续 PR 同步上游价格变化。
2026-06-16 19:37:02 +08:00
alfadb f597d98bdf test(openai): use unpriced model in usage test 2026-06-16 19:37:02 +08:00
alfadb 5a593a511e test(billing): tighten DeepSeek V4 fallback assertions; clarify branch comments
Address copilot-pull-request-reviewer feedback on #2157:

- billing_service_test.go: extend TestGetFallbackPricing_FamilyMatching
  with optional expectedOutput / expectedCacheRead fields and assert
  full Input/Output/CacheRead pricing for all 4 DeepSeek cases
  (v4-pro, v4-flash, deepseek-chat→flash, deepseek-reasoner→flash),
  preventing silent regression to 0 output/cache cost.
- billing_service.go: rewrite the DeepSeek block comment to explicitly
  describe its scope (V4 Pro/Flash + chat/reasoner aliases, no
  unknown-deepseek fallback) and tighten the OpenAI comment to make
  it unambiguous that it only describes the OpenAI/Codex branch
  immediately below it.
2026-06-16 19:37:02 +08:00
alfadb 27e26a3a90 chore: fix gofmt alignment 2026-06-16 19:37:02 +08:00
alfadb c906bf000e feat(billing): add DeepSeek V4 Pro / Flash fallback pricing
Pricing source: https://api-docs.deepseek.com/quick_start/pricing

deepseek-v4-pro:  input $0.435/M, output $0.87/M, cache_read $0.003625/M
deepseek-v4-flash: input $0.14/M,  output $0.28/M, cache_read $0.0028/M

Also map legacy aliases deepseek-chat / deepseek-reasoner → v4-flash.
2026-06-16 19:37:02 +08:00
a0yarkandCursor 6c2db4f461 fix(gemini): clean unsupported tool schema fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-16 18:05:47 +08:00
shaw b8a482e127 fix(ci): unblock main after recent merges
Three independent CI blockers landed on main from concurrent PR merges:

- openai_quota_service.go (introduced by b8169492): const block spacing
  not gofmt-compliant + trailing blank line. golangci-lint v2.9 flagged it
  on every push after the merge.
- openai_images_failover_test.go (introduced by PR #3155, da30c599):
  NewOpenAIGatewayHandler call missing the opsService argument added by
  PR #3230 (b62b573f). Test was authored before #3230 and merged without
  rebase, causing "not enough arguments" compile error.
- account_quota_reset_test.go: TestIsFixedDailyPeriodExpired_NotExpired
  and TestIsFixedWeeklyPeriodExpired_NotExpired used time.Now()-1min as
  periodStart, which crosses the 09:00 UTC reset boundary when CI runs in
  the 09:00:00-09:00:59 window. Anchoring periodStart to today's 12:00
  UTC removes the race.
2026-06-16 17:59:06 +08:00
Wesley Liddick 44f5791008 Merge pull request #3154 from wucm667/fix/responses-session-hash-input-field
fix(openai): Responses API session hash fallback 纳入 input 内容,避免 sticky 绑死账号
2026-06-16 17:01:16 +08:00
Wesley Liddick 9c2c8ab3e5 Merge pull request #3155 from wucm667/fix/openai-images-server-error-failover
fix(openai): 图像接口上游 server_error 触发 failover 换号,不再 5xx 透传
2026-06-16 17:00:40 +08:00
Bestony@Homelab 56c62c59c8 fix(auth): include client ip in acl denial message 2026-06-16 17:00:35 +08:00
Wesley Liddick e4ccb75d0f Merge pull request #3220 from wucm667/fix/oauth-signup-apply-promo-code
fix(auth): OAuth 注册支持应用 URL 上的 promo_code 优惠码
2026-06-16 16:59:38 +08:00
Wesley Liddick 2ce8788929 Merge pull request #3299 from alfadb/fix/openai-responses-probe-tool-capability
fix(openai-probe): /responses 能力探测增加工具调用校验
2026-06-16 16:58:48 +08:00
Wesley Liddick 2e0ff1cfd5 Merge pull request #3258 from bwliangc/feat/channel-monitor-jitter
feat(渠道监控): 检测间隔支持正负随机抖动配置
2026-06-16 16:58:23 +08:00
Wesley Liddick 16765bde69 Merge pull request #3230 from DaydreamCoding/feat/openai-cyber-policy-passthrough
feat(openai): cyber_policy 硬阻断全链路透传、审计与计费
2026-06-16 16:55:51 +08:00
shaw b816949291 feat(openai-quota): query + reset rate-limit credits for OpenAI accounts
Adds an admin-side action that mirrors the Codex Desktop "rate-limit reset"
flow against chatgpt.com upstream for OpenAI OAuth accounts.

Backend
- OpenAIQuotaService.QueryUsage / ResetCredit hit /wham/usage and
  /wham/rate-limit-reset-credits/consume with the Codex Desktop header set,
  reusing OpenAITokenProvider for refreshed tokens and PrivacyClientFactory
  for the impersonated Chrome TLS fingerprint.
- Honors the account's configured proxy by reading the eager-loaded
  account.Proxy directly (falls back to proxyRepo only when missing).
- GET /api/v1/admin/openai/accounts/:id/quota
  POST /api/v1/admin/openai/accounts/:id/reset-quota
- Wire DI for the new service + handler dependency.

Frontend
- OpenAIQuotaResetCell renders a single action row in AccountUsageCell's
  OpenAI section: the existing local "查询" (active sampling) is injected
  via #pre-actions, alongside a "次数 N" button that doubles as the
  upstream query trigger and the available-credit indicator, and a "重置"
  button that consumes one credit.
- No duplicate 5h/7d window display; the local UsageProgressBar owns those
  bars to avoid confusion.
2026-06-16 16:55:07 +08:00
alfadb b88f8e4c04 fix(openai-probe): /responses 能力探测增加工具调用校验
原探测仅以 HTTP 状态码判定 /v1/responses 端点是否存在(404/405 视为不存在,其余视为存在),无法识别"端点存在、基础补全可用、但工具调用不可用"的上游。火山方舟 coding/v3 的 kimi-k2.6 即属此类:携带 tools 的请求仅返回 reasoning、不产出 function_call,导致账号被误判 openai_responses_supported=true。网关据此走 /responses 转换路径后工具调用结果丢失,带工具的请求确定性失败。

改动:
- 探测请求携带一个工具并以 tool_choice=required 强制调用,仅当响应 output 数组包含 function_call 项时判定为支持;2xx 但无 function_call 判定为不支持,使网关改走 /v1/chat/completions 直转路径(同一模型在该路径下工具调用正常)。
- 探测模型改用账号 model_mapping 中的真实上游模型;占位模型在第三方上游会返回 400 model-not-found,无法判定能力。
- 探测超时 8s 调整为 15s(探测在后台异步执行,为推理型模型先推理再产出工具调用预留时间)。
- 非 2xx(404/405 除外)仍保守判定为支持,不改变既有账号行为;运行时回退函数 isResponsesEndpointSupportedByStatus 保持不变。
- 新增单元测试覆盖判定逻辑与探测模型选择。
2026-06-16 15:59:00 +08:00
shaw f069c9ae00 fix(outbox-dedup): buildSchedulerGroupPayload typed-nil broke dedup_key consistency
#3255 introduced payload-aware dedup_key (sha256 over event_type, account_id,
group_id, payload_json). enqueueSchedulerOutbox checks "if payload != nil"
before json.Marshal — but Go interface containing a typed-nil map (returned
by buildSchedulerGroupPayload(empty)) is NOT == nil at the interface level.

So an ungrouped account's account_changed event went through this path:
  payload := buildSchedulerGroupPayload(account.GroupIDs)  // typed-nil map
  enqueueSchedulerOutbox(..., payload)                     // interface != nil
    → json.Marshal(typedNilMap) = "null"
    → dedup_key hash = sha256(... + "null")

While other call sites pass literal nil:
  enqueueSchedulerOutbox(..., nil)                         // interface == nil
    → payloadJSON stays empty
    → dedup_key hash = sha256(... + "")

The two dedup_keys differ for what should be the same logical event,
silently degrading dedup effectiveness in bursts on ungrouped accounts.

Fix: change buildSchedulerGroupPayload return type from map[string]any to
any so empty input returns true untyped-nil. All call sites pass the
result straight to enqueueSchedulerOutbox(payload any) — no inspection,
no breakage.

Adds regression test TestEnqueueSchedulerOutbox_UngroupedAccountDedupesWithLiteralNilPayload
asserting (1) typed-nil regression doesn't sneak back, (2) dedup_key for
empty-groups payload matches the literal-nil-payload key.
2026-06-16 14:21:09 +08:00
shaw acaffe29ec fix(account-repo): refresh candidates SQL excluded healthy accounts; fix CI build
Post-merge audit of #3272 found two regressions:

1. ListOAuthRefreshCandidates used "AND NOT (a AND b)" which, under PG
   3-valued logic, evaluates to NULL when both temp_unschedulable_until
   and temp_unschedulable_reason are NULL — i.e., the common healthy
   account state. Such rows were silently excluded from the background
   token refresh worker, so their OAuth access tokens would never get
   refreshed and eventually start returning 401.

   Verified empirically against PostgreSQL: only 3 of 5 test rows
   matched before the fix; after switching to "(a AND b) IS NOT TRUE"
   the expected 4 rows match.

2. The new ListOAuthRefreshCandidates method on AccountRepository was
   not implemented on stubAccountRepo in api_contract_test.go (build
   tag "unit"), breaking "make test-unit" which CI runs in
   .github/workflows/backend-ci.yml.

Tests:
- Added IS NOT TRUE and "AND NOT (" assertions to the SQL-shape unit
  test so the predicate can't regress to the broken form again.
- "go test -tags=unit ./internal/..." now passes cleanly.
2026-06-16 14:08:50 +08:00
shaw 2ba52bf4aa Merge pull request #3274 from jianjianai/fix/scheduler-outbox-cleanup
fix: cleanup consumed scheduler outbox rows / 添加 scheduler_outbox 表的清理代码,避免表过大

Additional hardening: WHERE clause adds a 10s grace via
created_at < NOW() - INTERVAL '10 seconds' to defend against the PG
sequence-id vs commit race (id assigned in tx, commit delayed past
watermark advance). Without it, slow committers could lose their
outbox row before the snapshot poller reads it.
2026-06-16 11:57:43 +08:00
shaw 31dc8913ac chore(outbox-cleanup): add 10s grace to defend against id-vs-commit race
PG sequences advance outside transactions, so a slow committer can hold
an id that gets surpassed by the watermark before its commit becomes
visible. Without the grace period, cleanup would delete such rows before
the snapshot poller ever sees them. 10s is a comfortable upper bound
on realistic enqueueSchedulerOutbox commit latency.
2026-06-16 11:57:32 +08:00
jjaw cb14935e9a fix: cleanup consumed scheduler outbox rows 2026-06-16 11:56:40 +08:00
shaw 4254dcb352 Merge pull request #3255 from jianjianai/fix1/outbox-scheduler-snapshot-coalesce
降低高频账号状态变更下的 outbox 写入压力 / safely coalesce scheduler outbox events

Migrations renumbered 151/152 -> 152/153 to avoid collision with #3232.
2026-06-16 11:50:35 +08:00
shaw 1fdbe52f96 chore(migrations): renumber scheduler outbox dedup migrations 151/152 -> 152/153
#3232 (already merged) occupies 151. Renumber #3255's dedup migrations to
avoid collision and keep linear ordering. Updated runner constant + tests.
2026-06-16 11:50:25 +08:00
jjaw b3ec6288ad fix: release scheduler outbox dedup on claim 2026-06-16 11:48:13 +08:00
jjaw 60cf89ae26 fix: recover scheduler outbox invalid dedup index 2026-06-16 11:48:13 +08:00
jjaw 3ef70b045d fix: safely coalesce scheduler outbox events 2026-06-16 11:48:12 +08:00
jjaw 34e66ec0a5 fix: outbox scheduler snapshot coalesce 2026-06-16 11:48:12 +08:00
shaw 45f3b0dd74 Merge pull request #3272 from jianjianai/fix/token-refresh-retry-backoff
fix: token refresh 筛选避免拉取全部账号导致数据库爆炸 / reduce token refresh retry amplification
2026-06-16 11:47:07 +08:00
jjaw 9b270f11d7 refactor: inline token refresh retry reason prefix 2026-06-16 11:44:39 +08:00
jjaw 74199b6a6e fix: reduce token refresh retry amplification 2026-06-16 11:44:39 +08:00
shaw b56c501d30 Merge pull request #3273 from jianjianai/fix/redis-wait-queue-hotpath
fix: move user wait queue accounting off hot path / 用户槽位立即成功的请求不调用等待队列
2026-06-16 11:43:07 +08:00
jjaw b0579c4891 fix: move user wait queue accounting off hot path 2026-06-16 11:41:54 +08:00
shaw 87d0f8da66 Merge pull request #3132 from jianjianai/main
修复 token refresh 拉取大量账号时触发 PostgreSQL 参数上限
2026-06-16 11:40:47 +08:00
jjaw 8b698ff4c1 fix account list parameter limit 2026-06-16 11:39:15 +08:00
Wesley Liddick 62fef6ebed Merge pull request #3178 from jianjianai/fix/fix-failover-error-body-reuse
fix: 修复 OpenAI failover 错误响应体重复读取 / reuse cached OpenAI failover error body
2026-06-16 11:13:10 +08:00
Wesley Liddick 8ddc138094 Merge pull request #3232 from jianjianai/fix1/account-expiry-autopause-index
fix:account expiry autopause index / 账号过期自动禁用索引优化
2026-06-16 11:12:57 +08:00
Wesley Liddick 2f1f1971b4 Merge pull request #3195 from jianjianai/fix/invalid-refresh-token-nonretryable
fix: treat invalid_refresh_token as non-retryable / 将 invalid_refresh_token 判定为不可重试
2026-06-16 11:12:45 +08:00
Wesley Liddick 9acd104151 Merge pull request #3201 from alfadb/fix/dockerfile-copy-docs-legal
fix(docker): 将 docs/legal 纳入构建上下文以支持 admin-compliance gate
2026-06-16 11:12:34 +08:00
Wesley Liddick 15b0753c1d Merge pull request #3283 from wucm667/fix/non-json-200-response-failover
fix(gateway): 上游 200 返回非 JSON 错误报文时纳入 failover,避免坏上游被反复命中误扣费
2026-06-16 11:12:21 +08:00
Wesley Liddick a0fc2c4143 Merge pull request #3218 from wucm667/fix/antigravity-system-role-message
fix(antigravity): 处理 messages 中 role:system 消息,修复 Claude Code 接入 400
2026-06-16 11:12:08 +08:00
Wesley Liddick 28bed8b866 Merge pull request #3252 from wucm667/fix/upstream-zstd-response-decompression
fix(gateway): 解压 zstd 上游响应体,修复非流式 usage 静默记 0 的计费丢失
2026-06-16 11:11:51 +08:00
shaw bbd9702496 fix(frontend): bump form-data to >=4.0.6 via pnpm override
Resolves GHSA-hmw2-7cc7-3qxx (CRLF injection) flagged by
frontend-security CI. axios pulls form-data ^4.0.5 which locked to the
vulnerable 4.0.5; override forces all transitive consumers to 4.0.6+
without needing an audit exception.
2026-06-16 10:48:12 +08:00
Wesley Liddick 715594847b Merge pull request #3267 from codeQuest-fly/codex/fix-sub2api-injection
feat: configure Claude OAuth system prompt blocks
2026-06-16 10:43:38 +08:00
Wesley Liddick 29978ac9a6 Merge pull request #3251 from wucm667/fix/chatcompletions-responses-tool-strict-default
fix(apicompat): chat-completions 转 Responses 显式补全 tool strict=false,避免可选参数被填零值
2026-06-16 10:26:39 +08:00
dailingfei b63b411654 fix: remove unused billing attribution helper 2026-06-15 17:16:26 +08:00
wucm667 ab9987b2e2 fix(gateway): fail over on non-JSON 2xx responses 2026-06-15 11:04:24 +08:00
315944211 25a9762a17 feat: show account id in account list 2026-06-15 00:02:04 +08:00
dailingfei 8ce7b9a8f6 feat: configure Claude OAuth system prompt blocks 2026-06-13 04:12:13 +08:00
bwlcandClaude Fable 5 c70c6a2659 feat(渠道监控): 检测间隔支持正负随机抖动配置
新增 jitter_seconds 配置:每轮调度在 interval 基础上 ± [0, jitter]
均匀随机偏移触发,避免多个监控以固定节奏同步请求上游。

- ent schema 新增 jitter_seconds 字段(默认 0),附迁移 151
- 校验:jitter >= 0 且 interval - jitter >= 15s(创建/更新均校验)
- runner 由固定 ticker 改为每轮重新随机化的 timer,0 抖动时行为不变
- 前端监控表单新增「随机抖动 (± 秒)」输入框,上限随间隔联动

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 22:09:53 +08:00
wucm667 c1c28ac7bb fix(gateway): 解压 zstd 上游响应体 2026-06-12 15:06:01 +08:00
wucm667 edfd5e3736 fix(apicompat): default tool strict to false 2026-06-12 15:01:58 +08:00
wangziwenunique f6e0ebc6bf fix: preserve Anthropic window cooldowns 2026-06-12 13:35:03 +08:00
DaydreamCodingandClaude Opus 4.8 b62b573f7f feat(openai): cyber_policy 硬阻断全链路透传、审计与计费
上游对单次请求下发 error.code=cyber_policy 硬阻断时,网关在所有端点
(/v1/responses、/v1/chat/completions、/v1/messages、WebSocket)及流式/
非流式路径下,将该结果原样透传给客户端,绝不 failover、换号或同步拦截;
命中后异步完成审计与计费:

- 风控中心记录 cyber_policy 留痕并发送通知邮件,落库先于发信,SMTP 阻塞
  不影响留痕
- ops 错误请求记录,状态码对齐客户端实际接收(流式 200 / 非流式 400)
- 用量明细标记 request_type=cyber,按上游真实 token 计费,HTTP 与
  WebSocket 计费口径统一,零 token 命中不误扣
- 会话级自动屏蔽(管理员开关,默认关):命中的会话在可配 TTL 内本地拦截
  不再发往上游,仅屏蔽该会话不影响同 Key 其他会话
- 封号计数排除开关:可选让 cyber 命中不计入自动封号,命中当次不判定且
  历史行在违规计数中一并排除

WebSocket 多轮连接下 cyber 标记按 turn 生命周期管理,逐轮独立检测与记录;
透传的错误响应不被兜底逻辑追加内容污染。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-12 01:47:01 +08:00
jjaw e4c255a77a fix:account expiry autopause index 2026-06-12 01:38:09 +08:00
feitianbubu b256f91141 fix(gateway): intercept max_tokens=1 haiku probes for streaming requests too 2026-06-11 20:46:47 +08:00
wucm667 f8c80bf038 fix(auth): apply promo codes to oauth signups 2026-06-11 18:55:27 +08:00
wucm667 65559ac589 fix(antigravity): merge system role messages 2026-06-11 18:37:00 +08:00
方程andClaude Opus 4.7 6bf6722bae chore: gofmt test file
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-11 17:45:09 +08:00
方程andClaude Opus 4.7 0da1fe28ef fix(openai): prevent false image billing on text-only /v1/responses requests
Two defects in the image output counter could inflate imageCount for
text-only responses, causing per-image charges instead of token billing:

1. addDataArray counted every element in a top-level "data" array
   without checking whether each element contained actual image output
   (url/b64_json).  Non-image objects in a "data" array are now skipped.

2. addImageOutputItem accepted image_generation.completed items with
   no result/b64_json/url, inflating the count.  These items are now
   filtered the same way as every other item type.

Fixes #3196

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-11 16:56:43 +08:00
jjaw 727ac3f689 fix: add app_session_terminated to non-retryable refresh errors / 将 app_session_terminated 添加到不可重试的刷新错误中 2026-06-10 22:32:04 +08:00
alfadb ad13585456 fix(docker): ship docs/legal in build context for admin-compliance gate
LegalDocumentView.vue (admin-compliance acknowledgement gate) build-time
imports ../../../../docs/legal/*.md?raw. The Docker image build broke
because the frontend-builder stage only COPYs frontend/ (never docs/) and
.dockerignore excludes both docs/ and *.md from the build context.

Upstream CI runs `pnpm build` from the repo root (docs/ resolvable via
../docs/) and never exercises the Docker path, so this stayed hidden until
the buildkit package job surfaced "Could not resolve docs/legal/...md?raw".

Fix:
- COPY docs/legal/ into /app/docs/legal in Dockerfile and deploy/Dockerfile
  so it sits beside /app/frontend (WORKDIR), matching the relative import.
  Only the required subtree is copied to keep the build dependency minimal.
- Re-include docs/legal/*.md in .dockerignore so buildkit ships the subtree.
2026-06-10 16:34:19 +08:00
jjaw fa8f1749f5 fix: treat invalid_refresh_token as non-retryable / 将 invalid_refresh_token 判定为不可重试 2026-06-10 14:21:44 +08:00
jjaw 46bd7968a3 fix: reuse OpenAI failover error body 2026-06-09 21:56:35 +08:00
wucm667 da30c59923 fix(openai): fail over image server errors 2026-06-09 13:57:45 +08:00
wucm667 a67b10f468 fix(gateway): anchor responses fallback to input 2026-06-09 13:53:19 +08:00
824 changed files with 59473 additions and 19026 deletions

No files matched your search

+5
View File
@@ -11,6 +11,11 @@
*.md
!deploy/DOCKER.md
docs/
# admin-compliance gate (LegalDocumentView.vue) build-time imports
# docs/legal/*.md?raw into the frontend bundle; keep that subtree in the
# Docker build context even though docs/ is otherwise excluded.
!docs/legal/
!docs/legal/*.md
# IDE
.idea/
+1 -18
View File
@@ -28,29 +28,12 @@ jobs:
working-directory: backend
run: make test-integration
# 插件化改造回归安全网:特征化/不变量测试作为独立命名的合并门禁
# (这些测试也包含在 test-unit 中,独立 job 是为了回归信号清晰可辨)
# 详见 .claude/plugin-refactor/INVARIANTS.md
invariants:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
check-latest: false
cache: true
cache-dependency-path: backend/go.sum
- name: Regression invariants (plugin-refactor safety net)
working-directory: backend
run: make test-invariants
frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 9
- name: Setup Node.js
+3
View File
@@ -12,6 +12,9 @@ permissions:
pull-requests: write
statuses: write
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
cla-check:
if: |
+1 -1
View File
@@ -58,7 +58,7 @@ jobs:
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 9
+1 -1
View File
@@ -35,7 +35,7 @@ jobs:
steps:
- uses: actions/checkout@v6
- name: Set up pnpm
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
with:
version: 9
- name: Set up Node.js
+2 -5
View File
@@ -119,6 +119,8 @@ tests
CLAUDE.md
.claude
scripts
!backend/scripts/
!backend/scripts/resolve-version.sh
.code-review-state
#openspec/
code-reviews/
@@ -133,11 +135,6 @@ docs/*
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
!docs/legal/
!docs/legal/*.md
!docs/plugin-architecture/
!docs/plugin-architecture/*.md
!backend/scripts/
backend/scripts/*
!backend/scripts/bench-baseline.sh
.serena/
.codex/
frontend/coverage/
+8 -3
View File
@@ -27,8 +27,13 @@ RUN corepack enable && corepack prepare pnpm@9 --activate
COPY frontend/package.json frontend/pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
# Copy frontend source and build
# Copy frontend source and build.
# LegalDocumentView.vue (admin-compliance gate) build-time imports
# ../../../../docs/legal/*.md?raw, so docs/legal/ must sit beside frontend/
# in the image (WORKDIR /app/frontend -> resolves to /app/docs/legal/*.md).
# Copy only that subtree to keep the build dependency minimal.
COPY frontend/ ./
COPY docs/legal/ /app/docs/legal/
RUN pnpm run build
# -----------------------------------------------------------------------------
@@ -62,9 +67,9 @@ COPY backend/ ./
COPY --from=frontend-builder /app/backend/internal/web/dist ./internal/web/dist
# Build the binary (BuildType=release for CI builds, embed frontend)
# Version precedence: build arg VERSION > cmd/server/VERSION
# Version precedence: build arg VERSION > exact git tag > cmd/server/VERSION
RUN VERSION_VALUE="${VERSION}" && \
if [ -z "${VERSION_VALUE}" ]; then VERSION_VALUE="$(tr -d '\r\n' < ./cmd/server/VERSION)"; fi && \
if [ -z "${VERSION_VALUE}" ]; then VERSION_VALUE="$(./scripts/resolve-version.sh)"; fi && \
DATE_VALUE="${DATE:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}" && \
CGO_ENABLED=0 GOOS=linux go build \
-tags embed \
+148 -55
View File
@@ -12,7 +12,7 @@
**AI API Gateway Platform for Subscription Quota Distribution**
English | [日本語](README_JA.md)
English | [中文](README_CN.md) | [日本語](README_JA.md)
</div>
@@ -23,26 +23,11 @@ Please read the following carefully before using this project:
- **🚨 Terms of Service Risk**: Using this project may violate the terms of service of Anthropic and other upstream providers. Please review the relevant providers' user agreements before use; all risks arising from such use are borne solely by the user.
- **⚖️ Compliant Use**: Use this project only in compliance with the laws and regulations of your country or region. Any unlawful use is strictly prohibited.
- **📖 Disclaimer**: This project is provided for technical learning and research purposes only. The authors assume no liability for account bans, service interruptions, data loss, or any other direct or indirect damages resulting from the use of this project.
## Overview
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
## Features
- **Multi-Account Management** - Support multiple upstream account types (OAuth, API Key)
- **API Key Distribution** - Generate and manage API Keys for users
- **Precise Billing** - Token-level usage tracking and cost calculation
- **Smart Scheduling** - Intelligent account selection with sticky sessions
- **Concurrency Control** - Per-user and per-account concurrency limits
- **Rate Limiting** - Configurable request and token rate limits
- **Built-in Payment System** - Supports EasyPay, Alipay, WeChat Pay, and Stripe for user self-service top-up, no separate payment service needed ([Configuration Guide](docs/PAYMENT.md))
- **Admin Dashboard** - Web interface for monitoring and management
- **External System Integration** - Embed external systems (e.g. ticketing) via iframe to extend the admin dashboard
- **🚫 No Commercial Authorization**: The developers of this project have never authorized any individual or organization to conduct any form of commercial operation based on this project. Any commercial activity conducted in the name of or based on this project is unrelated to this project and its developers, and all resulting disputes, losses, and legal liabilities shall be borne solely by the party conducting such activity.
## ❤️ Sponsors
> [Want to appear here?](mailto:support@pincc.ai)
> [Want to appear here?](mailto:support@sub2api.org)
<table>
@@ -61,16 +46,6 @@ Sub2API is an AI API gateway platform designed to distribute and manage API quot
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via <a href="https://aigocode.com/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
</tr>
<tr>
<td width="180"><a href="https://code.silkapi.com/register?aff=SUB2API"><img src="assets/partners/logos/silkapi.png" alt="silkapi" width="150"></a></td>
<td>Thanks to SilkAPI for sponsoring this project! <a href="https://code.silkapi.com/register?aff=SUB2API">SilkAPI</a> is a relay service built on Sub2API, specializing in providing high-speed and stable Codex API relay.</td>
</tr>
<tr>
<td width="180"><a href="https://ylscode.com/"><img src="assets/partners/logos/ylscode.png" alt="ylscode" width="150"></a></td>
<td>Thanks to YLS Code for sponsoring this project! <a href="https://ylscode.com/">YLS Code</a> is dedicated to building secure enterprise-grade Coding Agent productivity services, offering stable and fast Codex / Claude / Gemini subscription services along with pay-as-you-go API options for flexible choices. Register now for a limited-time 3-day Codex trial bonus!</td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=KMVZQM"><img src="assets/partners/logos/AICodeMirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>Thanks to AICodeMirror for sponsoring this project! AICodeMirror provides official high-stability relay services for Claude Code / Codex / Gemini CLI, with enterprise-grade concurrency, fast invoicing, and 24/7 dedicated technical support. Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original price, with extra discounts on top-ups! AICodeMirror offers special benefits for sub2api users: register via <a href="https://www.aicodemirror.com/register?invitecode=KMVZQM">this link</a> to enjoy 20% off your first top-up, and enterprise customers can get up to 25% off!</td>
@@ -97,12 +72,6 @@ Sub2API is an AI API gateway platform designed to distribute and manage API quot
</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=fu2E"><img src="assets/partners/logos/runapi.png" alt="RunAPI" width="150"></a></td>
<td>Thanks to RunAPI for sponsoring this project! <a href="https://runapi.co/register?aff=fu2E">RunAPI</a> is an efficient and stable API platform and OpenRouter alternative. With one API Key, you can access 150+ popular models including OpenAI, Claude, Gemini, DeepSeek, and Grok, with pricing as low as 10% of the original rate. It is highly stable and seamlessly compatible with tools such as Claude Code and OpenClaw.
</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=sub2api"><img src="assets/partners/logos/unity2.png" alt="unity2" width="150"></a></td>
<td>Thanks to Unity2 for sponsoring this project! <a href="https://unity2.ai/register?source=sub2api">Unity2</a> is a high-performance AI model API relay for individuals, teams, and enterprises, handling 30B+ tokens/day with 5000 RPM concurrency. One API Key works across Claude Code, Codex, OpenAI models, IDE plugins, and Agent workflows, with balance billing, bundled subscriptions, enterprise invoicing, and 1-on-1 support. <a href="https://unity2.ai/register?source=sub2api">Register</a> to claim $2 in balance, plus $10 more by joining the official group — up to $12 in free credit.
@@ -121,8 +90,79 @@ Sub2API is an AI API gateway platform designed to distribute and manage API quot
</td>
</tr>
<tr>
<td width="180"><a href="https://apikl.ai"><img src="assets/partners/logos/apikl.png" alt="apikl" width="150"></a></td>
<td>Thanks to Apikl for sponsoring this project! Built on Sub2API, the platform provides developers with relay services for Codex / Claude series models, focusing on long-term stability, high-speed direct connections, and excellent cost-effectiveness. It offers pay-as-you-go balance billing, enterprise-grade official invoices, and one-on-one dedicated support. <a href="https://apikl.ai">Register now</a> for a 1:1 top-up bonus — double your balance!
</td>
</tr>
<tr>
<td width="180"><a href="https://tokeneum.ai"><img src="assets/partners/logos/tokeneum.png" alt="tokeneum" width="150"></a></td>
<td>Thanks to TokenEum for sponsoring this project! <a href="https://tokeneum.ai">TokenEum</a> is a comprehensive AI model aggregation platform and intelligent agent development company. It brings together top-tier international models — including Claude, Gemini, and OpenAI — alongside leading open-source models such as GLM, Qwen, and Kimi, offering a wide range of options across different quality and price tiers to suit every need. TokenEum also provides access to cutting-edge video generation models like Seedance2.0 and Happy Horse. Committed to transparency and honest business practices, TokenEum ensures all model information is accurate and reliable. Visit <a href="https://tokeneum.ai">tokeneum.ai</a> to get started.
</td>
</tr>
<tr>
<td width="180"><a href="https://666api.work/sub2api"><img src="assets/partners/logos/666api.jpg" alt="666api" width="150"></a></td>
<td>Thanks to 666api for sponsoring this project! <a href="https://666api.work/sub2api">666api</a> is an all-in-one platform offering:<br>
⚡ API Relay — Pay-as-you-go access to global models sourced 100% from official providers, up to 75% off official pricing<br>
&nbsp;&nbsp;&nbsp;&nbsp;Exclusive: Zhipu GLM 50% off · DeepSeek V4-pro 50% off · Seedance 2.0 8% off (whitelisted) · HappyHorse Overseas 30% off (whitelisted)<br>
🔑 GPT Subscription Accounts (same-origin IP included) · Global Residential IP <br>
💰 Invoices supported
</td>
</tr>
<tr>
<td width="180"><a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a full‑modal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, long‑task execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, end‑to‑end complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via <a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html">this link</a> to get 500,000 tokens of free inference quota per model.<a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://sui-xiang.com/"><img src="assets/partners/logos/sui-xiang.jpg" alt="sui-xiang" width="150"></a></td>
<td>Thanks to Suixiang AI Gateway for sponsoring this project! <a href="https://sui-xiang.com/">Suixiang AI Gateway</a> is a reliable and efficient API relay service provider offering relay services for Claude, Codex, Gemini, and more. A privacy-focused relay — no data reselling, no model dilution; privacy, transparency, and lightning-fast after-sales support. New accounts get ¥0.5 in trial credit daily by signing in; top-ups are 1:1, no subscription required, pay-as-you-go. Multi-line redundancy, cross-region disaster recovery, automatic failover, and uninterrupted long-link SSE. 99.9% availability — critical calls never fall behind.
</td>
</tr>
<tr>
<td width="180"><a href="https://www.miyaip.com/?invitecode=sub2api"><img src="assets/partners/logos/miyaip.png" alt="miyaip" width="150"></a></td>
<td>Thanks to MiyaIP for sponsoring this project! <a href="https://www.miyaip.com/?invitecode=sub2api">MiyaIP</a> is a platform dedicated to global residential proxy network services, committed to providing high-quality, pure overseas residential IP resources for enterprise developers, cross-border business teams, and AI application users. It delivers stable, independent overseas network environments for AI platforms, overseas SaaS, and other online services, supporting multi-region access testing and project environment isolation. Ideal for development and testing scenarios that require access to overseas AI services, such as: AI model platform access, AI development testing, AI SaaS service usage, AI API debugging, and multi-region network environment validation.
</td>
</tr>
<tr>
<td width="180"><a href="https://anpin.ai"><img src="assets/partners/logos/anpin.jpg" alt="anpin" width="150"></a></td>
<td>Thanks to <a href="https://anpin.ai">anpin.ai</a> for sponsoring this project! anpin.ai is a premium AI relay service platform dedicated to advancing AI accessibility. With an advanced technical architecture and globally distributed deployment, it provides users with a direct high-speed channel to the world's top-tier large language models.<br>
Self-built primary account pool: 1-3s ultra-fast response, supports channel-partner distribution<br>
Extreme stability: multi-line intelligent routing + redundant backup system, ensuring year-round high-availability operation;<br>
Model authenticity: no content intervention or secondary filtering — experience the purest, most powerful native model capabilities.<br>
1:1 top-up, enterprise-grade service with invoicing available. Anpin AI is not just a relay — it's your secure, reliable, and efficient bridge to the frontier world of intelligence.
</td>
</tr>
<tr>
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
<td>Thanks to Proxy4Free for sponsoring this project! Proxy4Free is a data proxy service provider for developers and AI applications, offering residential proxies, static residential proxies, ISP proxies, and datacenter proxies for scenarios such as Web Scraping, Browser Automation, and AI Agents. With global IP resources, stable connections, and flexible switching, it helps developers improve data collection success rates and reduce the risk of IP bans. Register via <a href="https://www.proxy4free.com/?keyword=4yjqecpc">this link</a> to get started and easily build more stable and efficient automation workflows.
</td>
</tr>
</table>
## Overview
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
## Features
- **Multi-Account Management** - Support multiple upstream account types (OAuth, API Key)
- **API Key Distribution** - Generate and manage API Keys for users
- **Precise Billing** - Token-level usage tracking and cost calculation
- **Smart Scheduling** - Intelligent account selection with sticky sessions
- **Concurrency Control** - Per-user and per-account concurrency limits
- **Rate Limiting** - Configurable request and token rate limits
- **Built-in Payment System** - Supports EasyPay, Alipay, WeChat Pay, and Stripe for user self-service top-up, no separate payment service needed ([Configuration Guide](docs/PAYMENT.md))
- **Admin Dashboard** - Web interface for monitoring and management
- **External System Integration** - Embed external systems (e.g. ticketing) via iframe to extend the admin dashboard
## Ecosystem
Community projects that extend or integrate with Sub2API:
@@ -419,7 +459,8 @@ pnpm run build
# 4. Build backend with embedded frontend
cd ../backend
go build -tags embed -o sub2api ./cmd/server
VERSION="$(./scripts/resolve-version.sh)"
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
# 5. Create configuration file
cp ../deploy/config.example.yaml ./config.yaml
@@ -482,20 +523,20 @@ Additional security-related options are available in `config.yaml`:
**⚠️ Security Warning: HTTP URL Configuration**
When `security.url_allowlist.enabled=false`, the system performs minimal URL validation by default, **rejecting HTTP URLs** and only allowing HTTPS. To allow HTTP URLs (e.g., for development or internal testing), you must explicitly set:
When `security.url_allowlist.enabled=false`, the system performs minimal URL validation and **allows HTTP URLs by default** (dev-friendly mode; Docker Compose deployments use the same default). For production, explicitly tighten this to HTTPS-only:
```yaml
security:
url_allowlist:
enabled: false # Disable allowlist checks
allow_insecure_http: true # Allow HTTP URLs (⚠️ INSECURE)
allow_insecure_http: false # HTTPS only (recommended for production)
```
**Or via environment variable:**
```bash
SECURITY_URL_ALLOWLIST_ENABLED=false
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
```
**Risks of allowing HTTP:**
@@ -509,7 +550,7 @@ SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
- ✅ Testing account connectivity before obtaining HTTPS
- ❌ Production environments (use HTTPS only)
**Example error without this setting:**
**Example error for HTTP URLs when `allow_insecure_http: false` is set:**
```
Invalid base URL: invalid url scheme: http
```
@@ -520,6 +561,25 @@ If you disable URL validation or response header filtering, harden your network
- Enforce TLS-only outbound traffic
- Strip sensitive upstream response headers at the proxy
#### ⚠️ Important: Creating the Admin Account
The initial admin account is **only created via the setup wizard** (served at `http://<host>:8080` on first run). The `default.admin_email` / `default.admin_password` fields in `config.yaml` are **not used** to create it — they exist in the template for historical reasons.
Because step 5 above pre-creates `config.yaml`, the setup wizard will be **skipped on first run**: the server detects an existing config and boots straight into normal mode with an empty `users` table, so the first login attempt fails with `invalid email or password`.
**Two ways to create the admin account:**
1. **Recommended — let the wizard generate `config.yaml`:** Skip step 5 (do not run the `cp`). Start `./sub2api` directly; the setup wizard at `http://localhost:8080` walks you through database, Redis, and admin account setup, then writes `config.yaml` for you.
2. **If you already created `config.yaml`:** Temporarily move it aside so the wizard can trigger on first run, then restore it afterwards:
```bash
mv config.yaml config.yaml.bak
./sub2api # wizard runs at http://localhost:8080 and writes a fresh config.yaml
# stop the server (Ctrl+C) once the wizard completes, then restore your config:
mv config.yaml.bak config.yaml
./sub2api # restart in normal mode and log in with the admin you just created
```
```bash
# 6. Run the application
./sub2api
@@ -559,6 +619,55 @@ Simple Mode is designed for individual developers or internal teams who want qui
---
## Grok / xAI OAuth Support
Sub2API supports Grok subscription accounts through xAI OAuth and forwards OpenAI-compatible Responses traffic to xAI.
### Supported Scope
- Platform name: `grok`
- Account type: OAuth subscription accounts
- Public Responses targets: `/v1/responses`, `/responses`, and `/backend-api/codex/responses`, forwarded to `${XAI_BASE_URL:-https://api.x.ai/v1}/responses`
- Public Claude-compatible target: `/v1/messages`, converted to xAI Responses and returned as Anthropic Messages output for Claude CLI style clients
- Public Chat Completions targets: `/v1/chat/completions` and `/chat/completions`, forwarded to `${XAI_BASE_URL:-https://api.x.ai/v1}/chat/completions`
- Codex CLI style Responses WebSocket ingress is accepted on the Responses targets and bridged to xAI HTTP/SSE Responses upstream
- Initial text models: `grok-4.3`, `grok-build-0.1`, `grok-4.20-0309-reasoning`, `grok-4.20-0309-non-reasoning`, and `grok-4.20-multi-agent-0309`
- Media targets for Grok groups: `/v1/images/generations`, `/images/generations`, `/v1/images/edits`, `/images/edits`, `/v1/videos/generations`, `/videos/generations`, `/v1/videos/{request_id}`, and `/videos/{request_id}`. Generation requests require the group image-generation permission.
- Media models: `grok-imagine`, `grok-imagine-image-quality`, `grok-imagine-image`, `grok-imagine-edit`, `grok-imagine-video`, and `grok-imagine-video-1.5`
- Out of scope for this provider: TTS, transcription, browser automation, cookies, and Grok web scraping
### OAuth Configuration
The Grok OAuth flow uses PKCE and does not require committing private secrets. The default client details follow the public xAI OAuth flow used by compatible clients, and every value can be overridden by environment variable:
| Variable | Default |
|----------|---------|
| `XAI_OAUTH_CLIENT_ID` | Public xAI OAuth client ID |
| `XAI_OAUTH_SCOPE` | `openid profile email offline_access grok-cli:access api:access` |
| `XAI_OAUTH_REDIRECT_URI` | `http://127.0.0.1:56121/callback` |
| `XAI_OAUTH_AUTHORIZE_URL` | `https://auth.x.ai/oauth2/authorize` |
| `XAI_OAUTH_TOKEN_URL` | `https://auth.x.ai/oauth2/token` |
| `XAI_BASE_URL` | `https://api.x.ai/v1` |
Administrators can create or reauthorize Grok accounts from the dashboard, or use the admin API:
| Endpoint | Purpose |
|----------|---------|
| `POST /api/v1/admin/grok/oauth/auth-url` | Generate an xAI OAuth authorization URL |
| `POST /api/v1/admin/grok/oauth/exchange-code` | Exchange a callback URL, query string, or code for OAuth credentials |
| `POST /api/v1/admin/grok/oauth/refresh-token` | Validate or refresh a Grok refresh token |
| `POST /api/v1/admin/grok/accounts/:id/refresh` | Refresh an existing Grok account |
Credential storage reuses the existing account JSON fields: `access_token`, `refresh_token`, `token_type`, `expires_at`, optional `email`, optional `subscription_tier`, and `entitlement_status`.
### Usage And Quota Display
xAI quota is passive. Sub2API does not invent subscription quota values; it records whitelisted xAI rate-limit headers from successful or rate-limited upstream responses when xAI sends them. Before the first usable upstream response, the dashboard shows quota as unknown and still displays local Sub2API usage stats.
`401` responses mark the account as needing reauthorization. `403` responses are treated as entitlement or subscription-tier failures instead of token-refresh loops. `429` responses use `Retry-After` or a short cooldown to temporarily remove the account from scheduling.
---
## Antigravity Support
Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
@@ -583,12 +692,6 @@ Antigravity accounts support optional **hybrid scheduling**. When enabled, the g
> **⚠️ Warning**: Anthropic Claude and Antigravity Claude **cannot be mixed within the same conversation context**. Use groups to isolate them properly.
### Known Issues
In Claude Code, Plan Mode cannot exit automatically. (Normally when using the native Claude API, after planning is complete, Claude Code will pop up options for users to approve or reject the plan.)
**Workaround**: Press `Shift + Tab` to manually exit Plan Mode, then type your response to approve or reject the plan.
---
## Project Structure
@@ -619,16 +722,6 @@ sub2api/
└── install.sh # One-click installation script
```
## Disclaimer
> **Please read carefully before using this project:**
>
> :rotating_light: **Terms of Service Risk**: Using this project may violate Anthropic's Terms of Service. Please read Anthropic's user agreement carefully before use. All risks arising from the use of this project are borne solely by the user.
>
> :book: **Disclaimer**: This project is for technical learning and research purposes only. The author assumes no responsibility for account suspension, service interruption, or any other losses caused by the use of this project.
---
## Star History
<a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
+768
View File
@@ -0,0 +1,768 @@
# Sub2API
<div align="center">
[![Go](https://img.shields.io/badge/Go-1.25.7-00ADD8.svg)](https://golang.org/)
[![Vue](https://img.shields.io/badge/Vue-3.4+-4FC08D.svg)](https://vuejs.org/)
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791.svg)](https://www.postgresql.org/)
[![Redis](https://img.shields.io/badge/Redis-7+-DC382D.svg)](https://redis.io/)
[![Docker](https://img.shields.io/badge/Docker-Ready-2496ED.svg)](https://www.docker.com/)
<a href="https://trendshift.io/repositories/21823" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21823" alt="Wei-Shaw%2Fsub2api | Trendshift" width="250" height="55"/></a>
**AI API 网关平台 - 订阅配额分发管理**
[English](README.md) | 中文 | [日本語](README_JA.md)
</div>
## ⚠️ 重要提醒
使用本项目前,请务必仔细阅读以下内容:
- **🚨 服务条款风险**:使用本项目可能违反 Anthropic 等上游服务商的服务条款。请在使用前仔细阅读相关服务商的用户协议,由此产生的一切风险由用户自行承担。
- **⚖️ 合规使用**:请在符合您所在国家或地区法律法规的前提下使用本项目,严禁将其用于任何违法违规用途。
- **📖 免责声明**:本项目仅供技术学习与研究使用,作者不对因使用本项目导致的账户封禁、服务中断、数据丢失或其他任何直接或间接损失承担责任。
- **🚫 无商业授权**:本项目从未授权任何个人或组织基于本项目开展任何形式的商业化运营。任何以本项目名义或基于本项目从事的商业行为均与本项目及其开发者无关,由此产生的一切纠纷、损失和法律责任由行为主体自行承担。
## ❤️ 赞助商
> [想出现在这里?](mailto:support@sub2api.org)
<table>
<tr>
<td width="180"><a href="https://www.openmodel.ai?ref=sub2api"><img src="assets/partners/logos/openmodel.jpg" alt="openmodel" width="150"></a></td>
<td>一个API,顶级模型随便用!<a href="https://www.openmodel.ai?ref=sub2api">OpenModel</a> 专注于生产级、高可用的 AI API 网关,让你的应用真正做到高速稳定:自动故障转移、智能选最优渠道、生产级 SLA 保障。远超单一供应商的 SLA,让稳定性成为您的核心竞争力。</td>
</tr>
<tr>
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
<td>感谢 ETok.ai 赞助了本项目!ETok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://etok.ai">这里</a>注册!</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过<a href="https://aigocode.com/invite/SUB2API">此链接</a>注册,首次充值可额外获得 10% 赠送额度!</td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=KMVZQM"><img src="assets/partners/logos/AICodeMirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>感谢 AICodeMirror 赞助了本项目!AICodeMirror 提供 Claude Code / Codex / Gemini CLI 官方高稳定性中转服务,企业级并发、快速开票、7×24 小时专属技术支持。Claude Code / Codex / Gemini 官方通道低至原价 38% / 2% / 9%,充值更享额外折扣!AICodeMirror 为 sub2api 用户提供专属福利:通过<a href="https://www.aicodemirror.com/register?invitecode=KMVZQM">此链接</a>注册,首次充值立享 8 折优惠,企业客户最高可享 75 折!</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
<td>感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AI成品号专卖/代充</a>注册下单的用户,可享GPT 官网订阅一折 的震撼价格!</td>
</tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>感谢 Bestproxy 赞助了本项目!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> 是一家提供高纯度住宅IP,支持一号一IP独享,结合真实家庭网络与指纹隔离,可实现链路环境隔离,降低关联风控概率。</td>
</tr>
<tr>
<td width="180"><a href="https://pateway.ai/?ch=1tsfr51"><img src="assets/partners/logos/pateway.png" alt="pateway" width="150"></a></td>
<td>感谢 PatewayAI 赞助了本项目!PatewayAI 是一家面向重度 AI 开发者、专注官方直连的高品质模型 API 中转服务商。提供 Claude 全系列与 Codex 系列模型,100% 官方源直供,不掺假不注水,欢迎检验。计费透明,Token 级账单可逐笔核验。
同时支持企业级高并发,并为企业客户提供了专业的管理平台,企业客户可签订正式合同并开具发票,更多详情进入官网获取联系方式。
现在通过 <a href="https://pateway.ai/?ch=1tsfr51">此链接</a> 注册即送 $3 试用额度,用户充值低至 6 折,邀请好友双向赠送,邀请奖励可达 $150。</td>
</tr>
<tr>
<td width="180"><a href="https://api.pptoken.org/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
<td>感谢 PPToken.org 赞助本项目! <a href="https://api.pptoken.org/register?promo=SUB2API">PPToken.org</a> 主打 GPT 系列模型 API 中转服务,支持 Codex、Claude Code、OpenAI 兼容客户端及 Gemini CLI 等工具接入。充值 1:1,1 元=1 美元额度;GPT 模型最低 0.16 倍倍率,综合成本约为官方价格的 0.22 折,最快首字 Token 约 1 秒,适合开发者低成本、高响应速度接入 GPT 模型能力。技术支持: 7×24 小时真人响应(不是机器人),群内@技术,10 分钟内有回复 。赞助商福利:前 200 名用户通过 <a href="https://api.pptoken.org/register?promo=SUB2API">[专属注册链接]</a> 注册,输入优惠码 `SUB2API`,可领取 Codex / Claude Code 免费试用额度,无门槛、不绑卡。
</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=sub2api"><img src="assets/partners/logos/unity2.png" alt="unity2" width="150"></a></td>
<td>感谢 Unity2 赞助本项目! <a href="https://unity2.ai/register?source=sub2api">Unity2</a> 是面向个人开发者、团队、企业的高性能 AI 模型 API 中转平台,长期服务国内头部企业,日均承载超 300 亿 token 调用,支持 5000 RPM 级高并发。一个 API Key 即可适配 Claude Code、Codex、OpenAI 模型、IDE 插件和 Agent 工作流等场景。具备企业级稳定供应能力,在高并发、持续调用和团队集中采购场景下依然保持低延迟、高可用。同时支持余额计费、组合订阅、首充优惠、企业开票、专属 1v1 对接,适合个人高频使用和企业长期接入。现在注册 Unity2.ai 可领取 $2 余额,加入官方群再送 $10 余额,合计最高可领 $12 免费额度,适合先体验后长期使用。<a href="https://unity2.ai/register?source=sub2api">注册链接</a>
</td>
</tr>
<tr>
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
<td>感谢 Veilx 赞助本项目! <a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN 专为超大规模 API 请求场景打造,针对 AI 中转站业务与 AI API 调用链路进行了深度优化,轻松应对高并发、高频请求与大流量传输,为开发者与企业提供更快、更稳、更低延迟的加速体验。无论是 OpenAI、Claude、Gemini 等 AI 接口中转,还是聊天、绘图、Embedding、流式输出等复杂场景,Veilx 都能显著提升响应速度与连接稳定性,有效降低网络波动带来的超时与失败问题。同时,Veilx 提供中国三网优化回国极速线路,大幅提升中国大陆地区访问海外 AI 服务的速度与稳定性,特别适合全球 AI 中转平台、海外 AI SaaS、跨境业务与高并发 API 系统部署。专为 AI API 而生,让你的 AI 中转服务更快、更稳、更省心。<a href="https://veilx.io/#/hello/SJRBRVDV">购买地址</a>
</td>
</tr>
<tr>
<td width="180"><a href="https://roxybrowser.com/invite/bgGKG7"><img src="assets/partners/logos/RoxyBrowser.png" alt="RoxyBrowser" width="150"></a></td>
<td>感谢 RoxyBrowser 赞助本项目!<a href="https://roxybrowser.com/invite/bgGKG7">RoxyBrowser</a> 是 Sub2API 的理想搭档:内置原生 Roxy AI Agent 与高质量原生住宅 IP,支持通过简单命令实现批量自动化,显著提升多账号管理的安全性与效率!点击<a href="https://roxybrowser.com/invite/bgGKG7">此链接</a>注册,可领取免费住宅 IP 套餐与终身 9 折优惠。
</td>
</tr>
<tr>
<td width="180"><a href="https://apikl.ai"><img src="assets/partners/logos/apikl.png" alt="apikl" width="150"></a></td>
<td>感谢 Apikl 赞助本项目!平台基于 Sub2API 搭建,为开发者提供 Codex / Claude 系列模型的中转服务,专注于长期稳定、高速直连与高性价比。支持按量计费的余额结算、企业级正规发票及一对一专属对接。<a href="https://apikl.ai">立即注册</a>即享充值 1:1 赠送 — 余额翻倍!
</td>
</tr>
<tr>
<td width="180"><a href="https://tokeneum.ai"><img src="assets/partners/logos/tokeneum.png" alt="tokeneum" width="150"></a></td>
<td>感谢 TokenEum 赞助本项目!<a href="https://tokeneum.ai">TokenEum</a> 是一家综合性 AI 模型聚合平台与智能体开发公司,汇聚 Claude、Gemini、OpenAI 等国际顶级模型,以及 GLM、Qwen、Kimi 等主流开源模型,提供不同质量与价格梯度的丰富选择,满足多样化需求。平台还接入了 Seedance2.0、Happy Horse 等前沿视频生成模型。秉持透明诚信的经营理念,TokenEum 确保所有模型信息真实可靠。访问 <a href="https://tokeneum.ai">tokeneum.ai</a> 开始使用。
</td>
</tr>
<tr>
<td width="180"><a href="https://666api.work/sub2api"><img src="assets/partners/logos/666api.jpg" alt="666api" width="150"></a></td>
<td>感谢 666api 赞助本项目!<a href="https://666api.work/sub2api">666api</a> 是一站式综合服务平台,提供:<br>
⚡ API 中转 — 全球模型按量计费接入,100% 官方源直供,最高 75 折优惠<br>
&nbsp;&nbsp;&nbsp;&nbsp;独家特惠:智谱 GLM 5 折 · DeepSeek V4-pro 5 折 · Seedance 2.0 0.8 折(白名单)· HappyHorse 海外版 3 折(白名单)<br>
🔑 GPT 订阅账号(含同源 IP)· 全球住宅 IP<br>
💰 支持开票
</td>
</tr>
<tr>
<td width="180"><a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html"><img src="assets/partners/logos/huoshan.png" alt="HuoShan" width="150"></a></td>
<td>感谢火山方舟 Agent Plan 模型赞助了本项目!方舟 Agent Plan 模型订阅套餐集成了包含 Doubao-Seed、Doubao-Seedance、Doubao-Seedream 等在内的字节跳动自研 SOTA 级模型,覆盖文本、代码、图像、视频等多模态任务。最新支持 MiniMax-M3、DeepSeek-V4 系列、GLM-5.1、Doubao-Seed-2.0 系列、Kimi-K2.6 等模型,工具不限。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。一次订阅,可以为不同任务切换合适的 AI 引擎。方舟 Coding Plan 为 Sub2Api 的用户提供了专属福利:通过<a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html">此链接</a>订阅方舟 Coding Plan,新客户首两个月享 2.5 折优惠 <a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html">>>For developers outside Mainland China, please click here</a></td>
</tr>
<tr>
<td width="180"><a href="https://sui-xiang.com/"><img src="assets/partners/logos/sui-xiang.jpg" alt="sui-xiang" width="150"></a></td>
<td>感谢 随想AI网关 赞助本项目!<a href="https://sui-xiang.com/">随想AI网关</a> 是一家可靠高效的 API 中继服务提供商,提供 Claude、Codex、Gemini 等的中继服务。注重隐私的中转站·无数据倒卖·无模型掺水,隐私,透明,极速售后。新账户注册每日签到就送 0.5 元测试额度,充值额度 1:1,无需订阅,按量付费。多线路冗余、跨区域容灾、自动故障切换,长链路 SSE 不中断。99.9% 可用性,关键调用从不掉队。
</td>
</tr>
<tr>
<td width="180"><a href="https://www.miyaip.com/?invitecode=sub2api"><img src="assets/partners/logos/miyaip.png" alt="miyaip" width="150"></a></td>
<td>感谢 MiyaIP 赞助本项目!<a href="https://www.miyaip.com/?invitecode=sub2api">MiyaIP</a> 是一家专注于全球住宅代理网络服务的平台,致力于为企业开发者、跨境业务团队及AI 应用用户提供高质量、纯净的海外住宅 IP 资源。为 AI 平台、海外 SaaS 及其他在线服务提供稳定、独立的海外网络环境,支持多地区访问测试和项目环境隔离。适用于需要访问海外 AI 服务的开发和测试场景,例如:AI 模型平台访问、AI 开发测试、AI SaaS 服务使用、AI API 调试、多地区网络环境验证
</td>
</tr>
<tr>
<td width="180"><a href="https://anpin.ai"><img src="assets/partners/logos/anpin.jpg" alt="anpin" width="150"></a></td>
<td>感谢 <a href="https://anpin.ai">anpin.ai</a> 赞助本项目!anpin.ai 是一家致力于推动 AI 普惠的高端 AI 中转服务平台。我们以先进的技术架构和全球分布式部署,为用户提供直达国际顶尖大模型的高速通道。<br>
自建一手号池:1-3S超快响应 支持同行分发<br>
极致稳定:多线智能路由 + 冗余备份系统,确保服务全年无休、高可用运行;<br>
模型真实性:不做任何内容干预与二次过滤,让您体验到最纯粹、最强大的原生模型能力。<br>
充值1:1 企业级服务可开票,安品Ai不只是中转站,更是您连接前沿智能世界的安全、可靠、高效桥梁
</td>
</tr>
<tr>
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
<td>感谢 Proxy4Free 赞助本项目!Proxy4Free 是面向开发者和 AI 应用的数据代理服务商,提供住宅代理、静态住宅代理、ISP 代理及数据中心代理等多种代理解决方案,适用于 Web Scraping、Browser Automation、AI Agent 等场景。支持全球 IP 资源、稳定连接与灵活切换,帮助开发者提升数据采集成功率,降低 IP 封禁风险。通过<a href="https://www.proxy4free.com/?keyword=4yjqecpc">此链接注册</a>即可开始体验,轻松构建更稳定、高效的自动化工作流。
</td>
</tr>
</table>
## 项目概述
Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的 API 配额。用户通过平台生成的 API Key 调用上游 AI 服务,平台负责鉴权、计费、负载均衡和请求转发。
## 核心功能
- **多账号管理** - 支持多种上游账号类型(OAuth、API Key)
- **API Key 分发** - 为用户生成和管理 API Key
- **精确计费** - Token 级别的用量追踪和成本计算
- **智能调度** - 智能账号选择,支持粘性会话
- **并发控制** - 用户级和账号级并发限制
- **速率限制** - 可配置的请求和 Token 速率限制
- **内置支付系统** - 支持 EasyPay 易支付、支付宝官方、微信官方、Stripe,用户自助充值,无需独立部署支付服务([配置指南](docs/PAYMENT_CN.md))
- **管理后台** - Web 界面进行监控和管理
- **外部系统集成** - 支持通过 iframe 嵌入外部系统(如工单等),扩展管理后台功能
## 生态项目
围绕 Sub2API 的社区扩展与集成项目:
| 项目 | 说明 | 功能 |
|------|------|------|
| ~~[Sub2ApiPay](https://github.com/touwaeriol/sub2apipay)~~ | ~~自助支付系统~~ | **已内置** — 支付功能已集成到 Sub2API 中,无需独立部署。详见 [支付配置指南](docs/PAYMENT_CN.md) |
| [sub2api-mobile](https://github.com/ckken/sub2api-mobile) | 移动端管理控制台 | 跨平台应用(iOS/Android/Web),支持用户管理、账号管理、监控看板、多后端切换;基于 Expo + React Native 构建 |
## 技术栈
| 组件 | 技术 |
|------|------|
| 后端 | Go 1.25.7, Gin, Ent |
| 前端 | Vue 3.4+, Vite 5+, TailwindCSS |
| 数据库 | PostgreSQL 15+ |
| 缓存/队列 | Redis 7+ |
---
## Nginx 反向代理注意事项
通过 Nginx 反向代理 Sub2API(或 CRS 服务)并搭配 Codex CLI 使用时,需要在 Nginx 配置的 `http` 块中添加:
```nginx
underscores_in_headers on;
```
Nginx 默认会丢弃名称中含下划线的请求头(如 `session_id`),这会导致多账号环境下的粘性会话功能失效。
---
## 部署方式
### 方式一:脚本安装(推荐)
一键安装脚本,自动从 GitHub Releases 下载预编译的二进制文件。
#### 前置条件
- Linux 服务器(amd64 或 arm64)
- PostgreSQL 15+(已安装并运行)
- Redis 7+(已安装并运行)
- Root 权限
#### 安装步骤
```bash
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash
```
脚本会自动:
1. 检测系统架构
2. 下载最新版本
3. 安装二进制文件到 `/opt/sub2api`
4. 创建 systemd 服务
5. 配置系统用户和权限
#### 安装后配置
```bash
# 1. 启动服务
sudo systemctl start sub2api
# 2. 设置开机自启
sudo systemctl enable sub2api
# 3. 在浏览器中打开设置向导
# http://你的服务器IP:8080
```
设置向导将引导你完成:
- 数据库配置
- Redis 配置
- 管理员账号创建
#### 升级
可以直接在 **管理后台** 左上角点击 **检测更新** 按钮进行在线升级。
网页升级功能支持:
- 自动检测新版本
- 一键下载并应用更新
- 支持回滚
#### 常用命令
```bash
# 查看状态
sudo systemctl status sub2api
# 查看日志
sudo journalctl -u sub2api -f
# 重启服务
sudo systemctl restart sub2api
# 卸载
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s -- uninstall -y
```
---
### 方式二:Docker Compose(推荐)
使用 Docker Compose 部署,包含 PostgreSQL 和 Redis 容器。
#### 前置条件
- Docker 20.10+
- Docker Compose v2+
#### 快速开始(一键部署)
使用自动化部署脚本快速搭建:
```bash
# 创建部署目录
mkdir -p sub2api-deploy && cd sub2api-deploy
# 下载并运行部署准备脚本
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
# 启动服务
docker compose up -d
# 查看日志
docker compose logs -f sub2api
```
**脚本功能:**
- 下载 `docker-compose.local.yml`(本地保存为 `docker-compose.yml`)和 `.env.example`
- 自动生成安全凭证(JWT_SECRET、TOTP_ENCRYPTION_KEY、POSTGRES_PASSWORD)
- 创建 `.env` 文件并填充自动生成的密钥
- 创建数据目录(使用本地目录,便于备份和迁移)
- 显示生成的凭证供你记录
#### 手动部署
如果你希望手动配置:
```bash
# 1. 克隆仓库
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api/deploy
# 2. 复制环境配置文件
cp .env.example .env
# 3. 编辑配置(生成安全密码)
nano .env
```
**`.env` 必须配置项:**
```bash
# PostgreSQL 密码(必需)
POSTGRES_PASSWORD=your_secure_password_here
# JWT 密钥(推荐 - 重启后保持用户登录状态)
JWT_SECRET=your_jwt_secret_here
# TOTP 加密密钥(推荐 - 重启后保留双因素认证)
TOTP_ENCRYPTION_KEY=your_totp_key_here
# 可选:管理员账号
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=your_admin_password
# 可选:自定义端口
SERVER_PORT=8080
```
**生成安全密钥:**
```bash
# 生成 JWT_SECRET
openssl rand -hex 32
# 生成 TOTP_ENCRYPTION_KEY
openssl rand -hex 32
# 生成 POSTGRES_PASSWORD
openssl rand -hex 32
```
```bash
# 4. 创建数据目录(本地版)
mkdir -p data postgres_data redis_data
# 5. 启动所有服务
# 选项 A:本地目录版(推荐 - 易于迁移)
docker compose -f docker-compose.local.yml up -d
# 选项 B:命名卷版(简单设置)
docker compose up -d
# 6. 查看状态
docker compose -f docker-compose.local.yml ps
# 7. 查看日志
docker compose -f docker-compose.local.yml logs -f sub2api
```
#### 部署版本对比
| 版本 | 数据存储 | 迁移便利性 | 适用场景 |
|------|---------|-----------|---------|
| **docker-compose.local.yml** | 本地目录 | ✅ 简单(打包整个目录) | 生产环境、频繁备份 |
| **docker-compose.yml** | 命名卷 | ⚠️ 需要 docker 命令 | 简单设置 |
**推荐:** 使用 `docker-compose.local.yml`(脚本部署)以便更轻松地管理数据。
#### 启用“数据管理”功能(datamanagementd)
如需启用管理后台“数据管理”,需要额外部署宿主机数据管理进程 `datamanagementd`。
关键点:
- 主进程固定探测:`/tmp/sub2api-datamanagement.sock`
- 只有该 Socket 可连通时,数据管理功能才会开启
- Docker 场景需将宿主机 Socket 挂载到容器同路径
详细部署步骤见:`deploy/DATAMANAGEMENTD_CN.md`
#### 访问
在浏览器中打开 `http://你的服务器IP:8080`
如果管理员密码是自动生成的,在日志中查找:
```bash
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
```
#### 升级
```bash
# 拉取最新镜像并重建容器
docker compose -f docker-compose.local.yml pull
docker compose -f docker-compose.local.yml up -d
```
#### 轻松迁移(本地目录版)
使用 `docker-compose.local.yml` 时,可以轻松迁移到新服务器:
```bash
# 源服务器
docker compose -f docker-compose.local.yml down
cd ..
tar czf sub2api-complete.tar.gz sub2api-deploy/
# 传输到新服务器
scp sub2api-complete.tar.gz user@new-server:/path/
# 新服务器
tar xzf sub2api-complete.tar.gz
cd sub2api-deploy/
docker compose -f docker-compose.local.yml up -d
```
#### 常用命令
```bash
# 停止所有服务
docker compose -f docker-compose.local.yml down
# 重启
docker compose -f docker-compose.local.yml restart
# 查看所有日志
docker compose -f docker-compose.local.yml logs -f
# 删除所有数据(谨慎!)
docker compose -f docker-compose.local.yml down
rm -rf data/ postgres_data/ redis_data/
```
---
### 方式三:源码编译
从源码编译安装,适合开发或定制需求。
#### 前置条件
- Go 1.21+
- Node.js 18+
- PostgreSQL 15+
- Redis 7+
#### 编译步骤
```bash
# 1. 克隆仓库
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api
# 2. 安装 pnpm(如果还没有安装)
npm install -g pnpm
# 3. 编译前端
cd frontend
pnpm install
pnpm run build
# 构建产物输出到 ../backend/internal/web/dist/
# 4. 编译后端(嵌入前端)
cd ../backend
VERSION="$(./scripts/resolve-version.sh)"
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
# 5. 创建配置文件
cp ../deploy/config.example.yaml ./config.yaml
# 6. 编辑配置
nano config.yaml
```
> **注意:** `-tags embed` 参数会将前端嵌入到二进制文件中。不使用此参数编译的程序将不包含前端界面。
**`config.yaml` 关键配置:**
```yaml
server:
host: "0.0.0.0"
port: 8080
mode: "release"
database:
host: "localhost"
port: 5432
user: "postgres"
password: "your_password"
dbname: "sub2api"
redis:
host: "localhost"
port: 6379
password: ""
jwt:
secret: "change-this-to-a-secure-random-string"
expire_hour: 24
default:
user_concurrency: 5
user_balance: 0
api_key_prefix: "sk-"
rate_multiplier: 1.0
```
### Sora 功能状态(暂不可用)
> ⚠️ 当前 Sora 相关功能因上游接入与媒体链路存在技术问题,暂时不可用。
> 现阶段请勿在生产环境依赖 Sora 能力。
> 文档中的 `gateway.sora_*` 配置仅作预留,待技术问题修复后再恢复可用。
### Sora 媒体签名 URL(功能恢复后可选)
当配置 `gateway.sora_media_signing_key` 且 `gateway.sora_media_signed_url_ttl_seconds > 0` 时,网关会将 Sora 输出的媒体地址改写为临时签名 URL(`/sora/media-signed/...`)。这样无需 API Key 即可在浏览器中直接访问,且具备过期控制与防篡改能力(签名包含 path + query)。
```yaml
gateway:
# /sora/media 是否强制要求 API Key(默认 false)
sora_media_require_api_key: false
# 媒体临时签名密钥(为空则禁用签名)
sora_media_signing_key: "your-signing-key"
# 临时签名 URL 有效期(秒)
sora_media_signed_url_ttl_seconds: 900
```
> 若未配置签名密钥,`/sora/media-signed` 将返回 503。
> 如需更严格的访问控制,可将 `sora_media_require_api_key` 设为 true,仅允许携带 API Key 的 `/sora/media` 访问。
访问策略说明:
- `/sora/media`:内部调用或客户端携带 API Key 才能下载
- `/sora/media-signed`:外部可访问,但有签名 + 过期控制
`config.yaml` 还支持以下安全相关配置:
- `cors.allowed_origins` 配置 CORS 白名单
- `security.url_allowlist` 配置上游/价格数据/CRS 主机白名单
- `security.url_allowlist.enabled` 可关闭 URL 校验(慎用)
- `security.url_allowlist.allow_insecure_http` 关闭校验时允许 HTTP URL
- `security.url_allowlist.allow_private_hosts` 允许私有/本地 IP 地址
- `security.response_headers.enabled` 可启用可配置响应头过滤(关闭时使用默认白名单)
- `security.csp` 配置 Content-Security-Policy
- `billing.circuit_breaker` 计费异常时 fail-closed
- `server.trusted_proxies` 启用可信代理解析 X-Forwarded-For
- `turnstile.required` 在 release 模式强制启用 Turnstile
**网关防御纵深建议(重点)**
- `gateway.upstream_response_read_max_bytes`:限制非流式上游响应读取大小(默认 `8MB`),用于防止异常响应导致内存放大。
- `gateway.proxy_probe_response_read_max_bytes`:限制代理探测响应读取大小(默认 `1MB`)。
- `gateway.gemini_debug_response_headers`:默认 `false`,仅在排障时短时开启,避免高频请求日志开销。
- `/auth/register`、`/auth/login`、`/auth/login/2fa`、`/auth/send-verify-code` 已提供服务端兜底限流(Redis 故障时 fail-close)。
- 推荐将 WAF/CDN 作为第一层防护,服务端限流与响应读取上限作为第二层兜底;两层同时保留,避免旁路流量与误配置风险。
**⚠️ 安全警告:HTTP URL 配置**
当 `security.url_allowlist.enabled=false` 时,系统仅执行最小 URL 校验,且**默认允许 HTTP URL**(开发友好模式,Docker Compose 部署的默认值一致)。生产环境建议显式收紧为仅允许 HTTPS:
```yaml
security:
url_allowlist:
enabled: false # 禁用白名单检查
allow_insecure_http: false # 仅允许 HTTPS(生产环境推荐)
```
**或通过环境变量:**
```bash
SECURITY_URL_ALLOWLIST_ENABLED=false
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
```
**允许 HTTP 的风险:**
- API 密钥和数据以**明文传输**(可被截获)
- 易受**中间人攻击 (MITM)**
- **不适合生产环境**
**适用场景:**
- ✅ 开发/测试环境的本地服务器(http://localhost)
- ✅ 内网可信端点
- ✅ 获取 HTTPS 前测试账号连通性
- ❌ 生产环境(仅使用 HTTPS)
**设置 `allow_insecure_http: false` 后,HTTP URL 会返回如下错误:**
```
Invalid base URL: invalid url scheme: http
```
如关闭 URL 校验或响应头过滤,请加强网络层防护:
- 出站访问白名单限制上游域名/IP
- 阻断私网/回环/链路本地地址
- 强制仅允许 TLS 出站
- 在反向代理层移除敏感响应头
#### ⚠️ 重要:创建管理员账号
初始管理员账号**只能通过 setup 向导创建**(首次启动时访问 `http://<host>:8080`)。`config.yaml` 中的 `default.admin_email` / `default.admin_password` 字段**不会被用来创建管理员**——它们只是出于历史原因保留在模板里。
由于上面第 5 步预先创建了 `config.yaml`,**setup 向导在首次启动时会被跳过**:服务检测到 config 已存在,会直接进入正常模式,此时 `users` 表为空,首次登录会返回 `invalid email or password`。
**创建管理员的两种方式:**
1. **推荐——让向导自动生成 `config.yaml`:** 跳过上面的第 5 步(不要执行 `cp`)。直接运行 `./sub2api`,访问 `http://localhost:8080`,向导会引导你完成数据库、Redis 和管理员账号配置,并自动写出 `config.yaml`。
2. **如果你已经创建了 `config.yaml`:** 首次启动前先把它临时移走以触发向导,完成后再恢复:
```bash
mv config.yaml config.yaml.bak
./sub2api # 向导在 http://localhost:8080 启动,并生成新的 config.yaml
# 向导完成后 Ctrl+C 停服,再恢复你的配置:
mv config.yaml.bak config.yaml
./sub2api # 重启进入正常模式,用刚创建的管理员登录
```
```bash
# 6. 运行应用
./sub2api
```
#### HTTP/2 (h2c) 与 HTTP/1.1 回退
后端明文端口默认支持 h2c,并保留 HTTP/1.1 回退用于 WebSocket 与旧客户端。浏览器通常不支持 h2c,性能收益主要在反向代理或内网链路。
**反向代理示例(Caddy):**
```caddyfile
transport http {
versions h2c h1
}
```
**验证:**
```bash
# h2c prior knowledge
curl --http2-prior-knowledge -I http://localhost:8080/health
# HTTP/1.1 回退
curl --http1.1 -I http://localhost:8080/health
# WebSocket 回退验证(需管理员 token)
websocat -H="Sec-WebSocket-Protocol: sub2api-admin, jwt.<ADMIN_TOKEN>" ws://localhost:8080/api/v1/admin/ops/ws/qps
```
#### 开发模式
```bash
# 后端(支持热重载)
cd backend
go run ./cmd/server
# 前端(支持热重载)
cd frontend
pnpm run dev
```
#### 代码生成
修改 `backend/ent/schema` 后,需要重新生成 Ent + Wire:
```bash
cd backend
go generate ./ent
go generate ./cmd/server
```
---
## 简易模式
简易模式适合个人开发者或内部团队快速使用,不依赖完整 SaaS 功能。
- 启用方式:设置环境变量 `RUN_MODE=simple`
- 功能差异:隐藏 SaaS 相关功能,跳过计费流程
- 安全注意事项:生产环境需同时设置 `SIMPLE_MODE_CONFIRM=true` 才允许启动
---
## Antigravity 使用说明
Sub2API 支持 [Antigravity](https://antigravity.so/) 账户,授权后可通过专用端点访问 Claude 和 Gemini 模型。
### 专用端点
| 端点 | 模型 |
|------|------|
| `/antigravity/v1/messages` | Claude 模型 |
| `/antigravity/v1beta/` | Gemini 模型 |
### Claude Code 配置示例
```bash
export ANTHROPIC_BASE_URL="http://localhost:8080/antigravity"
export ANTHROPIC_AUTH_TOKEN="sk-xxx"
```
### 混合调度模式
Antigravity 账户支持可选的**混合调度**功能。开启后,通用端点 `/v1/messages` 和 `/v1beta/` 也会调度该账户。
> **⚠️ 注意**:Anthropic Claude 和 Antigravity Claude **不能在同一上下文中混合使用**,请通过分组功能做好隔离。
---
## 项目结构
```
sub2api/
├── backend/ # Go 后端服务
│ ├── cmd/server/ # 应用入口
│ ├── internal/ # 内部模块
│ │ ├── config/ # 配置管理
│ │ ├── model/ # 数据模型
│ │ ├── service/ # 业务逻辑
│ │ ├── handler/ # HTTP 处理器
│ │ └── gateway/ # API 网关核心
│ └── resources/ # 静态资源
│
├── frontend/ # Vue 3 前端
│ └── src/
│ ├── api/ # API 调用
│ ├── stores/ # 状态管理
│ ├── views/ # 页面组件
│ └── components/ # 通用组件
│
└── deploy/ # 部署文件
├── docker-compose.yml # Docker Compose 配置
├── .env.example # Docker Compose 环境变量
├── config.example.yaml # 二进制部署完整配置文件
└── install.sh # 一键安装脚本
```
## Star History
<a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
</picture>
</a>
---
## 许可证
本项目基于 [GNU 宽通用公共许可证 v3.0](LICENSE)(或更高版本)授权。
Copyright (c) 2026 Wesley Liddick
---
<div align="center">
**如果觉得有用,请给个 Star 支持一下!**
</div>
+95 -55
View File
@@ -12,7 +12,7 @@
**サブスクリプションクォータ配分のための AI API ゲートウェイプラットフォーム**
[English](README.md) | 日本語
[English](README.md) | [中文](README_CN.md) | 日本語
</div>
@@ -23,26 +23,11 @@
- **🚨 利用規約のリスク**:本プロジェクトの使用は、Anthropic をはじめとする上流プロバイダーの利用規約に違反する可能性があります。ご利用前に各プロバイダーのユーザー規約を必ずご確認ください。使用により生じるすべてのリスクはユーザーご自身が負うものとします。
- **⚖️ 法令遵守**:お住まいの国または地域の法令を遵守した上で本プロジェクトをご利用ください。いかなる違法な目的での使用も固く禁じます。
- **📖 免責事項**:本プロジェクトは技術的な学習および研究の目的でのみ提供されます。本プロジェクトの使用により生じたアカウントの停止、サービスの中断、データの損失、その他一切の直接的または間接的な損害について、作者は一切の責任を負いません。
## 概要
Sub2API は、AI 製品のサブスクリプションから API クォータを配分・管理するために設計された AI API ゲートウェイプラットフォームです。ユーザーはプラットフォームが生成した API キーを通じて上流の AI サービスにアクセスでき、プラットフォームは認証、課金、負荷分散、リクエスト転送を処理します。
## 機能
- **マルチアカウント管理** - 複数の上流アカウントタイプ(OAuth、APIキー)をサポート
- **APIキー配布** - ユーザー向けの APIキーの生成と管理
- **精密な課金** - トークンレベルの使用量追跡とコスト計算
- **スマートスケジューリング** - スティッキーセッション付きのインテリジェントなアカウント選択
- **同時実行制御** - ユーザーごと・アカウントごとの同時実行数制限
- **レート制限** - 設定可能なリクエスト数およびトークンレート制限
- **内蔵決済システム** - EasyPay、Alipay、WeChat Pay、Stripe に対応。ユーザーのセルフサービスチャージが可能で、別途決済サービスのデプロイは不要([設定ガイド](docs/PAYMENT.md))
- **管理ダッシュボード** - 監視・管理のための Web インターフェース
- **外部システム連携** - 外部システム(チケット管理など)を iframe 経由で管理ダッシュボードに埋め込み可能
- **🚫 商用利用の非許諾**:本プロジェクトの開発者は、いかなる個人または組織に対しても、本プロジェクトを利用したいかなる形態の商業運営も一切許諾していません。本プロジェクトの名義で、または本プロジェクトに基づいて行われる商業行為はすべて本プロジェクトおよびその開発者とは無関係であり、それにより生じる一切の紛争、損失、法的責任は行為者自身が負うものとします。
## ❤️ スポンサー
> [こちらに掲載しませんか?](mailto:support@pincc.ai)
> [こちらに掲載しませんか?](mailto:support@sub2api.org)
<table>
@@ -61,16 +46,6 @@ Sub2API は、AI 製品のサブスクリプションから API クォータを
<td>AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:<a href="https://aigocode.com/invite/SUB2API">こちらのリンク</a>から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!</td>
</tr>
<tr>
<td width="180"><a href="https://code.silkapi.com/register?aff=SUB2API"><img src="assets/partners/logos/silkapi.png" alt="silkapi" width="150"></a></td>
<td>SilkAPI のご支援に感謝します!<a href="https://code.silkapi.com/register?aff=SUB2API">SilkAPI</a> は Sub2API をベースに構築された中継サービスで、高速かつ安定した Codex API 中継の提供に特化しています。</td>
</tr>
<tr>
<td width="180"><a href="https://ylscode.com/"><img src="assets/partners/logos/ylscode.png" alt="ylscode" width="150"></a></td>
<td>YLS Code のご支援に感謝します!<a href="https://ylscode.com/">YLS Code</a> は安全なエンタープライズグレードの Coding Agent 生産性サービスの構築に取り組んでおり、安定かつ高速な Codex / Claude / Gemini サブスクリプションサービスと従量課金 API の柔軟なプランを提供しています。期間限定で新規登録者に 3 日間の Codex 試用特典をプレゼント中!</td>
</tr>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=KMVZQM"><img src="assets/partners/logos/AICodeMirror.jpg" alt="AICodeMirror" width="150"></a></td>
<td>AICodeMirror のご支援に感謝します!AICodeMirror は Claude Code / Codex / Gemini CLI の公式高安定性リレーサービスを提供しており、エンタープライズグレードの同時実行、迅速な請求書発行、24時間年中無休の専属テクニカルサポートを備えています。Claude Code / Codex / Gemini の公式チャネルを定価の 38% / 2% / 9% で利用可能、チャージ時にはさらに追加割引!AICodeMirror は sub2api ユーザー向けに特別特典を提供中:<a href="https://www.aicodemirror.com/register?invitecode=KMVZQM">こちらのリンク</a>から登録すると、初回チャージが 20% オフ、法人のお客様は最大 25% オフ!</td>
@@ -99,12 +74,6 @@ Sub2API は、AI 製品のサブスクリプションから API クォータを
</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=fu2E"><img src="assets/partners/logos/runapi.png" alt="RunAPI" width="150"></a></td>
<td>RunAPI のご支援に感謝します!<a href="https://runapi.co/register?aff=fu2E">RunAPI</a> は効率的で安定した API プラットフォームで、OpenRouter の代替として利用できます。1つの API キーで OpenAI、Claude、Gemini、DeepSeek、Grok など 150以上の主要モデルにアクセスでき、価格は最低 10% から。非常に安定しており、Claude Code や OpenClaw などのツールとシームレスに互換します。
</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=sub2api"><img src="assets/partners/logos/unity2.png" alt="unity2" width="150"></a></td>
<td>Unity2 のご支援に感謝します!<a href="https://unity2.ai/register?source=sub2api">Unity2</a> は個人開発者、チーム、企業向けの高性能 AI モデル API 中継プラットフォームです。中国の大手企業に長期にわたりサービスを提供しており、1日あたり 300 億以上のトークン呼び出しを処理し、5000 RPM 級の高並列性をサポートします。1つの API キーで Claude Code、Codex、OpenAI モデル、IDE プラグイン、Agent ワークフローなど様々なシナリオに対応できます。エンタープライズグレードの安定供給能力を備え、高並列・継続的な呼び出し・チームの集中購入シーンでも低レイテンシと高可用性を維持します。残高課金、組み合わせサブスクリプション、初回チャージ特典、企業向け請求書発行、専属 1v1 サポートにも対応しており、個人の頻繁な利用にも企業の長期導入にも適しています。今 Unity2.ai に登録すると $2 の残高、公式グループに参加するとさらに $10 の残高がもらえ、合計最大 $12 の無料クレジットを獲得できます — 試用後に長期利用したい方に最適です。<a href="https://unity2.ai/register?source=sub2api">登録リンク</a>
@@ -123,8 +92,75 @@ Sub2API は、AI 製品のサブスクリプションから API クォータを
</td>
</tr>
<tr>
<td width="180"><a href="https://apikl.ai"><img src="assets/partners/logos/apikl.png" alt="apikl" width="150"></a></td>
<td>Apikl のご支援に感謝します!Sub2API をベースに構築された本プラットフォームは、開発者向けに Codex / Claude シリーズモデルの中継サービスを提供しています。長期安定性、高速直結、高いコストパフォーマンスを重視し、従量課金の残高ベース課金、エンタープライズグレードの正規請求書、1対1の専属サポートを提供します。<a href="https://apikl.ai">今すぐ登録</a>でチャージ 1:1 ボーナス — 残高が倍に!
</td>
</tr>
<tr>
<td width="180"><a href="https://tokeneum.ai"><img src="assets/partners/logos/tokeneum.png" alt="tokeneum" width="150"></a></td>
<td>TokenEum のご支援に感謝します!<a href="https://tokeneum.ai">TokenEum</a> は総合的な AI モデル集約プラットフォームおよびインテリジェントエージェント開発企業です。Claude、Gemini、OpenAI などの世界トップクラスのモデルに加え、GLM、Qwen、Kimi などの主要なオープンソースモデルも集約しており、品質と価格の異なる豊富な選択肢を提供してあらゆるニーズに対応します。また、Seedance2.0 や Happy Horse などの最先端の動画生成モデルも利用可能です。TokenEum は透明性と誠実なビジネスを重視し、すべてのモデル情報の正確性と信頼性を保証します。<a href="https://tokeneum.ai">tokeneum.ai</a> でぜひお試しください。
</td>
</tr>
<tr>
<td width="180"><a href="https://666api.work/sub2api"><img src="assets/partners/logos/666api.jpg" alt="666api" width="150"></a></td>
<td>666api のご支援に感謝します!<a href="https://666api.work/sub2api">666api</a> はオールインワンプラットフォームで、以下を提供しています:⚡ API 中継 — グローバルモデルへの従量課金アクセス、100% 公式ソースから直接供給、公式価格の最大 75% オフ。独占特典:Zhipu GLM 50% オフ・DeepSeek V4-pro 50% オフ・Seedance2.0 8% オフ(ホワイトリスト)・HappyHorse Overseas 30% オフ(ホワイトリスト)🔑 GPT サブスクリプションアカウント — 同源 IP 込み・グローバル住宅 IP 💰 請求書発行対応
</td>
</tr>
<tr>
<td width="180"><a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Dola seed のご支援に感謝します!Dola Seed 2.0 は、ByteDance がグローバル市場向けに独自開発した全モーダル汎用大規模モデルです。統一されたマルチモーダルアーキテクチャに基づき、テキスト・画像・音声・動画の共同理解と生成をサポートします。エージェント協調をネイティブに有効化し、強力な推論・長期タスク実行・ツール統合・コーディング能力を備えています。スマートコックピット、パーソナルアシスタント、教育、カスタマーサポート、マーケティング、リテールなど多様なシナリオに広く適用可能です。マルチモーダル知覚、エンドツーエンドの複雑タスク配信、安定したインタラクション、データセキュリティに優れ、ModelArk プラットフォームを通じて容易にアクセス・デプロイできます。<a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html">こちらのリンク</a>から登録すると、各モデルにつき 50 万トークンの無料推論クォータを獲得できます。<a href="https://dis.chatdesks.cn/chatdesk/hsyqsub2api.html"> >>中国大陸地域の開発者はこちらをクリック</a></td>
</tr>
<tr>
<td width="180"><a href="https://sui-xiang.com/"><img src="assets/partners/logos/sui-xiang.jpg" alt="sui-xiang" width="150"></a></td>
<td>随想AI ゲートウェイのご支援に感謝します!<a href="https://sui-xiang.com/">随想AI ゲートウェイ</a> は信頼性と効率に優れた API 中継サービスプロバイダーで、Claude、Codex、Gemini などの中継サービスを提供しています。プライバシー重視の中継ステーション・データ転売なし・モデル水増しなし、プライバシー・透明性・超高速アフターサービス。新規アカウント登録後、毎日サインインで 0.5 元のテストクレジットがもらえ、チャージは 1:1、サブスクリプション不要、従量課金。マルチライン冗長、クロスリージョン災害復旧、自動フェイルオーバー、長時間 SSE 接続が途切れません。99.9% の可用性、重要な呼び出しは決して遅れません。
</td>
</tr>
<tr>
<td width="180"><a href="https://www.miyaip.com/?invitecode=sub2api"><img src="assets/partners/logos/miyaip.png" alt="miyaip" width="150"></a></td>
<td>MiyaIP のご支援に感謝します!<a href="https://www.miyaip.com/?invitecode=sub2api">MiyaIP</a> はグローバル住宅プロキシネットワークサービスに特化したプラットフォームで、企業開発者、越境ビジネスチーム、AI アプリケーションユーザーに高品質で純粋な海外住宅 IP リソースを提供することに注力しています。AI プラットフォーム、海外 SaaS、その他のオンラインサービスに安定した独立した海外ネットワーク環境を提供し、複数地域でのアクセステストやプロジェクト環境の分離をサポートします。海外 AI サービスへのアクセスが必要な開発・テストシナリオに最適です。例:AI モデルプラットフォームアクセス、AI 開発テスト、AI SaaS サービス利用、AI API デバッグ、複数地域のネットワーク環境検証など。
</td>
</tr>
<tr>
<td width="180"><a href="https://anpin.ai"><img src="assets/partners/logos/anpin.jpg" alt="anpin" width="150"></a></td>
<td><a href="https://anpin.ai">anpin.ai</a> のご支援に感謝します!anpin.ai は AI の普及推進に取り組むハイエンド AI 中継サービスプラットフォームです。先進的な技術アーキテクチャとグローバル分散デプロイメントにより、国際トップクラスの大規模モデルへの高速直通ルートを提供します。<br>
自社構築の一次アカウントプール:1-3秒の超高速応答、同業者への配布に対応<br>
極めて高い安定性:マルチライン・インテリジェントルーティング + 冗長バックアップシステムにより、年中無休の高可用性運用を確保;<br>
モデルの真正性:一切のコンテンツ介入や二次フィルタリングを行わず、最も純粋で強力なネイティブモデル能力を体験できます。<br>
チャージ 1:1、エンタープライズグレードサービスは請求書発行可能。安品 AI は単なる中継所ではなく、最先端のインテリジェント世界へと繋がる安全・信頼性・高効率の橋渡し役です。
</td>
</tr>
<tr>
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
<td>Proxy4Free のご支援に感謝します!Proxy4Free は開発者と AI アプリケーション向けのデータプロキシサービスプロバイダーで、住宅プロキシ、静的住宅プロキシ、ISP プロキシ、データセンタープロキシなど多様なプロキシソリューションを提供しており、Web Scraping、Browser Automation、AI Agent などのシナリオに適しています。グローバル IP リソース、安定した接続、柔軟な切り替えをサポートし、開発者のデータ収集成功率の向上と IP ブロックリスクの低減を支援します。<a href="https://www.proxy4free.com/?keyword=4yjqecpc">こちらのリンクから登録</a>して、より安定した効率的な自動化ワークフローを簡単に構築しましょう。
</td>
</tr>
</table>
## 概要
Sub2API は、AI 製品のサブスクリプションから API クォータを配分・管理するために設計された AI API ゲートウェイプラットフォームです。ユーザーはプラットフォームが生成した API キーを通じて上流の AI サービスにアクセスでき、プラットフォームは認証、課金、負荷分散、リクエスト転送を処理します。
## 機能
- **マルチアカウント管理** - 複数の上流アカウントタイプ(OAuth、APIキー)をサポート
- **APIキー配布** - ユーザー向けの APIキーの生成と管理
- **精密な課金** - トークンレベルの使用量追跡とコスト計算
- **スマートスケジューリング** - スティッキーセッション付きのインテリジェントなアカウント選択
- **同時実行制御** - ユーザーごと・アカウントごとの同時実行数制限
- **レート制限** - 設定可能なリクエスト数およびトークンレート制限
- **内蔵決済システム** - EasyPay、Alipay、WeChat Pay、Stripe に対応。ユーザーのセルフサービスチャージが可能で、別途決済サービスのデプロイは不要([設定ガイド](docs/PAYMENT.md))
- **管理ダッシュボード** - 監視・管理のための Web インターフェース
- **外部システム連携** - 外部システム(チケット管理など)を iframe 経由で管理ダッシュボードに埋め込み可能
## エコシステム
Sub2API を拡張・統合するコミュニティプロジェクト:
@@ -421,7 +457,8 @@ pnpm run build
# 4. フロントエンドを組み込んだバックエンドをビルド
cd ../backend
go build -tags embed -o sub2api ./cmd/server
VERSION="$(./scripts/resolve-version.sh)"
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
# 5. 設定ファイルを作成
cp ../deploy/config.example.yaml ./config.yaml
@@ -484,20 +521,20 @@ default:
**⚠️ セキュリティ警告: HTTP URL 設定**
`security.url_allowlist.enabled=false` の場合、システムはデフォルトで最小限の URL バリデーションを行い、**HTTP URL を拒否**して HTTPS のみを許可します。HTTP URL を許可するには(開発環境や内部テスト用など)、以下を明示的に設定する必要があります:
`security.url_allowlist.enabled=false` の場合、システムは最小限の URL バリデーションのみを行い、**デフォルトで HTTP URL を許可**します(開発フレンドリーモード。Docker Compose デプロイのデフォルトも同じです)。本番環境では、以下のように明示的に HTTPS のみに制限することを推奨します:
```yaml
security:
url_allowlist:
enabled: false # 許可リストチェックを無効化
allow_insecure_http: true # HTTP URL を許可(⚠️ セキュリティリスクあり)
allow_insecure_http: false # HTTPS のみ許可(本番環境推奨)
```
**または環境変数で設定:**
```bash
SECURITY_URL_ALLOWLIST_ENABLED=false
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
```
**HTTP を許可するリスク:**
@@ -511,7 +548,7 @@ SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
- ✅ HTTPS 取得前のアカウント接続テスト
- ❌ 本番環境(HTTPS のみを使用)
**この設定なしで表示されるエラー例:**
**`allow_insecure_http: false` 設定時に HTTP URL で表示されるエラー例:**
```
Invalid base URL: invalid url scheme: http
```
@@ -522,6 +559,25 @@ URL バリデーションまたはレスポンスヘッダーフィルタリン
- TLS のみのアウトバウンドトラフィックを強制
- プロキシで機密性の高い上流レスポンスヘッダーを除去
#### ⚠️ 重要:管理者アカウントの作成
初期管理者アカウントは**セットアップウィザード経由でのみ作成**されます(初回起動時に `http://<host>:8080` にアクセス)。`config.yaml` の `default.admin_email` / `default.admin_password` フィールドは**管理者作成には使われません**。テンプレートに残っているのは歴史的経緯によるものです。
上記ステップ 5 で事前に `config.yaml` を作成しているため、**初回起動時にセットアップウィザードはスキップされます**。サーバーは既存の config を検出して通常モードで直接起動し、この時点では `users` テーブルが空のため、初回ログインは `invalid email or password` を返します。
**管理者アカウントを作成する 2 つの方法:**
1. **推奨 — ウィザードに `config.yaml` を自動生成させる:** 上記ステップ 5 をスキップします(`cp` を実行しない)。`./sub2api` を直接起動し、`http://localhost:8080` にアクセスすると、セットアップウィザードがデータベース・Redis・管理者アカウントの設定を案内し、`config.yaml` を自動生成します。
2. **すでに `config.yaml` を作成してしまった場合:** 初回起動前に一時的に退避してウィザードを発生させ、完了後に戻します:
```bash
mv config.yaml config.yaml.bak
./sub2api # ウィザードが http://localhost:8080 で起動し、新しい config.yaml を生成します
# ウィザード完了後、Ctrl+C でサーバーを停止し、設定を復元します:
mv config.yaml.bak config.yaml
./sub2api # 通常モードで再起動し、作成した管理者でログインします
```
```bash
# 6. アプリケーションを実行
./sub2api
@@ -585,12 +641,6 @@ Antigravity アカウントはオプションの**ハイブリッドスケジュ
> **⚠️ 警告**: Anthropic Claude と Antigravity Claude は**同じ会話コンテキスト内で混在させることはできません**。グループを使用して適切に分離してください。
### 既知の問題
Claude Code では、Plan Mode を自動的に終了できません。(通常、ネイティブの Claude API を使用する場合、計画が完了すると Claude Code はユーザーに計画を承認または拒否するオプションをポップアップ表示します。)
**回避策**: `Shift + Tab` を押して手動で Plan Mode を終了し、計画を承認または拒否するためのレスポンスを入力してください。
---
## プロジェクト構成
@@ -621,16 +671,6 @@ sub2api/
└── install.sh # ワンクリックインストールスクリプト
```
## 免責事項
> **本プロジェクトをご利用の前に、以下をよくお読みください:**
>
> :rotating_light: **利用規約違反のリスク**: 本プロジェクトの使用は Anthropic の利用規約に違反する可能性があります。使用前に Anthropic のユーザー契約をよくお読みください。本プロジェクトの使用に起因するすべてのリスクは、ユーザー自身が負うものとします。
>
> :book: **免責事項**: 本プロジェクトは技術的な学習および研究目的のみで提供されています。作者は、本プロジェクトの使用によるアカウント停止、サービス中断、その他の損失について一切の責任を負いません。
---
## スター履歴
<a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

+2 -1
View File
@@ -15,7 +15,8 @@ RUN go mod download
COPY . .
# 构建应用
RUN go build -o main ./cmd/server/
RUN VERSION_VALUE="$(./scripts/resolve-version.sh)" && \
go build -ldflags="-s -w -X main.Version=${VERSION_VALUE}" -o main ./cmd/server/
# 暴露端口
EXPOSE 8080
+3 -16
View File
@@ -1,6 +1,6 @@
.PHONY: build generate test test-unit test-integration test-e2e test-invariants new-module
.PHONY: build generate test test-unit test-integration test-e2e
VERSION ?= $(shell tr -d '\r\n' < ./cmd/server/VERSION)
VERSION ?= $(shell ./scripts/resolve-version.sh)
LDFLAGS ?= -s -w -X main.Version=$(VERSION)
build:
@@ -20,21 +20,8 @@ test-unit:
test-integration:
go test -tags=integration ./...
# 插件化改造回归安全网(特征化/不变量测试,详见 .claude/plugin-refactor/INVARIANTS.md)
test-invariants:
go test -tags=unit -count=1 -run 'Characterization|Invariant' ./internal/...
# 生成插件模块骨架:make new-module ID=job.foo
# (生成后按提示在 internal/modules/standard/imports.go 手工加 import 行)
new-module:
ifndef ID
$(error ID is required: make new-module ID=job.foo)
endif
go run ./tools/newmodule -id "$(ID)"
# scripts/e2e-test.sh 已不存在,test-e2e 与 test-e2e-local 等价(env 驱动的真实服务 e2e)
test-e2e:
go test -tags=e2e -v -timeout=300s ./internal/integration/...
./scripts/e2e-test.sh
test-e2e-local:
go test -tags=e2e -v -timeout=300s ./internal/integration/...
+1 -1
View File
@@ -1 +1 @@
0.1.136
0.1.144
-16
View File
@@ -18,7 +18,6 @@ import (
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler"
_ "github.com/Wei-Shaw/sub2api/internal/modules/standard" // 插件模块插装清单(唯一插装点)
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/setup"
@@ -155,21 +154,6 @@ func runMainServer() {
}
defer app.Cleanup()
// 启动插件模块:Build(实例化 → Provision → Validate)+ Start(按稳定序)。
// 任一失败立即中止启动(fail-fast)。注意:log.Fatalf 经 os.Exit 退出,
// defer 的 app.Cleanup() 不会执行;而部分后台服务在 Wire 构造期已自启动并
// 持有 Redis leader 锁,必须先显式 Cleanup 再退出,避免锁滞留到 TTL 过期。
// ⚠ 不要把下面的 log.Fatalf 改成 return:那会让上面 defer 的 Cleanup 与
// 此处显式 Cleanup 双触发,而 Cleanup 各步骤并未统一保证幂等(审计 B-2)。
if err := app.Runtime.Build(); err != nil {
app.Cleanup()
log.Fatalf("Failed to build plugin modules: %v", err)
}
if err := app.Runtime.Start(context.Background()); err != nil {
app.Cleanup()
log.Fatalf("Failed to start plugin modules: %v", err)
}
// 启动服务器
go func() {
if err := app.Server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+9 -18
View File
@@ -14,7 +14,6 @@ import (
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler"
"github.com/Wei-Shaw/sub2api/internal/payment"
"github.com/Wei-Shaw/sub2api/internal/plugin"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/server"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
@@ -25,10 +24,7 @@ import (
)
type Application struct {
Server *http.Server
// Runtime 是插件模块生命周期驱动器:main 在 HTTP server 启动前
// 调用 Build + Start,关闭时由 Cleanup 序列执行 Stop。
Runtime *plugin.Runtime
Server *http.Server
Cleanup func()
}
@@ -47,9 +43,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
// Server layer ProviderSet
server.ProviderSet,
// Plugin kernel ProviderSet (Host + module Runtime)
plugin.ProviderSet,
// Privacy client factory for OpenAI training opt-out
providePrivacyClientFactory,
@@ -60,7 +53,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
provideCleanup,
// Application struct
wire.Struct(new(Application), "Server", "Runtime", "Cleanup"),
wire.Struct(new(Application), "Server", "Cleanup"),
)
return nil, nil
}
@@ -101,13 +94,13 @@ func provideCleanup(
openaiOAuth *service.OpenAIOAuthService,
geminiOAuth *service.GeminiOAuthService,
antigravityOAuth *service.AntigravityOAuthService,
grokOAuth *service.GrokOAuthService,
openAIGateway *service.OpenAIGatewayService,
scheduledTestRunner *service.ScheduledTestRunnerService,
backupSvc *service.BackupService,
paymentOrderExpiry *service.PaymentOrderExpiryService,
channelMonitorRunner *service.ChannelMonitorRunner,
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
moduleRuntime *plugin.Runtime,
) func() {
return func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -120,14 +113,6 @@ func provideCleanup(
// 应用层清理步骤可并行执行,基础设施资源(Redis/Ent)最后按顺序关闭。
parallelSteps := []cleanupStep{
// 插件模块 Stop 属于业务服务关闭组:模块停止时可能仍需写 DB/Redis,
// 必须先于基础设施(Redis/Ent)关闭执行。
{"PluginModuleRuntime", func() error {
if moduleRuntime == nil {
return nil
}
return moduleRuntime.Stop(ctx)
}},
{"OpsScheduledReportService", func() error {
if opsScheduledReport != nil {
opsScheduledReport.Stop()
@@ -238,6 +223,12 @@ func provideCleanup(
antigravityOAuth.Stop()
return nil
}},
{"GrokOAuthService", func() error {
if grokOAuth != nil {
grokOAuth.Stop()
}
return nil
}},
{"OpenAIWSPool", func() error {
if openAIGateway != nil {
openAIGateway.CloseOpenAIWSPool()
+24 -33
View File
@@ -13,7 +13,6 @@ import (
"github.com/Wei-Shaw/sub2api/internal/handler"
"github.com/Wei-Shaw/sub2api/internal/handler/admin"
"github.com/Wei-Shaw/sub2api/internal/payment"
"github.com/Wei-Shaw/sub2api/internal/plugin"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/server"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
@@ -28,7 +27,6 @@ import (
import (
_ "embed"
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
_ "github.com/Wei-Shaw/sub2api/internal/modules/standard"
)
// Injectors from wire.go:
@@ -143,7 +141,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
privacyClientFactory := providePrivacyClientFactory()
openAIOAuthService := service.ProvideOpenAIOAuthService(proxyRepository, openAIOAuthClient, privacyClientFactory)
openAITokenProvider := service.ProvideOpenAITokenProvider(accountRepository, geminiTokenCache, openAIOAuthService, oAuthRefreshAPI)
openAIGatewayService := service.NewOpenAIGatewayService(accountRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, httpUpstream, deferredService, openAITokenProvider, modelPricingResolver, channelService, balanceNotifyService, settingService, serviceUserPlatformQuotaRepository)
grokOAuthClient := repository.NewGrokOAuthClient()
grokOAuthService := service.NewGrokOAuthService(proxyRepository, grokOAuthClient)
grokTokenProvider := service.ProvideGrokTokenProvider(accountRepository, geminiTokenCache, grokOAuthService, oAuthRefreshAPI, tempUnschedCache)
openAIGatewayService := service.NewOpenAIGatewayService(accountRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, httpUpstream, deferredService, openAITokenProvider, grokTokenProvider, modelPricingResolver, channelService, balanceNotifyService, settingService, serviceUserPlatformQuotaRepository)
geminiOAuthClient := repository.NewGeminiOAuthClient(configConfig)
geminiCliCodeAssistClient := repository.NewGeminiCliCodeAssistClient()
driveClient := repository.NewGeminiDriveClient()
@@ -180,9 +181,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService)
claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream)
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository)
grokQuotaFetcher := service.NewGrokQuotaFetcher()
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory)
usageCache := service.NewUsageCache()
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, usageCache, identityCache, tlsFingerprintProfileService)
accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService)
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService)
accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService)
crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig)
accountHandler := admin.NewAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator)
adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService)
@@ -193,9 +196,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
backupService := service.ProvideBackupService(settingRepository, configConfig, secretEncryptor, backupObjectStoreFactory, dbDumper)
backupHandler := admin.NewBackupHandler(backupService, userService)
oAuthHandler := admin.NewOAuthHandler(oAuthService)
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService)
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService, openAIQuotaService)
geminiOAuthHandler := admin.NewGeminiOAuthHandler(geminiOAuthService)
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream)
grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService)
proxyHandler := admin.NewProxyHandler(adminService)
adminRedeemHandler := admin.NewRedeemHandler(adminService, redeemService)
promoHandler := admin.NewPromoHandler(promoService)
@@ -243,21 +248,12 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
paymentHandler := admin.NewPaymentHandler(paymentService, paymentConfigService)
affiliateHandler := admin.NewAffiliateHandler(affiliateService, adminService)
complianceHandler := admin.NewComplianceHandler(settingService)
pluginConfig, err := plugin.ProvideModuleConfig(configConfig)
if err != nil {
return nil, err
}
host := plugin.ProvideHost(pluginConfig, client, redisClient)
runtime := plugin.ProvideModuleRuntime(host, pluginConfig)
moduleHandler := admin.NewModuleHandler(runtime)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, paymentHandler, affiliateHandler, complianceHandler, moduleHandler)
gatewayplatformRegistry := handler.ProvideGatewayPlatformRegistry(gatewayService, antigravityGatewayService)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, paymentHandler, affiliateHandler, complianceHandler)
usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig)
chain := handler.ProvideGatewayHookChain(contentModerationService)
userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient)
userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig)
gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, gatewayplatformRegistry, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, chain, userMessageQueueService, configConfig, settingService)
openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, chain, configConfig)
gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService)
openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, configConfig)
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService)
totpHandler := handler.NewTotpHandler(totpService)
handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService, channelService)
@@ -276,7 +272,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
opsAlertEvaluatorService := service.ProvideOpsAlertEvaluatorService(opsService, opsRepository, emailService, redisClient, configConfig, proxyRepository)
opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig, channelMonitorService, settingRepository, opsService)
opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository)
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db)
@@ -284,10 +280,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db)
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService)
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, schedulerSnapshotService, tokenRefreshService, accountExpiryService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher, runtime)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, schedulerSnapshotService, tokenRefreshService, accountExpiryService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher)
application := &Application{
Server: httpServer,
Runtime: runtime,
Cleanup: v,
}
return application, nil
@@ -296,10 +291,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
// wire.go:
type Application struct {
Server *http.Server
// Runtime 是插件模块生命周期驱动器:main 在 HTTP server 启动前
// 调用 Build + Start,关闭时由 Cleanup 序列执行 Stop。
Runtime *plugin.Runtime
Server *http.Server
Cleanup func()
}
@@ -339,13 +331,13 @@ func provideCleanup(
openaiOAuth *service.OpenAIOAuthService,
geminiOAuth *service.GeminiOAuthService,
antigravityOAuth *service.AntigravityOAuthService,
grokOAuth *service.GrokOAuthService,
openAIGateway *service.OpenAIGatewayService,
scheduledTestRunner *service.ScheduledTestRunnerService,
backupSvc *service.BackupService,
paymentOrderExpiry *service.PaymentOrderExpiryService,
channelMonitorRunner *service.ChannelMonitorRunner,
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
moduleRuntime *plugin.Runtime,
) func() {
return func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -357,13 +349,6 @@ func provideCleanup(
}
parallelSteps := []cleanupStep{
{"PluginModuleRuntime", func() error {
if moduleRuntime == nil {
return nil
}
return moduleRuntime.Stop(ctx)
}},
{"OpsScheduledReportService", func() error {
if opsScheduledReport != nil {
opsScheduledReport.Stop()
@@ -474,6 +459,12 @@ func provideCleanup(
antigravityOAuth.Stop()
return nil
}},
{"GrokOAuthService", func() error {
if grokOAuth != nil {
grokOAuth.Stop()
}
return nil
}},
{"OpenAIWSPool", func() error {
if openAIGateway != nil {
openAIGateway.CloseOpenAIWSPool()
+1 -1
View File
@@ -74,13 +74,13 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
openAIOAuthSvc,
geminiOAuthSvc,
antigravityOAuthSvc,
nil, // grokOAuth
nil, // openAIGateway
nil, // scheduledTestRunner
nil, // backupSvc
nil, // paymentOrderExpiry
nil, // channelMonitorRunner
nil, // quotaFlusher
nil, // moduleRuntime
)
require.NotPanics(t, func() {
+64 -5
View File
@@ -77,6 +77,10 @@ type Account struct {
SessionWindowEnd *time.Time `json:"session_window_end,omitempty"`
// SessionWindowStatus holds the value of the "session_window_status" field.
SessionWindowStatus *string `json:"session_window_status,omitempty"`
// Parent account id for a linked spark shadow (NULL = normal).
ParentAccountID *int64 `json:"parent_account_id,omitempty"`
// 'global' (default) or 'spark' (shadow reads codex_bengalfox).
QuotaDimension account.QuotaDimension `json:"quota_dimension,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AccountQuery when eager-loading is set.
Edges AccountEdges `json:"edges"`
@@ -89,13 +93,17 @@ type AccountEdges struct {
Groups []*Group `json:"groups,omitempty"`
// Proxy holds the value of the proxy edge.
Proxy *Proxy `json:"proxy,omitempty"`
// Parent holds the value of the parent edge.
Parent *Account `json:"parent,omitempty"`
// Children holds the value of the children edge.
Children []*Account `json:"children,omitempty"`
// UsageLogs holds the value of the usage_logs edge.
UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
// AccountGroups holds the value of the account_groups edge.
AccountGroups []*AccountGroup `json:"account_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [4]bool
loadedTypes [6]bool
}
// GroupsOrErr returns the Groups value or an error if the edge
@@ -118,10 +126,30 @@ func (e AccountEdges) ProxyOrErr() (*Proxy, error) {
return nil, &NotLoadedError{edge: "proxy"}
}
// ParentOrErr returns the Parent value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e AccountEdges) ParentOrErr() (*Account, error) {
if e.Parent != nil {
return e.Parent, nil
} else if e.loadedTypes[2] {
return nil, &NotFoundError{label: account.Label}
}
return nil, &NotLoadedError{edge: "parent"}
}
// ChildrenOrErr returns the Children value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) ChildrenOrErr() ([]*Account, error) {
if e.loadedTypes[3] {
return e.Children, nil
}
return nil, &NotLoadedError{edge: "children"}
}
// UsageLogsOrErr returns the UsageLogs value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) UsageLogsOrErr() ([]*UsageLog, error) {
if e.loadedTypes[2] {
if e.loadedTypes[4] {
return e.UsageLogs, nil
}
return nil, &NotLoadedError{edge: "usage_logs"}
@@ -130,7 +158,7 @@ func (e AccountEdges) UsageLogsOrErr() ([]*UsageLog, error) {
// AccountGroupsOrErr returns the AccountGroups value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
if e.loadedTypes[3] {
if e.loadedTypes[5] {
return e.AccountGroups, nil
}
return nil, &NotLoadedError{edge: "account_groups"}
@@ -147,9 +175,9 @@ func (*Account) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool)
case account.FieldRateMultiplier:
values[i] = new(sql.NullFloat64)
case account.FieldID, account.FieldProxyID, account.FieldProxyFallbackOriginID, account.FieldConcurrency, account.FieldLoadFactor, account.FieldPriority:
case account.FieldID, account.FieldProxyID, account.FieldProxyFallbackOriginID, account.FieldConcurrency, account.FieldLoadFactor, account.FieldPriority, account.FieldParentAccountID:
values[i] = new(sql.NullInt64)
case account.FieldName, account.FieldNotes, account.FieldPlatform, account.FieldType, account.FieldStatus, account.FieldErrorMessage, account.FieldTempUnschedulableReason, account.FieldSessionWindowStatus:
case account.FieldName, account.FieldNotes, account.FieldPlatform, account.FieldType, account.FieldStatus, account.FieldErrorMessage, account.FieldTempUnschedulableReason, account.FieldSessionWindowStatus, account.FieldQuotaDimension:
values[i] = new(sql.NullString)
case account.FieldCreatedAt, account.FieldUpdatedAt, account.FieldDeletedAt, account.FieldLastUsedAt, account.FieldExpiresAt, account.FieldRateLimitedAt, account.FieldRateLimitResetAt, account.FieldOverloadUntil, account.FieldTempUnschedulableUntil, account.FieldSessionWindowStart, account.FieldSessionWindowEnd:
values[i] = new(sql.NullTime)
@@ -368,6 +396,19 @@ func (_m *Account) assignValues(columns []string, values []any) error {
_m.SessionWindowStatus = new(string)
*_m.SessionWindowStatus = value.String
}
case account.FieldParentAccountID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field parent_account_id", values[i])
} else if value.Valid {
_m.ParentAccountID = new(int64)
*_m.ParentAccountID = value.Int64
}
case account.FieldQuotaDimension:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field quota_dimension", values[i])
} else if value.Valid {
_m.QuotaDimension = account.QuotaDimension(value.String)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
@@ -391,6 +432,16 @@ func (_m *Account) QueryProxy() *ProxyQuery {
return NewAccountClient(_m.config).QueryProxy(_m)
}
// QueryParent queries the "parent" edge of the Account entity.
func (_m *Account) QueryParent() *AccountQuery {
return NewAccountClient(_m.config).QueryParent(_m)
}
// QueryChildren queries the "children" edge of the Account entity.
func (_m *Account) QueryChildren() *AccountQuery {
return NewAccountClient(_m.config).QueryChildren(_m)
}
// QueryUsageLogs queries the "usage_logs" edge of the Account entity.
func (_m *Account) QueryUsageLogs() *UsageLogQuery {
return NewAccountClient(_m.config).QueryUsageLogs(_m)
@@ -542,6 +593,14 @@ func (_m *Account) String() string {
builder.WriteString("session_window_status=")
builder.WriteString(*v)
}
builder.WriteString(", ")
if v := _m.ParentAccountID; v != nil {
builder.WriteString("parent_account_id=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("quota_dimension=")
builder.WriteString(fmt.Sprintf("%v", _m.QuotaDimension))
builder.WriteByte(')')
return builder.String()
}
+90
View File
@@ -3,6 +3,7 @@
package account
import (
"fmt"
"time"
"entgo.io/ent"
@@ -73,10 +74,18 @@ const (
FieldSessionWindowEnd = "session_window_end"
// FieldSessionWindowStatus holds the string denoting the session_window_status field in the database.
FieldSessionWindowStatus = "session_window_status"
// FieldParentAccountID holds the string denoting the parent_account_id field in the database.
FieldParentAccountID = "parent_account_id"
// FieldQuotaDimension holds the string denoting the quota_dimension field in the database.
FieldQuotaDimension = "quota_dimension"
// EdgeGroups holds the string denoting the groups edge name in mutations.
EdgeGroups = "groups"
// EdgeProxy holds the string denoting the proxy edge name in mutations.
EdgeProxy = "proxy"
// EdgeParent holds the string denoting the parent edge name in mutations.
EdgeParent = "parent"
// EdgeChildren holds the string denoting the children edge name in mutations.
EdgeChildren = "children"
// EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations.
EdgeUsageLogs = "usage_logs"
// EdgeAccountGroups holds the string denoting the account_groups edge name in mutations.
@@ -95,6 +104,14 @@ const (
ProxyInverseTable = "proxies"
// ProxyColumn is the table column denoting the proxy relation/edge.
ProxyColumn = "proxy_id"
// ParentTable is the table that holds the parent relation/edge.
ParentTable = "accounts"
// ParentColumn is the table column denoting the parent relation/edge.
ParentColumn = "parent_account_id"
// ChildrenTable is the table that holds the children relation/edge.
ChildrenTable = "accounts"
// ChildrenColumn is the table column denoting the children relation/edge.
ChildrenColumn = "parent_account_id"
// UsageLogsTable is the table that holds the usage_logs relation/edge.
UsageLogsTable = "usage_logs"
// UsageLogsInverseTable is the table name for the UsageLog entity.
@@ -143,6 +160,8 @@ var Columns = []string{
FieldSessionWindowStart,
FieldSessionWindowEnd,
FieldSessionWindowStatus,
FieldParentAccountID,
FieldQuotaDimension,
}
var (
@@ -203,6 +222,32 @@ var (
SessionWindowStatusValidator func(string) error
)
// QuotaDimension defines the type for the "quota_dimension" enum field.
type QuotaDimension string
// QuotaDimensionGlobal is the default value of the QuotaDimension enum.
const DefaultQuotaDimension = QuotaDimensionGlobal
// QuotaDimension values.
const (
QuotaDimensionGlobal QuotaDimension = "global"
QuotaDimensionSpark QuotaDimension = "spark"
)
func (qd QuotaDimension) String() string {
return string(qd)
}
// QuotaDimensionValidator is a validator for the "quota_dimension" field enum values. It is called by the builders before save.
func QuotaDimensionValidator(qd QuotaDimension) error {
switch qd {
case QuotaDimensionGlobal, QuotaDimensionSpark:
return nil
default:
return fmt.Errorf("account: invalid enum value for quota_dimension field: %q", qd)
}
}
// OrderOption defines the ordering options for the Account queries.
type OrderOption func(*sql.Selector)
@@ -346,6 +391,16 @@ func BySessionWindowStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSessionWindowStatus, opts...).ToFunc()
}
// ByParentAccountID orders the results by the parent_account_id field.
func ByParentAccountID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldParentAccountID, opts...).ToFunc()
}
// ByQuotaDimension orders the results by the quota_dimension field.
func ByQuotaDimension(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldQuotaDimension, opts...).ToFunc()
}
// ByGroupsCount orders the results by groups count.
func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
@@ -367,6 +422,27 @@ func ByProxyField(field string, opts ...sql.OrderTermOption) OrderOption {
}
}
// ByParentField orders the results by parent field.
func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...))
}
}
// ByChildrenCount orders the results by children count.
func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newChildrenStep(), opts...)
}
}
// ByChildren orders the results by children terms.
func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newChildrenStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByUsageLogsCount orders the results by usage_logs count.
func ByUsageLogsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
@@ -408,6 +484,20 @@ func newProxyStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2O, false, ProxyTable, ProxyColumn),
)
}
func newParentStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
)
}
func newChildrenStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
)
}
func newUsageLogsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
+101
View File
@@ -190,6 +190,11 @@ func SessionWindowStatus(v string) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldSessionWindowStatus, v))
}
// ParentAccountID applies equality check predicate on the "parent_account_id" field. It's identical to ParentAccountIDEQ.
func ParentAccountID(v int64) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldParentAccountID, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldCreatedAt, v))
@@ -1550,6 +1555,56 @@ func SessionWindowStatusContainsFold(v string) predicate.Account {
return predicate.Account(sql.FieldContainsFold(FieldSessionWindowStatus, v))
}
// ParentAccountIDEQ applies the EQ predicate on the "parent_account_id" field.
func ParentAccountIDEQ(v int64) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldParentAccountID, v))
}
// ParentAccountIDNEQ applies the NEQ predicate on the "parent_account_id" field.
func ParentAccountIDNEQ(v int64) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldParentAccountID, v))
}
// ParentAccountIDIn applies the In predicate on the "parent_account_id" field.
func ParentAccountIDIn(vs ...int64) predicate.Account {
return predicate.Account(sql.FieldIn(FieldParentAccountID, vs...))
}
// ParentAccountIDNotIn applies the NotIn predicate on the "parent_account_id" field.
func ParentAccountIDNotIn(vs ...int64) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldParentAccountID, vs...))
}
// ParentAccountIDIsNil applies the IsNil predicate on the "parent_account_id" field.
func ParentAccountIDIsNil() predicate.Account {
return predicate.Account(sql.FieldIsNull(FieldParentAccountID))
}
// ParentAccountIDNotNil applies the NotNil predicate on the "parent_account_id" field.
func ParentAccountIDNotNil() predicate.Account {
return predicate.Account(sql.FieldNotNull(FieldParentAccountID))
}
// QuotaDimensionEQ applies the EQ predicate on the "quota_dimension" field.
func QuotaDimensionEQ(v QuotaDimension) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldQuotaDimension, v))
}
// QuotaDimensionNEQ applies the NEQ predicate on the "quota_dimension" field.
func QuotaDimensionNEQ(v QuotaDimension) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldQuotaDimension, v))
}
// QuotaDimensionIn applies the In predicate on the "quota_dimension" field.
func QuotaDimensionIn(vs ...QuotaDimension) predicate.Account {
return predicate.Account(sql.FieldIn(FieldQuotaDimension, vs...))
}
// QuotaDimensionNotIn applies the NotIn predicate on the "quota_dimension" field.
func QuotaDimensionNotIn(vs ...QuotaDimension) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldQuotaDimension, vs...))
}
// HasGroups applies the HasEdge predicate on the "groups" edge.
func HasGroups() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
@@ -1596,6 +1651,52 @@ func HasProxyWith(preds ...predicate.Proxy) predicate.Account {
})
}
// HasParent applies the HasEdge predicate on the "parent" edge.
func HasParent() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates).
func HasParentWith(preds ...predicate.Account) predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := newParentStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasChildren applies the HasEdge predicate on the "children" edge.
func HasChildren() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates).
func HasChildrenWith(preds ...predicate.Account) predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := newChildrenStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasUsageLogs applies the HasEdge predicate on the "usage_logs" edge.
func HasUsageLogs() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
+211
View File
@@ -391,6 +391,34 @@ func (_c *AccountCreate) SetNillableSessionWindowStatus(v *string) *AccountCreat
return _c
}
// SetParentAccountID sets the "parent_account_id" field.
func (_c *AccountCreate) SetParentAccountID(v int64) *AccountCreate {
_c.mutation.SetParentAccountID(v)
return _c
}
// SetNillableParentAccountID sets the "parent_account_id" field if the given value is not nil.
func (_c *AccountCreate) SetNillableParentAccountID(v *int64) *AccountCreate {
if v != nil {
_c.SetParentAccountID(*v)
}
return _c
}
// SetQuotaDimension sets the "quota_dimension" field.
func (_c *AccountCreate) SetQuotaDimension(v account.QuotaDimension) *AccountCreate {
_c.mutation.SetQuotaDimension(v)
return _c
}
// SetNillableQuotaDimension sets the "quota_dimension" field if the given value is not nil.
func (_c *AccountCreate) SetNillableQuotaDimension(v *account.QuotaDimension) *AccountCreate {
if v != nil {
_c.SetQuotaDimension(*v)
}
return _c
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_c *AccountCreate) AddGroupIDs(ids ...int64) *AccountCreate {
_c.mutation.AddGroupIDs(ids...)
@@ -411,6 +439,40 @@ func (_c *AccountCreate) SetProxy(v *Proxy) *AccountCreate {
return _c.SetProxyID(v.ID)
}
// SetParentID sets the "parent" edge to the Account entity by ID.
func (_c *AccountCreate) SetParentID(id int64) *AccountCreate {
_c.mutation.SetParentID(id)
return _c
}
// SetNillableParentID sets the "parent" edge to the Account entity by ID if the given value is not nil.
func (_c *AccountCreate) SetNillableParentID(id *int64) *AccountCreate {
if id != nil {
_c = _c.SetParentID(*id)
}
return _c
}
// SetParent sets the "parent" edge to the Account entity.
func (_c *AccountCreate) SetParent(v *Account) *AccountCreate {
return _c.SetParentID(v.ID)
}
// AddChildIDs adds the "children" edge to the Account entity by IDs.
func (_c *AccountCreate) AddChildIDs(ids ...int64) *AccountCreate {
_c.mutation.AddChildIDs(ids...)
return _c
}
// AddChildren adds the "children" edges to the Account entity.
func (_c *AccountCreate) AddChildren(v ...*Account) *AccountCreate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddChildIDs(ids...)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_c *AccountCreate) AddUsageLogIDs(ids ...int64) *AccountCreate {
_c.mutation.AddUsageLogIDs(ids...)
@@ -515,6 +577,10 @@ func (_c *AccountCreate) defaults() error {
v := account.DefaultSchedulable
_c.mutation.SetSchedulable(v)
}
if _, ok := _c.mutation.QuotaDimension(); !ok {
v := account.DefaultQuotaDimension
_c.mutation.SetQuotaDimension(v)
}
return nil
}
@@ -584,6 +650,14 @@ func (_c *AccountCreate) check() error {
return &ValidationError{Name: "session_window_status", err: fmt.Errorf(`ent: validator failed for field "Account.session_window_status": %w`, err)}
}
}
if _, ok := _c.mutation.QuotaDimension(); !ok {
return &ValidationError{Name: "quota_dimension", err: errors.New(`ent: missing required field "Account.quota_dimension"`)}
}
if v, ok := _c.mutation.QuotaDimension(); ok {
if err := account.QuotaDimensionValidator(v); err != nil {
return &ValidationError{Name: "quota_dimension", err: fmt.Errorf(`ent: validator failed for field "Account.quota_dimension": %w`, err)}
}
}
return nil
}
@@ -723,6 +797,10 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
_spec.SetField(account.FieldSessionWindowStatus, field.TypeString, value)
_node.SessionWindowStatus = &value
}
if value, ok := _c.mutation.QuotaDimension(); ok {
_spec.SetField(account.FieldQuotaDimension, field.TypeEnum, value)
_node.QuotaDimension = value
}
if nodes := _c.mutation.GroupsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
@@ -760,6 +838,39 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
_node.ProxyID = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: account.ParentTable,
Columns: []string{account.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.ParentAccountID = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -1290,6 +1401,36 @@ func (u *AccountUpsert) ClearSessionWindowStatus() *AccountUpsert {
return u
}
// SetParentAccountID sets the "parent_account_id" field.
func (u *AccountUpsert) SetParentAccountID(v int64) *AccountUpsert {
u.Set(account.FieldParentAccountID, v)
return u
}
// UpdateParentAccountID sets the "parent_account_id" field to the value that was provided on create.
func (u *AccountUpsert) UpdateParentAccountID() *AccountUpsert {
u.SetExcluded(account.FieldParentAccountID)
return u
}
// ClearParentAccountID clears the value of the "parent_account_id" field.
func (u *AccountUpsert) ClearParentAccountID() *AccountUpsert {
u.SetNull(account.FieldParentAccountID)
return u
}
// SetQuotaDimension sets the "quota_dimension" field.
func (u *AccountUpsert) SetQuotaDimension(v account.QuotaDimension) *AccountUpsert {
u.Set(account.FieldQuotaDimension, v)
return u
}
// UpdateQuotaDimension sets the "quota_dimension" field to the value that was provided on create.
func (u *AccountUpsert) UpdateQuotaDimension() *AccountUpsert {
u.SetExcluded(account.FieldQuotaDimension)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
@@ -1874,6 +2015,41 @@ func (u *AccountUpsertOne) ClearSessionWindowStatus() *AccountUpsertOne {
})
}
// SetParentAccountID sets the "parent_account_id" field.
func (u *AccountUpsertOne) SetParentAccountID(v int64) *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
s.SetParentAccountID(v)
})
}
// UpdateParentAccountID sets the "parent_account_id" field to the value that was provided on create.
func (u *AccountUpsertOne) UpdateParentAccountID() *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
s.UpdateParentAccountID()
})
}
// ClearParentAccountID clears the value of the "parent_account_id" field.
func (u *AccountUpsertOne) ClearParentAccountID() *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
s.ClearParentAccountID()
})
}
// SetQuotaDimension sets the "quota_dimension" field.
func (u *AccountUpsertOne) SetQuotaDimension(v account.QuotaDimension) *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
s.SetQuotaDimension(v)
})
}
// UpdateQuotaDimension sets the "quota_dimension" field to the value that was provided on create.
func (u *AccountUpsertOne) UpdateQuotaDimension() *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
s.UpdateQuotaDimension()
})
}
// Exec executes the query.
func (u *AccountUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
@@ -2624,6 +2800,41 @@ func (u *AccountUpsertBulk) ClearSessionWindowStatus() *AccountUpsertBulk {
})
}
// SetParentAccountID sets the "parent_account_id" field.
func (u *AccountUpsertBulk) SetParentAccountID(v int64) *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
s.SetParentAccountID(v)
})
}
// UpdateParentAccountID sets the "parent_account_id" field to the value that was provided on create.
func (u *AccountUpsertBulk) UpdateParentAccountID() *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
s.UpdateParentAccountID()
})
}
// ClearParentAccountID clears the value of the "parent_account_id" field.
func (u *AccountUpsertBulk) ClearParentAccountID() *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
s.ClearParentAccountID()
})
}
// SetQuotaDimension sets the "quota_dimension" field.
func (u *AccountUpsertBulk) SetQuotaDimension(v account.QuotaDimension) *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
s.SetQuotaDimension(v)
})
}
// UpdateQuotaDimension sets the "quota_dimension" field to the value that was provided on create.
func (u *AccountUpsertBulk) UpdateQuotaDimension() *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
s.UpdateQuotaDimension()
})
}
// Exec executes the query.
func (u *AccountUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
+154 -1
View File
@@ -30,6 +30,8 @@ type AccountQuery struct {
predicates []predicate.Account
withGroups *GroupQuery
withProxy *ProxyQuery
withParent *AccountQuery
withChildren *AccountQuery
withUsageLogs *UsageLogQuery
withAccountGroups *AccountGroupQuery
modifiers []func(*sql.Selector)
@@ -113,6 +115,50 @@ func (_q *AccountQuery) QueryProxy() *ProxyQuery {
return query
}
// QueryParent chains the current query on the "parent" edge.
func (_q *AccountQuery) QueryParent() *AccountQuery {
query := (&AccountClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, account.ParentTable, account.ParentColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryChildren chains the current query on the "children" edge.
func (_q *AccountQuery) QueryChildren() *AccountQuery {
query := (&AccountClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, account.ChildrenTable, account.ChildrenColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryUsageLogs chains the current query on the "usage_logs" edge.
func (_q *AccountQuery) QueryUsageLogs() *UsageLogQuery {
query := (&UsageLogClient{config: _q.config}).Query()
@@ -351,6 +397,8 @@ func (_q *AccountQuery) Clone() *AccountQuery {
predicates: append([]predicate.Account{}, _q.predicates...),
withGroups: _q.withGroups.Clone(),
withProxy: _q.withProxy.Clone(),
withParent: _q.withParent.Clone(),
withChildren: _q.withChildren.Clone(),
withUsageLogs: _q.withUsageLogs.Clone(),
withAccountGroups: _q.withAccountGroups.Clone(),
// clone intermediate query.
@@ -381,6 +429,28 @@ func (_q *AccountQuery) WithProxy(opts ...func(*ProxyQuery)) *AccountQuery {
return _q
}
// WithParent tells the query-builder to eager-load the nodes that are connected to
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithParent(opts ...func(*AccountQuery)) *AccountQuery {
query := (&AccountClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withParent = query
return _q
}
// WithChildren tells the query-builder to eager-load the nodes that are connected to
// the "children" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithChildren(opts ...func(*AccountQuery)) *AccountQuery {
query := (&AccountClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withChildren = query
return _q
}
// WithUsageLogs tells the query-builder to eager-load the nodes that are connected to
// the "usage_logs" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithUsageLogs(opts ...func(*UsageLogQuery)) *AccountQuery {
@@ -481,9 +551,11 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
var (
nodes = []*Account{}
_spec = _q.querySpec()
loadedTypes = [4]bool{
loadedTypes = [6]bool{
_q.withGroups != nil,
_q.withProxy != nil,
_q.withParent != nil,
_q.withChildren != nil,
_q.withUsageLogs != nil,
_q.withAccountGroups != nil,
}
@@ -522,6 +594,19 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
return nil, err
}
}
if query := _q.withParent; query != nil {
if err := _q.loadParent(ctx, query, nodes, nil,
func(n *Account, e *Account) { n.Edges.Parent = e }); err != nil {
return nil, err
}
}
if query := _q.withChildren; query != nil {
if err := _q.loadChildren(ctx, query, nodes,
func(n *Account) { n.Edges.Children = []*Account{} },
func(n *Account, e *Account) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil {
return nil, err
}
}
if query := _q.withUsageLogs; query != nil {
if err := _q.loadUsageLogs(ctx, query, nodes,
func(n *Account) { n.Edges.UsageLogs = []*UsageLog{} },
@@ -632,6 +717,71 @@ func (_q *AccountQuery) loadProxy(ctx context.Context, query *ProxyQuery, nodes
}
return nil
}
func (_q *AccountQuery) loadParent(ctx context.Context, query *AccountQuery, nodes []*Account, init func(*Account), assign func(*Account, *Account)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*Account)
for i := range nodes {
if nodes[i].ParentAccountID == nil {
continue
}
fk := *nodes[i].ParentAccountID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(account.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "parent_account_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *AccountQuery) loadChildren(ctx context.Context, query *AccountQuery, nodes []*Account, init func(*Account), assign func(*Account, *Account)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*Account)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
if len(query.ctx.Fields) > 0 {
query.ctx.AppendFieldOnce(account.FieldParentAccountID)
}
query.Where(predicate.Account(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(account.ChildrenColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.ParentAccountID
if fk == nil {
return fmt.Errorf(`foreign-key "parent_account_id" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "parent_account_id" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *AccountQuery) loadUsageLogs(ctx context.Context, query *UsageLogQuery, nodes []*Account, init func(*Account), assign func(*Account, *UsageLog)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*Account)
@@ -724,6 +874,9 @@ func (_q *AccountQuery) querySpec() *sqlgraph.QuerySpec {
if _q.withProxy != nil {
_spec.Node.AddColumnOnce(account.FieldProxyID)
}
if _q.withParent != nil {
_spec.Node.AddColumnOnce(account.FieldParentAccountID)
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
+354
View File
@@ -530,6 +530,40 @@ func (_u *AccountUpdate) ClearSessionWindowStatus() *AccountUpdate {
return _u
}
// SetParentAccountID sets the "parent_account_id" field.
func (_u *AccountUpdate) SetParentAccountID(v int64) *AccountUpdate {
_u.mutation.SetParentAccountID(v)
return _u
}
// SetNillableParentAccountID sets the "parent_account_id" field if the given value is not nil.
func (_u *AccountUpdate) SetNillableParentAccountID(v *int64) *AccountUpdate {
if v != nil {
_u.SetParentAccountID(*v)
}
return _u
}
// ClearParentAccountID clears the value of the "parent_account_id" field.
func (_u *AccountUpdate) ClearParentAccountID() *AccountUpdate {
_u.mutation.ClearParentAccountID()
return _u
}
// SetQuotaDimension sets the "quota_dimension" field.
func (_u *AccountUpdate) SetQuotaDimension(v account.QuotaDimension) *AccountUpdate {
_u.mutation.SetQuotaDimension(v)
return _u
}
// SetNillableQuotaDimension sets the "quota_dimension" field if the given value is not nil.
func (_u *AccountUpdate) SetNillableQuotaDimension(v *account.QuotaDimension) *AccountUpdate {
if v != nil {
_u.SetQuotaDimension(*v)
}
return _u
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_u *AccountUpdate) AddGroupIDs(ids ...int64) *AccountUpdate {
_u.mutation.AddGroupIDs(ids...)
@@ -550,6 +584,40 @@ func (_u *AccountUpdate) SetProxy(v *Proxy) *AccountUpdate {
return _u.SetProxyID(v.ID)
}
// SetParentID sets the "parent" edge to the Account entity by ID.
func (_u *AccountUpdate) SetParentID(id int64) *AccountUpdate {
_u.mutation.SetParentID(id)
return _u
}
// SetNillableParentID sets the "parent" edge to the Account entity by ID if the given value is not nil.
func (_u *AccountUpdate) SetNillableParentID(id *int64) *AccountUpdate {
if id != nil {
_u = _u.SetParentID(*id)
}
return _u
}
// SetParent sets the "parent" edge to the Account entity.
func (_u *AccountUpdate) SetParent(v *Account) *AccountUpdate {
return _u.SetParentID(v.ID)
}
// AddChildIDs adds the "children" edge to the Account entity by IDs.
func (_u *AccountUpdate) AddChildIDs(ids ...int64) *AccountUpdate {
_u.mutation.AddChildIDs(ids...)
return _u
}
// AddChildren adds the "children" edges to the Account entity.
func (_u *AccountUpdate) AddChildren(v ...*Account) *AccountUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddChildIDs(ids...)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *AccountUpdate) AddUsageLogIDs(ids ...int64) *AccountUpdate {
_u.mutation.AddUsageLogIDs(ids...)
@@ -597,6 +665,33 @@ func (_u *AccountUpdate) ClearProxy() *AccountUpdate {
return _u
}
// ClearParent clears the "parent" edge to the Account entity.
func (_u *AccountUpdate) ClearParent() *AccountUpdate {
_u.mutation.ClearParent()
return _u
}
// ClearChildren clears all "children" edges to the Account entity.
func (_u *AccountUpdate) ClearChildren() *AccountUpdate {
_u.mutation.ClearChildren()
return _u
}
// RemoveChildIDs removes the "children" edge to Account entities by IDs.
func (_u *AccountUpdate) RemoveChildIDs(ids ...int64) *AccountUpdate {
_u.mutation.RemoveChildIDs(ids...)
return _u
}
// RemoveChildren removes "children" edges to Account entities.
func (_u *AccountUpdate) RemoveChildren(v ...*Account) *AccountUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveChildIDs(ids...)
}
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *AccountUpdate) ClearUsageLogs() *AccountUpdate {
_u.mutation.ClearUsageLogs()
@@ -687,6 +782,11 @@ func (_u *AccountUpdate) check() error {
return &ValidationError{Name: "session_window_status", err: fmt.Errorf(`ent: validator failed for field "Account.session_window_status": %w`, err)}
}
}
if v, ok := _u.mutation.QuotaDimension(); ok {
if err := account.QuotaDimensionValidator(v); err != nil {
return &ValidationError{Name: "quota_dimension", err: fmt.Errorf(`ent: validator failed for field "Account.quota_dimension": %w`, err)}
}
}
return nil
}
@@ -843,6 +943,9 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if _u.mutation.SessionWindowStatusCleared() {
_spec.ClearField(account.FieldSessionWindowStatus, field.TypeString)
}
if value, ok := _u.mutation.QuotaDimension(); ok {
_spec.SetField(account.FieldQuotaDimension, field.TypeEnum, value)
}
if _u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
@@ -929,6 +1032,80 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ParentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: account.ParentTable,
Columns: []string{account.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: account.ParentTable,
Columns: []string{account.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -1493,6 +1670,40 @@ func (_u *AccountUpdateOne) ClearSessionWindowStatus() *AccountUpdateOne {
return _u
}
// SetParentAccountID sets the "parent_account_id" field.
func (_u *AccountUpdateOne) SetParentAccountID(v int64) *AccountUpdateOne {
_u.mutation.SetParentAccountID(v)
return _u
}
// SetNillableParentAccountID sets the "parent_account_id" field if the given value is not nil.
func (_u *AccountUpdateOne) SetNillableParentAccountID(v *int64) *AccountUpdateOne {
if v != nil {
_u.SetParentAccountID(*v)
}
return _u
}
// ClearParentAccountID clears the value of the "parent_account_id" field.
func (_u *AccountUpdateOne) ClearParentAccountID() *AccountUpdateOne {
_u.mutation.ClearParentAccountID()
return _u
}
// SetQuotaDimension sets the "quota_dimension" field.
func (_u *AccountUpdateOne) SetQuotaDimension(v account.QuotaDimension) *AccountUpdateOne {
_u.mutation.SetQuotaDimension(v)
return _u
}
// SetNillableQuotaDimension sets the "quota_dimension" field if the given value is not nil.
func (_u *AccountUpdateOne) SetNillableQuotaDimension(v *account.QuotaDimension) *AccountUpdateOne {
if v != nil {
_u.SetQuotaDimension(*v)
}
return _u
}
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
func (_u *AccountUpdateOne) AddGroupIDs(ids ...int64) *AccountUpdateOne {
_u.mutation.AddGroupIDs(ids...)
@@ -1513,6 +1724,40 @@ func (_u *AccountUpdateOne) SetProxy(v *Proxy) *AccountUpdateOne {
return _u.SetProxyID(v.ID)
}
// SetParentID sets the "parent" edge to the Account entity by ID.
func (_u *AccountUpdateOne) SetParentID(id int64) *AccountUpdateOne {
_u.mutation.SetParentID(id)
return _u
}
// SetNillableParentID sets the "parent" edge to the Account entity by ID if the given value is not nil.
func (_u *AccountUpdateOne) SetNillableParentID(id *int64) *AccountUpdateOne {
if id != nil {
_u = _u.SetParentID(*id)
}
return _u
}
// SetParent sets the "parent" edge to the Account entity.
func (_u *AccountUpdateOne) SetParent(v *Account) *AccountUpdateOne {
return _u.SetParentID(v.ID)
}
// AddChildIDs adds the "children" edge to the Account entity by IDs.
func (_u *AccountUpdateOne) AddChildIDs(ids ...int64) *AccountUpdateOne {
_u.mutation.AddChildIDs(ids...)
return _u
}
// AddChildren adds the "children" edges to the Account entity.
func (_u *AccountUpdateOne) AddChildren(v ...*Account) *AccountUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddChildIDs(ids...)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *AccountUpdateOne) AddUsageLogIDs(ids ...int64) *AccountUpdateOne {
_u.mutation.AddUsageLogIDs(ids...)
@@ -1560,6 +1805,33 @@ func (_u *AccountUpdateOne) ClearProxy() *AccountUpdateOne {
return _u
}
// ClearParent clears the "parent" edge to the Account entity.
func (_u *AccountUpdateOne) ClearParent() *AccountUpdateOne {
_u.mutation.ClearParent()
return _u
}
// ClearChildren clears all "children" edges to the Account entity.
func (_u *AccountUpdateOne) ClearChildren() *AccountUpdateOne {
_u.mutation.ClearChildren()
return _u
}
// RemoveChildIDs removes the "children" edge to Account entities by IDs.
func (_u *AccountUpdateOne) RemoveChildIDs(ids ...int64) *AccountUpdateOne {
_u.mutation.RemoveChildIDs(ids...)
return _u
}
// RemoveChildren removes "children" edges to Account entities.
func (_u *AccountUpdateOne) RemoveChildren(v ...*Account) *AccountUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveChildIDs(ids...)
}
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *AccountUpdateOne) ClearUsageLogs() *AccountUpdateOne {
_u.mutation.ClearUsageLogs()
@@ -1663,6 +1935,11 @@ func (_u *AccountUpdateOne) check() error {
return &ValidationError{Name: "session_window_status", err: fmt.Errorf(`ent: validator failed for field "Account.session_window_status": %w`, err)}
}
}
if v, ok := _u.mutation.QuotaDimension(); ok {
if err := account.QuotaDimensionValidator(v); err != nil {
return &ValidationError{Name: "quota_dimension", err: fmt.Errorf(`ent: validator failed for field "Account.quota_dimension": %w`, err)}
}
}
return nil
}
@@ -1836,6 +2113,9 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
if _u.mutation.SessionWindowStatusCleared() {
_spec.ClearField(account.FieldSessionWindowStatus, field.TypeString)
}
if value, ok := _u.mutation.QuotaDimension(); ok {
_spec.SetField(account.FieldQuotaDimension, field.TypeEnum, value)
}
if _u.mutation.GroupsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
@@ -1922,6 +2202,80 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ParentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: account.ParentTable,
Columns: []string{account.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: account.ParentTable,
Columns: []string{account.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.ChildrenTable,
Columns: []string{account.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
+12 -1
View File
@@ -43,6 +43,8 @@ type ChannelMonitor struct {
Enabled bool `json:"enabled,omitempty"`
// IntervalSeconds holds the value of the "interval_seconds" field.
IntervalSeconds int `json:"interval_seconds,omitempty"`
// 每次调度在 interval 基础上 ± [0, jitter] 的均匀随机偏移(秒);0 表示固定间隔。service 层另保证 interval - jitter >= 15
JitterSeconds int `json:"jitter_seconds,omitempty"`
// LastCheckedAt holds the value of the "last_checked_at" field.
LastCheckedAt *time.Time `json:"last_checked_at,omitempty"`
// CreatedBy holds the value of the "created_by" field.
@@ -112,7 +114,7 @@ func (*ChannelMonitor) scanValues(columns []string) ([]any, error) {
values[i] = new([]byte)
case channelmonitor.FieldEnabled:
values[i] = new(sql.NullBool)
case channelmonitor.FieldID, channelmonitor.FieldIntervalSeconds, channelmonitor.FieldCreatedBy, channelmonitor.FieldTemplateID:
case channelmonitor.FieldID, channelmonitor.FieldIntervalSeconds, channelmonitor.FieldJitterSeconds, channelmonitor.FieldCreatedBy, channelmonitor.FieldTemplateID:
values[i] = new(sql.NullInt64)
case channelmonitor.FieldName, channelmonitor.FieldProvider, channelmonitor.FieldAPIMode, channelmonitor.FieldEndpoint, channelmonitor.FieldAPIKeyEncrypted, channelmonitor.FieldPrimaryModel, channelmonitor.FieldGroupName, channelmonitor.FieldBodyOverrideMode:
values[i] = new(sql.NullString)
@@ -213,6 +215,12 @@ func (_m *ChannelMonitor) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.IntervalSeconds = int(value.Int64)
}
case channelmonitor.FieldJitterSeconds:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field jitter_seconds", values[i])
} else if value.Valid {
_m.JitterSeconds = int(value.Int64)
}
case channelmonitor.FieldLastCheckedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field last_checked_at", values[i])
@@ -341,6 +349,9 @@ func (_m *ChannelMonitor) String() string {
builder.WriteString("interval_seconds=")
builder.WriteString(fmt.Sprintf("%v", _m.IntervalSeconds))
builder.WriteString(", ")
builder.WriteString("jitter_seconds=")
builder.WriteString(fmt.Sprintf("%v", _m.JitterSeconds))
builder.WriteString(", ")
if v := _m.LastCheckedAt; v != nil {
builder.WriteString("last_checked_at=")
builder.WriteString(v.Format(time.ANSIC))
@@ -39,6 +39,8 @@ const (
FieldEnabled = "enabled"
// FieldIntervalSeconds holds the string denoting the interval_seconds field in the database.
FieldIntervalSeconds = "interval_seconds"
// FieldJitterSeconds holds the string denoting the jitter_seconds field in the database.
FieldJitterSeconds = "jitter_seconds"
// FieldLastCheckedAt holds the string denoting the last_checked_at field in the database.
FieldLastCheckedAt = "last_checked_at"
// FieldCreatedBy holds the string denoting the created_by field in the database.
@@ -97,6 +99,7 @@ var Columns = []string{
FieldGroupName,
FieldEnabled,
FieldIntervalSeconds,
FieldJitterSeconds,
FieldLastCheckedAt,
FieldCreatedBy,
FieldTemplateID,
@@ -144,6 +147,10 @@ var (
DefaultEnabled bool
// IntervalSecondsValidator is a validator for the "interval_seconds" field. It is called by the builders before save.
IntervalSecondsValidator func(int) error
// DefaultJitterSeconds holds the default value on creation for the "jitter_seconds" field.
DefaultJitterSeconds int
// JitterSecondsValidator is a validator for the "jitter_seconds" field. It is called by the builders before save.
JitterSecondsValidator func(int) error
// DefaultExtraHeaders holds the default value on creation for the "extra_headers" field.
DefaultExtraHeaders map[string]string
// DefaultBodyOverrideMode holds the default value on creation for the "body_override_mode" field.
@@ -239,6 +246,11 @@ func ByIntervalSeconds(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldIntervalSeconds, opts...).ToFunc()
}
// ByJitterSeconds orders the results by the jitter_seconds field.
func ByJitterSeconds(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldJitterSeconds, opts...).ToFunc()
}
// ByLastCheckedAt orders the results by the last_checked_at field.
func ByLastCheckedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLastCheckedAt, opts...).ToFunc()
+45
View File
@@ -105,6 +105,11 @@ func IntervalSeconds(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldEQ(FieldIntervalSeconds, v))
}
// JitterSeconds applies equality check predicate on the "jitter_seconds" field. It's identical to JitterSecondsEQ.
func JitterSeconds(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldEQ(FieldJitterSeconds, v))
}
// LastCheckedAt applies equality check predicate on the "last_checked_at" field. It's identical to LastCheckedAtEQ.
func LastCheckedAt(v time.Time) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldEQ(FieldLastCheckedAt, v))
@@ -675,6 +680,46 @@ func IntervalSecondsLTE(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldLTE(FieldIntervalSeconds, v))
}
// JitterSecondsEQ applies the EQ predicate on the "jitter_seconds" field.
func JitterSecondsEQ(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldEQ(FieldJitterSeconds, v))
}
// JitterSecondsNEQ applies the NEQ predicate on the "jitter_seconds" field.
func JitterSecondsNEQ(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldNEQ(FieldJitterSeconds, v))
}
// JitterSecondsIn applies the In predicate on the "jitter_seconds" field.
func JitterSecondsIn(vs ...int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldIn(FieldJitterSeconds, vs...))
}
// JitterSecondsNotIn applies the NotIn predicate on the "jitter_seconds" field.
func JitterSecondsNotIn(vs ...int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldNotIn(FieldJitterSeconds, vs...))
}
// JitterSecondsGT applies the GT predicate on the "jitter_seconds" field.
func JitterSecondsGT(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldGT(FieldJitterSeconds, v))
}
// JitterSecondsGTE applies the GTE predicate on the "jitter_seconds" field.
func JitterSecondsGTE(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldGTE(FieldJitterSeconds, v))
}
// JitterSecondsLT applies the LT predicate on the "jitter_seconds" field.
func JitterSecondsLT(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldLT(FieldJitterSeconds, v))
}
// JitterSecondsLTE applies the LTE predicate on the "jitter_seconds" field.
func JitterSecondsLTE(v int) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldLTE(FieldJitterSeconds, v))
}
// LastCheckedAtEQ applies the EQ predicate on the "last_checked_at" field.
func LastCheckedAtEQ(v time.Time) predicate.ChannelMonitor {
return predicate.ChannelMonitor(sql.FieldEQ(FieldLastCheckedAt, v))
+90
View File
@@ -137,6 +137,20 @@ func (_c *ChannelMonitorCreate) SetIntervalSeconds(v int) *ChannelMonitorCreate
return _c
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (_c *ChannelMonitorCreate) SetJitterSeconds(v int) *ChannelMonitorCreate {
_c.mutation.SetJitterSeconds(v)
return _c
}
// SetNillableJitterSeconds sets the "jitter_seconds" field if the given value is not nil.
func (_c *ChannelMonitorCreate) SetNillableJitterSeconds(v *int) *ChannelMonitorCreate {
if v != nil {
_c.SetJitterSeconds(*v)
}
return _c
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (_c *ChannelMonitorCreate) SetLastCheckedAt(v time.Time) *ChannelMonitorCreate {
_c.mutation.SetLastCheckedAt(v)
@@ -305,6 +319,10 @@ func (_c *ChannelMonitorCreate) defaults() {
v := channelmonitor.DefaultEnabled
_c.mutation.SetEnabled(v)
}
if _, ok := _c.mutation.JitterSeconds(); !ok {
v := channelmonitor.DefaultJitterSeconds
_c.mutation.SetJitterSeconds(v)
}
if _, ok := _c.mutation.ExtraHeaders(); !ok {
v := channelmonitor.DefaultExtraHeaders
_c.mutation.SetExtraHeaders(v)
@@ -390,6 +408,14 @@ func (_c *ChannelMonitorCreate) check() error {
return &ValidationError{Name: "interval_seconds", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.interval_seconds": %w`, err)}
}
}
if _, ok := _c.mutation.JitterSeconds(); !ok {
return &ValidationError{Name: "jitter_seconds", err: errors.New(`ent: missing required field "ChannelMonitor.jitter_seconds"`)}
}
if v, ok := _c.mutation.JitterSeconds(); ok {
if err := channelmonitor.JitterSecondsValidator(v); err != nil {
return &ValidationError{Name: "jitter_seconds", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.jitter_seconds": %w`, err)}
}
}
if _, ok := _c.mutation.CreatedBy(); !ok {
return &ValidationError{Name: "created_by", err: errors.New(`ent: missing required field "ChannelMonitor.created_by"`)}
}
@@ -479,6 +505,10 @@ func (_c *ChannelMonitorCreate) createSpec() (*ChannelMonitor, *sqlgraph.CreateS
_spec.SetField(channelmonitor.FieldIntervalSeconds, field.TypeInt, value)
_node.IntervalSeconds = value
}
if value, ok := _c.mutation.JitterSeconds(); ok {
_spec.SetField(channelmonitor.FieldJitterSeconds, field.TypeInt, value)
_node.JitterSeconds = value
}
if value, ok := _c.mutation.LastCheckedAt(); ok {
_spec.SetField(channelmonitor.FieldLastCheckedAt, field.TypeTime, value)
_node.LastCheckedAt = &value
@@ -744,6 +774,24 @@ func (u *ChannelMonitorUpsert) AddIntervalSeconds(v int) *ChannelMonitorUpsert {
return u
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (u *ChannelMonitorUpsert) SetJitterSeconds(v int) *ChannelMonitorUpsert {
u.Set(channelmonitor.FieldJitterSeconds, v)
return u
}
// UpdateJitterSeconds sets the "jitter_seconds" field to the value that was provided on create.
func (u *ChannelMonitorUpsert) UpdateJitterSeconds() *ChannelMonitorUpsert {
u.SetExcluded(channelmonitor.FieldJitterSeconds)
return u
}
// AddJitterSeconds adds v to the "jitter_seconds" field.
func (u *ChannelMonitorUpsert) AddJitterSeconds(v int) *ChannelMonitorUpsert {
u.Add(channelmonitor.FieldJitterSeconds, v)
return u
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (u *ChannelMonitorUpsert) SetLastCheckedAt(v time.Time) *ChannelMonitorUpsert {
u.Set(channelmonitor.FieldLastCheckedAt, v)
@@ -1053,6 +1101,27 @@ func (u *ChannelMonitorUpsertOne) UpdateIntervalSeconds() *ChannelMonitorUpsertO
})
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (u *ChannelMonitorUpsertOne) SetJitterSeconds(v int) *ChannelMonitorUpsertOne {
return u.Update(func(s *ChannelMonitorUpsert) {
s.SetJitterSeconds(v)
})
}
// AddJitterSeconds adds v to the "jitter_seconds" field.
func (u *ChannelMonitorUpsertOne) AddJitterSeconds(v int) *ChannelMonitorUpsertOne {
return u.Update(func(s *ChannelMonitorUpsert) {
s.AddJitterSeconds(v)
})
}
// UpdateJitterSeconds sets the "jitter_seconds" field to the value that was provided on create.
func (u *ChannelMonitorUpsertOne) UpdateJitterSeconds() *ChannelMonitorUpsertOne {
return u.Update(func(s *ChannelMonitorUpsert) {
s.UpdateJitterSeconds()
})
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (u *ChannelMonitorUpsertOne) SetLastCheckedAt(v time.Time) *ChannelMonitorUpsertOne {
return u.Update(func(s *ChannelMonitorUpsert) {
@@ -1544,6 +1613,27 @@ func (u *ChannelMonitorUpsertBulk) UpdateIntervalSeconds() *ChannelMonitorUpsert
})
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (u *ChannelMonitorUpsertBulk) SetJitterSeconds(v int) *ChannelMonitorUpsertBulk {
return u.Update(func(s *ChannelMonitorUpsert) {
s.SetJitterSeconds(v)
})
}
// AddJitterSeconds adds v to the "jitter_seconds" field.
func (u *ChannelMonitorUpsertBulk) AddJitterSeconds(v int) *ChannelMonitorUpsertBulk {
return u.Update(func(s *ChannelMonitorUpsert) {
s.AddJitterSeconds(v)
})
}
// UpdateJitterSeconds sets the "jitter_seconds" field to the value that was provided on create.
func (u *ChannelMonitorUpsertBulk) UpdateJitterSeconds() *ChannelMonitorUpsertBulk {
return u.Update(func(s *ChannelMonitorUpsert) {
s.UpdateJitterSeconds()
})
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (u *ChannelMonitorUpsertBulk) SetLastCheckedAt(v time.Time) *ChannelMonitorUpsertBulk {
return u.Update(func(s *ChannelMonitorUpsert) {
+64
View File
@@ -189,6 +189,27 @@ func (_u *ChannelMonitorUpdate) AddIntervalSeconds(v int) *ChannelMonitorUpdate
return _u
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (_u *ChannelMonitorUpdate) SetJitterSeconds(v int) *ChannelMonitorUpdate {
_u.mutation.ResetJitterSeconds()
_u.mutation.SetJitterSeconds(v)
return _u
}
// SetNillableJitterSeconds sets the "jitter_seconds" field if the given value is not nil.
func (_u *ChannelMonitorUpdate) SetNillableJitterSeconds(v *int) *ChannelMonitorUpdate {
if v != nil {
_u.SetJitterSeconds(*v)
}
return _u
}
// AddJitterSeconds adds value to the "jitter_seconds" field.
func (_u *ChannelMonitorUpdate) AddJitterSeconds(v int) *ChannelMonitorUpdate {
_u.mutation.AddJitterSeconds(v)
return _u
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (_u *ChannelMonitorUpdate) SetLastCheckedAt(v time.Time) *ChannelMonitorUpdate {
_u.mutation.SetLastCheckedAt(v)
@@ -462,6 +483,11 @@ func (_u *ChannelMonitorUpdate) check() error {
return &ValidationError{Name: "interval_seconds", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.interval_seconds": %w`, err)}
}
}
if v, ok := _u.mutation.JitterSeconds(); ok {
if err := channelmonitor.JitterSecondsValidator(v); err != nil {
return &ValidationError{Name: "jitter_seconds", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.jitter_seconds": %w`, err)}
}
}
if v, ok := _u.mutation.BodyOverrideMode(); ok {
if err := channelmonitor.BodyOverrideModeValidator(v); err != nil {
return &ValidationError{Name: "body_override_mode", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.body_override_mode": %w`, err)}
@@ -526,6 +552,12 @@ func (_u *ChannelMonitorUpdate) sqlSave(ctx context.Context) (_node int, err err
if value, ok := _u.mutation.AddedIntervalSeconds(); ok {
_spec.AddField(channelmonitor.FieldIntervalSeconds, field.TypeInt, value)
}
if value, ok := _u.mutation.JitterSeconds(); ok {
_spec.SetField(channelmonitor.FieldJitterSeconds, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedJitterSeconds(); ok {
_spec.AddField(channelmonitor.FieldJitterSeconds, field.TypeInt, value)
}
if value, ok := _u.mutation.LastCheckedAt(); ok {
_spec.SetField(channelmonitor.FieldLastCheckedAt, field.TypeTime, value)
}
@@ -846,6 +878,27 @@ func (_u *ChannelMonitorUpdateOne) AddIntervalSeconds(v int) *ChannelMonitorUpda
return _u
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (_u *ChannelMonitorUpdateOne) SetJitterSeconds(v int) *ChannelMonitorUpdateOne {
_u.mutation.ResetJitterSeconds()
_u.mutation.SetJitterSeconds(v)
return _u
}
// SetNillableJitterSeconds sets the "jitter_seconds" field if the given value is not nil.
func (_u *ChannelMonitorUpdateOne) SetNillableJitterSeconds(v *int) *ChannelMonitorUpdateOne {
if v != nil {
_u.SetJitterSeconds(*v)
}
return _u
}
// AddJitterSeconds adds value to the "jitter_seconds" field.
func (_u *ChannelMonitorUpdateOne) AddJitterSeconds(v int) *ChannelMonitorUpdateOne {
_u.mutation.AddJitterSeconds(v)
return _u
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (_u *ChannelMonitorUpdateOne) SetLastCheckedAt(v time.Time) *ChannelMonitorUpdateOne {
_u.mutation.SetLastCheckedAt(v)
@@ -1132,6 +1185,11 @@ func (_u *ChannelMonitorUpdateOne) check() error {
return &ValidationError{Name: "interval_seconds", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.interval_seconds": %w`, err)}
}
}
if v, ok := _u.mutation.JitterSeconds(); ok {
if err := channelmonitor.JitterSecondsValidator(v); err != nil {
return &ValidationError{Name: "jitter_seconds", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.jitter_seconds": %w`, err)}
}
}
if v, ok := _u.mutation.BodyOverrideMode(); ok {
if err := channelmonitor.BodyOverrideModeValidator(v); err != nil {
return &ValidationError{Name: "body_override_mode", err: fmt.Errorf(`ent: validator failed for field "ChannelMonitor.body_override_mode": %w`, err)}
@@ -1213,6 +1271,12 @@ func (_u *ChannelMonitorUpdateOne) sqlSave(ctx context.Context) (_node *ChannelM
if value, ok := _u.mutation.AddedIntervalSeconds(); ok {
_spec.AddField(channelmonitor.FieldIntervalSeconds, field.TypeInt, value)
}
if value, ok := _u.mutation.JitterSeconds(); ok {
_spec.SetField(channelmonitor.FieldJitterSeconds, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedJitterSeconds(); ok {
_spec.AddField(channelmonitor.FieldJitterSeconds, field.TypeInt, value)
}
if value, ok := _u.mutation.LastCheckedAt(); ok {
_spec.SetField(channelmonitor.FieldLastCheckedAt, field.TypeTime, value)
}
+32
View File
@@ -820,6 +820,38 @@ func (c *AccountClient) QueryProxy(_m *Account) *ProxyQuery {
return query
}
// QueryParent queries the parent edge of a Account.
func (c *AccountClient) QueryParent(_m *Account) *AccountQuery {
query := (&AccountClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, id),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, account.ParentTable, account.ParentColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryChildren queries the children edge of a Account.
func (c *AccountClient) QueryChildren(_m *Account) *AccountQuery {
query := (&AccountClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, id),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, account.ChildrenTable, account.ChildrenColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUsageLogs queries the usage_logs edge of a Account.
func (c *AccountClient) QueryUsageLogs(_m *Account) *UsageLogQuery {
query := (&UsageLogClient{config: c.config}).Query()
+47 -3
View File
@@ -31,6 +31,14 @@ type Group struct {
Description *string `json:"description,omitempty"`
// RateMultiplier holds the value of the "rate_multiplier" field.
RateMultiplier float64 `json:"rate_multiplier,omitempty"`
// 是否启用高峰时段倍率
PeakRateEnabled bool `json:"peak_rate_enabled,omitempty"`
// 高峰开始时间 HH:MM(含),如 14:00;空表示未配置
PeakStart string `json:"peak_start,omitempty"`
// 高峰结束时间 HH:MM(不含),如 18:00
PeakEnd string `json:"peak_end,omitempty"`
// 高峰时段叠加倍率,仅在 peak_rate_enabled 且处于 [peak_start, peak_end) 时乘入文本倍率
PeakRateMultiplier float64 `json:"peak_rate_multiplier,omitempty"`
// IsExclusive holds the value of the "is_exclusive" field.
IsExclusive bool `json:"is_exclusive,omitempty"`
// Status holds the value of the "status" field.
@@ -197,13 +205,13 @@ func (*Group) scanValues(columns []string) ([]any, error) {
switch columns[i] {
case group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelsListConfig:
values[i] = new([]byte)
case group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldImageRateIndependent, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet:
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldImageRateIndependent, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet:
values[i] = new(sql.NullBool)
case group.FieldRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k:
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k:
values[i] = new(sql.NullFloat64)
case group.FieldID, group.FieldDefaultValidityDays, group.FieldFallbackGroupID, group.FieldFallbackGroupIDOnInvalidRequest, group.FieldSortOrder, group.FieldRpmLimit:
values[i] = new(sql.NullInt64)
case group.FieldName, group.FieldDescription, group.FieldStatus, group.FieldPlatform, group.FieldSubscriptionType, group.FieldDefaultMappedModel:
case group.FieldName, group.FieldDescription, group.FieldPeakStart, group.FieldPeakEnd, group.FieldStatus, group.FieldPlatform, group.FieldSubscriptionType, group.FieldDefaultMappedModel:
values[i] = new(sql.NullString)
case group.FieldCreatedAt, group.FieldUpdatedAt, group.FieldDeletedAt:
values[i] = new(sql.NullTime)
@@ -266,6 +274,30 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.RateMultiplier = value.Float64
}
case group.FieldPeakRateEnabled:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field peak_rate_enabled", values[i])
} else if value.Valid {
_m.PeakRateEnabled = value.Bool
}
case group.FieldPeakStart:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field peak_start", values[i])
} else if value.Valid {
_m.PeakStart = value.String
}
case group.FieldPeakEnd:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field peak_end", values[i])
} else if value.Valid {
_m.PeakEnd = value.String
}
case group.FieldPeakRateMultiplier:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field peak_rate_multiplier", values[i])
} else if value.Valid {
_m.PeakRateMultiplier = value.Float64
}
case group.FieldIsExclusive:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field is_exclusive", values[i])
@@ -554,6 +586,18 @@ func (_m *Group) String() string {
builder.WriteString("rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", _m.RateMultiplier))
builder.WriteString(", ")
builder.WriteString("peak_rate_enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.PeakRateEnabled))
builder.WriteString(", ")
builder.WriteString("peak_start=")
builder.WriteString(_m.PeakStart)
builder.WriteString(", ")
builder.WriteString("peak_end=")
builder.WriteString(_m.PeakEnd)
builder.WriteString(", ")
builder.WriteString("peak_rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", _m.PeakRateMultiplier))
builder.WriteString(", ")
builder.WriteString("is_exclusive=")
builder.WriteString(fmt.Sprintf("%v", _m.IsExclusive))
builder.WriteString(", ")
+44
View File
@@ -28,6 +28,14 @@ const (
FieldDescription = "description"
// FieldRateMultiplier holds the string denoting the rate_multiplier field in the database.
FieldRateMultiplier = "rate_multiplier"
// FieldPeakRateEnabled holds the string denoting the peak_rate_enabled field in the database.
FieldPeakRateEnabled = "peak_rate_enabled"
// FieldPeakStart holds the string denoting the peak_start field in the database.
FieldPeakStart = "peak_start"
// FieldPeakEnd holds the string denoting the peak_end field in the database.
FieldPeakEnd = "peak_end"
// FieldPeakRateMultiplier holds the string denoting the peak_rate_multiplier field in the database.
FieldPeakRateMultiplier = "peak_rate_multiplier"
// FieldIsExclusive holds the string denoting the is_exclusive field in the database.
FieldIsExclusive = "is_exclusive"
// FieldStatus holds the string denoting the status field in the database.
@@ -167,6 +175,10 @@ var Columns = []string{
FieldName,
FieldDescription,
FieldRateMultiplier,
FieldPeakRateEnabled,
FieldPeakStart,
FieldPeakEnd,
FieldPeakRateMultiplier,
FieldIsExclusive,
FieldStatus,
FieldPlatform,
@@ -235,6 +247,18 @@ var (
NameValidator func(string) error
// DefaultRateMultiplier holds the default value on creation for the "rate_multiplier" field.
DefaultRateMultiplier float64
// DefaultPeakRateEnabled holds the default value on creation for the "peak_rate_enabled" field.
DefaultPeakRateEnabled bool
// DefaultPeakStart holds the default value on creation for the "peak_start" field.
DefaultPeakStart string
// PeakStartValidator is a validator for the "peak_start" field. It is called by the builders before save.
PeakStartValidator func(string) error
// DefaultPeakEnd holds the default value on creation for the "peak_end" field.
DefaultPeakEnd string
// PeakEndValidator is a validator for the "peak_end" field. It is called by the builders before save.
PeakEndValidator func(string) error
// DefaultPeakRateMultiplier holds the default value on creation for the "peak_rate_multiplier" field.
DefaultPeakRateMultiplier float64
// DefaultIsExclusive holds the default value on creation for the "is_exclusive" field.
DefaultIsExclusive bool
// DefaultStatus holds the default value on creation for the "status" field.
@@ -323,6 +347,26 @@ func ByRateMultiplier(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRateMultiplier, opts...).ToFunc()
}
// ByPeakRateEnabled orders the results by the peak_rate_enabled field.
func ByPeakRateEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPeakRateEnabled, opts...).ToFunc()
}
// ByPeakStart orders the results by the peak_start field.
func ByPeakStart(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPeakStart, opts...).ToFunc()
}
// ByPeakEnd orders the results by the peak_end field.
func ByPeakEnd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPeakEnd, opts...).ToFunc()
}
// ByPeakRateMultiplier orders the results by the peak_rate_multiplier field.
func ByPeakRateMultiplier(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPeakRateMultiplier, opts...).ToFunc()
}
// ByIsExclusive orders the results by the is_exclusive field.
func ByIsExclusive(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldIsExclusive, opts...).ToFunc()
+200
View File
@@ -85,6 +85,26 @@ func RateMultiplier(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldRateMultiplier, v))
}
// PeakRateEnabled applies equality check predicate on the "peak_rate_enabled" field. It's identical to PeakRateEnabledEQ.
func PeakRateEnabled(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakRateEnabled, v))
}
// PeakStart applies equality check predicate on the "peak_start" field. It's identical to PeakStartEQ.
func PeakStart(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakStart, v))
}
// PeakEnd applies equality check predicate on the "peak_end" field. It's identical to PeakEndEQ.
func PeakEnd(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakEnd, v))
}
// PeakRateMultiplier applies equality check predicate on the "peak_rate_multiplier" field. It's identical to PeakRateMultiplierEQ.
func PeakRateMultiplier(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakRateMultiplier, v))
}
// IsExclusive applies equality check predicate on the "is_exclusive" field. It's identical to IsExclusiveEQ.
func IsExclusive(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldIsExclusive, v))
@@ -520,6 +540,186 @@ func RateMultiplierLTE(v float64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldRateMultiplier, v))
}
// PeakRateEnabledEQ applies the EQ predicate on the "peak_rate_enabled" field.
func PeakRateEnabledEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakRateEnabled, v))
}
// PeakRateEnabledNEQ applies the NEQ predicate on the "peak_rate_enabled" field.
func PeakRateEnabledNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldPeakRateEnabled, v))
}
// PeakStartEQ applies the EQ predicate on the "peak_start" field.
func PeakStartEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakStart, v))
}
// PeakStartNEQ applies the NEQ predicate on the "peak_start" field.
func PeakStartNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldPeakStart, v))
}
// PeakStartIn applies the In predicate on the "peak_start" field.
func PeakStartIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldPeakStart, vs...))
}
// PeakStartNotIn applies the NotIn predicate on the "peak_start" field.
func PeakStartNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldPeakStart, vs...))
}
// PeakStartGT applies the GT predicate on the "peak_start" field.
func PeakStartGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldPeakStart, v))
}
// PeakStartGTE applies the GTE predicate on the "peak_start" field.
func PeakStartGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldPeakStart, v))
}
// PeakStartLT applies the LT predicate on the "peak_start" field.
func PeakStartLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldPeakStart, v))
}
// PeakStartLTE applies the LTE predicate on the "peak_start" field.
func PeakStartLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldPeakStart, v))
}
// PeakStartContains applies the Contains predicate on the "peak_start" field.
func PeakStartContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldPeakStart, v))
}
// PeakStartHasPrefix applies the HasPrefix predicate on the "peak_start" field.
func PeakStartHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldPeakStart, v))
}
// PeakStartHasSuffix applies the HasSuffix predicate on the "peak_start" field.
func PeakStartHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldPeakStart, v))
}
// PeakStartEqualFold applies the EqualFold predicate on the "peak_start" field.
func PeakStartEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldPeakStart, v))
}
// PeakStartContainsFold applies the ContainsFold predicate on the "peak_start" field.
func PeakStartContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldPeakStart, v))
}
// PeakEndEQ applies the EQ predicate on the "peak_end" field.
func PeakEndEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakEnd, v))
}
// PeakEndNEQ applies the NEQ predicate on the "peak_end" field.
func PeakEndNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldPeakEnd, v))
}
// PeakEndIn applies the In predicate on the "peak_end" field.
func PeakEndIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldPeakEnd, vs...))
}
// PeakEndNotIn applies the NotIn predicate on the "peak_end" field.
func PeakEndNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldPeakEnd, vs...))
}
// PeakEndGT applies the GT predicate on the "peak_end" field.
func PeakEndGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldPeakEnd, v))
}
// PeakEndGTE applies the GTE predicate on the "peak_end" field.
func PeakEndGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldPeakEnd, v))
}
// PeakEndLT applies the LT predicate on the "peak_end" field.
func PeakEndLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldPeakEnd, v))
}
// PeakEndLTE applies the LTE predicate on the "peak_end" field.
func PeakEndLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldPeakEnd, v))
}
// PeakEndContains applies the Contains predicate on the "peak_end" field.
func PeakEndContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldPeakEnd, v))
}
// PeakEndHasPrefix applies the HasPrefix predicate on the "peak_end" field.
func PeakEndHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldPeakEnd, v))
}
// PeakEndHasSuffix applies the HasSuffix predicate on the "peak_end" field.
func PeakEndHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldPeakEnd, v))
}
// PeakEndEqualFold applies the EqualFold predicate on the "peak_end" field.
func PeakEndEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldPeakEnd, v))
}
// PeakEndContainsFold applies the ContainsFold predicate on the "peak_end" field.
func PeakEndContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldPeakEnd, v))
}
// PeakRateMultiplierEQ applies the EQ predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPeakRateMultiplier, v))
}
// PeakRateMultiplierNEQ applies the NEQ predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierNEQ(v float64) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldPeakRateMultiplier, v))
}
// PeakRateMultiplierIn applies the In predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldIn(FieldPeakRateMultiplier, vs...))
}
// PeakRateMultiplierNotIn applies the NotIn predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierNotIn(vs ...float64) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldPeakRateMultiplier, vs...))
}
// PeakRateMultiplierGT applies the GT predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierGT(v float64) predicate.Group {
return predicate.Group(sql.FieldGT(FieldPeakRateMultiplier, v))
}
// PeakRateMultiplierGTE applies the GTE predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierGTE(v float64) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldPeakRateMultiplier, v))
}
// PeakRateMultiplierLT applies the LT predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierLT(v float64) predicate.Group {
return predicate.Group(sql.FieldLT(FieldPeakRateMultiplier, v))
}
// PeakRateMultiplierLTE applies the LTE predicate on the "peak_rate_multiplier" field.
func PeakRateMultiplierLTE(v float64) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldPeakRateMultiplier, v))
}
// IsExclusiveEQ applies the EQ predicate on the "is_exclusive" field.
func IsExclusiveEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldIsExclusive, v))
+290
View File
@@ -105,6 +105,62 @@ func (_c *GroupCreate) SetNillableRateMultiplier(v *float64) *GroupCreate {
return _c
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (_c *GroupCreate) SetPeakRateEnabled(v bool) *GroupCreate {
_c.mutation.SetPeakRateEnabled(v)
return _c
}
// SetNillablePeakRateEnabled sets the "peak_rate_enabled" field if the given value is not nil.
func (_c *GroupCreate) SetNillablePeakRateEnabled(v *bool) *GroupCreate {
if v != nil {
_c.SetPeakRateEnabled(*v)
}
return _c
}
// SetPeakStart sets the "peak_start" field.
func (_c *GroupCreate) SetPeakStart(v string) *GroupCreate {
_c.mutation.SetPeakStart(v)
return _c
}
// SetNillablePeakStart sets the "peak_start" field if the given value is not nil.
func (_c *GroupCreate) SetNillablePeakStart(v *string) *GroupCreate {
if v != nil {
_c.SetPeakStart(*v)
}
return _c
}
// SetPeakEnd sets the "peak_end" field.
func (_c *GroupCreate) SetPeakEnd(v string) *GroupCreate {
_c.mutation.SetPeakEnd(v)
return _c
}
// SetNillablePeakEnd sets the "peak_end" field if the given value is not nil.
func (_c *GroupCreate) SetNillablePeakEnd(v *string) *GroupCreate {
if v != nil {
_c.SetPeakEnd(*v)
}
return _c
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (_c *GroupCreate) SetPeakRateMultiplier(v float64) *GroupCreate {
_c.mutation.SetPeakRateMultiplier(v)
return _c
}
// SetNillablePeakRateMultiplier sets the "peak_rate_multiplier" field if the given value is not nil.
func (_c *GroupCreate) SetNillablePeakRateMultiplier(v *float64) *GroupCreate {
if v != nil {
_c.SetPeakRateMultiplier(*v)
}
return _c
}
// SetIsExclusive sets the "is_exclusive" field.
func (_c *GroupCreate) SetIsExclusive(v bool) *GroupCreate {
_c.mutation.SetIsExclusive(v)
@@ -640,6 +696,22 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultRateMultiplier
_c.mutation.SetRateMultiplier(v)
}
if _, ok := _c.mutation.PeakRateEnabled(); !ok {
v := group.DefaultPeakRateEnabled
_c.mutation.SetPeakRateEnabled(v)
}
if _, ok := _c.mutation.PeakStart(); !ok {
v := group.DefaultPeakStart
_c.mutation.SetPeakStart(v)
}
if _, ok := _c.mutation.PeakEnd(); !ok {
v := group.DefaultPeakEnd
_c.mutation.SetPeakEnd(v)
}
if _, ok := _c.mutation.PeakRateMultiplier(); !ok {
v := group.DefaultPeakRateMultiplier
_c.mutation.SetPeakRateMultiplier(v)
}
if _, ok := _c.mutation.IsExclusive(); !ok {
v := group.DefaultIsExclusive
_c.mutation.SetIsExclusive(v)
@@ -742,6 +814,28 @@ func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.RateMultiplier(); !ok {
return &ValidationError{Name: "rate_multiplier", err: errors.New(`ent: missing required field "Group.rate_multiplier"`)}
}
if _, ok := _c.mutation.PeakRateEnabled(); !ok {
return &ValidationError{Name: "peak_rate_enabled", err: errors.New(`ent: missing required field "Group.peak_rate_enabled"`)}
}
if _, ok := _c.mutation.PeakStart(); !ok {
return &ValidationError{Name: "peak_start", err: errors.New(`ent: missing required field "Group.peak_start"`)}
}
if v, ok := _c.mutation.PeakStart(); ok {
if err := group.PeakStartValidator(v); err != nil {
return &ValidationError{Name: "peak_start", err: fmt.Errorf(`ent: validator failed for field "Group.peak_start": %w`, err)}
}
}
if _, ok := _c.mutation.PeakEnd(); !ok {
return &ValidationError{Name: "peak_end", err: errors.New(`ent: missing required field "Group.peak_end"`)}
}
if v, ok := _c.mutation.PeakEnd(); ok {
if err := group.PeakEndValidator(v); err != nil {
return &ValidationError{Name: "peak_end", err: fmt.Errorf(`ent: validator failed for field "Group.peak_end": %w`, err)}
}
}
if _, ok := _c.mutation.PeakRateMultiplier(); !ok {
return &ValidationError{Name: "peak_rate_multiplier", err: errors.New(`ent: missing required field "Group.peak_rate_multiplier"`)}
}
if _, ok := _c.mutation.IsExclusive(); !ok {
return &ValidationError{Name: "is_exclusive", err: errors.New(`ent: missing required field "Group.is_exclusive"`)}
}
@@ -873,6 +967,22 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
_node.RateMultiplier = value
}
if value, ok := _c.mutation.PeakRateEnabled(); ok {
_spec.SetField(group.FieldPeakRateEnabled, field.TypeBool, value)
_node.PeakRateEnabled = value
}
if value, ok := _c.mutation.PeakStart(); ok {
_spec.SetField(group.FieldPeakStart, field.TypeString, value)
_node.PeakStart = value
}
if value, ok := _c.mutation.PeakEnd(); ok {
_spec.SetField(group.FieldPeakEnd, field.TypeString, value)
_node.PeakEnd = value
}
if value, ok := _c.mutation.PeakRateMultiplier(); ok {
_spec.SetField(group.FieldPeakRateMultiplier, field.TypeFloat64, value)
_node.PeakRateMultiplier = value
}
if value, ok := _c.mutation.IsExclusive(); ok {
_spec.SetField(group.FieldIsExclusive, field.TypeBool, value)
_node.IsExclusive = value
@@ -1223,6 +1333,60 @@ func (u *GroupUpsert) AddRateMultiplier(v float64) *GroupUpsert {
return u
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (u *GroupUpsert) SetPeakRateEnabled(v bool) *GroupUpsert {
u.Set(group.FieldPeakRateEnabled, v)
return u
}
// UpdatePeakRateEnabled sets the "peak_rate_enabled" field to the value that was provided on create.
func (u *GroupUpsert) UpdatePeakRateEnabled() *GroupUpsert {
u.SetExcluded(group.FieldPeakRateEnabled)
return u
}
// SetPeakStart sets the "peak_start" field.
func (u *GroupUpsert) SetPeakStart(v string) *GroupUpsert {
u.Set(group.FieldPeakStart, v)
return u
}
// UpdatePeakStart sets the "peak_start" field to the value that was provided on create.
func (u *GroupUpsert) UpdatePeakStart() *GroupUpsert {
u.SetExcluded(group.FieldPeakStart)
return u
}
// SetPeakEnd sets the "peak_end" field.
func (u *GroupUpsert) SetPeakEnd(v string) *GroupUpsert {
u.Set(group.FieldPeakEnd, v)
return u
}
// UpdatePeakEnd sets the "peak_end" field to the value that was provided on create.
func (u *GroupUpsert) UpdatePeakEnd() *GroupUpsert {
u.SetExcluded(group.FieldPeakEnd)
return u
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (u *GroupUpsert) SetPeakRateMultiplier(v float64) *GroupUpsert {
u.Set(group.FieldPeakRateMultiplier, v)
return u
}
// UpdatePeakRateMultiplier sets the "peak_rate_multiplier" field to the value that was provided on create.
func (u *GroupUpsert) UpdatePeakRateMultiplier() *GroupUpsert {
u.SetExcluded(group.FieldPeakRateMultiplier)
return u
}
// AddPeakRateMultiplier adds v to the "peak_rate_multiplier" field.
func (u *GroupUpsert) AddPeakRateMultiplier(v float64) *GroupUpsert {
u.Add(group.FieldPeakRateMultiplier, v)
return u
}
// SetIsExclusive sets the "is_exclusive" field.
func (u *GroupUpsert) SetIsExclusive(v bool) *GroupUpsert {
u.Set(group.FieldIsExclusive, v)
@@ -1833,6 +1997,69 @@ func (u *GroupUpsertOne) UpdateRateMultiplier() *GroupUpsertOne {
})
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (u *GroupUpsertOne) SetPeakRateEnabled(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetPeakRateEnabled(v)
})
}
// UpdatePeakRateEnabled sets the "peak_rate_enabled" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdatePeakRateEnabled() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakRateEnabled()
})
}
// SetPeakStart sets the "peak_start" field.
func (u *GroupUpsertOne) SetPeakStart(v string) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetPeakStart(v)
})
}
// UpdatePeakStart sets the "peak_start" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdatePeakStart() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakStart()
})
}
// SetPeakEnd sets the "peak_end" field.
func (u *GroupUpsertOne) SetPeakEnd(v string) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetPeakEnd(v)
})
}
// UpdatePeakEnd sets the "peak_end" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdatePeakEnd() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakEnd()
})
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (u *GroupUpsertOne) SetPeakRateMultiplier(v float64) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetPeakRateMultiplier(v)
})
}
// AddPeakRateMultiplier adds v to the "peak_rate_multiplier" field.
func (u *GroupUpsertOne) AddPeakRateMultiplier(v float64) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.AddPeakRateMultiplier(v)
})
}
// UpdatePeakRateMultiplier sets the "peak_rate_multiplier" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdatePeakRateMultiplier() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakRateMultiplier()
})
}
// SetIsExclusive sets the "is_exclusive" field.
func (u *GroupUpsertOne) SetIsExclusive(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -2688,6 +2915,69 @@ func (u *GroupUpsertBulk) UpdateRateMultiplier() *GroupUpsertBulk {
})
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (u *GroupUpsertBulk) SetPeakRateEnabled(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetPeakRateEnabled(v)
})
}
// UpdatePeakRateEnabled sets the "peak_rate_enabled" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdatePeakRateEnabled() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakRateEnabled()
})
}
// SetPeakStart sets the "peak_start" field.
func (u *GroupUpsertBulk) SetPeakStart(v string) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetPeakStart(v)
})
}
// UpdatePeakStart sets the "peak_start" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdatePeakStart() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakStart()
})
}
// SetPeakEnd sets the "peak_end" field.
func (u *GroupUpsertBulk) SetPeakEnd(v string) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetPeakEnd(v)
})
}
// UpdatePeakEnd sets the "peak_end" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdatePeakEnd() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakEnd()
})
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (u *GroupUpsertBulk) SetPeakRateMultiplier(v float64) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetPeakRateMultiplier(v)
})
}
// AddPeakRateMultiplier adds v to the "peak_rate_multiplier" field.
func (u *GroupUpsertBulk) AddPeakRateMultiplier(v float64) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.AddPeakRateMultiplier(v)
})
}
// UpdatePeakRateMultiplier sets the "peak_rate_multiplier" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdatePeakRateMultiplier() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdatePeakRateMultiplier()
})
}
// SetIsExclusive sets the "is_exclusive" field.
func (u *GroupUpsertBulk) SetIsExclusive(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
+176
View File
@@ -117,6 +117,69 @@ func (_u *GroupUpdate) AddRateMultiplier(v float64) *GroupUpdate {
return _u
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (_u *GroupUpdate) SetPeakRateEnabled(v bool) *GroupUpdate {
_u.mutation.SetPeakRateEnabled(v)
return _u
}
// SetNillablePeakRateEnabled sets the "peak_rate_enabled" field if the given value is not nil.
func (_u *GroupUpdate) SetNillablePeakRateEnabled(v *bool) *GroupUpdate {
if v != nil {
_u.SetPeakRateEnabled(*v)
}
return _u
}
// SetPeakStart sets the "peak_start" field.
func (_u *GroupUpdate) SetPeakStart(v string) *GroupUpdate {
_u.mutation.SetPeakStart(v)
return _u
}
// SetNillablePeakStart sets the "peak_start" field if the given value is not nil.
func (_u *GroupUpdate) SetNillablePeakStart(v *string) *GroupUpdate {
if v != nil {
_u.SetPeakStart(*v)
}
return _u
}
// SetPeakEnd sets the "peak_end" field.
func (_u *GroupUpdate) SetPeakEnd(v string) *GroupUpdate {
_u.mutation.SetPeakEnd(v)
return _u
}
// SetNillablePeakEnd sets the "peak_end" field if the given value is not nil.
func (_u *GroupUpdate) SetNillablePeakEnd(v *string) *GroupUpdate {
if v != nil {
_u.SetPeakEnd(*v)
}
return _u
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (_u *GroupUpdate) SetPeakRateMultiplier(v float64) *GroupUpdate {
_u.mutation.ResetPeakRateMultiplier()
_u.mutation.SetPeakRateMultiplier(v)
return _u
}
// SetNillablePeakRateMultiplier sets the "peak_rate_multiplier" field if the given value is not nil.
func (_u *GroupUpdate) SetNillablePeakRateMultiplier(v *float64) *GroupUpdate {
if v != nil {
_u.SetPeakRateMultiplier(*v)
}
return _u
}
// AddPeakRateMultiplier adds value to the "peak_rate_multiplier" field.
func (_u *GroupUpdate) AddPeakRateMultiplier(v float64) *GroupUpdate {
_u.mutation.AddPeakRateMultiplier(v)
return _u
}
// SetIsExclusive sets the "is_exclusive" field.
func (_u *GroupUpdate) SetIsExclusive(v bool) *GroupUpdate {
_u.mutation.SetIsExclusive(v)
@@ -921,6 +984,16 @@ func (_u *GroupUpdate) check() error {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)}
}
}
if v, ok := _u.mutation.PeakStart(); ok {
if err := group.PeakStartValidator(v); err != nil {
return &ValidationError{Name: "peak_start", err: fmt.Errorf(`ent: validator failed for field "Group.peak_start": %w`, err)}
}
}
if v, ok := _u.mutation.PeakEnd(); ok {
if err := group.PeakEndValidator(v); err != nil {
return &ValidationError{Name: "peak_end", err: fmt.Errorf(`ent: validator failed for field "Group.peak_end": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := group.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Group.status": %w`, err)}
@@ -980,6 +1053,21 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.AddedRateMultiplier(); ok {
_spec.AddField(group.FieldRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.PeakRateEnabled(); ok {
_spec.SetField(group.FieldPeakRateEnabled, field.TypeBool, value)
}
if value, ok := _u.mutation.PeakStart(); ok {
_spec.SetField(group.FieldPeakStart, field.TypeString, value)
}
if value, ok := _u.mutation.PeakEnd(); ok {
_spec.SetField(group.FieldPeakEnd, field.TypeString, value)
}
if value, ok := _u.mutation.PeakRateMultiplier(); ok {
_spec.SetField(group.FieldPeakRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.AddedPeakRateMultiplier(); ok {
_spec.AddField(group.FieldPeakRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.IsExclusive(); ok {
_spec.SetField(group.FieldIsExclusive, field.TypeBool, value)
}
@@ -1530,6 +1618,69 @@ func (_u *GroupUpdateOne) AddRateMultiplier(v float64) *GroupUpdateOne {
return _u
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (_u *GroupUpdateOne) SetPeakRateEnabled(v bool) *GroupUpdateOne {
_u.mutation.SetPeakRateEnabled(v)
return _u
}
// SetNillablePeakRateEnabled sets the "peak_rate_enabled" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillablePeakRateEnabled(v *bool) *GroupUpdateOne {
if v != nil {
_u.SetPeakRateEnabled(*v)
}
return _u
}
// SetPeakStart sets the "peak_start" field.
func (_u *GroupUpdateOne) SetPeakStart(v string) *GroupUpdateOne {
_u.mutation.SetPeakStart(v)
return _u
}
// SetNillablePeakStart sets the "peak_start" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillablePeakStart(v *string) *GroupUpdateOne {
if v != nil {
_u.SetPeakStart(*v)
}
return _u
}
// SetPeakEnd sets the "peak_end" field.
func (_u *GroupUpdateOne) SetPeakEnd(v string) *GroupUpdateOne {
_u.mutation.SetPeakEnd(v)
return _u
}
// SetNillablePeakEnd sets the "peak_end" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillablePeakEnd(v *string) *GroupUpdateOne {
if v != nil {
_u.SetPeakEnd(*v)
}
return _u
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (_u *GroupUpdateOne) SetPeakRateMultiplier(v float64) *GroupUpdateOne {
_u.mutation.ResetPeakRateMultiplier()
_u.mutation.SetPeakRateMultiplier(v)
return _u
}
// SetNillablePeakRateMultiplier sets the "peak_rate_multiplier" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillablePeakRateMultiplier(v *float64) *GroupUpdateOne {
if v != nil {
_u.SetPeakRateMultiplier(*v)
}
return _u
}
// AddPeakRateMultiplier adds value to the "peak_rate_multiplier" field.
func (_u *GroupUpdateOne) AddPeakRateMultiplier(v float64) *GroupUpdateOne {
_u.mutation.AddPeakRateMultiplier(v)
return _u
}
// SetIsExclusive sets the "is_exclusive" field.
func (_u *GroupUpdateOne) SetIsExclusive(v bool) *GroupUpdateOne {
_u.mutation.SetIsExclusive(v)
@@ -2347,6 +2498,16 @@ func (_u *GroupUpdateOne) check() error {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)}
}
}
if v, ok := _u.mutation.PeakStart(); ok {
if err := group.PeakStartValidator(v); err != nil {
return &ValidationError{Name: "peak_start", err: fmt.Errorf(`ent: validator failed for field "Group.peak_start": %w`, err)}
}
}
if v, ok := _u.mutation.PeakEnd(); ok {
if err := group.PeakEndValidator(v); err != nil {
return &ValidationError{Name: "peak_end", err: fmt.Errorf(`ent: validator failed for field "Group.peak_end": %w`, err)}
}
}
if v, ok := _u.mutation.Status(); ok {
if err := group.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Group.status": %w`, err)}
@@ -2423,6 +2584,21 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.AddedRateMultiplier(); ok {
_spec.AddField(group.FieldRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.PeakRateEnabled(); ok {
_spec.SetField(group.FieldPeakRateEnabled, field.TypeBool, value)
}
if value, ok := _u.mutation.PeakStart(); ok {
_spec.SetField(group.FieldPeakStart, field.TypeString, value)
}
if value, ok := _u.mutation.PeakEnd(); ok {
_spec.SetField(group.FieldPeakEnd, field.TypeString, value)
}
if value, ok := _u.mutation.PeakRateMultiplier(); ok {
_spec.SetField(group.FieldPeakRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.AddedPeakRateMultiplier(); ok {
_spec.AddField(group.FieldPeakRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.IsExclusive(); ok {
_spec.SetField(group.FieldIsExclusive, field.TypeBool, value)
}
@@ -46,6 +46,16 @@ func TestPaymentOrdersOutTradeNoPartialUniqueIndex(t *testing.T) {
require.Equal(t, (&entsql.IndexAnnotation{Where: "out_trade_no <> ''"}).Where, idx.Annotation.Where)
}
func TestAccountsParentAccountForeignKey(t *testing.T) {
fk := findForeignKeyByColumn(t, AccountsTable, "parent_account_id")
require.Len(t, fk.Columns, 1)
require.Equal(t, "parent_account_id", fk.Columns[0].Name)
require.False(t, fk.Columns[0].Unique, "active-shadow uniqueness is enforced by the partial uq_accounts_spark_shadow_per_parent index")
require.Len(t, fk.RefColumns, 1)
require.Equal(t, "id", fk.RefColumns[0].Name)
require.Equal(t, entschema.Restrict, fk.OnDelete)
}
func findForeignKeyBySymbol(t *testing.T, table *entschema.Table, symbol string) *entschema.ForeignKey {
t.Helper()
@@ -71,3 +81,18 @@ func findIndexByName(t *testing.T, table *entschema.Table, name string) *entsche
require.Failf(t, "missing index", "table %s should include index %s", table.Name, name)
return nil
}
func findForeignKeyByColumn(t *testing.T, table *entschema.Table, column string) *entschema.ForeignKey {
t.Helper()
for _, fk := range table.ForeignKeys {
for _, col := range fk.Columns {
if col.Name == column {
return fk
}
}
}
require.Failf(t, "missing foreign key", "table %s should include foreign key for column %s", table.Name, column)
return nil
}
+29 -10
View File
@@ -124,7 +124,9 @@ var (
{Name: "session_window_start", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "session_window_end", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "session_window_status", Type: field.TypeString, Nullable: true, Size: 20},
{Name: "quota_dimension", Type: field.TypeEnum, Enums: []string{"global", "spark"}, Default: "global"},
{Name: "proxy_id", Type: field.TypeInt64, Nullable: true},
{Name: "parent_account_id", Type: field.TypeInt64, Nullable: true},
}
// AccountsTable holds the schema information for the "accounts" table.
AccountsTable = &schema.Table{
@@ -134,10 +136,16 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "accounts_proxies_proxy",
Columns: []*schema.Column{AccountsColumns[29]},
Columns: []*schema.Column{AccountsColumns[30]},
RefColumns: []*schema.Column{ProxiesColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "accounts_accounts_children",
Columns: []*schema.Column{AccountsColumns[31]},
RefColumns: []*schema.Column{AccountsColumns[0]},
OnDelete: schema.Restrict,
},
},
Indexes: []*schema.Index{
{
@@ -158,7 +166,7 @@ var (
{
Name: "account_proxy_id",
Unique: false,
Columns: []*schema.Column{AccountsColumns[29]},
Columns: []*schema.Column{AccountsColumns[30]},
},
{
Name: "account_priority",
@@ -205,6 +213,11 @@ var (
Unique: false,
Columns: []*schema.Column{AccountsColumns[3]},
},
{
Name: "account_parent_account_id",
Unique: false,
Columns: []*schema.Column{AccountsColumns[31]},
},
},
}
// AccountGroupsColumns holds the columns for the "account_groups" table.
@@ -437,6 +450,7 @@ var (
{Name: "group_name", Type: field.TypeString, Nullable: true, Size: 100, Default: ""},
{Name: "enabled", Type: field.TypeBool, Default: true},
{Name: "interval_seconds", Type: field.TypeInt},
{Name: "jitter_seconds", Type: field.TypeInt, Default: 0},
{Name: "last_checked_at", Type: field.TypeTime, Nullable: true},
{Name: "created_by", Type: field.TypeInt64},
{Name: "extra_headers", Type: field.TypeJSON},
@@ -452,7 +466,7 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "channel_monitors_channel_monitor_request_templates_request_template",
Columns: []*schema.Column{ChannelMonitorsColumns[18]},
Columns: []*schema.Column{ChannelMonitorsColumns[19]},
RefColumns: []*schema.Column{ChannelMonitorRequestTemplatesColumns[0]},
OnDelete: schema.SetNull,
},
@@ -461,7 +475,7 @@ var (
{
Name: "channelmonitor_enabled_last_checked_at",
Unique: false,
Columns: []*schema.Column{ChannelMonitorsColumns[11], ChannelMonitorsColumns[13]},
Columns: []*schema.Column{ChannelMonitorsColumns[11], ChannelMonitorsColumns[14]},
},
{
Name: "channelmonitor_provider",
@@ -481,7 +495,7 @@ var (
{
Name: "channelmonitor_template_id",
Unique: false,
Columns: []*schema.Column{ChannelMonitorsColumns[18]},
Columns: []*schema.Column{ChannelMonitorsColumns[19]},
},
},
}
@@ -643,6 +657,10 @@ var (
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "description", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "peak_rate_enabled", Type: field.TypeBool, Default: false},
{Name: "peak_start", Type: field.TypeString, Size: 5, Default: ""},
{Name: "peak_end", Type: field.TypeString, Size: 5, Default: ""},
{Name: "peak_rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "is_exclusive", Type: field.TypeBool, Default: false},
{Name: "status", Type: field.TypeString, Size: 20, Default: "active"},
{Name: "platform", Type: field.TypeString, Size: 50, Default: "anthropic"},
@@ -682,22 +700,22 @@ var (
{
Name: "group_status",
Unique: false,
Columns: []*schema.Column{GroupsColumns[8]},
Columns: []*schema.Column{GroupsColumns[12]},
},
{
Name: "group_platform",
Unique: false,
Columns: []*schema.Column{GroupsColumns[9]},
Columns: []*schema.Column{GroupsColumns[13]},
},
{
Name: "group_subscription_type",
Unique: false,
Columns: []*schema.Column{GroupsColumns[10]},
Columns: []*schema.Column{GroupsColumns[14]},
},
{
Name: "group_is_exclusive",
Unique: false,
Columns: []*schema.Column{GroupsColumns[7]},
Columns: []*schema.Column{GroupsColumns[11]},
},
{
Name: "group_deleted_at",
@@ -707,7 +725,7 @@ var (
{
Name: "group_sort_order",
Unique: false,
Columns: []*schema.Column{GroupsColumns[28]},
Columns: []*schema.Column{GroupsColumns[32]},
},
},
}
@@ -1819,6 +1837,7 @@ func init() {
Table: "api_keys",
}
AccountsTable.ForeignKeys[0].RefTable = ProxiesTable
AccountsTable.ForeignKeys[1].RefTable = AccountsTable
AccountsTable.Annotation = &entsql.Annotation{
Table: "accounts",
}
+611 -6
View File
@@ -2310,12 +2310,18 @@ type AccountMutation struct {
session_window_start *time.Time
session_window_end *time.Time
session_window_status *string
quota_dimension *account.QuotaDimension
clearedFields map[string]struct{}
groups map[int64]struct{}
removedgroups map[int64]struct{}
clearedgroups bool
proxy *int64
clearedproxy bool
parent *int64
clearedparent bool
children map[int64]struct{}
removedchildren map[int64]struct{}
clearedchildren bool
usage_logs map[int64]struct{}
removedusage_logs map[int64]struct{}
clearedusage_logs bool
@@ -3776,6 +3782,91 @@ func (m *AccountMutation) ResetSessionWindowStatus() {
delete(m.clearedFields, account.FieldSessionWindowStatus)
}
// SetParentAccountID sets the "parent_account_id" field.
func (m *AccountMutation) SetParentAccountID(i int64) {
m.parent = &i
}
// ParentAccountID returns the value of the "parent_account_id" field in the mutation.
func (m *AccountMutation) ParentAccountID() (r int64, exists bool) {
v := m.parent
if v == nil {
return
}
return *v, true
}
// OldParentAccountID returns the old "parent_account_id" field's value of the Account entity.
// If the Account object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *AccountMutation) OldParentAccountID(ctx context.Context) (v *int64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldParentAccountID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldParentAccountID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldParentAccountID: %w", err)
}
return oldValue.ParentAccountID, nil
}
// ClearParentAccountID clears the value of the "parent_account_id" field.
func (m *AccountMutation) ClearParentAccountID() {
m.parent = nil
m.clearedFields[account.FieldParentAccountID] = struct{}{}
}
// ParentAccountIDCleared returns if the "parent_account_id" field was cleared in this mutation.
func (m *AccountMutation) ParentAccountIDCleared() bool {
_, ok := m.clearedFields[account.FieldParentAccountID]
return ok
}
// ResetParentAccountID resets all changes to the "parent_account_id" field.
func (m *AccountMutation) ResetParentAccountID() {
m.parent = nil
delete(m.clearedFields, account.FieldParentAccountID)
}
// SetQuotaDimension sets the "quota_dimension" field.
func (m *AccountMutation) SetQuotaDimension(ad account.QuotaDimension) {
m.quota_dimension = &ad
}
// QuotaDimension returns the value of the "quota_dimension" field in the mutation.
func (m *AccountMutation) QuotaDimension() (r account.QuotaDimension, exists bool) {
v := m.quota_dimension
if v == nil {
return
}
return *v, true
}
// OldQuotaDimension returns the old "quota_dimension" field's value of the Account entity.
// If the Account object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *AccountMutation) OldQuotaDimension(ctx context.Context) (v account.QuotaDimension, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldQuotaDimension is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldQuotaDimension requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldQuotaDimension: %w", err)
}
return oldValue.QuotaDimension, nil
}
// ResetQuotaDimension resets all changes to the "quota_dimension" field.
func (m *AccountMutation) ResetQuotaDimension() {
m.quota_dimension = nil
}
// AddGroupIDs adds the "groups" edge to the Group entity by ids.
func (m *AccountMutation) AddGroupIDs(ids ...int64) {
if m.groups == nil {
@@ -3857,6 +3948,100 @@ func (m *AccountMutation) ResetProxy() {
m.clearedproxy = false
}
// SetParentID sets the "parent" edge to the Account entity by id.
func (m *AccountMutation) SetParentID(id int64) {
m.parent = &id
}
// ClearParent clears the "parent" edge to the Account entity.
func (m *AccountMutation) ClearParent() {
m.clearedparent = true
m.clearedFields[account.FieldParentAccountID] = struct{}{}
}
// ParentCleared reports if the "parent" edge to the Account entity was cleared.
func (m *AccountMutation) ParentCleared() bool {
return m.ParentAccountIDCleared() || m.clearedparent
}
// ParentID returns the "parent" edge ID in the mutation.
func (m *AccountMutation) ParentID() (id int64, exists bool) {
if m.parent != nil {
return *m.parent, true
}
return
}
// ParentIDs returns the "parent" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// ParentID instead. It exists only for internal usage by the builders.
func (m *AccountMutation) ParentIDs() (ids []int64) {
if id := m.parent; id != nil {
ids = append(ids, *id)
}
return
}
// ResetParent resets all changes to the "parent" edge.
func (m *AccountMutation) ResetParent() {
m.parent = nil
m.clearedparent = false
}
// AddChildIDs adds the "children" edge to the Account entity by ids.
func (m *AccountMutation) AddChildIDs(ids ...int64) {
if m.children == nil {
m.children = make(map[int64]struct{})
}
for i := range ids {
m.children[ids[i]] = struct{}{}
}
}
// ClearChildren clears the "children" edge to the Account entity.
func (m *AccountMutation) ClearChildren() {
m.clearedchildren = true
}
// ChildrenCleared reports if the "children" edge to the Account entity was cleared.
func (m *AccountMutation) ChildrenCleared() bool {
return m.clearedchildren
}
// RemoveChildIDs removes the "children" edge to the Account entity by IDs.
func (m *AccountMutation) RemoveChildIDs(ids ...int64) {
if m.removedchildren == nil {
m.removedchildren = make(map[int64]struct{})
}
for i := range ids {
delete(m.children, ids[i])
m.removedchildren[ids[i]] = struct{}{}
}
}
// RemovedChildren returns the removed IDs of the "children" edge to the Account entity.
func (m *AccountMutation) RemovedChildrenIDs() (ids []int64) {
for id := range m.removedchildren {
ids = append(ids, id)
}
return
}
// ChildrenIDs returns the "children" edge IDs in the mutation.
func (m *AccountMutation) ChildrenIDs() (ids []int64) {
for id := range m.children {
ids = append(ids, id)
}
return
}
// ResetChildren resets all changes to the "children" edge.
func (m *AccountMutation) ResetChildren() {
m.children = nil
m.clearedchildren = false
m.removedchildren = nil
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by ids.
func (m *AccountMutation) AddUsageLogIDs(ids ...int64) {
if m.usage_logs == nil {
@@ -3945,7 +4130,7 @@ func (m *AccountMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *AccountMutation) Fields() []string {
fields := make([]string, 0, 29)
fields := make([]string, 0, 31)
if m.created_at != nil {
fields = append(fields, account.FieldCreatedAt)
}
@@ -4033,6 +4218,12 @@ func (m *AccountMutation) Fields() []string {
if m.session_window_status != nil {
fields = append(fields, account.FieldSessionWindowStatus)
}
if m.parent != nil {
fields = append(fields, account.FieldParentAccountID)
}
if m.quota_dimension != nil {
fields = append(fields, account.FieldQuotaDimension)
}
return fields
}
@@ -4099,6 +4290,10 @@ func (m *AccountMutation) Field(name string) (ent.Value, bool) {
return m.SessionWindowEnd()
case account.FieldSessionWindowStatus:
return m.SessionWindowStatus()
case account.FieldParentAccountID:
return m.ParentAccountID()
case account.FieldQuotaDimension:
return m.QuotaDimension()
}
return nil, false
}
@@ -4166,6 +4361,10 @@ func (m *AccountMutation) OldField(ctx context.Context, name string) (ent.Value,
return m.OldSessionWindowEnd(ctx)
case account.FieldSessionWindowStatus:
return m.OldSessionWindowStatus(ctx)
case account.FieldParentAccountID:
return m.OldParentAccountID(ctx)
case account.FieldQuotaDimension:
return m.OldQuotaDimension(ctx)
}
return nil, fmt.Errorf("unknown Account field %s", name)
}
@@ -4378,6 +4577,20 @@ func (m *AccountMutation) SetField(name string, value ent.Value) error {
}
m.SetSessionWindowStatus(v)
return nil
case account.FieldParentAccountID:
v, ok := value.(int64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetParentAccountID(v)
return nil
case account.FieldQuotaDimension:
v, ok := value.(account.QuotaDimension)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetQuotaDimension(v)
return nil
}
return fmt.Errorf("unknown Account field %s", name)
}
@@ -4519,6 +4732,9 @@ func (m *AccountMutation) ClearedFields() []string {
if m.FieldCleared(account.FieldSessionWindowStatus) {
fields = append(fields, account.FieldSessionWindowStatus)
}
if m.FieldCleared(account.FieldParentAccountID) {
fields = append(fields, account.FieldParentAccountID)
}
return fields
}
@@ -4581,6 +4797,9 @@ func (m *AccountMutation) ClearField(name string) error {
case account.FieldSessionWindowStatus:
m.ClearSessionWindowStatus()
return nil
case account.FieldParentAccountID:
m.ClearParentAccountID()
return nil
}
return fmt.Errorf("unknown Account nullable field %s", name)
}
@@ -4676,19 +4895,31 @@ func (m *AccountMutation) ResetField(name string) error {
case account.FieldSessionWindowStatus:
m.ResetSessionWindowStatus()
return nil
case account.FieldParentAccountID:
m.ResetParentAccountID()
return nil
case account.FieldQuotaDimension:
m.ResetQuotaDimension()
return nil
}
return fmt.Errorf("unknown Account field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *AccountMutation) AddedEdges() []string {
edges := make([]string, 0, 3)
edges := make([]string, 0, 5)
if m.groups != nil {
edges = append(edges, account.EdgeGroups)
}
if m.proxy != nil {
edges = append(edges, account.EdgeProxy)
}
if m.parent != nil {
edges = append(edges, account.EdgeParent)
}
if m.children != nil {
edges = append(edges, account.EdgeChildren)
}
if m.usage_logs != nil {
edges = append(edges, account.EdgeUsageLogs)
}
@@ -4709,6 +4940,16 @@ func (m *AccountMutation) AddedIDs(name string) []ent.Value {
if id := m.proxy; id != nil {
return []ent.Value{*id}
}
case account.EdgeParent:
if id := m.parent; id != nil {
return []ent.Value{*id}
}
case account.EdgeChildren:
ids := make([]ent.Value, 0, len(m.children))
for id := range m.children {
ids = append(ids, id)
}
return ids
case account.EdgeUsageLogs:
ids := make([]ent.Value, 0, len(m.usage_logs))
for id := range m.usage_logs {
@@ -4721,10 +4962,13 @@ func (m *AccountMutation) AddedIDs(name string) []ent.Value {
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *AccountMutation) RemovedEdges() []string {
edges := make([]string, 0, 3)
edges := make([]string, 0, 5)
if m.removedgroups != nil {
edges = append(edges, account.EdgeGroups)
}
if m.removedchildren != nil {
edges = append(edges, account.EdgeChildren)
}
if m.removedusage_logs != nil {
edges = append(edges, account.EdgeUsageLogs)
}
@@ -4741,6 +4985,12 @@ func (m *AccountMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
case account.EdgeChildren:
ids := make([]ent.Value, 0, len(m.removedchildren))
for id := range m.removedchildren {
ids = append(ids, id)
}
return ids
case account.EdgeUsageLogs:
ids := make([]ent.Value, 0, len(m.removedusage_logs))
for id := range m.removedusage_logs {
@@ -4753,13 +5003,19 @@ func (m *AccountMutation) RemovedIDs(name string) []ent.Value {
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *AccountMutation) ClearedEdges() []string {
edges := make([]string, 0, 3)
edges := make([]string, 0, 5)
if m.clearedgroups {
edges = append(edges, account.EdgeGroups)
}
if m.clearedproxy {
edges = append(edges, account.EdgeProxy)
}
if m.clearedparent {
edges = append(edges, account.EdgeParent)
}
if m.clearedchildren {
edges = append(edges, account.EdgeChildren)
}
if m.clearedusage_logs {
edges = append(edges, account.EdgeUsageLogs)
}
@@ -4774,6 +5030,10 @@ func (m *AccountMutation) EdgeCleared(name string) bool {
return m.clearedgroups
case account.EdgeProxy:
return m.clearedproxy
case account.EdgeParent:
return m.clearedparent
case account.EdgeChildren:
return m.clearedchildren
case account.EdgeUsageLogs:
return m.clearedusage_logs
}
@@ -4787,6 +5047,9 @@ func (m *AccountMutation) ClearEdge(name string) error {
case account.EdgeProxy:
m.ClearProxy()
return nil
case account.EdgeParent:
m.ClearParent()
return nil
}
return fmt.Errorf("unknown Account unique edge %s", name)
}
@@ -4801,6 +5064,12 @@ func (m *AccountMutation) ResetEdge(name string) error {
case account.EdgeProxy:
m.ResetProxy()
return nil
case account.EdgeParent:
m.ResetParent()
return nil
case account.EdgeChildren:
m.ResetChildren()
return nil
case account.EdgeUsageLogs:
m.ResetUsageLogs()
return nil
@@ -8871,6 +9140,8 @@ type ChannelMonitorMutation struct {
enabled *bool
interval_seconds *int
addinterval_seconds *int
jitter_seconds *int
addjitter_seconds *int
last_checked_at *time.Time
created_by *int64
addcreated_by *int64
@@ -9469,6 +9740,62 @@ func (m *ChannelMonitorMutation) ResetIntervalSeconds() {
m.addinterval_seconds = nil
}
// SetJitterSeconds sets the "jitter_seconds" field.
func (m *ChannelMonitorMutation) SetJitterSeconds(i int) {
m.jitter_seconds = &i
m.addjitter_seconds = nil
}
// JitterSeconds returns the value of the "jitter_seconds" field in the mutation.
func (m *ChannelMonitorMutation) JitterSeconds() (r int, exists bool) {
v := m.jitter_seconds
if v == nil {
return
}
return *v, true
}
// OldJitterSeconds returns the old "jitter_seconds" field's value of the ChannelMonitor entity.
// If the ChannelMonitor object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *ChannelMonitorMutation) OldJitterSeconds(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldJitterSeconds is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldJitterSeconds requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldJitterSeconds: %w", err)
}
return oldValue.JitterSeconds, nil
}
// AddJitterSeconds adds i to the "jitter_seconds" field.
func (m *ChannelMonitorMutation) AddJitterSeconds(i int) {
if m.addjitter_seconds != nil {
*m.addjitter_seconds += i
} else {
m.addjitter_seconds = &i
}
}
// AddedJitterSeconds returns the value that was added to the "jitter_seconds" field in this mutation.
func (m *ChannelMonitorMutation) AddedJitterSeconds() (r int, exists bool) {
v := m.addjitter_seconds
if v == nil {
return
}
return *v, true
}
// ResetJitterSeconds resets all changes to the "jitter_seconds" field.
func (m *ChannelMonitorMutation) ResetJitterSeconds() {
m.jitter_seconds = nil
m.addjitter_seconds = nil
}
// SetLastCheckedAt sets the "last_checked_at" field.
func (m *ChannelMonitorMutation) SetLastCheckedAt(t time.Time) {
m.last_checked_at = &t
@@ -9926,7 +10253,7 @@ func (m *ChannelMonitorMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *ChannelMonitorMutation) Fields() []string {
fields := make([]string, 0, 18)
fields := make([]string, 0, 19)
if m.created_at != nil {
fields = append(fields, channelmonitor.FieldCreatedAt)
}
@@ -9963,6 +10290,9 @@ func (m *ChannelMonitorMutation) Fields() []string {
if m.interval_seconds != nil {
fields = append(fields, channelmonitor.FieldIntervalSeconds)
}
if m.jitter_seconds != nil {
fields = append(fields, channelmonitor.FieldJitterSeconds)
}
if m.last_checked_at != nil {
fields = append(fields, channelmonitor.FieldLastCheckedAt)
}
@@ -10013,6 +10343,8 @@ func (m *ChannelMonitorMutation) Field(name string) (ent.Value, bool) {
return m.Enabled()
case channelmonitor.FieldIntervalSeconds:
return m.IntervalSeconds()
case channelmonitor.FieldJitterSeconds:
return m.JitterSeconds()
case channelmonitor.FieldLastCheckedAt:
return m.LastCheckedAt()
case channelmonitor.FieldCreatedBy:
@@ -10058,6 +10390,8 @@ func (m *ChannelMonitorMutation) OldField(ctx context.Context, name string) (ent
return m.OldEnabled(ctx)
case channelmonitor.FieldIntervalSeconds:
return m.OldIntervalSeconds(ctx)
case channelmonitor.FieldJitterSeconds:
return m.OldJitterSeconds(ctx)
case channelmonitor.FieldLastCheckedAt:
return m.OldLastCheckedAt(ctx)
case channelmonitor.FieldCreatedBy:
@@ -10163,6 +10497,13 @@ func (m *ChannelMonitorMutation) SetField(name string, value ent.Value) error {
}
m.SetIntervalSeconds(v)
return nil
case channelmonitor.FieldJitterSeconds:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetJitterSeconds(v)
return nil
case channelmonitor.FieldLastCheckedAt:
v, ok := value.(time.Time)
if !ok {
@@ -10216,6 +10557,9 @@ func (m *ChannelMonitorMutation) AddedFields() []string {
if m.addinterval_seconds != nil {
fields = append(fields, channelmonitor.FieldIntervalSeconds)
}
if m.addjitter_seconds != nil {
fields = append(fields, channelmonitor.FieldJitterSeconds)
}
if m.addcreated_by != nil {
fields = append(fields, channelmonitor.FieldCreatedBy)
}
@@ -10229,6 +10573,8 @@ func (m *ChannelMonitorMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case channelmonitor.FieldIntervalSeconds:
return m.AddedIntervalSeconds()
case channelmonitor.FieldJitterSeconds:
return m.AddedJitterSeconds()
case channelmonitor.FieldCreatedBy:
return m.AddedCreatedBy()
}
@@ -10247,6 +10593,13 @@ func (m *ChannelMonitorMutation) AddField(name string, value ent.Value) error {
}
m.AddIntervalSeconds(v)
return nil
case channelmonitor.FieldJitterSeconds:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddJitterSeconds(v)
return nil
case channelmonitor.FieldCreatedBy:
v, ok := value.(int64)
if !ok {
@@ -10344,6 +10697,9 @@ func (m *ChannelMonitorMutation) ResetField(name string) error {
case channelmonitor.FieldIntervalSeconds:
m.ResetIntervalSeconds()
return nil
case channelmonitor.FieldJitterSeconds:
m.ResetJitterSeconds()
return nil
case channelmonitor.FieldLastCheckedAt:
m.ResetLastCheckedAt()
return nil
@@ -14969,6 +15325,11 @@ type GroupMutation struct {
description *string
rate_multiplier *float64
addrate_multiplier *float64
peak_rate_enabled *bool
peak_start *string
peak_end *string
peak_rate_multiplier *float64
addpeak_rate_multiplier *float64
is_exclusive *bool
status *string
platform *string
@@ -15395,6 +15756,170 @@ func (m *GroupMutation) ResetRateMultiplier() {
m.addrate_multiplier = nil
}
// SetPeakRateEnabled sets the "peak_rate_enabled" field.
func (m *GroupMutation) SetPeakRateEnabled(b bool) {
m.peak_rate_enabled = &b
}
// PeakRateEnabled returns the value of the "peak_rate_enabled" field in the mutation.
func (m *GroupMutation) PeakRateEnabled() (r bool, exists bool) {
v := m.peak_rate_enabled
if v == nil {
return
}
return *v, true
}
// OldPeakRateEnabled returns the old "peak_rate_enabled" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldPeakRateEnabled(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldPeakRateEnabled is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldPeakRateEnabled requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPeakRateEnabled: %w", err)
}
return oldValue.PeakRateEnabled, nil
}
// ResetPeakRateEnabled resets all changes to the "peak_rate_enabled" field.
func (m *GroupMutation) ResetPeakRateEnabled() {
m.peak_rate_enabled = nil
}
// SetPeakStart sets the "peak_start" field.
func (m *GroupMutation) SetPeakStart(s string) {
m.peak_start = &s
}
// PeakStart returns the value of the "peak_start" field in the mutation.
func (m *GroupMutation) PeakStart() (r string, exists bool) {
v := m.peak_start
if v == nil {
return
}
return *v, true
}
// OldPeakStart returns the old "peak_start" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldPeakStart(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldPeakStart is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldPeakStart requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPeakStart: %w", err)
}
return oldValue.PeakStart, nil
}
// ResetPeakStart resets all changes to the "peak_start" field.
func (m *GroupMutation) ResetPeakStart() {
m.peak_start = nil
}
// SetPeakEnd sets the "peak_end" field.
func (m *GroupMutation) SetPeakEnd(s string) {
m.peak_end = &s
}
// PeakEnd returns the value of the "peak_end" field in the mutation.
func (m *GroupMutation) PeakEnd() (r string, exists bool) {
v := m.peak_end
if v == nil {
return
}
return *v, true
}
// OldPeakEnd returns the old "peak_end" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldPeakEnd(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldPeakEnd is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldPeakEnd requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPeakEnd: %w", err)
}
return oldValue.PeakEnd, nil
}
// ResetPeakEnd resets all changes to the "peak_end" field.
func (m *GroupMutation) ResetPeakEnd() {
m.peak_end = nil
}
// SetPeakRateMultiplier sets the "peak_rate_multiplier" field.
func (m *GroupMutation) SetPeakRateMultiplier(f float64) {
m.peak_rate_multiplier = &f
m.addpeak_rate_multiplier = nil
}
// PeakRateMultiplier returns the value of the "peak_rate_multiplier" field in the mutation.
func (m *GroupMutation) PeakRateMultiplier() (r float64, exists bool) {
v := m.peak_rate_multiplier
if v == nil {
return
}
return *v, true
}
// OldPeakRateMultiplier returns the old "peak_rate_multiplier" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldPeakRateMultiplier(ctx context.Context) (v float64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldPeakRateMultiplier is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldPeakRateMultiplier requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldPeakRateMultiplier: %w", err)
}
return oldValue.PeakRateMultiplier, nil
}
// AddPeakRateMultiplier adds f to the "peak_rate_multiplier" field.
func (m *GroupMutation) AddPeakRateMultiplier(f float64) {
if m.addpeak_rate_multiplier != nil {
*m.addpeak_rate_multiplier += f
} else {
m.addpeak_rate_multiplier = &f
}
}
// AddedPeakRateMultiplier returns the value that was added to the "peak_rate_multiplier" field in this mutation.
func (m *GroupMutation) AddedPeakRateMultiplier() (r float64, exists bool) {
v := m.addpeak_rate_multiplier
if v == nil {
return
}
return *v, true
}
// ResetPeakRateMultiplier resets all changes to the "peak_rate_multiplier" field.
func (m *GroupMutation) ResetPeakRateMultiplier() {
m.peak_rate_multiplier = nil
m.addpeak_rate_multiplier = nil
}
// SetIsExclusive sets the "is_exclusive" field.
func (m *GroupMutation) SetIsExclusive(b bool) {
m.is_exclusive = &b
@@ -17177,7 +17702,7 @@ func (m *GroupMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupMutation) Fields() []string {
fields := make([]string, 0, 35)
fields := make([]string, 0, 39)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -17196,6 +17721,18 @@ func (m *GroupMutation) Fields() []string {
if m.rate_multiplier != nil {
fields = append(fields, group.FieldRateMultiplier)
}
if m.peak_rate_enabled != nil {
fields = append(fields, group.FieldPeakRateEnabled)
}
if m.peak_start != nil {
fields = append(fields, group.FieldPeakStart)
}
if m.peak_end != nil {
fields = append(fields, group.FieldPeakEnd)
}
if m.peak_rate_multiplier != nil {
fields = append(fields, group.FieldPeakRateMultiplier)
}
if m.is_exclusive != nil {
fields = append(fields, group.FieldIsExclusive)
}
@@ -17303,6 +17840,14 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.Description()
case group.FieldRateMultiplier:
return m.RateMultiplier()
case group.FieldPeakRateEnabled:
return m.PeakRateEnabled()
case group.FieldPeakStart:
return m.PeakStart()
case group.FieldPeakEnd:
return m.PeakEnd()
case group.FieldPeakRateMultiplier:
return m.PeakRateMultiplier()
case group.FieldIsExclusive:
return m.IsExclusive()
case group.FieldStatus:
@@ -17382,6 +17927,14 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldDescription(ctx)
case group.FieldRateMultiplier:
return m.OldRateMultiplier(ctx)
case group.FieldPeakRateEnabled:
return m.OldPeakRateEnabled(ctx)
case group.FieldPeakStart:
return m.OldPeakStart(ctx)
case group.FieldPeakEnd:
return m.OldPeakEnd(ctx)
case group.FieldPeakRateMultiplier:
return m.OldPeakRateMultiplier(ctx)
case group.FieldIsExclusive:
return m.OldIsExclusive(ctx)
case group.FieldStatus:
@@ -17491,6 +18044,34 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetRateMultiplier(v)
return nil
case group.FieldPeakRateEnabled:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPeakRateEnabled(v)
return nil
case group.FieldPeakStart:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPeakStart(v)
return nil
case group.FieldPeakEnd:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPeakEnd(v)
return nil
case group.FieldPeakRateMultiplier:
v, ok := value.(float64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetPeakRateMultiplier(v)
return nil
case group.FieldIsExclusive:
v, ok := value.(bool)
if !ok {
@@ -17705,6 +18286,9 @@ func (m *GroupMutation) AddedFields() []string {
if m.addrate_multiplier != nil {
fields = append(fields, group.FieldRateMultiplier)
}
if m.addpeak_rate_multiplier != nil {
fields = append(fields, group.FieldPeakRateMultiplier)
}
if m.adddaily_limit_usd != nil {
fields = append(fields, group.FieldDailyLimitUsd)
}
@@ -17751,6 +18335,8 @@ func (m *GroupMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case group.FieldRateMultiplier:
return m.AddedRateMultiplier()
case group.FieldPeakRateMultiplier:
return m.AddedPeakRateMultiplier()
case group.FieldDailyLimitUsd:
return m.AddedDailyLimitUsd()
case group.FieldWeeklyLimitUsd:
@@ -17791,6 +18377,13 @@ func (m *GroupMutation) AddField(name string, value ent.Value) error {
}
m.AddRateMultiplier(v)
return nil
case group.FieldPeakRateMultiplier:
v, ok := value.(float64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddPeakRateMultiplier(v)
return nil
case group.FieldDailyLimitUsd:
v, ok := value.(float64)
if !ok {
@@ -17989,6 +18582,18 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldRateMultiplier:
m.ResetRateMultiplier()
return nil
case group.FieldPeakRateEnabled:
m.ResetPeakRateEnabled()
return nil
case group.FieldPeakStart:
m.ResetPeakStart()
return nil
case group.FieldPeakEnd:
m.ResetPeakEnd()
return nil
case group.FieldPeakRateMultiplier:
m.ResetPeakRateMultiplier()
return nil
case group.FieldIsExclusive:
m.ResetIsExclusive()
return nil
+48 -22
View File
@@ -529,12 +529,18 @@ func init() {
channelmonitorDescIntervalSeconds := channelmonitorFields[9].Descriptor()
// channelmonitor.IntervalSecondsValidator is a validator for the "interval_seconds" field. It is called by the builders before save.
channelmonitor.IntervalSecondsValidator = channelmonitorDescIntervalSeconds.Validators[0].(func(int) error)
// channelmonitorDescJitterSeconds is the schema descriptor for jitter_seconds field.
channelmonitorDescJitterSeconds := channelmonitorFields[10].Descriptor()
// channelmonitor.DefaultJitterSeconds holds the default value on creation for the jitter_seconds field.
channelmonitor.DefaultJitterSeconds = channelmonitorDescJitterSeconds.Default.(int)
// channelmonitor.JitterSecondsValidator is a validator for the "jitter_seconds" field. It is called by the builders before save.
channelmonitor.JitterSecondsValidator = channelmonitorDescJitterSeconds.Validators[0].(func(int) error)
// channelmonitorDescExtraHeaders is the schema descriptor for extra_headers field.
channelmonitorDescExtraHeaders := channelmonitorFields[13].Descriptor()
channelmonitorDescExtraHeaders := channelmonitorFields[14].Descriptor()
// channelmonitor.DefaultExtraHeaders holds the default value on creation for the extra_headers field.
channelmonitor.DefaultExtraHeaders = channelmonitorDescExtraHeaders.Default.(map[string]string)
// channelmonitorDescBodyOverrideMode is the schema descriptor for body_override_mode field.
channelmonitorDescBodyOverrideMode := channelmonitorFields[14].Descriptor()
channelmonitorDescBodyOverrideMode := channelmonitorFields[15].Descriptor()
// channelmonitor.DefaultBodyOverrideMode holds the default value on creation for the body_override_mode field.
channelmonitor.DefaultBodyOverrideMode = channelmonitorDescBodyOverrideMode.Default.(string)
// channelmonitor.BodyOverrideModeValidator is a validator for the "body_override_mode" field. It is called by the builders before save.
@@ -790,92 +796,112 @@ func init() {
groupDescRateMultiplier := groupFields[2].Descriptor()
// group.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
group.DefaultRateMultiplier = groupDescRateMultiplier.Default.(float64)
// groupDescPeakRateEnabled is the schema descriptor for peak_rate_enabled field.
groupDescPeakRateEnabled := groupFields[3].Descriptor()
// group.DefaultPeakRateEnabled holds the default value on creation for the peak_rate_enabled field.
group.DefaultPeakRateEnabled = groupDescPeakRateEnabled.Default.(bool)
// groupDescPeakStart is the schema descriptor for peak_start field.
groupDescPeakStart := groupFields[4].Descriptor()
// group.DefaultPeakStart holds the default value on creation for the peak_start field.
group.DefaultPeakStart = groupDescPeakStart.Default.(string)
// group.PeakStartValidator is a validator for the "peak_start" field. It is called by the builders before save.
group.PeakStartValidator = groupDescPeakStart.Validators[0].(func(string) error)
// groupDescPeakEnd is the schema descriptor for peak_end field.
groupDescPeakEnd := groupFields[5].Descriptor()
// group.DefaultPeakEnd holds the default value on creation for the peak_end field.
group.DefaultPeakEnd = groupDescPeakEnd.Default.(string)
// group.PeakEndValidator is a validator for the "peak_end" field. It is called by the builders before save.
group.PeakEndValidator = groupDescPeakEnd.Validators[0].(func(string) error)
// groupDescPeakRateMultiplier is the schema descriptor for peak_rate_multiplier field.
groupDescPeakRateMultiplier := groupFields[6].Descriptor()
// group.DefaultPeakRateMultiplier holds the default value on creation for the peak_rate_multiplier field.
group.DefaultPeakRateMultiplier = groupDescPeakRateMultiplier.Default.(float64)
// groupDescIsExclusive is the schema descriptor for is_exclusive field.
groupDescIsExclusive := groupFields[3].Descriptor()
groupDescIsExclusive := groupFields[7].Descriptor()
// group.DefaultIsExclusive holds the default value on creation for the is_exclusive field.
group.DefaultIsExclusive = groupDescIsExclusive.Default.(bool)
// groupDescStatus is the schema descriptor for status field.
groupDescStatus := groupFields[4].Descriptor()
groupDescStatus := groupFields[8].Descriptor()
// group.DefaultStatus holds the default value on creation for the status field.
group.DefaultStatus = groupDescStatus.Default.(string)
// group.StatusValidator is a validator for the "status" field. It is called by the builders before save.
group.StatusValidator = groupDescStatus.Validators[0].(func(string) error)
// groupDescPlatform is the schema descriptor for platform field.
groupDescPlatform := groupFields[5].Descriptor()
groupDescPlatform := groupFields[9].Descriptor()
// group.DefaultPlatform holds the default value on creation for the platform field.
group.DefaultPlatform = groupDescPlatform.Default.(string)
// group.PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
group.PlatformValidator = groupDescPlatform.Validators[0].(func(string) error)
// groupDescSubscriptionType is the schema descriptor for subscription_type field.
groupDescSubscriptionType := groupFields[6].Descriptor()
groupDescSubscriptionType := groupFields[10].Descriptor()
// group.DefaultSubscriptionType holds the default value on creation for the subscription_type field.
group.DefaultSubscriptionType = groupDescSubscriptionType.Default.(string)
// group.SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save.
group.SubscriptionTypeValidator = groupDescSubscriptionType.Validators[0].(func(string) error)
// groupDescDefaultValidityDays is the schema descriptor for default_validity_days field.
groupDescDefaultValidityDays := groupFields[10].Descriptor()
groupDescDefaultValidityDays := groupFields[14].Descriptor()
// group.DefaultDefaultValidityDays holds the default value on creation for the default_validity_days field.
group.DefaultDefaultValidityDays = groupDescDefaultValidityDays.Default.(int)
// groupDescAllowImageGeneration is the schema descriptor for allow_image_generation field.
groupDescAllowImageGeneration := groupFields[11].Descriptor()
groupDescAllowImageGeneration := groupFields[15].Descriptor()
// group.DefaultAllowImageGeneration holds the default value on creation for the allow_image_generation field.
group.DefaultAllowImageGeneration = groupDescAllowImageGeneration.Default.(bool)
// groupDescImageRateIndependent is the schema descriptor for image_rate_independent field.
groupDescImageRateIndependent := groupFields[12].Descriptor()
groupDescImageRateIndependent := groupFields[16].Descriptor()
// group.DefaultImageRateIndependent holds the default value on creation for the image_rate_independent field.
group.DefaultImageRateIndependent = groupDescImageRateIndependent.Default.(bool)
// groupDescImageRateMultiplier is the schema descriptor for image_rate_multiplier field.
groupDescImageRateMultiplier := groupFields[13].Descriptor()
groupDescImageRateMultiplier := groupFields[17].Descriptor()
// group.DefaultImageRateMultiplier holds the default value on creation for the image_rate_multiplier field.
group.DefaultImageRateMultiplier = groupDescImageRateMultiplier.Default.(float64)
// groupDescClaudeCodeOnly is the schema descriptor for claude_code_only field.
groupDescClaudeCodeOnly := groupFields[17].Descriptor()
groupDescClaudeCodeOnly := groupFields[21].Descriptor()
// group.DefaultClaudeCodeOnly holds the default value on creation for the claude_code_only field.
group.DefaultClaudeCodeOnly = groupDescClaudeCodeOnly.Default.(bool)
// groupDescModelRoutingEnabled is the schema descriptor for model_routing_enabled field.
groupDescModelRoutingEnabled := groupFields[21].Descriptor()
groupDescModelRoutingEnabled := groupFields[25].Descriptor()
// group.DefaultModelRoutingEnabled holds the default value on creation for the model_routing_enabled field.
group.DefaultModelRoutingEnabled = groupDescModelRoutingEnabled.Default.(bool)
// groupDescMcpXMLInject is the schema descriptor for mcp_xml_inject field.
groupDescMcpXMLInject := groupFields[22].Descriptor()
groupDescMcpXMLInject := groupFields[26].Descriptor()
// group.DefaultMcpXMLInject holds the default value on creation for the mcp_xml_inject field.
group.DefaultMcpXMLInject = groupDescMcpXMLInject.Default.(bool)
// groupDescSupportedModelScopes is the schema descriptor for supported_model_scopes field.
groupDescSupportedModelScopes := groupFields[23].Descriptor()
groupDescSupportedModelScopes := groupFields[27].Descriptor()
// group.DefaultSupportedModelScopes holds the default value on creation for the supported_model_scopes field.
group.DefaultSupportedModelScopes = groupDescSupportedModelScopes.Default.([]string)
// groupDescSortOrder is the schema descriptor for sort_order field.
groupDescSortOrder := groupFields[24].Descriptor()
groupDescSortOrder := groupFields[28].Descriptor()
// group.DefaultSortOrder holds the default value on creation for the sort_order field.
group.DefaultSortOrder = groupDescSortOrder.Default.(int)
// groupDescAllowMessagesDispatch is the schema descriptor for allow_messages_dispatch field.
groupDescAllowMessagesDispatch := groupFields[25].Descriptor()
groupDescAllowMessagesDispatch := groupFields[29].Descriptor()
// group.DefaultAllowMessagesDispatch holds the default value on creation for the allow_messages_dispatch field.
group.DefaultAllowMessagesDispatch = groupDescAllowMessagesDispatch.Default.(bool)
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
groupDescRequireOauthOnly := groupFields[26].Descriptor()
groupDescRequireOauthOnly := groupFields[30].Descriptor()
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
groupDescRequirePrivacySet := groupFields[27].Descriptor()
groupDescRequirePrivacySet := groupFields[31].Descriptor()
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
groupDescDefaultMappedModel := groupFields[28].Descriptor()
groupDescDefaultMappedModel := groupFields[32].Descriptor()
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
groupDescMessagesDispatchModelConfig := groupFields[29].Descriptor()
groupDescMessagesDispatchModelConfig := groupFields[33].Descriptor()
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
// groupDescModelsListConfig is the schema descriptor for models_list_config field.
groupDescModelsListConfig := groupFields[30].Descriptor()
groupDescModelsListConfig := groupFields[34].Descriptor()
// group.DefaultModelsListConfig holds the default value on creation for the models_list_config field.
group.DefaultModelsListConfig = groupDescModelsListConfig.Default.(domain.GroupModelsListConfig)
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
groupDescRpmLimit := groupFields[31].Descriptor()
groupDescRpmLimit := groupFields[35].Descriptor()
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
+14
View File
@@ -196,6 +196,11 @@ func (Account) Fields() []ent.Field {
Optional().
Nillable().
MaxLen(20),
field.Int64("parent_account_id").Optional().Nillable().
Comment("Parent account id for a linked spark shadow (NULL = normal)."),
field.Enum("quota_dimension").Values("global", "spark").Default("global").
Comment("'global' (default) or 'spark' (shadow reads codex_bengalfox)."),
}
}
@@ -212,6 +217,14 @@ func (Account) Edges() []ent.Edge {
edge.To("proxy", Proxy.Type).
Field("proxy_id").
Unique(),
// children/parent: linked spark shadow relationship.
// parent_account_id is nullable, and the active one-shadow-per-parent rule
// is enforced by the partial unique index in migration 154a.
edge.To("children", Account.Type).
Annotations(entsql.OnDelete(entsql.Restrict)).
From("parent").
Field("parent_account_id").
Unique(),
// usage_logs: 该账户的使用日志
edge.To("usage_logs", UsageLog.Type),
}
@@ -235,5 +248,6 @@ func (Account) Indexes() []ent.Index {
index.Fields("platform", "priority"),
index.Fields("priority", "status"),
index.Fields("deleted_at"), // 软删除查询优化
index.Fields("parent_account_id"),
}
}
+4
View File
@@ -62,6 +62,10 @@ func (ChannelMonitor) Fields() []ent.Field {
Default(true),
field.Int("interval_seconds").
Range(15, 3600),
field.Int("jitter_seconds").
Default(0).
Range(0, 3600).
Comment("每次调度在 interval 基础上 ± [0, jitter] 的均匀随机偏移(秒);0 表示固定间隔。service 层另保证 interval - jitter >= 15"),
field.Time("last_checked_at").
Optional().
Nillable(),
+16
View File
@@ -45,6 +45,22 @@ func (Group) Fields() []ent.Field {
field.Float("rate_multiplier").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(1.0),
// 高峰时段倍率(added by migration 158)
field.Bool("peak_rate_enabled").
Default(false).
Comment("是否启用高峰时段倍率"),
field.String("peak_start").
MaxLen(5).
Default("").
Comment("高峰开始时间 HH:MM(含),如 14:00;空表示未配置;不支持跨天"),
field.String("peak_end").
MaxLen(5).
Default("").
Comment("高峰结束时间 HH:MM(不含),必须大于 peak_start;不支持跨天,如 22:00-02:00"),
field.Float("peak_rate_multiplier").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(1.0).
Comment("高峰时段叠加倍率,仅在 peak_rate_enabled 且处于 [peak_start, peak_end) 时乘入文本倍率"),
field.Bool("is_exclusive").
Default(false),
field.String("status").
+1 -1
View File
@@ -41,7 +41,7 @@ func (UserPlatformQuota) Fields() []ent.Field {
// 注意:平台列表的单一权威源为 service.AllowedQuotaPlatforms;
// 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。
switch s {
case "anthropic", "openai", "gemini", "antigravity":
case "anthropic", "openai", "gemini", "antigravity", "grok":
return nil
default:
return fmt.Errorf("platform %q is not allowed", s)
+17
View File
@@ -0,0 +1,17 @@
package ent
import "context"
// WithoutTx 返回一个剥离了所附 *Tx 的 ctx 副本,使调用方可以在基础 client
// (autocommit)上执行 best-effort、非关键的副作用,而不加入——也就不会毒化——
// 外层事务。
//
// Postgres 语义:事务内任一语句失败即把整个事务标记为 aborted,后续语句全部被拒,
// 直到 ROLLBACK。因此对 fail-open 的副作用(如注册时的默认平台配额快照)必须做事务
// 隔离,否则一条无关紧要的写入失败会连累调用方的关键事务。
func WithoutTx(ctx context.Context) context.Context {
if TxFromContext(ctx) == nil {
return ctx
}
return context.WithValue(ctx, txCtxKey{}, (*Tx)(nil))
}
+3 -1
View File
@@ -86,6 +86,7 @@ require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/dlclark/regexp2/v2 v2.1.0 // indirect
github.com/docker/docker v28.5.1+incompatible // indirect
github.com/docker/go-connections v0.6.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
@@ -119,7 +120,7 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mdelapenya/tlscert v0.2.0 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/mitchellh/mapstructure v1.5.0
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.1.0 // indirect
github.com/moby/patternmatcher v0.6.0 // indirect
@@ -155,6 +156,7 @@ require (
github.com/testcontainers/testcontainers-go v0.40.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tiktoken-go/tokenizer v0.8.0 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
+6
View File
@@ -108,6 +108,8 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/dlclark/regexp2/v2 v2.1.0 h1:jHXRmHRZGbuQzDZjMlCAXOvQb75iv3HyLDzXGj5H1AY=
github.com/dlclark/regexp2/v2 v2.1.0/go.mod h1:Bz5TMy5d8fPK0ximH0Yi9KvsRHNnvXqUx9XG6a4wB+I=
github.com/docker/docker v28.5.1+incompatible h1:Bm8DchhSD2J6PsFzxC35TZo4TLGR2PdW/E69rU45NhM=
github.com/docker/docker v28.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94=
@@ -164,6 +166,8 @@ github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE=
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=
@@ -358,6 +362,8 @@ github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/tiktoken-go/tokenizer v0.8.0 h1:drHWno2Zx3eAm/hk/LmvBKXPpSImB7BRyh/ru4+3Q7Y=
github.com/tiktoken-go/tokenizer v0.8.0/go.mod h1:pTmPz4r14MV3JkUGAmAcdLdYhSxN68MCjrP+EoxBdx0=
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
+44 -48
View File
@@ -93,15 +93,6 @@ type Config struct {
Gemini GeminiConfig `mapstructure:"gemini"`
Update UpdateConfig `mapstructure:"update"`
Idempotency IdempotencyConfig `mapstructure:"idempotency"`
// Modules 是插件模块配置子树(modules:)的原始内容。
// 顶层 key 为模块 ID 字面量(如 "job.hello"),value 为该模块的原始配置
// (含可选 enabled 键),语义解析由 internal/plugin 包负责。
//
// 注意:该字段不走 viper.Unmarshal(mapstructure:"-"),而是在 load() 中通过
// viper.Get 手工提取——Unmarshal 基于 AllSettings 重建嵌套结构,会把含点的
// 模块 ID key 错误拆分为多级嵌套。缺省(未配置)时为空 map,行为与现状完全等价。
Modules map[string]map[string]any `mapstructure:"-" yaml:"-"`
}
type LogConfig struct {
@@ -652,6 +643,10 @@ type ProxyProbeConfig struct {
type BillingConfig struct {
CircuitBreaker CircuitBreakerConfig `mapstructure:"circuit_breaker"`
// MinimumBalanceReserve is the conservative preflight floor for balance billing.
// Requests in balance mode are rejected when the cached balance is below this
// amount, even if it is still positive. Set to 0 to keep the legacy balance > 0 gate.
MinimumBalanceReserve float64 `mapstructure:"minimum_balance_reserve"`
// UserPlatformQuotaCacheTTLSeconds 用户 × 平台 quota 缓存 TTL(秒),默认 86400=1天,覆盖典型 daily 窗口。
// 消费点:
// - billing_cache_service.cacheWriteWorker 异步累加
@@ -726,6 +721,9 @@ type GatewayConfig struct {
// OpenAIPassthroughAllowTimeoutHeaders: OpenAI 透传模式是否放行客户端超时头
// 关闭(默认)可避免 x-stainless-timeout 等头导致上游提前断流。
OpenAIPassthroughAllowTimeoutHeaders bool `mapstructure:"openai_passthrough_allow_timeout_headers"`
// OpenAICompactModel: /responses/compact 上游使用的模型。
// compact 端点支持模型滞后于普通 /responses 时,可用该配置降级规避上游错误。
OpenAICompactModel string `mapstructure:"openai_compact_model"`
// OpenAIWS: OpenAI Responses WebSocket 配置(默认开启,可按需回滚到 HTTP)
OpenAIWS GatewayOpenAIWSConfig `mapstructure:"openai_ws"`
// OpenAIScheduler: OpenAI 高级调度器粘性逃逸配置
@@ -872,7 +870,7 @@ func (c *UserMessageQueueConfig) GetEffectiveMode() string {
type GatewayOpenAIWSConfig struct {
// ModeRouterV2Enabled: 新版 WS mode 路由开关(默认 false;关闭时保持 legacy 行为)
ModeRouterV2Enabled bool `mapstructure:"mode_router_v2_enabled"`
// IngressModeDefault: ingress 默认模式(off/ctx_pool/passthrough)
// IngressModeDefault: ingress 默认模式(off/ctx_pool/passthrough/http_bridge)
IngressModeDefault string `mapstructure:"ingress_mode_default"`
// Enabled: 全局总开关(默认 true)
Enabled bool `mapstructure:"enabled"`
@@ -966,6 +964,14 @@ type GatewayOpenAIWSSchedulerScoreWeights struct {
Queue float64 `mapstructure:"queue"`
ErrorRate float64 `mapstructure:"error_rate"`
TTFT float64 `mapstructure:"ttft"`
// Reset 倾向「会话窗口最早重置」的账号(use-it-or-lose-it)。
// >0 时,剩余重置时间越短的账号得分越高,从而被优先用尽。默认 0(关闭,不改变原有行为)。
Reset float64 `mapstructure:"reset"`
// QuotaHeadroom 倾向 7d 剩余额度更健康的账号;默认 0(关闭,不改变原有行为)。
QuotaHeadroom float64 `mapstructure:"quota_headroom"`
// PreviousResponse/SessionSticky 仅在开启 OpenAI 高级调度的粘性加权时生效。
PreviousResponse float64 `mapstructure:"previous_response"`
SessionSticky float64 `mapstructure:"session_sticky"`
}
// GatewayOpenAISchedulerConfig OpenAI 高级调度器配置。
@@ -1064,6 +1070,11 @@ type GatewaySchedulingConfig struct {
// 兜底层账户选择策略: "last_used"(按最后使用时间排序,默认) 或 "random"(随机)
FallbackSelectionMode string `mapstructure:"fallback_selection_mode"`
// PreferSoonestReset 开启后,负载感知选择会优先选用「会话窗口最早重置」的账号
// (use-it-or-lose-it:先用尽即将重置的账号,保留重置时间还很久的账号)。
// 默认 false,保持原有「优先级 → 负载率 → LRU」行为不变。
PreferSoonestReset bool `mapstructure:"prefer_soonest_reset"`
// 负载计算
LoadBatchEnabled bool `mapstructure:"load_batch_enabled"`
LoadBatchCacheTTLMS int `mapstructure:"load_batch_cache_ttl_ms"`
@@ -1406,11 +1417,6 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
if err := viper.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("unmarshal config error: %w", err)
}
modules, err := normalizeModulesSubtree(viper.Get("modules"))
if err != nil {
return nil, fmt.Errorf("parse modules config error: %w", err)
}
cfg.Modules = modules
if cfg.Gateway.OpenAIScheduler.StickyEscapeTTFTMs == 0 {
cfg.Gateway.OpenAIScheduler.StickyEscapeTTFTMs = 15000
}
@@ -1544,33 +1550,6 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
return &cfg, nil
}
// normalizeModulesSubtree 将 viper 读取的 modules: 原始子树规整为
// map[模块ID]map[配置键]值。raw 为 nil(未配置)时返回空 map(零行为影响);
// 子树或某个模块项不是映射时返回错误。空模块项(如 "job.hello:" 后无内容)
// 规整为空 map,表示"提及但无私有配置"。
func normalizeModulesSubtree(raw any) (map[string]map[string]any, error) {
result := make(map[string]map[string]any)
if raw == nil {
return result, nil
}
top, ok := raw.(map[string]any)
if !ok {
return nil, fmt.Errorf("modules: expected a mapping, got %T", raw)
}
for key, value := range top {
if value == nil {
result[key] = map[string]any{}
continue
}
entry, ok := value.(map[string]any)
if !ok {
return nil, fmt.Errorf("modules.%s: expected a mapping, got %T", key, value)
}
result[key] = entry
}
return result, nil
}
func setDefaults() {
viper.SetDefault("run_mode", RunModeStandard)
@@ -1648,6 +1627,7 @@ func setDefaults() {
viper.SetDefault("billing.circuit_breaker.failure_threshold", 5)
viper.SetDefault("billing.circuit_breaker.reset_timeout_seconds", 30)
viper.SetDefault("billing.circuit_breaker.half_open_requests", 3)
viper.SetDefault("billing.minimum_balance_reserve", 0.000001)
viper.SetDefault("billing.user_platform_quota_cache_ttl_seconds", 86400)
viper.SetDefault("billing.user_platform_quota_sentinel_ttl_seconds", 3600)
@@ -1862,6 +1842,7 @@ func setDefaults() {
viper.SetDefault("gateway.force_codex_cli", false)
viper.SetDefault("gateway.codex_image_generation_bridge_enabled", false)
viper.SetDefault("gateway.openai_passthrough_allow_timeout_headers", false)
viper.SetDefault("gateway.openai_compact_model", "gpt-5.4")
// OpenAI Responses WebSocket(默认开启;可通过 force_http 紧急回滚)
viper.SetDefault("gateway.openai_ws.enabled", true)
viper.SetDefault("gateway.openai_ws.mode_router_v2_enabled", false)
@@ -1911,6 +1892,10 @@ func setDefaults() {
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.queue", 0.7)
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.error_rate", 0.8)
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.ttft", 0.5)
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.reset", 0.0)
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.quota_headroom", 0.0)
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.previous_response", 5.0)
viper.SetDefault("gateway.openai_ws.scheduler_score_weights.session_sticky", 3.0)
// OpenAI HTTP upstream protocol strategy
viper.SetDefault("gateway.openai_http2.enabled", true)
viper.SetDefault("gateway.openai_http2.allow_proxy_fallback_to_http1", true)
@@ -1947,6 +1932,7 @@ func setDefaults() {
viper.SetDefault("gateway.scheduling.fallback_wait_timeout", 30*time.Second)
viper.SetDefault("gateway.scheduling.fallback_max_waiting", 100)
viper.SetDefault("gateway.scheduling.fallback_selection_mode", "last_used")
viper.SetDefault("gateway.scheduling.prefer_soonest_reset", false)
viper.SetDefault("gateway.scheduling.load_batch_enabled", true)
viper.SetDefault("gateway.scheduling.load_batch_cache_ttl_ms", 200)
viper.SetDefault("gateway.scheduling.snapshot_mget_chunk_size", 128)
@@ -1964,7 +1950,10 @@ func setDefaults() {
viper.SetDefault("gateway.usage_record.worker_count", 128)
viper.SetDefault("gateway.usage_record.queue_size", 16384)
viper.SetDefault("gateway.usage_record.task_timeout_seconds", 5)
viper.SetDefault("gateway.usage_record.overflow_policy", UsageRecordOverflowPolicySample)
// 默认 sync:队列满时由提交方内联执行(提交点在响应写出之后,不阻塞客户端)。
// sample/drop 会在溢出时静默丢弃计费任务,造成扣费与 usage_logs 对账缺口(issue #3656),
// 仅供显式配置的运维场景使用。
viper.SetDefault("gateway.usage_record.overflow_policy", UsageRecordOverflowPolicySync)
viper.SetDefault("gateway.usage_record.overflow_sample_percent", 10)
viper.SetDefault("gateway.usage_record.auto_scale_enabled", true)
viper.SetDefault("gateway.usage_record.auto_scale_min_workers", 128)
@@ -2308,6 +2297,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("billing.circuit_breaker.half_open_requests must be positive")
}
}
if c.Billing.MinimumBalanceReserve < 0 {
return fmt.Errorf("billing.minimum_balance_reserve must be non-negative")
}
if c.Database.MaxOpenConns <= 0 {
return fmt.Errorf("database.max_open_conns must be positive")
}
@@ -2644,11 +2636,11 @@ func (c *Config) Validate() error {
}
if mode := strings.ToLower(strings.TrimSpace(c.Gateway.OpenAIWS.IngressModeDefault)); mode != "" {
switch mode {
case "off", "ctx_pool", "passthrough":
case "off", "ctx_pool", "passthrough", "http_bridge":
case "shared", "dedicated":
slog.Warn("gateway.openai_ws.ingress_mode_default is deprecated, treating as ctx_pool; please update to off|ctx_pool|passthrough", "value", mode)
slog.Warn("gateway.openai_ws.ingress_mode_default is deprecated, treating as ctx_pool; please update to off|ctx_pool|passthrough|http_bridge", "value", mode)
default:
return fmt.Errorf("gateway.openai_ws.ingress_mode_default must be one of off|ctx_pool|passthrough")
return fmt.Errorf("gateway.openai_ws.ingress_mode_default must be one of off|ctx_pool|passthrough|http_bridge")
}
}
if mode := strings.ToLower(strings.TrimSpace(c.Gateway.OpenAIWS.StoreDisabledConnMode)); mode != "" {
@@ -2686,14 +2678,18 @@ func (c *Config) Validate() error {
c.Gateway.OpenAIWS.SchedulerScoreWeights.Load < 0 ||
c.Gateway.OpenAIWS.SchedulerScoreWeights.Queue < 0 ||
c.Gateway.OpenAIWS.SchedulerScoreWeights.ErrorRate < 0 ||
c.Gateway.OpenAIWS.SchedulerScoreWeights.TTFT < 0 {
c.Gateway.OpenAIWS.SchedulerScoreWeights.TTFT < 0 ||
c.Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom < 0 ||
c.Gateway.OpenAIWS.SchedulerScoreWeights.PreviousResponse < 0 ||
c.Gateway.OpenAIWS.SchedulerScoreWeights.SessionSticky < 0 {
return fmt.Errorf("gateway.openai_ws.scheduler_score_weights.* must be non-negative")
}
weightSum := c.Gateway.OpenAIWS.SchedulerScoreWeights.Priority +
c.Gateway.OpenAIWS.SchedulerScoreWeights.Load +
c.Gateway.OpenAIWS.SchedulerScoreWeights.Queue +
c.Gateway.OpenAIWS.SchedulerScoreWeights.ErrorRate +
c.Gateway.OpenAIWS.SchedulerScoreWeights.TTFT
c.Gateway.OpenAIWS.SchedulerScoreWeights.TTFT +
c.Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom
if weightSum <= 0 {
return fmt.Errorf("gateway.openai_ws.scheduler_score_weights must not all be zero")
}
+45 -3
View File
@@ -167,6 +167,9 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
if cfg.Gateway.OpenAIWS.PayloadLogSampleRate != 0.2 {
t.Fatalf("Gateway.OpenAIWS.PayloadLogSampleRate = %v, want 0.2", cfg.Gateway.OpenAIWS.PayloadLogSampleRate)
}
if cfg.Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom != 0 {
t.Fatalf("Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom = %v, want 0", cfg.Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom)
}
if !cfg.Gateway.OpenAIWS.StoreDisabledForceNewConn {
t.Fatalf("Gateway.OpenAIWS.StoreDisabledForceNewConn = false, want true")
}
@@ -181,6 +184,23 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
}
}
func TestLoadDefaultOpenAICompactModel(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, "gpt-5.4", cfg.Gateway.OpenAICompactModel)
}
func TestLoadOpenAICompactModelFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_COMPACT_MODEL", "gpt-5.3-codex")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, "gpt-5.3-codex", cfg.Gateway.OpenAICompactModel)
}
func TestLoadDefaultOpenAIHTTP2Enabled(t *testing.T) {
resetViperWithJWTSecret(t)
@@ -1157,6 +1177,11 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Billing.CircuitBreaker.HalfOpenRequests = 0 },
wantErr: "billing.circuit_breaker.half_open_requests",
},
{
name: "billing minimum balance reserve",
mutate: func(c *Config) { c.Billing.MinimumBalanceReserve = -0.01 },
wantErr: "billing.minimum_balance_reserve",
},
{
name: "database max open conns",
mutate: func(c *Config) { c.Database.MaxOpenConns = 0 },
@@ -1670,7 +1695,7 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
wantErr: "gateway.openai_ws.store_disabled_conn_mode",
},
{
name: "ingress_mode_default 必须为 off|ctx_pool|passthrough",
name: "ingress_mode_default 必须为 off|ctx_pool|passthrough|http_bridge",
mutate: func(c *Config) { c.Gateway.OpenAIWS.IngressModeDefault = "invalid" },
wantErr: "gateway.openai_ws.ingress_mode_default",
},
@@ -1712,6 +1737,11 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIWS.SchedulerScoreWeights.Queue = -0.1 },
wantErr: "gateway.openai_ws.scheduler_score_weights.* must be non-negative",
},
{
name: "scheduler_score_weights quota_headroom 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom = -0.1 },
wantErr: "gateway.openai_ws.scheduler_score_weights.* must be non-negative",
},
{
name: "scheduler_score_weights 不能全为 0",
mutate: func(c *Config) {
@@ -1751,6 +1781,18 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
require.Contains(t, err.Error(), tc.wantErr)
})
}
t.Run("quota_headroom 可作为唯一有效调度权重", func(t *testing.T) {
cfg := buildValid(t)
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.Priority = 0
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.Load = 0
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.Queue = 0
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.ErrorRate = 0
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.TTFT = 0
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.QuotaHeadroom = 0.1
require.NoError(t, cfg.Validate())
})
}
func TestValidateConfig_AutoScaleDisabledIgnoreAutoScaleFields(t *testing.T) {
@@ -1861,8 +1903,8 @@ func TestLoad_DefaultGatewayUsageRecordConfig(t *testing.T) {
if cfg.Gateway.UsageRecord.TaskTimeoutSeconds != 5 {
t.Fatalf("task_timeout_seconds = %d, want 5", cfg.Gateway.UsageRecord.TaskTimeoutSeconds)
}
if cfg.Gateway.UsageRecord.OverflowPolicy != UsageRecordOverflowPolicySample {
t.Fatalf("overflow_policy = %s, want %s", cfg.Gateway.UsageRecord.OverflowPolicy, UsageRecordOverflowPolicySample)
if cfg.Gateway.UsageRecord.OverflowPolicy != UsageRecordOverflowPolicySync {
t.Fatalf("overflow_policy = %s, want %s", cfg.Gateway.UsageRecord.OverflowPolicy, UsageRecordOverflowPolicySync)
}
if cfg.Gateway.UsageRecord.OverflowSamplePercent != 10 {
t.Fatalf("overflow_sample_percent = %d, want 10", cfg.Gateway.UsageRecord.OverflowSamplePercent)
@@ -1,89 +0,0 @@
package config
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
// TestLoadModulesSubtreeDefaultEmpty 验证不配置 modules: 子树时,
// cfg.Modules 为空(非 nil)map,解析结果与现状完全等价。
func TestLoadModulesSubtreeDefaultEmpty(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.NotNil(t, cfg.Modules)
require.Empty(t, cfg.Modules)
}
// TestLoadModulesSubtreeParsing 验证 modules: 子树解析:
// 含点的模块 ID 必须作为完整 key 保留(不被 viper 按 "." 拆分为多级嵌套)。
func TestLoadModulesSubtreeParsing(t *testing.T) {
resetViperWithJWTSecret(t)
tempDir := t.TempDir()
configPath := filepath.Join(tempDir, "config.yaml")
yaml := `
modules:
job.hello:
enabled: true
greeting: "hi"
payment.provider.stripe:
enabled: false
job.bare:
`
require.NoError(t, os.WriteFile(configPath, []byte(yaml), 0o644))
t.Setenv("DATA_DIR", tempDir)
cfg, err := Load()
require.NoError(t, err)
require.Len(t, cfg.Modules, 3)
require.Equal(t, map[string]any{"enabled": true, "greeting": "hi"}, cfg.Modules["job.hello"])
require.Equal(t, map[string]any{"enabled": false}, cfg.Modules["payment.provider.stripe"])
// 空模块项规整为空 map(提及但无私有配置)。
require.NotNil(t, cfg.Modules["job.bare"])
require.Empty(t, cfg.Modules["job.bare"])
}
// TestLoadModulesSubtreeInvalidShape 验证 modules 子树形状非法时报错。
func TestLoadModulesSubtreeInvalidShape(t *testing.T) {
resetViperWithJWTSecret(t)
tempDir := t.TempDir()
configPath := filepath.Join(tempDir, "config.yaml")
require.NoError(t, os.WriteFile(configPath, []byte("modules:\n job.hello: true\n"), 0o644))
t.Setenv("DATA_DIR", tempDir)
_, err := Load()
require.Error(t, err)
require.Contains(t, err.Error(), "modules")
}
// TestNormalizeModulesSubtree 直接覆盖规整函数的边界分支。
func TestNormalizeModulesSubtree(t *testing.T) {
t.Run("nil input", func(t *testing.T) {
out, err := normalizeModulesSubtree(nil)
require.NoError(t, err)
require.NotNil(t, out)
require.Empty(t, out)
})
t.Run("non-map top level", func(t *testing.T) {
_, err := normalizeModulesSubtree([]any{"x"})
require.Error(t, err)
})
t.Run("non-map entry", func(t *testing.T) {
_, err := normalizeModulesSubtree(map[string]any{"job.hello": 42})
require.Error(t, err)
require.Contains(t, err.Error(), "job.hello")
})
t.Run("nil entry becomes empty map", func(t *testing.T) {
out, err := normalizeModulesSubtree(map[string]any{"job.hello": nil})
require.NoError(t, err)
require.NotNil(t, out["job.hello"])
require.Empty(t, out["job.hello"])
})
}
+10 -3
View File
@@ -22,6 +22,7 @@ const (
PlatformOpenAI = "openai"
PlatformGemini = "gemini"
PlatformAntigravity = "antigravity"
PlatformGrok = "grok"
)
// Account type constants
@@ -67,6 +68,9 @@ const (
SubscriptionStatusSuspended = "suspended"
)
// AntigravityGemini31ProAgentModel is the upstream route for Gemini 3.1 Pro High.
const AntigravityGemini31ProAgentModel = "gemini-pro-agent"
// DefaultAntigravityModelMapping 是 Antigravity 平台的默认模型映射
// 当账号未配置 model_mapping 时使用此默认值
// 与前端 useModelWhitelist.ts 中的 antigravityDefaultMappings 保持一致
@@ -102,10 +106,12 @@ var DefaultAntigravityModelMapping = map[string]string{
"gemini-3-flash-preview": "gemini-3-flash",
"gemini-3-pro-preview": "gemini-3-pro-high",
// Gemini 3.1 白名单
"gemini-3.1-pro-high": "gemini-3.1-pro-high",
"gemini-3.1-pro-low": "gemini-3.1-pro-low",
AntigravityGemini31ProAgentModel: AntigravityGemini31ProAgentModel,
"gemini-3.1-pro": AntigravityGemini31ProAgentModel,
"gemini-3.1-pro-high": AntigravityGemini31ProAgentModel,
"gemini-3.1-pro-low": "gemini-3.1-pro-low",
// Gemini 3.1 preview 映射
"gemini-3.1-pro-preview": "gemini-3.1-pro-high",
"gemini-3.1-pro-preview": AntigravityGemini31ProAgentModel,
// Gemini 3.1 image 白名单
"gemini-3.1-flash-image": "gemini-3.1-flash-image",
// Gemini 3.1 image preview 映射
@@ -135,6 +141,7 @@ var DefaultBedrockModelMapping = map[string]string{
"claude-opus-4-1": "us.anthropic.claude-opus-4-1-20250805-v1:0",
"claude-opus-4-20250514": "us.anthropic.claude-opus-4-20250514-v1:0",
// Claude Sonnet
"claude-sonnet-5": "us.anthropic.claude-sonnet-5-v1",
"claude-sonnet-4-6-thinking": "us.anthropic.claude-sonnet-4-6",
"claude-sonnet-4-6": "us.anthropic.claude-sonnet-4-6",
"claude-sonnet-4-5": "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
+22
View File
@@ -43,6 +43,28 @@ func TestDefaultAntigravityModelMapping_ContainsNewClaudeModels(t *testing.T) {
}
}
func TestDefaultAntigravityModelMapping_Gemini31ProAliases(t *testing.T) {
t.Parallel()
cases := map[string]string{
AntigravityGemini31ProAgentModel: AntigravityGemini31ProAgentModel,
"gemini-3.1-pro": AntigravityGemini31ProAgentModel,
"gemini-3.1-pro-high": AntigravityGemini31ProAgentModel,
"gemini-3.1-pro-preview": AntigravityGemini31ProAgentModel,
"gemini-3.1-pro-low": "gemini-3.1-pro-low",
}
for from, want := range cases {
got, ok := DefaultAntigravityModelMapping[from]
if !ok {
t.Fatalf("expected mapping for %q to exist", from)
}
if got != want {
t.Fatalf("unexpected mapping for %q: got %q want %q", from, got, want)
}
}
}
func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) {
t.Parallel()
-82
View File
@@ -1,82 +0,0 @@
package gatewayhook
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"go.uber.org/zap"
)
// Chain 按固定顺序执行 pre-flight 钩子。
//
// 执行语义(SEAM-DESIGN 裁决 H 链层三件必补):
// 1. 每钩子 recover():panic 记 error 日志后按 fail-open 继续下一钩子;
// 2. 钩子返回 error 默认 fail-open:记日志后继续下一钩子(与内容审核现状一致);
// 3. 首个 Blocked Decision 即短路返回;非 Blocked 的 Decision 视为放行并继续。
//
// Run 永不向调用方返回 error:返回 nil 即放行。
type Chain struct {
hooks []PreFlightHook
log *zap.Logger
}
// NewChain 构造钩子链。log 传 nil 时延迟回退到进程全局 logger;
// nil 钩子被忽略。
func NewChain(log *zap.Logger, hooks ...PreFlightHook) *Chain {
filtered := make([]PreFlightHook, 0, len(hooks))
for _, hook := range hooks {
if hook != nil {
filtered = append(filtered, hook)
}
}
return &Chain{hooks: filtered, log: log}
}
// IsEmpty 报告链上是否没有任何钩子(nil 链视为空链)。
// 调用侧可据此零开销跳过钩子请求的构造。
func (c *Chain) IsEmpty() bool {
return c == nil || len(c.hooks) == 0
}
// Run 按序执行钩子,返回首个 Blocked Decision;全部放行(或链为空)返回 nil。
func (c *Chain) Run(ctx context.Context, req *Request) *Decision {
if c.IsEmpty() {
return nil
}
for _, hook := range c.hooks {
if decision := c.runHook(ctx, hook, req); decision != nil && decision.Blocked {
return decision
}
}
return nil
}
// runHook 执行单个钩子并隔离其 panic / error(均按 fail-open 降级为放行)。
func (c *Chain) runHook(ctx context.Context, hook PreFlightHook, req *Request) (decision *Decision) {
hookID := ""
defer func() {
if r := recover(); r != nil {
c.logger().Error("gatewayhook.hook_panic",
zap.String("hook_id", hookID),
zap.Any("panic_value", r),
zap.Stack("stack"))
decision = nil // fail-open:panic 钩子视为放行
}
}()
hookID = hook.HookID()
d, err := hook.CheckPreFlight(ctx, req)
if err != nil {
c.logger().Warn("gatewayhook.hook_error",
zap.String("hook_id", hookID),
zap.Error(err))
return nil // fail-open:钩子自身故障视为放行
}
return d
}
func (c *Chain) logger() *zap.Logger {
if c != nil && c.log != nil {
return c.log
}
return logger.L()
}
-130
View File
@@ -1,130 +0,0 @@
package gatewayhook
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
)
// stubHook 是可编程的测试钩子,记录自己是否被执行。
type stubHook struct {
id string
decision *Decision
err error
panicVal any
calls *[]string
}
func (h *stubHook) HookID() string { return h.id }
func (h *stubHook) CheckPreFlight(ctx context.Context, req *Request) (*Decision, error) {
if h.calls != nil {
*h.calls = append(*h.calls, h.id)
}
if h.panicVal != nil {
panic(h.panicVal)
}
return h.decision, h.err
}
func TestChainRun_ExecutesHooksInOrder(t *testing.T) {
var calls []string
chain := NewChain(zap.NewNop(),
&stubHook{id: "first", calls: &calls},
&stubHook{id: "second", calls: &calls},
&stubHook{id: "third", calls: &calls},
)
decision := chain.Run(context.Background(), &Request{})
require.Nil(t, decision, "全部放行时 Run 必须返回 nil")
require.Equal(t, []string{"first", "second", "third"}, calls, "钩子必须按注册顺序执行")
}
func TestChainRun_FirstBlockedShortCircuits(t *testing.T) {
var calls []string
blocked := &Decision{Blocked: true, StatusCode: 403, ErrorType: "content_policy_violation", Message: "blocked"}
chain := NewChain(zap.NewNop(),
&stubHook{id: "pass", calls: &calls},
&stubHook{id: "block", decision: blocked, calls: &calls},
&stubHook{id: "never", calls: &calls},
)
decision := chain.Run(context.Background(), &Request{})
require.Same(t, blocked, decision, "必须原样返回首个 Blocked Decision")
require.Equal(t, []string{"pass", "block"}, calls, "Blocked 之后的钩子不得执行")
}
func TestChainRun_NonBlockedDecisionContinues(t *testing.T) {
var calls []string
chain := NewChain(zap.NewNop(),
&stubHook{id: "flag-only", decision: &Decision{Blocked: false, Message: "flagged"}, calls: &calls},
&stubHook{id: "after", calls: &calls},
)
decision := chain.Run(context.Background(), &Request{})
require.Nil(t, decision, "非 Blocked 的 Decision 视为放行")
require.Equal(t, []string{"flag-only", "after"}, calls)
}
func TestChainRun_PanicIsolatedAndFailOpen(t *testing.T) {
core, logs := observer.New(zap.ErrorLevel)
var calls []string
blocked := &Decision{Blocked: true, StatusCode: 403, Message: "blocked"}
chain := NewChain(zap.New(core),
&stubHook{id: "boomer", panicVal: "boom", calls: &calls},
&stubHook{id: "blocker", decision: blocked, calls: &calls},
)
decision := chain.Run(context.Background(), &Request{})
require.Same(t, blocked, decision, "panic 钩子 fail-open 后链必须继续执行后续钩子")
require.Equal(t, []string{"boomer", "blocker"}, calls)
entries := logs.FilterMessage("gatewayhook.hook_panic").All()
require.Len(t, entries, 1, "panic 必须记一条 error 日志")
fields := entries[0].ContextMap()
require.Equal(t, "boomer", fields["hook_id"])
require.Equal(t, "boom", fields["panic_value"])
// 仅 panic 钩子的链:整体放行。
onlyPanic := NewChain(zap.New(core), &stubHook{id: "boomer2", panicVal: errors.New("kaboom")})
require.Nil(t, onlyPanic.Run(context.Background(), &Request{}))
}
func TestChainRun_HookErrorFailOpen(t *testing.T) {
core, logs := observer.New(zap.WarnLevel)
var calls []string
chain := NewChain(zap.New(core),
// 即使 error 钩子同时返回了 Blocked Decision,error 优先按 fail-open 丢弃。
&stubHook{id: "broken", decision: &Decision{Blocked: true}, err: errors.New("hook exploded"), calls: &calls},
&stubHook{id: "after", calls: &calls},
)
decision := chain.Run(context.Background(), &Request{})
require.Nil(t, decision, "钩子 error 必须 fail-open 放行")
require.Equal(t, []string{"broken", "after"}, calls, "error 钩子之后链必须继续")
entries := logs.FilterMessage("gatewayhook.hook_error").All()
require.Len(t, entries, 1)
require.Equal(t, "broken", entries[0].ContextMap()["hook_id"])
}
func TestChainRun_EmptyChain(t *testing.T) {
require.Nil(t, NewChain(zap.NewNop()).Run(context.Background(), &Request{}))
require.True(t, NewChain(zap.NewNop()).IsEmpty())
var nilChain *Chain
require.True(t, nilChain.IsEmpty(), "nil 链视为空链")
require.Nil(t, nilChain.Run(context.Background(), &Request{}), "nil 链 Run 必须安全放行")
// nil 钩子在构造时被过滤。
require.True(t, NewChain(zap.NewNop(), nil, nil).IsEmpty())
}
-96
View File
@@ -1,96 +0,0 @@
// Package gatewayhook 定义网关 pre-flight 钩子链(Phase-2 SEAM-DESIGN 裁决 H)。
//
// 设计要点:
// - 独立包:不依赖 internal/handler 与 internal/server/middleware(CallerInfo
// 即为与 middleware.AuthSubject 解耦的最小身份视图);
// - 链只产 Decision,错误格式化留在各调用点(5 种 HTTP 拦截格式差异由
// 特征化测试锁定,与协议常量无映射关系);
// - 核心钩子(如内容审核)由 Wire 装配;gateway.hook.* 命名空间的模块收集
// 机制留待 Phase-3 与平台 Provider 需求合并设计,本包不做 Runtime 收集。
package gatewayhook
import (
"context"
"net/http"
"github.com/Wei-Shaw/sub2api/internal/service"
)
// CallerInfo 是调用方身份的最小视图(与 middleware.AuthSubject 解耦)。
type CallerInfo struct {
// UserID 为认证后的用户 ID。
UserID int64
// GroupID 为 API Key 所属分组 ID(可能为 nil)。
GroupID *int64
// KeyID 为平台 API Key ID。
KeyID int64
}
// RequestHeaders 是入站请求头的只读访问器(不暴露 gin.Context / http.Header 本体)。
type RequestHeaders struct {
header http.Header
}
// NewRequestHeaders 包装 http.Header 为只读访问器;传 nil 得到空访问器。
func NewRequestHeaders(header http.Header) RequestHeaders {
return RequestHeaders{header: header}
}
// Get 返回指定 key 的首个 header 值(语义同 http.Header.Get)。
func (r RequestHeaders) Get(key string) string {
if r.header == nil {
return ""
}
return r.header.Get(key)
}
// Values 返回指定 key 的全部 header 值(语义同 http.Header.Values)。
func (r RequestHeaders) Values(key string) []string {
if r.header == nil {
return nil
}
return r.header.Values(key)
}
// Request 是 pre-flight 钩子的协议无关只读入参。
type Request struct {
// Protocol 复用 service.ContentModerationProtocol* 现有常量值
// (如 "anthropic_messages" / "openai_chat_completions"),禁止新造枚举。
Protocol string
// Model 为请求的模型名(未做 TrimSpace,由钩子按需规范化)。
Model string
// Body 为送检请求体。各调用点保留自己的入参表达式
// (如 images 调用点传 parsed.ModerationBody()),不强行统一。
Body []byte
// Caller 为调用方最小身份视图。
Caller CallerInfo
// APIKey 为完整平台 API Key 上下文(audit 类钩子需要;可能为 nil)。
APIKey *service.APIKey
// Headers 为入站请求头的只读访问器。
Headers RequestHeaders
// Path 为入站端点路径(调用侧按 inbound endpoint 归一化后传入)。
Path string
}
// Decision 是钩子的协议无关决策;nil 表示放行。
// ErrorType 对 gemini 调用点无效(googleError 格式化器不消费该字段)。
type Decision struct {
Blocked bool
StatusCode int
ErrorType string
Message string
}
// PreFlightHook 是网关转发前的拦截钩子。
//
// 契约(链层强制,见 chain.go):
// - 返回 (nil, nil) 表示放行;
// - 返回 Blocked Decision 表示拦截(链短路返回);
// - 返回 error 表示钩子自身故障,链层按 fail-open 处理(记日志后继续下一钩子);
// - 钩子内 panic 同样被链层隔离并按 fail-open 降级。
type PreFlightHook interface {
// HookID 返回钩子的稳定标识(用于日志与排障)。
HookID() string
// CheckPreFlight 对请求执行转发前检查。
CheckPreFlight(ctx context.Context, req *Request) (*Decision, error)
}
@@ -1,91 +0,0 @@
package gatewayplatform
// 本文件的三个 adapter 仅包装现有 service 的 Forward 入口(实现零移动)。
//
// 错误透传铁律(SEAM-DESIGN 裁决 / T4 特征化锁定):底层返回的 error 一律
// 原样 return,禁止任何包裹——handler 对 *service.BetaBlockedError /
// *service.PromptTooLongError / *service.UpstreamFailoverError 的 errors.As
// 断言链依赖错误原值。
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// geminiForwardAction 是 /v1/messages gemini 分支传给 ForwardGemini 的 action
// 常量(SEAM-DESIGN 裁决:硬编码 "generateContent" + 测试锁定;该参数仅决定
// 客户端响应形态合法性,上游恒为 streamGenerateContent)。
const geminiForwardAction = "generateContent"
// AnthropicProvider 包装 GatewayService.Forward(Claude 协议主路径;
// :794 条件不命中侧,含 antigravity 平台的 APIKey 账号)。
type AnthropicProvider struct {
gateway *service.GatewayService
}
// NewAnthropicProvider 构造 anthropic 平台 Provider。
func NewAnthropicProvider(gateway *service.GatewayService) *AnthropicProvider {
return &AnthropicProvider{gateway: gateway}
}
// Platform 返回 service.PlatformAnthropic。
func (p *AnthropicProvider) Platform() string { return service.PlatformAnthropic }
// Forward 转发到 GatewayService.Forward;error 原样透传。
func (p *AnthropicProvider) Forward(ctx context.Context, c *gin.Context, account *service.Account, req *ForwardRequest) (*service.ForwardResult, error) {
return p.gateway.Forward(ctx, c, account, req.Parsed)
}
// AntigravityProvider 包装 AntigravityGatewayService.Forward(Claude 协议 →
// antigravity 上游;:794 条件命中侧:Platform == Antigravity && Type != APIKey)。
type AntigravityProvider struct {
antigravity *service.AntigravityGatewayService
}
// NewAntigravityProvider 构造 antigravity 平台 Provider。
func NewAntigravityProvider(antigravity *service.AntigravityGatewayService) *AntigravityProvider {
return &AntigravityProvider{antigravity: antigravity}
}
// Platform 返回 service.PlatformAntigravity。
func (p *AntigravityProvider) Platform() string { return service.PlatformAntigravity }
// Forward 转发到 AntigravityGatewayService.Forward;error 原样透传。
func (p *AntigravityProvider) Forward(ctx context.Context, c *gin.Context, account *service.Account, req *ForwardRequest) (*service.ForwardResult, error) {
return p.antigravity.Forward(ctx, c, account, req.Body, req.IsStickySession)
}
// GeminiProvider 包装 AntigravityGatewayService.ForwardGemini(gemini 平台
// 分组下的 antigravity 账号,:444 命中侧;gemini 平台的非 antigravity 账号
// 走 GeminiMessagesCompatService,映射逻辑保留在调用点)。
type GeminiProvider struct {
antigravity *service.AntigravityGatewayService
}
// NewGeminiProvider 构造 gemini 平台 Provider。
func NewGeminiProvider(antigravity *service.AntigravityGatewayService) *GeminiProvider {
return &GeminiProvider{antigravity: antigravity}
}
// Platform 返回 service.PlatformGemini。
func (p *GeminiProvider) Platform() string { return service.PlatformGemini }
// Forward 转发到 AntigravityGatewayService.ForwardGemini;error 原样透传。
// model/stream 取自 req.Parsed(与原调用点 reqModel/reqStream 同源),
// 粘性会话维度经 WithForwardGeminiSession 透传。
func (p *GeminiProvider) Forward(ctx context.Context, c *gin.Context, account *service.Account, req *ForwardRequest) (*service.ForwardResult, error) {
return p.antigravity.ForwardGemini(
ctx,
c,
account,
req.Parsed.Model,
geminiForwardAction,
req.Parsed.Stream,
req.Body,
req.IsStickySession,
service.WithForwardGeminiSession(req.SessionGroupID, req.SessionKey),
)
}
@@ -1,52 +0,0 @@
// Package gatewayplatform 定义 /v1/messages 平台 Forward 分发的 Provider 接缝
// (Phase-3 SEAM-DESIGN v2 裁决记录)。
//
// 设计要点:
// - Provider v1 接口仅 Platform/Forward 两方法(DefaultModels / FallbackModel /
// InvalidateToken 等经评审裁决不进接口);
// - adapter 实现零移动:仅包装现有 service 的 Forward 入口;底层 error 一律
// 原样透传(handler 对 BetaBlockedError / PromptTooLongError 等的
// errors.As 断言链依赖错误原值,禁止任何包裹);
// - Registry 构造期注册、运行期并发只读;平台 → Provider 的映射逻辑
// (如 :794 的 Type != APIKey 条件)保留在调用点,registry 只做查找;
// - OpenAI 走独立 OpenAIGatewayHandler 与独立计费管线,不进本注册表;
// 禁止统一跨平台返回类型(OpenAIForwardResult 载荷计费字段会丢失)。
package gatewayplatform
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// ForwardRequest 是平台 Forward 的统一入参面。字段集为两处分发点现有入参的
// 并集 {Parsed, Body, IsStickySession, SessionGroupID, SessionKey},不为未接入
// 平台虚构维度;各调用点保留自己的入参表达式,按各 Provider 的消费面填充。
type ForwardRequest struct {
// Parsed 为已解析的网关请求(anthropic / gemini Provider 消费;
// gemini Provider 读取 Parsed.Model 与 Parsed.Stream)。
Parsed *service.ParsedRequest
// Body 为转发请求体原文(antigravity / gemini Provider 消费)。
Body []byte
// IsStickySession 表示请求已命中粘性会话绑定(antigravity / gemini
// Provider 消费)。
IsStickySession bool
// SessionGroupID 与 SessionKey 为粘性会话维度(仅 gemini Provider 消费,
// 经 WithForwardGeminiSession 透传到模型限流切换时的粘性绑定清除)。
SessionGroupID int64
SessionKey string
}
// Provider 是单一平台的 Forward 入口。
//
// 契约:
// - Platform 返回 service.Platform* 现有常量,作为 Registry 的查找键;
// - Forward 将请求转发到对应平台 service,error 必须原样透传(禁止包裹)。
type Provider interface {
// Platform 返回该 Provider 服务的平台标识(service.Platform* 常量)。
Platform() string
// Forward 执行平台转发。
Forward(ctx context.Context, c *gin.Context, account *service.Account, req *ForwardRequest) (*service.ForwardResult, error)
}
@@ -1,38 +0,0 @@
package gatewayplatform
import "fmt"
// Registry 是 platform → Provider 的只读查找表:构造期一次性注册,
// 构造完成后并发只读(无锁)。
type Registry struct {
providers map[string]Provider
}
// NewRegistry 构造注册表。providers 中出现 nil Provider、空 Platform() 或
// 重复平台时 panic——装配错误必须在启动期(Wire 装配)暴露,而非请求期。
func NewRegistry(providers ...Provider) *Registry {
m := make(map[string]Provider, len(providers))
for _, p := range providers {
if p == nil {
panic("gatewayplatform: nil provider")
}
platform := p.Platform()
if platform == "" {
panic("gatewayplatform: provider with empty platform")
}
if _, dup := m[platform]; dup {
panic(fmt.Sprintf("gatewayplatform: duplicate provider for platform %q", platform))
}
m[platform] = p
}
return &Registry{providers: m}
}
// Get 返回平台对应的 Provider;未注册(或 nil Registry)返回 nil。
// 调用点须保证所查平台已在装配期注册(Wire 注册全集,miss 属编程错误)。
func (r *Registry) Get(platform string) Provider {
if r == nil {
return nil
}
return r.providers[platform]
}
@@ -1,112 +0,0 @@
package gatewayplatform
import (
"context"
"sync"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// stubProvider 是注册表测试用的最小 Provider 实现。
type stubProvider struct {
platform string
}
func (s *stubProvider) Platform() string { return s.platform }
func (s *stubProvider) Forward(_ context.Context, _ *gin.Context, _ *service.Account, _ *ForwardRequest) (*service.ForwardResult, error) {
return nil, nil
}
func TestRegistry_GetReturnsRegisteredProvider(t *testing.T) {
anthropic := &stubProvider{platform: service.PlatformAnthropic}
antigravity := &stubProvider{platform: service.PlatformAntigravity}
gemini := &stubProvider{platform: service.PlatformGemini}
registry := NewRegistry(anthropic, antigravity, gemini)
require.Same(t, Provider(anthropic), registry.Get(service.PlatformAnthropic))
require.Same(t, Provider(antigravity), registry.Get(service.PlatformAntigravity))
require.Same(t, Provider(gemini), registry.Get(service.PlatformGemini))
}
func TestRegistry_GetUnregisteredPlatformReturnsNil(t *testing.T) {
registry := NewRegistry(&stubProvider{platform: service.PlatformAnthropic})
require.Nil(t, registry.Get(service.PlatformOpenAI), "未注册平台必须返回 nil")
require.Nil(t, registry.Get(""), "空平台必须返回 nil")
var nilRegistry *Registry
require.Nil(t, nilRegistry.Get(service.PlatformAnthropic), "nil Registry 必须返回 nil 而非 panic")
}
func TestNewRegistry_DuplicatePlatformPanics(t *testing.T) {
require.PanicsWithValue(t,
`gatewayplatform: duplicate provider for platform "anthropic"`,
func() {
NewRegistry(
&stubProvider{platform: service.PlatformAnthropic},
&stubProvider{platform: service.PlatformAnthropic},
)
})
}
func TestNewRegistry_NilProviderPanics(t *testing.T) {
require.PanicsWithValue(t, "gatewayplatform: nil provider", func() {
NewRegistry(&stubProvider{platform: service.PlatformAnthropic}, nil)
})
}
func TestNewRegistry_EmptyPlatformPanics(t *testing.T) {
require.PanicsWithValue(t, "gatewayplatform: provider with empty platform", func() {
NewRegistry(&stubProvider{platform: ""})
})
}
// TestRegistry_ConcurrentGet 验证构造完成后的注册表可被并发只读访问
// (配合 -race 检测数据竞争)。
func TestRegistry_ConcurrentGet(t *testing.T) {
registry := NewRegistry(
&stubProvider{platform: service.PlatformAnthropic},
&stubProvider{platform: service.PlatformAntigravity},
&stubProvider{platform: service.PlatformGemini},
)
platforms := []string{
service.PlatformAnthropic,
service.PlatformAntigravity,
service.PlatformGemini,
service.PlatformOpenAI, // miss 路径同样并发安全
}
var wg sync.WaitGroup
for i := 0; i < 32; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := 0; j < 200; j++ {
platform := platforms[(i+j)%len(platforms)]
got := registry.Get(platform)
if platform == service.PlatformOpenAI {
require.Nil(t, got)
} else {
require.NotNil(t, got)
require.Equal(t, platform, got.Platform())
}
}
}(i)
}
wg.Wait()
}
// TestAdapters_PlatformIdentity 锁定三个 adapter 的注册键 = service.Platform* 常量
// (Registry 查找键与 :444/:794 调用点的查找表达式一致)。
func TestAdapters_PlatformIdentity(t *testing.T) {
require.Equal(t, service.PlatformAnthropic, NewAnthropicProvider(nil).Platform())
require.Equal(t, service.PlatformAntigravity, NewAntigravityProvider(nil).Platform())
require.Equal(t, service.PlatformGemini, NewGeminiProvider(nil).Platform())
}
@@ -106,7 +106,7 @@ type codexJWTOpenAIClaims struct {
}
type codexAccountIndex struct {
accountsByKey map[string]service.Account
accountsByKey map[string][]service.Account
}
func (h *AccountHandler) ImportCodexSession(c *gin.Context) {
@@ -178,7 +178,7 @@ func (h *AccountHandler) importCodexSessions(ctx context.Context, req CodexSessi
}
skipMixedChannelCheck := req.ConfirmMixedChannelRisk != nil && *req.ConfirmMixedChannelRisk
seenIdentity := map[string]int{}
seenIdentity := map[string]codexSeenIdentity{}
for _, entry := range entries {
item, err := normalizeCodexImportEntry(entry)
if err != nil {
@@ -225,7 +225,7 @@ func (h *AccountHandler) importCodexSessions(ctx context.Context, req CodexSessi
})
}
if duplicateIndex, ok := firstSeenCodexIdentity(seenIdentity, item.IdentityKeys); ok {
if duplicateIndex, ok := firstSeenCodexIdentity(seenIdentity, item.IdentityKeys, item.UserID); ok {
message := fmt.Sprintf("与第 %d 条导入项重复,已跳过", duplicateIndex)
result.Skipped++
result.Items = append(result.Items, CodexSessionImportItem{
@@ -241,9 +241,29 @@ func (h *AccountHandler) importCodexSessions(ctx context.Context, req CodexSessi
})
continue
}
markCodexIdentitySeen(seenIdentity, item.IdentityKeys, entry.Index)
markCodexIdentitySeen(seenIdentity, item.IdentityKeys, entry.Index, item.UserID)
if existing := index.Find(item.IdentityKeys); existing != nil && updateExisting {
existing, matchedKey := index.Find(item.IdentityKeys, item.UserID)
if existing != nil && updateExisting {
if strings.HasPrefix(matchedKey, "account:") && item.UserID != "" &&
codexCredentialString(existing.Credentials, "chatgpt_user_id") == "" {
result.Warnings = append(result.Warnings, CodexSessionImportMessage{
Index: entry.Index,
Name: accountName,
Message: "已有账号未记录 chatgpt_user_id,已按共享的 chatgpt_account_id 匹配并回填,请确认两者属于同一用户",
})
}
preserveExistingRefresh := item.RefreshToken == "" &&
codexCredentialString(existing.Credentials, "refresh_token") != ""
if preserveExistingRefresh {
result.Warnings = append(result.Warnings, CodexSessionImportMessage{
Index: entry.Index,
Name: accountName,
Message: "已有账号包含 refresh_token,本次 accessToken-only 导入已保留自动续期凭据",
})
effectiveExpiresAt = nil
autoPauseOnExpired = nil
}
mergedCredentials := mergeCodexImportCredentials(existing.Credentials, credentials, item)
mergedExtra := mergeCodexImportMap(existing.Extra, extra)
updateInput := &service.UpdateAccountInput{
@@ -583,7 +603,7 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err
fingerprint := codexTokenFingerprint(item.AccessToken)
item.Extra["access_token_sha256"] = fingerprint
item.IdentityKeys = buildCodexIdentityKeys(item.AccountID, item.UserID, item.Email, item.AccessToken)
item.IdentityKeys = buildCodexImportIdentityKeys(item.AccountID, item.UserID, item.Email, item.AccessToken, item.RefreshToken)
item.Name = buildCodexImportAccountName(item, entry.Index)
return item, nil
@@ -774,16 +794,20 @@ func sanitizeCodexImportCredentialExtras(input map[string]any) map[string]any {
return nil
}
protected := map[string]struct{}{
"access_token": {},
"refresh_token": {},
"id_token": {},
"expires_at": {},
"email": {},
"chatgpt_account_id": {},
"chatgpt_user_id": {},
"organization_id": {},
"plan_type": {},
"client_id": {},
"access_token": {},
"refresh_token": {},
"id_token": {},
"expires_at": {},
"email": {},
"chatgpt_account_id": {},
"chatgpt_user_id": {},
"organization_id": {},
"plan_type": {},
"client_id": {},
"auth_mode": {},
"openai_auth_mode": {},
"token_type": {},
"chatgpt_account_is_fedramp": {},
}
out := make(map[string]any, len(input))
for key, value := range input {
@@ -802,13 +826,25 @@ func sanitizeCodexImportCredentialExtras(input map[string]any) map[string]any {
return out
}
func buildCodexIdentityKeys(accountID, userID, email, accessToken string) []string {
keys := make([]string, 0, 4)
// buildCodexImportIdentityKeys 生成导入条目的匹配键。refresh_token 缺失时
// Codex session 只能作为 accessToken-only 凭据使用,此时以 access token
// 指纹作为唯一稳定身份,避免同 workspace 下共享的 account/user 标识误合并。
func buildCodexImportIdentityKeys(accountID, userID, email, accessToken, refreshToken string) []string {
accessToken = strings.TrimSpace(accessToken)
refreshToken = strings.TrimSpace(refreshToken)
if refreshToken == "" && accessToken != "" {
return []string{"access:" + codexTokenFingerprint(accessToken)}
}
return buildCodexStoredIdentityKeys(accountID, userID, email, accessToken)
}
// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度,
// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。
func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string {
keys := make([]string, 0, 3)
accountID = strings.TrimSpace(accountID)
userID = strings.TrimSpace(userID)
if accountID != "" {
keys = append(keys, "account:"+accountID)
}
accessToken = strings.TrimSpace(accessToken)
if userID != "" {
keys = append(keys, "user:"+userID)
}
@@ -817,14 +853,17 @@ func buildCodexIdentityKeys(accountID, userID, email, accessToken string) []stri
keys = append(keys, "email:"+email)
}
}
if accessToken = strings.TrimSpace(accessToken); accessToken != "" {
if accessToken != "" {
keys = append(keys, "access:"+codexTokenFingerprint(accessToken))
}
if accountID != "" {
keys = append(keys, "account:"+accountID)
}
return keys
}
func buildCodexAccountIndex(accounts []service.Account) *codexAccountIndex {
index := &codexAccountIndex{accountsByKey: map[string]service.Account{}}
index := &codexAccountIndex{accountsByKey: map[string][]service.Account{}}
for _, account := range accounts {
index.Add(account)
}
@@ -836,43 +875,99 @@ func (i *codexAccountIndex) Add(account service.Account) {
return
}
if i.accountsByKey == nil {
i.accountsByKey = map[string]service.Account{}
i.accountsByKey = map[string][]service.Account{}
}
keys := buildCodexIdentityKeys(
i.remove(account.ID)
keys := buildCodexStoredIdentityKeys(
codexCredentialString(account.Credentials, "chatgpt_account_id"),
codexCredentialString(account.Credentials, "chatgpt_user_id"),
codexCredentialString(account.Credentials, "email"),
codexCredentialString(account.Credentials, "access_token"),
)
for _, key := range keys {
i.accountsByKey[key] = account
i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account)
}
}
func (i *codexAccountIndex) Find(keys []string) *service.Account {
func (i *codexAccountIndex) remove(accountID int64) {
for key, accounts := range i.accountsByKey {
kept := accounts[:0]
for _, account := range accounts {
if account.ID != accountID {
kept = append(kept, account)
}
}
if len(kept) == 0 {
delete(i.accountsByKey, key)
continue
}
i.accountsByKey[key] = kept
}
}
// upsertCodexAccount 保留同一键下的全部候选账号(共享的 account: 键可对应
// 团队内多个账号),同一账号重复 Add 时原位替换为最新状态。
func upsertCodexAccount(accounts []service.Account, account service.Account) []service.Account {
for idx := range accounts {
if accounts[idx].ID == account.ID {
accounts[idx] = account
return accounts
}
}
return append(accounts, account)
}
// Find 返回第一个通过跨用户校验的候选账号及其命中的匹配键。
func (i *codexAccountIndex) Find(keys []string, userID string) (*service.Account, string) {
if i == nil {
return nil
return nil, ""
}
for _, key := range keys {
if account, ok := i.accountsByKey[key]; ok {
return &account
for _, account := range i.accountsByKey[key] {
if codexIdentityConflicts(key, userID, codexCredentialString(account.Credentials, "chatgpt_user_id")) {
continue
}
return &account, key
}
}
return nil
return nil, ""
}
func firstSeenCodexIdentity(seen map[string]int, keys []string) (int, bool) {
// codexIdentityConflicts 判断 account: 键的命中是否把同一 ChatGPT 团队的两个
// 不同成员误连到一起:双方都携带 user id 且不相等时视为冲突。存量索引侧
// 仍保留 account 键,任一侧缺少 user id 时允许匹配,使含 refresh_token
// 的常规导入和 accessToken-only 账号升级为完整 OAuth 时仍能更新原账号。
func codexIdentityConflicts(key, userID, storedUserID string) bool {
if !strings.HasPrefix(key, "account:") {
return false
}
userID = strings.TrimSpace(userID)
storedUserID = strings.TrimSpace(storedUserID)
return userID != "" && storedUserID != "" && userID != storedUserID
}
type codexSeenIdentity struct {
index int
userID string
}
func firstSeenCodexIdentity(seen map[string]codexSeenIdentity, keys []string, userID string) (int, bool) {
for _, key := range keys {
if index, ok := seen[key]; ok {
return index, true
entry, ok := seen[key]
if !ok {
continue
}
if codexIdentityConflicts(key, userID, entry.userID) {
continue
}
return entry.index, true
}
return 0, false
}
func markCodexIdentitySeen(seen map[string]int, keys []string, index int) {
func markCodexIdentitySeen(seen map[string]codexSeenIdentity, keys []string, index int, userID string) {
for _, key := range keys {
seen[key] = index
seen[key] = codexSeenIdentity{index: index, userID: userID}
}
}
@@ -893,8 +988,15 @@ func mergeCodexImportCredentials(existing, incoming map[string]any, item *codexI
return out
}
if strings.TrimSpace(item.RefreshToken) == "" {
delete(out, "refresh_token")
delete(out, "client_id")
if codexCredentialString(existing, "refresh_token") == "" {
delete(out, "refresh_token")
delete(out, "client_id")
} else {
out["refresh_token"] = existing["refresh_token"]
if clientID, ok := existing["client_id"]; ok {
out["client_id"] = clientID
}
}
}
if strings.TrimSpace(item.IDToken) == "" {
delete(out, "id_token")
@@ -1,12 +1,15 @@
package admin
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
)
func TestParseCodexSessionImportEntriesSupportsRawTokenJSONAndArray(t *testing.T) {
@@ -142,7 +145,7 @@ func TestNormalizeCodexSessionJSONExtractsCredentialsAndIgnoresSessionToken(t *t
}
}
func TestMergeCodexImportCredentialsClearsStaleRefreshFieldsWhenIncomingHasNoRefreshToken(t *testing.T) {
func TestMergeCodexImportCredentialsPreservesExistingRefreshFieldsWhenIncomingHasNoRefreshToken(t *testing.T) {
existing := map[string]any{
"access_token": "old-access-token",
"refresh_token": "old-refresh-token",
@@ -169,11 +172,11 @@ func TestMergeCodexImportCredentialsClearsStaleRefreshFieldsWhenIncomingHasNoRef
if merged["chatgpt_account_id"] != "acct-new" {
t.Fatalf("chatgpt_account_id = %v, want acct-new", merged["chatgpt_account_id"])
}
if _, ok := merged["refresh_token"]; ok {
t.Fatalf("refresh_token should be cleared")
if merged["refresh_token"] != "old-refresh-token" {
t.Fatalf("refresh_token = %v, want old-refresh-token", merged["refresh_token"])
}
if _, ok := merged["client_id"]; ok {
t.Fatalf("client_id should be cleared")
if merged["client_id"] != "old-client-id" {
t.Fatalf("client_id = %v, want old-client-id", merged["client_id"])
}
if _, ok := merged["id_token"]; ok {
t.Fatalf("id_token should be cleared")
@@ -299,14 +302,20 @@ func TestResolveCodexImportExpiryForNoRefreshTokenUsesEarlierRequestExpiry(t *te
}
func TestCodexIdentityKeysPreferStrongIdentifiers(t *testing.T) {
keys := buildCodexIdentityKeys("acct-1", "user-1", "same@example.com", "token")
keys := buildCodexImportIdentityKeys("acct-1", "user-1", "same@example.com", "token", "refresh")
if len(keys) == 0 || keys[0] != "user:user-1" {
t.Fatalf("user key should have highest priority when refresh token exists: %v", keys)
}
if keys[len(keys)-1] != "account:acct-1" {
t.Fatalf("shared account key should be the last fallback: %v", keys)
}
for _, key := range keys {
if strings.HasPrefix(key, "email:") {
t.Fatalf("strong identity should not include email fallback: %v", keys)
}
}
keys = buildCodexIdentityKeys("", "", "same@example.com", "token")
keys = buildCodexImportIdentityKeys("", "", "same@example.com", "token", "refresh")
hasEmail := false
for _, key := range keys {
if key == "email:same@example.com" {
@@ -316,6 +325,605 @@ func TestCodexIdentityKeysPreferStrongIdentifiers(t *testing.T) {
if !hasEmail {
t.Fatalf("weak identity should include email fallback: %v", keys)
}
keys = buildCodexImportIdentityKeys("acct-1", "user-1", "same@example.com", "token", "")
if len(keys) != 1 || !strings.HasPrefix(keys[0], "access:") {
t.Fatalf("accessToken-only identity should use only access fingerprint: %v", keys)
}
}
func TestCodexAccountIndexDoesNotMatchDifferentUsersInSameChatGPTAccount(t *testing.T) {
existing := service.Account{
ID: 10,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"chatgpt_user_id": "user-1",
"access_token": "token-1",
"refresh_token": "refresh-1",
},
}
index := buildCodexAccountIndex([]service.Account{existing})
keys := buildCodexImportIdentityKeys("team-1", "user-2", "", "token-2", "refresh-2")
if got, _ := index.Find(keys, "user-2"); got != nil {
t.Fatalf("Find matched account ID %d for a different chatgpt_user_id in the same team", got.ID)
}
keys = buildCodexImportIdentityKeys("team-1", "user-1", "", "token-2", "refresh-2")
got, _ := index.Find(keys, "user-1")
if got == nil || got.ID != existing.ID {
t.Fatalf("Find by same chatgpt_user_id = %v, want account ID %d", got, existing.ID)
}
}
func TestCodexAccountIndexFallsBackToAccountKeyWhenRefreshTokenExistsAndUserIDMissing(t *testing.T) {
// 含 refresh_token 的常规导入沿用 a5638a4e 的兼容逻辑:存量账号缺少
// chatgpt_user_id 时,携带 user id 的重新导入仍可命中并回填。
legacy := service.Account{
ID: 20,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"access_token": "token-old",
"refresh_token": "refresh-old",
},
}
index := buildCodexAccountIndex([]service.Account{legacy})
keys := buildCodexImportIdentityKeys("team-1", "user-1", "", "token-new", "refresh-new")
got, matchedKey := index.Find(keys, "user-1")
if got == nil || got.ID != legacy.ID {
t.Fatalf("Find legacy account without stored user id = %v, want account ID %d", got, legacy.ID)
}
if matchedKey != "account:team-1" {
t.Fatalf("matched key = %q, want account:team-1", matchedKey)
}
// 反向:含 refresh_token 的导入条目无法解析出 user id 时,仍应通过
// account 键命中已有账号,保持常规导入去重行为。
full := service.Account{
ID: 21,
Credentials: map[string]any{
"chatgpt_account_id": "team-2",
"chatgpt_user_id": "user-9",
"access_token": "token-old",
"refresh_token": "refresh-old",
},
}
index = buildCodexAccountIndex([]service.Account{full})
keys = buildCodexImportIdentityKeys("team-2", "", "", "token-opaque", "refresh-new")
got, _ = index.Find(keys, "")
if got == nil || got.ID != full.ID {
t.Fatalf("Find by account key without entry user id = %v, want account ID %d", got, full.ID)
}
}
func TestCodexAccountIndexAccessTokenOnlyUsesTokenFingerprint(t *testing.T) {
existing := service.Account{
ID: 22,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"chatgpt_user_id": "user-1",
"access_token": "token-old",
},
}
index := buildCodexAccountIndex([]service.Account{existing})
keys := buildCodexImportIdentityKeys("team-1", "user-1", "", "token-new", "")
if got, matchedKey := index.Find(keys, "user-1"); got != nil {
t.Fatalf("accessToken-only import matched by %q despite different token: account ID %d", matchedKey, got.ID)
}
keys = buildCodexImportIdentityKeys("team-1", "user-1", "", "token-old", "")
got, matchedKey := index.Find(keys, "user-1")
if got == nil || got.ID != existing.ID {
t.Fatalf("Find accessToken-only duplicate by fingerprint = %v, want account ID %d", got, existing.ID)
}
if !strings.HasPrefix(matchedKey, "access:") {
t.Fatalf("matched key = %q, want access fingerprint", matchedKey)
}
}
func TestCodexAccountIndexKeepsAllCandidatesForSharedAccountKey(t *testing.T) {
legacy := service.Account{
ID: 30,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"access_token": "token-legacy",
"refresh_token": "refresh-legacy",
},
}
member := service.Account{
ID: 31,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"chatgpt_user_id": "user-2",
"access_token": "token-member",
"refresh_token": "refresh-member",
},
}
// 无论索引构建顺序如何,携带新 user id 的条目都应跳过 user-2 的账号,
// 命中缺少 user id 的存量账号,而不是因单一候选被遮蔽而落空。
for _, accounts := range [][]service.Account{
{member, legacy},
{legacy, member},
} {
index := buildCodexAccountIndex(accounts)
keys := buildCodexImportIdentityKeys("team-1", "user-1", "", "token-new", "refresh-new")
got, matchedKey := index.Find(keys, "user-1")
if got == nil || got.ID != legacy.ID {
t.Fatalf("Find with shared account key = %v, want legacy account ID %d", got, legacy.ID)
}
if matchedKey != "account:team-1" {
t.Fatalf("matched key = %q, want account:team-1", matchedKey)
}
keys = buildCodexImportIdentityKeys("team-1", "user-2", "", "token-new", "refresh-new")
got, matchedKey = index.Find(keys, "user-2")
if got == nil || got.ID != member.ID {
t.Fatalf("Find by user key = %v, want member account ID %d", got, member.ID)
}
if matchedKey != "user:user-2" {
t.Fatalf("matched key = %q, want user:user-2", matchedKey)
}
}
}
func TestCodexAccountIndexUpsertReplacesSameAccount(t *testing.T) {
legacy := service.Account{
ID: 40,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"access_token": "token-old",
},
}
index := buildCodexAccountIndex([]service.Account{legacy})
backfilled := service.Account{
ID: 40,
Credentials: map[string]any{
"chatgpt_account_id": "team-1",
"chatgpt_user_id": "user-1",
"access_token": "token-new",
"refresh_token": "refresh-new",
},
}
index.Add(backfilled)
// 回填后同一账号在 account 键下应被原位替换而非残留旧副本:
// 其他成员的条目不应再通过旧副本(无 user id)命中该账号。
keys := buildCodexImportIdentityKeys("team-1", "user-2", "", "token-other", "refresh-other")
if got, matchedKey := index.Find(keys, "user-2"); got != nil {
t.Fatalf("stale candidate matched after upsert by %q: account ID %d", matchedKey, got.ID)
}
keys = buildCodexImportIdentityKeys("team-1", "user-1", "", "token-other", "refresh-other")
got, _ := index.Find(keys, "user-1")
if got == nil || got.ID != backfilled.ID {
t.Fatalf("Find after upsert = %v, want account ID %d", got, backfilled.ID)
}
if uid := codexCredentialString(got.Credentials, "chatgpt_user_id"); uid != "user-1" {
t.Fatalf("upsert did not replace credentials, chatgpt_user_id = %q", uid)
}
}
func TestCodexIdentitySeenDistinguishesTeamMembers(t *testing.T) {
seen := map[string]codexSeenIdentity{}
member1 := buildCodexImportIdentityKeys("team-1", "user-1", "", "token-1", "refresh-1")
markCodexIdentitySeen(seen, member1, 1, "user-1")
member2 := buildCodexImportIdentityKeys("team-1", "user-2", "", "token-2", "refresh-2")
if index, ok := firstSeenCodexIdentity(seen, member2, "user-2"); ok {
t.Fatalf("different team member treated as duplicate of entry %d", index)
}
again := buildCodexImportIdentityKeys("team-1", "user-1", "", "token-3", "refresh-3")
index, ok := firstSeenCodexIdentity(seen, again, "user-1")
if !ok || index != 1 {
t.Fatalf("same user re-entry dedup = (%d, %v), want (1, true)", index, ok)
}
// 无 user id 的条目不应因共享 account id 与已见团队成员互相去重;
// 只有相同 access token 指纹才视为重复。
opaque := buildCodexImportIdentityKeys("team-1", "", "", "token-4", "")
index, ok = firstSeenCodexIdentity(seen, opaque, "")
if ok {
t.Fatalf("entry without user id dedup = (%d, %v), want no match", index, ok)
}
}
func TestNormalizeCodexImportUsesJWTSubForAccessTokenOnlyIdentity(t *testing.T) {
accessToken := buildCodexImportTestJWT(t, time.Now().Add(time.Hour), map[string]any{
"sub": "user-from-access-token",
"https://api.openai.com/auth": map[string]any{
"chatgpt_account_id": "workspace-1",
},
})
item, err := normalizeCodexImportEntry(codexImportEntry{Index: 1, Value: accessToken})
if err != nil {
t.Fatalf("normalizeCodexImportEntry error = %v", err)
}
if item.UserID != "user-from-access-token" {
t.Fatalf("UserID = %q, want JWT sub", item.UserID)
}
if len(item.IdentityKeys) != 1 || !strings.HasPrefix(item.IdentityKeys[0], "access:") {
t.Fatalf("IdentityKeys = %v, want access fingerprint only for accessToken-only import", item.IdentityKeys)
}
if got := item.Credentials["chatgpt_user_id"]; got != "user-from-access-token" {
t.Fatalf("credential chatgpt_user_id = %v, want JWT sub", got)
}
}
func TestImportCodexSessionsAccessTokenOnlySameWorkspaceDifferentUsersCreatesTwoAccounts(t *testing.T) {
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: buildCodexAccessOnlyImportValue(t, "workspace-1", "user-1")},
{Index: 2, Value: buildCodexAccessOnlyImportValue(t, "workspace-1", "user-2")},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 2 || result.Updated != 0 || result.Skipped != 0 || result.Failed != 0 {
t.Fatalf("result = %+v, want two created accounts", result)
}
if len(svc.createdAccounts) != 2 {
t.Fatalf("created accounts = %d, want 2", len(svc.createdAccounts))
}
if svc.createdAccounts[0].Credentials["chatgpt_user_id"] == svc.createdAccounts[1].Credentials["chatgpt_user_id"] {
t.Fatalf("created accounts share user id: %v", svc.createdAccounts)
}
}
func TestImportCodexSessionsAccessTokenOnlySameWorkspaceAndUserDifferentTokensCreatesTwoAccounts(t *testing.T) {
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: map[string]any{
"access_token": buildCodexImportTestJWT(t, time.Now().Add(time.Hour), map[string]any{
"sub": "shared-user",
"jti": "token-1",
"https://api.openai.com/auth": map[string]any{
"chatgpt_account_id": "workspace-1",
},
}),
}},
{Index: 2, Value: map[string]any{
"access_token": buildCodexImportTestJWT(t, time.Now().Add(time.Hour), map[string]any{
"sub": "shared-user",
"jti": "token-2",
"https://api.openai.com/auth": map[string]any{
"chatgpt_account_id": "workspace-1",
},
}),
}},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 2 || result.Updated != 0 || result.Skipped != 0 || result.Failed != 0 {
t.Fatalf("result = %+v, want two created accounts", result)
}
if len(svc.createdAccounts) != 2 {
t.Fatalf("created accounts = %d, want 2", len(svc.createdAccounts))
}
}
func TestImportCodexSessionsAccessTokenOnlySameUserUpdatesExisting(t *testing.T) {
existingToken := buildCodexAccessToken(t, "workspace-1", "user-1", time.Now().Add(time.Hour))
svc := newCodexImportMemoryAdminService([]service.Account{{
ID: 10,
Name: "existing",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"chatgpt_account_id": "workspace-1",
"chatgpt_user_id": "user-1",
"access_token": existingToken,
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: map[string]any{"access_token": existingToken}},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 0 || result.Updated != 1 || result.Failed != 0 {
t.Fatalf("result = %+v, want one updated account", result)
}
if len(svc.createdAccounts) != 0 {
t.Fatalf("created accounts = %d, want 0", len(svc.createdAccounts))
}
if len(svc.updatedAccounts) != 1 || svc.updatedAccounts[0].id != 10 {
t.Fatalf("updated accounts = %+v, want account 10", svc.updatedAccounts)
}
}
func TestImportCodexSessionsUpgradesAccessTokenOnlyAccountWithRefreshToken(t *testing.T) {
oldToken := buildCodexAccessTokenWithJTI(t, "workspace-1", "user-1", "old-token", time.Now().Add(time.Hour))
newToken := buildCodexAccessTokenWithJTI(t, "workspace-1", "user-1", "new-token", time.Now().Add(time.Hour))
svc := newCodexImportMemoryAdminService([]service.Account{{
ID: 12,
Name: "existing",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"chatgpt_account_id": "workspace-1",
"chatgpt_user_id": "user-1",
"access_token": oldToken,
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: map[string]any{
"access_token": newToken,
"refresh_token": "refresh-new",
}},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 0 || result.Updated != 1 || result.Failed != 0 {
t.Fatalf("result = %+v, want one updated account", result)
}
if len(svc.updatedAccounts) != 1 || svc.updatedAccounts[0].id != 12 {
t.Fatalf("updated accounts = %+v, want account 12", svc.updatedAccounts)
}
if got := svc.updatedAccounts[0].input.Credentials["refresh_token"]; got != "refresh-new" {
t.Fatalf("updated refresh_token = %v, want refresh-new", got)
}
}
func TestImportCodexSessionsAccessTokenOnlyPreservesExistingRefreshToken(t *testing.T) {
existingToken := buildCodexAccessToken(t, "workspace-1", "user-1", time.Now().Add(time.Hour))
svc := newCodexImportMemoryAdminService([]service.Account{{
ID: 13,
Name: "existing",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"chatgpt_account_id": "workspace-1",
"chatgpt_user_id": "user-1",
"access_token": existingToken,
"refresh_token": "refresh-old",
"client_id": "client-old",
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: map[string]any{"access_token": existingToken}},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 0 || result.Updated != 1 || result.Failed != 0 {
t.Fatalf("result = %+v, want one updated account", result)
}
update := svc.updatedAccounts[0].input
if got := update.Credentials["refresh_token"]; got != "refresh-old" {
t.Fatalf("refresh_token = %v, want refresh-old", got)
}
if got := update.Credentials["client_id"]; got != "client-old" {
t.Fatalf("client_id = %v, want client-old", got)
}
if update.ExpiresAt != nil {
t.Fatalf("ExpiresAt = %v, want nil to preserve OAuth account expiry", *update.ExpiresAt)
}
if update.AutoPauseOnExpired != nil {
t.Fatalf("AutoPauseOnExpired = %v, want nil to preserve OAuth account scheduling", *update.AutoPauseOnExpired)
}
}
func TestImportCodexSessionsBatchOldAccessTokenDoesNotRollbackRefreshToken(t *testing.T) {
oldToken := buildCodexAccessTokenWithJTI(t, "workspace-1", "user-1", "old-token", time.Now().Add(time.Hour))
newToken := buildCodexAccessTokenWithJTI(t, "workspace-1", "user-1", "new-token", time.Now().Add(time.Hour))
svc := newCodexImportMemoryAdminService([]service.Account{{
ID: 14,
Name: "existing",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"chatgpt_account_id": "workspace-1",
"chatgpt_user_id": "user-1",
"access_token": oldToken,
"refresh_token": "refresh-old",
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: map[string]any{
"access_token": newToken,
"refresh_token": "refresh-new",
}},
{Index: 2, Value: map[string]any{"access_token": oldToken}},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Updated != 1 || result.Created != 1 || result.Failed != 0 {
t.Fatalf("result = %+v, want first item updated and stale access token created separately", result)
}
if len(svc.updatedAccounts) != 1 || svc.updatedAccounts[0].id != 14 {
t.Fatalf("updated accounts = %+v, want account 14 updated once", svc.updatedAccounts)
}
stored, err := svc.GetAccount(context.Background(), 14)
if err != nil {
t.Fatalf("GetAccount error = %v", err)
}
if got := stored.Credentials["access_token"]; got != newToken {
t.Fatalf("stored access_token rolled back = %v, want new token", got)
}
if got := stored.Credentials["refresh_token"]; got != "refresh-new" {
t.Fatalf("stored refresh_token = %v, want refresh-new", got)
}
}
func TestImportCodexSessionsWithRefreshTokenKeepsExistingDedup(t *testing.T) {
existingToken := buildCodexAccessToken(t, "workspace-1", "user-1", time.Now().Add(time.Hour))
svc := newCodexImportMemoryAdminService([]service.Account{{
ID: 11,
Name: "existing",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"chatgpt_account_id": "workspace-1",
"chatgpt_user_id": "user-1",
"access_token": existingToken,
"refresh_token": "refresh-old",
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-new")},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 0 || result.Updated != 1 || result.Failed != 0 {
t.Fatalf("result = %+v, want one updated account", result)
}
if got := svc.updatedAccounts[0].input.Credentials["refresh_token"]; got != "refresh-new" {
t.Fatalf("updated refresh_token = %v, want refresh-new", got)
}
}
type codexImportMemoryAdminService struct {
*stubAdminService
nextID int64
updatedAccounts []struct {
id int64
input *service.UpdateAccountInput
}
}
func newCodexImportMemoryAdminService(accounts []service.Account) *codexImportMemoryAdminService {
stub := newStubAdminService()
stub.accounts = append([]service.Account(nil), accounts...)
return &codexImportMemoryAdminService{
stubAdminService: stub,
nextID: 100,
}
}
func (s *codexImportMemoryAdminService) CreateAccount(ctx context.Context, input *service.CreateAccountInput) (*service.Account, error) {
s.createdAccounts = append(s.createdAccounts, input)
if s.createAccountErr != nil {
return nil, s.createAccountErr
}
account := service.Account{
ID: s.nextID,
Name: input.Name,
Platform: input.Platform,
Type: input.Type,
Status: service.StatusActive,
Credentials: cloneCodexImportTestMap(input.Credentials),
Extra: cloneCodexImportTestMap(input.Extra),
}
s.nextID++
s.accounts = append(s.accounts, account)
return &account, nil
}
func (s *codexImportMemoryAdminService) UpdateAccount(ctx context.Context, id int64, input *service.UpdateAccountInput) (*service.Account, error) {
s.updatedAccounts = append(s.updatedAccounts, struct {
id int64
input *service.UpdateAccountInput
}{id: id, input: input})
if s.updateAccountErr != nil {
return nil, s.updateAccountErr
}
for idx := range s.accounts {
if s.accounts[idx].ID == id {
s.accounts[idx].Credentials = cloneCodexImportTestMap(input.Credentials)
s.accounts[idx].Extra = cloneCodexImportTestMap(input.Extra)
return &s.accounts[idx], nil
}
}
account := service.Account{ID: id, Status: service.StatusActive, Credentials: cloneCodexImportTestMap(input.Credentials)}
return &account, nil
}
func (s *codexImportMemoryAdminService) GetAccount(ctx context.Context, id int64) (*service.Account, error) {
for idx := range s.accounts {
if s.accounts[idx].ID == id {
return &s.accounts[idx], nil
}
}
return s.stubAdminService.GetAccount(ctx, id)
}
func buildCodexAccessOnlyImportValue(t *testing.T, accountID, userID string) map[string]any {
t.Helper()
return map[string]any{
"access_token": buildCodexAccessToken(t, accountID, userID, time.Now().Add(time.Hour)),
}
}
func buildCodexRefreshImportValue(t *testing.T, accountID, userID, refreshToken string) map[string]any {
t.Helper()
return map[string]any{
"access_token": buildCodexAccessToken(t, accountID, userID, time.Now().Add(time.Hour)),
"refresh_token": refreshToken,
}
}
func buildCodexAccessToken(t *testing.T, accountID, userID string, exp time.Time) string {
t.Helper()
return buildCodexAccessTokenWithJTI(t, accountID, userID, "", exp)
}
func buildCodexAccessTokenWithJTI(t *testing.T, accountID, userID, jti string, exp time.Time) string {
t.Helper()
claims := map[string]any{
"sub": userID,
"https://api.openai.com/auth": map[string]any{
"chatgpt_account_id": accountID,
},
}
if jti != "" {
claims["jti"] = jti
}
return buildCodexImportTestJWT(t, exp, claims)
}
func cloneCodexImportTestMap(input map[string]any) map[string]any {
if input == nil {
return nil
}
out := make(map[string]any, len(input))
for key, value := range input {
out[key] = value
}
return out
}
func boolPtr(v bool) *bool {
return &v
}
func buildCodexImportTestJWT(t *testing.T, exp time.Time, extraClaims map[string]any) string {
+29 -3
View File
@@ -30,6 +30,9 @@ type DataPayload struct {
ExportedAt string `json:"exported_at"`
Proxies []DataProxy `json:"proxies"`
Accounts []DataAccount `json:"accounts"`
// SkippedShadows 记录导出时被排除的 spark 影子账号数量(见 ExportData)。仅作可见性提示,
// 导入侧忽略该字段;omitempty 保持向后兼容。
SkippedShadows int `json:"skipped_shadows,omitempty"`
}
type DataProxy struct {
@@ -50,6 +53,10 @@ type DataProxy struct {
// DataAccount 是管理员显式备份导出使用的账号结构,故意不走 dto.Account 的脱敏路径,
// Credentials 原文返回。这是"管理员备份"这一显式行为的一部分;如未来需要导出脱敏版本,
// 应新增独立结构而非修改这里。
// 注意:本结构不含 parent_account_id/quota_dimension——spark 影子账号在 ExportData 处被显式
// 排除(影子不持凭据、通用凭据型导入强制 credentials 非空无法重建父子链接),不在此表达。
// 影子的独立调度配置(priority/并发/分组/status 管理员可单独调)亦不在本备份范围,属已知局限
// (外审第6轮裁决:保持排除 + 前端警告,而非升级格式做完整往返)。
type DataAccount struct {
Name string `json:"name"`
Notes *string `json:"notes,omitempty"`
@@ -105,6 +112,24 @@ func (h *AccountHandler) ExportData(c *gin.Context) {
return
}
// 排除 spark 影子账号:影子不持凭据,通用凭据型导出无法表达父子链接、导入侧又强制 credentials
// 非空——若混入会产出无法还原的坏备份(导入即失败)。影子的独立调度配置(priority/并发/分组/
// status,管理员可单独调)随之不进备份,还原后需在重建的影子上重新调优;前端按 skipped_shadows
// 提示用户(外审第5轮发现、第6轮裁决:保持排除 + 警告,不做完整往返)。
skippedShadows := 0
exportable := make([]service.Account, 0, len(accounts))
for i := range accounts {
if accounts[i].IsCredentialShadow() {
skippedShadows++
continue
}
exportable = append(exportable, accounts[i])
}
accounts = exportable
if skippedShadows > 0 {
slog.Info("export_skipped_spark_shadows", "count", skippedShadows)
}
includeProxies, err := parseIncludeProxies(c)
if err != nil {
response.BadRequest(c, err.Error())
@@ -191,9 +216,10 @@ func (h *AccountHandler) ExportData(c *gin.Context) {
}
payload := DataPayload{
ExportedAt: time.Now().UTC().Format(time.RFC3339),
Proxies: dataProxies,
Accounts: dataAccounts,
ExportedAt: time.Now().UTC().Format(time.RFC3339),
Proxies: dataProxies,
Accounts: dataAccounts,
SkippedShadows: skippedShadows,
}
response.Success(c, payload)
@@ -18,10 +18,11 @@ type dataResponse struct {
}
type dataPayload struct {
Type string `json:"type"`
Version int `json:"version"`
Proxies []dataProxy `json:"proxies"`
Accounts []dataAccount `json:"accounts"`
Type string `json:"type"`
Version int `json:"version"`
Proxies []dataProxy `json:"proxies"`
Accounts []dataAccount `json:"accounts"`
SkippedShadows int `json:"skipped_shadows"`
}
type dataProxy struct {
@@ -172,6 +173,46 @@ func TestExportDataWithoutProxies(t *testing.T) {
require.Nil(t, resp.Data.Accounts[0].ProxyKey)
}
// TestExportDataExcludesSparkShadow 验证外审第5轮 P1/P2:导出时排除 spark 影子账号
// (影子无凭据、导入侧强制 credentials 非空,混入会产出无法还原的坏备份),并透出跳过计数。
func TestExportDataExcludesSparkShadow(t *testing.T) {
router, adminSvc := setupAccountDataRouter()
parentID := int64(21)
adminSvc.accounts = []service.Account{
{
ID: parentID,
Name: "mother",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{"token": "secret"},
Status: service.StatusActive,
},
{
ID: 22,
Name: "mother (Spark)",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{}, // 影子恒空凭据
ParentAccountID: &parentID, // 影子标记
QuotaDimension: service.QuotaDimensionSpark,
Status: service.StatusActive,
},
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/data?include_proxies=false", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var resp dataResponse
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, 0, resp.Code)
require.Len(t, resp.Data.Accounts, 1, "影子应被排除,仅导出母账号")
require.Equal(t, "mother", resp.Data.Accounts[0].Name)
require.Equal(t, 1, resp.Data.SkippedShadows, "跳过的影子数量应透出")
}
func TestExportDataPassesAccountFiltersAndSort(t *testing.T) {
router, adminSvc := setupAccountDataRouter()
adminSvc.accounts = []service.Account{
@@ -11,6 +11,7 @@ import (
"log"
"log/slog"
"net/http"
"sort"
"strconv"
"strings"
"sync"
@@ -25,6 +26,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
@@ -169,13 +171,29 @@ type CheckMixedChannelRequest struct {
// AccountWithConcurrency extends Account with real-time concurrency info
type AccountWithConcurrency struct {
*dto.Account
CurrentConcurrency int `json:"current_concurrency"`
CurrentConcurrency int `json:"current_concurrency"`
SchedulerScore *AccountSchedulerScore `json:"scheduler_score,omitempty"`
SchedulerScores []AccountSchedulerGroupScore `json:"scheduler_scores,omitempty"`
// 以下字段仅对 Anthropic OAuth/SetupToken 账号有效,且仅在启用相应功能时返回
CurrentWindowCost *float64 `json:"current_window_cost,omitempty"` // 当前窗口费用
ActiveSessions *int `json:"active_sessions,omitempty"` // 当前活跃会话数
CurrentRPM *int `json:"current_rpm,omitempty"` // 当前分钟 RPM 计数
}
type AccountSchedulerScore struct {
BaseScore float64 `json:"base_score"`
StickyScore float64 `json:"sticky_score"`
StickyScoreInfinity bool `json:"sticky_score_infinity"`
StickyWeightedEnabled bool `json:"sticky_weighted_enabled"`
}
type AccountSchedulerGroupScore struct {
GroupID *int64 `json:"group_id"`
GroupName string `json:"group_name,omitempty"`
GroupPriority *int `json:"group_priority,omitempty"`
AccountSchedulerScore
}
const accountListGroupUngroupedQueryValue = "ungrouped"
func (h *AccountHandler) buildAccountResponseWithRuntime(ctx context.Context, account *service.Account) AccountWithConcurrency {
@@ -219,9 +237,237 @@ func (h *AccountHandler) buildAccountResponseWithRuntime(ctx context.Context, ac
}
}
h.enrichShadowParents(ctx, []AccountWithConcurrency{item})
return item
}
// scoreOpenAIAccountSchedulerPool 对池内 OpenAI 账号计算调度分数快照。
// loadMap 为共享的账号负载数据(含池内全部账号即可,多余条目无害);传 nil 时自行批查。
func (h *AccountHandler) scoreOpenAIAccountSchedulerPool(ctx context.Context, accounts []service.Account, loadMap map[int64]*service.AccountLoadInfo) map[int64]AccountSchedulerScore {
if len(accounts) == 0 {
return nil
}
openAIAccounts := make([]*service.Account, 0, len(accounts))
for i := range accounts {
account := &accounts[i]
if account.Platform != service.PlatformOpenAI {
continue
}
openAIAccounts = append(openAIAccounts, account)
}
if len(openAIAccounts) == 0 {
return nil
}
if loadMap == nil {
loadMap = h.fetchOpenAIAccountLoadMap(ctx, openAIAccounts)
}
var scores map[int64]service.OpenAIAccountSchedulerScoreSnapshot
if h.rateLimitService != nil {
scores = h.rateLimitService.BuildOpenAIAccountSchedulerScoreSnapshot(ctx, openAIAccounts, loadMap)
} else {
scores = service.BuildOpenAIAccountSchedulerScoreSnapshot(openAIAccounts, loadMap)
}
result := make(map[int64]AccountSchedulerScore, len(scores))
for accountID, score := range scores {
result[accountID] = AccountSchedulerScore{
BaseScore: score.BaseScore,
StickyScore: score.StickyScore,
StickyScoreInfinity: score.StickyScoreInfinity,
StickyWeightedEnabled: score.StickyWeightedEnabled,
}
}
return result
}
// fetchOpenAIAccountLoadMap 一次性批查给定 OpenAI 账号的负载数据;
// 失败时记录日志并返回空表(分数按零负载计算,属可接受降级)。
func (h *AccountHandler) fetchOpenAIAccountLoadMap(ctx context.Context, openAIAccounts []*service.Account) map[int64]*service.AccountLoadInfo {
loadMap := map[int64]*service.AccountLoadInfo{}
if h.concurrencyService == nil || len(openAIAccounts) == 0 {
return loadMap
}
seen := make(map[int64]struct{}, len(openAIAccounts))
loadReq := make([]service.AccountWithConcurrency, 0, len(openAIAccounts))
for _, account := range openAIAccounts {
if account == nil {
continue
}
if _, ok := seen[account.ID]; ok {
continue
}
seen[account.ID] = struct{}{}
loadReq = append(loadReq, service.AccountWithConcurrency{
ID: account.ID,
MaxConcurrency: account.EffectiveLoadFactor(),
})
}
if batchLoad, err := h.concurrencyService.GetAccountsLoadBatch(ctx, loadReq); err != nil {
slog.Warn("openai_scheduler_score_load_batch_failed", "error", err)
} else if batchLoad != nil {
loadMap = batchLoad
}
return loadMap
}
func (h *AccountHandler) buildOpenAIAccountSchedulerScores(
ctx context.Context,
accounts []service.Account,
filterPool []service.Account,
) (map[int64]*AccountSchedulerScore, map[int64][]AccountSchedulerGroupScore) {
if len(accounts) == 0 {
return nil, nil
}
if len(filterPool) == 0 {
filterPool = accounts
}
pageOpenAIAccountIDs := make(map[int64]struct{})
groupIDs := make(map[int64]struct{})
for i := range accounts {
account := &accounts[i]
if account.Platform != service.PlatformOpenAI {
continue
}
pageOpenAIAccountIDs[account.ID] = struct{}{}
if len(account.AccountGroups) == 0 && len(account.GroupIDs) == 0 {
continue
}
for _, accountGroup := range account.AccountGroups {
if accountGroup.GroupID > 0 {
groupIDs[accountGroup.GroupID] = struct{}{}
}
}
for _, groupID := range account.GroupIDs {
if groupID > 0 {
groupIDs[groupID] = struct{}{}
}
}
}
if len(pageOpenAIAccountIDs) == 0 {
return nil, nil
}
// 先取各分组池,再对"过滤池 ∪ 分组池"的账号并集做一次负载批查,
// 避免每个池各查一次 Redis 的 N+1。
groupIDList := make([]int64, 0, len(groupIDs))
for groupID := range groupIDs {
groupIDList = append(groupIDList, groupID)
}
sort.Slice(groupIDList, func(i, j int) bool { return groupIDList[i] < groupIDList[j] })
groupPools := make(map[int64][]service.Account, len(groupIDList))
if h.adminService != nil {
for _, groupID := range groupIDList {
gid := groupID
pool, err := h.adminService.ListOpenAISchedulableAccountsForSchedulerScore(ctx, &gid)
if err != nil {
slog.Warn("openai_scheduler_group_score_pool_failed", "group_id", gid, "error", err)
continue
}
groupPools[gid] = pool
}
}
loadUnion := make([]*service.Account, 0, len(filterPool))
collectOpenAIAccounts := func(pool []service.Account) {
for i := range pool {
if pool[i].Platform == service.PlatformOpenAI {
loadUnion = append(loadUnion, &pool[i])
}
}
}
collectOpenAIAccounts(filterPool)
for _, pool := range groupPools {
collectOpenAIAccounts(pool)
}
loadMap := h.fetchOpenAIAccountLoadMap(ctx, loadUnion)
baseScores := make(map[int64]*AccountSchedulerScore)
for accountID, score := range h.scoreOpenAIAccountSchedulerPool(ctx, filterPool, loadMap) {
copiedScore := score
baseScores[accountID] = &copiedScore
}
groupScoresByAccount := make(map[int64][]AccountSchedulerGroupScore)
scoreGroupPool := func(groupID *int64, groupNameByID map[int64]string, groupPriorityByAccount map[int64]int, pool []service.Account) {
if len(pool) == 0 {
return
}
scores := h.scoreOpenAIAccountSchedulerPool(ctx, pool, loadMap)
for accountID, schedulerScore := range scores {
if _, ok := pageOpenAIAccountIDs[accountID]; !ok {
continue
}
groupScore := AccountSchedulerGroupScore{
GroupID: groupID,
AccountSchedulerScore: schedulerScore,
}
if groupID != nil {
groupScore.GroupName = groupNameByID[*groupID]
if priority, ok := groupPriorityByAccount[accountID]; ok {
groupScore.GroupPriority = &priority
}
}
groupScoresByAccount[accountID] = append(groupScoresByAccount[accountID], groupScore)
}
}
for _, groupID := range groupIDList {
gid := groupID
pool, ok := groupPools[gid]
if !ok {
continue
}
groupNameByID := make(map[int64]string)
groupPriorityByAccount := make(map[int64]int)
for i := range pool {
account := &pool[i]
for _, accountGroup := range account.AccountGroups {
if accountGroup.GroupID != gid {
continue
}
groupPriorityByAccount[account.ID] = accountGroup.Priority
if accountGroup.Group != nil {
groupNameByID[gid] = accountGroup.Group.Name
}
}
}
scoreGroupPool(&gid, groupNameByID, groupPriorityByAccount, pool)
}
for accountID := range groupScoresByAccount {
sort.SliceStable(groupScoresByAccount[accountID], func(i, j int) bool {
left := groupScoresByAccount[accountID][i]
right := groupScoresByAccount[accountID][j]
return *left.GroupID < *right.GroupID
})
}
return baseScores, groupScoresByAccount
}
func (h *AccountHandler) listAccountSchedulerScoreFilterPool(
ctx context.Context,
platform, accountType, status, search string,
groupID int64,
privacyMode string,
) []service.Account {
if h.adminService == nil || (platform != "" && platform != service.PlatformOpenAI) {
return nil
}
// 池只用于 OpenAI 分数计算(非 OpenAI 账号会在打分时被丢弃),
// 无论列表页平台过滤为何,查询一律限定 openai,避免无过滤时全表扫描。
accounts, err := h.adminService.ListAccountsForSchedulerScoreFilter(ctx, service.PlatformOpenAI, accountType, status, search, groupID, privacyMode)
if err != nil {
slog.Warn("openai_scheduler_filter_score_pool_failed", "error", err)
return nil
}
return accounts
}
// List handles listing all accounts with pagination
// GET /api/v1/admin/accounts
func (h *AccountHandler) List(c *gin.Context) {
@@ -274,6 +520,20 @@ func (h *AccountHandler) List(c *gin.Context) {
var windowCosts map[int64]float64
var activeSessions map[int64]int
var rpmCounts map[int64]int
// 仅当前页存在 OpenAI 账号时才计算调度分数,避免为空结果付出池查询开销。
var schedulerScores map[int64]*AccountSchedulerScore
var schedulerGroupScores map[int64][]AccountSchedulerGroupScore
pageHasOpenAIAccounts := false
for i := range accounts {
if accounts[i].Platform == service.PlatformOpenAI {
pageHasOpenAIAccounts = true
break
}
}
if pageHasOpenAIAccounts {
schedulerFilterPool := h.listAccountSchedulerScoreFilterPool(c.Request.Context(), platform, accountType, status, search, groupID, privacyMode)
schedulerScores, schedulerGroupScores = h.buildOpenAIAccountSchedulerScores(c.Request.Context(), accounts, schedulerFilterPool)
}
// 始终获取并发数(Redis ZCARD,极低开销)
if h.concurrencyService != nil {
@@ -354,6 +614,8 @@ func (h *AccountHandler) List(c *gin.Context) {
item := AccountWithConcurrency{
Account: dto.AccountFromService(acc),
CurrentConcurrency: concurrencyCounts[acc.ID],
SchedulerScore: schedulerScores[acc.ID],
SchedulerScores: schedulerGroupScores[acc.ID],
}
// 添加窗口费用(仅当启用时)
@@ -380,6 +642,8 @@ func (h *AccountHandler) List(c *gin.Context) {
result[i] = item
}
h.enrichShadowParents(c.Request.Context(), result)
etag := buildAccountsListETag(result, total, page, pageSize, platform, accountType, status, search, lite)
if etag != "" {
c.Header("ETag", etag)
@@ -832,6 +1096,12 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
if !account.IsOAuth() {
return nil, "", infraerrors.BadRequest("NOT_OAUTH", "cannot refresh non-OAuth account")
}
// spark 影子凭据由母账号管理、自身恒空,刷新无意义且会先打上游;在调用上游前早拒
// (覆盖单账号与批量两入口;批量侧将其计为 failed 并附说明)(外审第6轮)。
if account.IsCredentialShadow() {
return nil, "", infraerrors.BadRequest("SPARK_SHADOW_NO_REFRESH",
"cannot refresh spark shadow account; its credentials are managed by the parent account")
}
var newCredentials map[string]any
@@ -849,6 +1119,7 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
newCredentials[k] = v
}
}
newCredentials = service.NormalizeOpenAIPersonalAccessTokenCredentials(account, tokenInfo, newCredentials)
} else if account.Platform == service.PlatformGemini {
tokenInfo, err := h.geminiOAuthService.RefreshAccountToken(ctx, account)
if err != nil {
@@ -1811,7 +2082,7 @@ func (h *AccountHandler) ResetQuota(c *gin.Context) {
}
if err := h.adminService.ResetAccountQuota(c.Request.Context(), accountID); err != nil {
response.InternalError(c, "Failed to reset account quota: "+err.Error())
response.ErrorFrom(c, err)
return
}
@@ -2063,6 +2334,56 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
return
}
// Handle Grok accounts
if account.Platform == service.PlatformGrok {
defaultModels := xai.DefaultModels()
hasExplicitMapping := false
switch rawMapping := account.Credentials["model_mapping"].(type) {
case map[string]any:
hasExplicitMapping = len(rawMapping) > 0
case map[string]string:
hasExplicitMapping = len(rawMapping) > 0
}
if !hasExplicitMapping {
response.Success(c, defaultModels)
return
}
mapping := account.GetModelMapping()
if len(mapping) == 0 {
response.Success(c, defaultModels)
return
}
defaultByID := make(map[string]xai.Model, len(defaultModels))
for _, model := range defaultModels {
defaultByID[model.ID] = model
}
requestedModels := make([]string, 0, len(mapping))
for requestedModel := range mapping {
requestedModels = append(requestedModels, requestedModel)
}
sort.Strings(requestedModels)
var models []xai.Model
for _, requestedModel := range requestedModels {
if defaultModel, found := defaultByID[requestedModel]; found {
models = append(models, defaultModel)
continue
}
models = append(models, xai.Model{
ID: requestedModel,
Object: "model",
OwnedBy: "xai",
DisplayName: requestedModel,
})
}
response.Success(c, models)
return
}
// Handle Claude/Anthropic accounts
// For OAuth and Setup-Token accounts: return default models
if account.IsOAuth() {
@@ -61,6 +61,7 @@ func setupSyncUpstreamModelsRouter(adminSvc service.AdminService, upstream servi
nil,
nil,
nil,
nil,
upstream,
&config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
nil,
@@ -70,6 +71,77 @@ func setupSyncUpstreamModelsRouter(adminSvc service.AdminService, upstream servi
return router
}
func TestAccountHandlerGetAvailableModels_GrokUsesXAIModels(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
account: service.Account{
ID: 44,
Name: "grok-oauth",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{
"model_mapping": map[string]any{
"grok-4.3": "grok-4.3",
},
},
},
}
router := setupAvailableModelsRouter(svc)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/44/models", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var resp struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Len(t, resp.Data, 1)
require.Equal(t, "grok-4.3", resp.Data[0].ID)
}
func TestAccountHandlerGetAvailableModels_GrokDefaultsToXAIModelsWithoutMapping(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
account: service.Account{
ID: 45,
Name: "grok-oauth-defaults",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
},
}
router := setupAvailableModelsRouter(svc)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/45/models", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var resp struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.NotEmpty(t, resp.Data)
var ids []string
for _, model := range resp.Data {
id := model.ID
ids = append(ids, id)
require.NotContains(t, strings.ToLower(id), "claude")
}
require.Contains(t, ids, "grok-4.3")
require.Contains(t, ids, "grok-build-0.1")
}
func TestAccountHandlerGetAvailableModels_OpenAIOAuthUsesExplicitModelMapping(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
@@ -141,6 +213,48 @@ func TestAccountHandlerGetAvailableModels_OpenAIOAuthPassthroughFallsBackToDefau
require.NotEqual(t, "gpt-5", resp.Data[0].ID)
}
func TestAccountHandlerGetAvailableModels_OpenAISparkShadowReturnsMappingModels(t *testing.T) {
parentID := int64(100)
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
account: service.Account{
ID: 44,
Name: "openai-spark-shadow",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
ParentAccountID: &parentID,
QuotaDimension: service.QuotaDimensionSpark,
Credentials: map[string]any{
"model_mapping": map[string]any{
"gpt-5.3-codex-spark": "gpt-5.3-codex-spark",
},
},
},
}
router := setupAvailableModelsRouter(svc)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/44/models", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var resp struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
ids := make([]string, 0, len(resp.Data))
for _, m := range resp.Data {
ids = append(ids, m.ID)
}
require.ElementsMatch(t, []string{
"gpt-5.3-codex-spark",
}, ids, "影子可用模型由 model_mapping 派生(非写死)")
}
func TestAccountHandlerSyncUpstreamModels_ConfigErrorReturnsBadRequest(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
@@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
@@ -50,3 +51,222 @@ func TestAccountHandlerListIncludesCreatedAt(t *testing.T) {
_, offset := parsed.Zone()
require.Equal(t, 0, offset)
}
func TestAccountHandlerListReturnsSchedulerScoresPerGroup(t *testing.T) {
router, adminSvc := setupAccountListRouter()
now := time.Now().UTC()
groupID := int64(41)
adminSvc.accounts = []service.Account{
{
ID: 101,
Name: "account-high-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 10,
Priority: 1,
AccountGroups: []service.AccountGroup{
{AccountID: 101, GroupID: groupID, Priority: 100, Group: &service.Group{ID: groupID, Name: "openai"}},
},
GroupIDs: []int64{groupID},
CreatedAt: now,
UpdatedAt: now,
},
{
ID: 102,
Name: "account-low-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 10,
Priority: 100000,
AccountGroups: []service.AccountGroup{
{AccountID: 102, GroupID: groupID, Priority: 1, Group: &service.Group{ID: groupID, Name: "openai"}},
},
GroupIDs: []int64{groupID},
CreatedAt: now,
UpdatedAt: now,
},
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=20&platform=openai", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var payload struct {
Data struct {
Items []struct {
ID int64 `json:"id"`
SchedulerScore struct {
BaseScore float64 `json:"base_score"`
} `json:"scheduler_score"`
SchedulerScores []struct {
GroupID *int64 `json:"group_id"`
GroupName string `json:"group_name"`
GroupPriority *int `json:"group_priority"`
BaseScore float64 `json:"base_score"`
} `json:"scheduler_scores"`
} `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
require.Len(t, payload.Data.Items, 2)
var high, low *struct {
ID int64 `json:"id"`
SchedulerScore struct {
BaseScore float64 `json:"base_score"`
} `json:"scheduler_score"`
SchedulerScores []struct {
GroupID *int64 `json:"group_id"`
GroupName string `json:"group_name"`
GroupPriority *int `json:"group_priority"`
BaseScore float64 `json:"base_score"`
} `json:"scheduler_scores"`
}
for i := range payload.Data.Items {
item := &payload.Data.Items[i]
switch item.ID {
case 101:
high = item
case 102:
low = item
}
}
require.NotNil(t, high)
require.NotNil(t, low)
require.Len(t, high.SchedulerScores, 1)
require.Len(t, low.SchedulerScores, 1)
require.Equal(t, groupID, *high.SchedulerScores[0].GroupID)
require.Equal(t, "openai", high.SchedulerScores[0].GroupName)
require.Equal(t, 100, *high.SchedulerScores[0].GroupPriority)
require.Equal(t, 1, *low.SchedulerScores[0].GroupPriority)
require.Greater(t, high.SchedulerScores[0].BaseScore, low.SchedulerScores[0].BaseScore)
}
func TestAccountHandlerListKeepsSchedulerScoreScopedToFilter(t *testing.T) {
router, adminSvc := setupAccountListRouter()
now := time.Now().UTC()
groupID := int64(42)
visibleAccount := service.Account{
ID: 201,
Name: "visible-low-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 10,
Priority: 100000,
AccountGroups: []service.AccountGroup{
{AccountID: 201, GroupID: groupID, Priority: 1, Group: &service.Group{ID: groupID, Name: "openai"}},
},
GroupIDs: []int64{groupID},
CreatedAt: now,
UpdatedAt: now,
}
hiddenGroupPeer := service.Account{
ID: 202,
Name: "hidden-high-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 10,
Priority: 1,
AccountGroups: []service.AccountGroup{
{AccountID: 202, GroupID: groupID, Priority: 2, Group: &service.Group{ID: groupID, Name: "openai"}},
},
GroupIDs: []int64{groupID},
CreatedAt: now,
UpdatedAt: now,
}
adminSvc.accounts = []service.Account{visibleAccount}
adminSvc.accountSchedulerScoreFilterAccounts = []service.Account{visibleAccount, hiddenGroupPeer}
adminSvc.openAISchedulerScorePoolAccounts = []service.Account{visibleAccount, hiddenGroupPeer}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=1&platform=openai", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var payload struct {
Data struct {
Items []struct {
ID int64 `json:"id"`
SchedulerScore struct {
BaseScore float64 `json:"base_score"`
} `json:"scheduler_score"`
SchedulerScores []struct {
GroupID *int64 `json:"group_id"`
BaseScore float64 `json:"base_score"`
} `json:"scheduler_scores"`
} `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
require.Len(t, payload.Data.Items, 1)
item := payload.Data.Items[0]
require.Equal(t, int64(201), item.ID)
require.Len(t, item.SchedulerScores, 1)
require.Equal(t, groupID, *item.SchedulerScores[0].GroupID)
require.Equal(t, item.SchedulerScores[0].BaseScore, item.SchedulerScore.BaseScore)
}
func TestAccountHandlerListSchedulerScoreIgnoresPagination(t *testing.T) {
router, adminSvc := setupAccountListRouter()
now := time.Now().UTC()
visibleAccount := service.Account{
ID: 301,
Name: "visible-low-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 10,
Priority: 100000,
CreatedAt: now,
UpdatedAt: now,
}
hiddenFilterPeer := service.Account{
ID: 302,
Name: "hidden-high-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 10,
Priority: 1,
CreatedAt: now,
UpdatedAt: now,
}
adminSvc.accounts = []service.Account{visibleAccount}
adminSvc.accountSchedulerScoreFilterAccounts = []service.Account{visibleAccount, hiddenFilterPeer}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=1&platform=openai", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var payload struct {
Data struct {
Items []struct {
ID int64 `json:"id"`
SchedulerScore struct {
BaseScore float64 `json:"base_score"`
} `json:"scheduler_score"`
SchedulerScores []struct {
GroupID *int64 `json:"group_id"`
BaseScore float64 `json:"base_score"`
} `json:"scheduler_scores"`
} `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
require.Len(t, payload.Data.Items, 1)
require.Equal(t, int64(301), payload.Data.Items[0].ID)
require.Less(t, payload.Data.Items[0].SchedulerScore.BaseScore, 3.75)
require.Empty(t, payload.Data.Items[0].SchedulerScores)
}
@@ -0,0 +1,29 @@
package admin
import (
"context"
"net/http"
"testing"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
// TestRefreshSingleAccount_RejectsShadow 验证外审第6轮:手动刷新对 spark 影子在调用上游前早拒
// (影子凭据由母账号管理、自身恒空,刷新无意义)。该守卫同时覆盖单账号与批量刷新两入口。
func TestRefreshSingleAccount_RejectsShadow(t *testing.T) {
h := &AccountHandler{} // 影子在使用任何依赖前即返回,无需注入
parentID := int64(5)
shadow := &service.Account{
ID: 9,
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth, // IsOAuth()=true,确保不是先撞 NOT_OAUTH
ParentAccountID: &parentID,
QuotaDimension: service.QuotaDimensionSpark,
}
_, _, err := h.refreshSingleAccount(context.Background(), shadow)
require.Error(t, err, "影子刷新应被早拒")
require.Equal(t, http.StatusBadRequest, infraerrors.Code(err))
}
@@ -0,0 +1,56 @@
package admin
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/service"
)
// enrichShadowParentInfo 把母账号的展示信息回填到影子行的 parent_* 字段。
// 纯函数:仅依赖传入的母账号 map,便于单测;非影子或母账号缺失时优雅留空。
func enrichShadowParentInfo(items []AccountWithConcurrency, parents map[int64]*service.Account) {
for i := range items {
a := items[i].Account
if a == nil || a.ParentAccountID == nil {
continue
}
p := parents[*a.ParentAccountID]
if p == nil {
continue
}
a.ParentEmail = p.GetCredential("email")
a.ParentPlanType = p.GetCredential("plan_type")
a.ParentSubscriptionExpiresAt = p.GetCredential("subscription_expires_at")
a.ParentChatGPTAccountID = p.GetCredential("chatgpt_account_id")
a.ParentPrivacyMode = p.GetExtraString("privacy_mode")
}
}
// enrichShadowParents 收集本批影子行的母账号 ID、一次批量解析(避免 N+1),再回填。
// 解析失败时不报错(parent_* 留空,降级)。
func (h *AccountHandler) enrichShadowParents(ctx context.Context, items []AccountWithConcurrency) {
seen := make(map[int64]struct{})
for i := range items {
a := items[i].Account
if a == nil || a.ParentAccountID == nil {
continue
}
seen[*a.ParentAccountID] = struct{}{}
}
if len(seen) == 0 {
return
}
parentIDs := make([]int64, 0, len(seen))
for pid := range seen {
parentIDs = append(parentIDs, pid)
}
parents, err := h.adminService.GetAccountsByIDs(ctx, parentIDs)
if err != nil {
return
}
pmap := make(map[int64]*service.Account, len(parents))
for _, p := range parents {
pmap[p.ID] = p
}
enrichShadowParentInfo(items, pmap)
}
@@ -0,0 +1,42 @@
package admin
import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestEnrichShadowParentInfo(t *testing.T) {
pid := int64(100)
parent := &service.Account{
ID: 100,
Credentials: map[string]any{
"email": "owner@example.com",
"plan_type": "pro",
"subscription_expires_at": "2026-12-31T00:00:00Z",
"chatgpt_account_id": "acct_123",
},
Extra: map[string]any{"privacy_mode": "training_off"},
}
parents := map[int64]*service.Account{100: parent}
shadow := AccountWithConcurrency{Account: &dto.Account{ID: 200, ParentAccountID: &pid}}
normal := AccountWithConcurrency{Account: &dto.Account{ID: 1}}
orphan := AccountWithConcurrency{Account: &dto.Account{ID: 201, ParentAccountID: ptrInt64(999)}}
items := []AccountWithConcurrency{shadow, normal, orphan}
enrichShadowParentInfo(items, parents)
require.Equal(t, "owner@example.com", items[0].ParentEmail, "影子回填母账号邮箱")
require.Equal(t, "pro", items[0].ParentPlanType)
require.Equal(t, "training_off", items[0].ParentPrivacyMode)
require.Equal(t, "2026-12-31T00:00:00Z", items[0].ParentSubscriptionExpiresAt)
require.Equal(t, "acct_123", items[0].ParentChatGPTAccountID)
require.Empty(t, items[1].ParentEmail, "非影子不回填")
require.Empty(t, items[2].ParentEmail, "母账号缺失时优雅留空")
}
func ptrInt64(v int64) *int64 { return &v }
@@ -10,26 +10,29 @@ import (
)
type stubAdminService struct {
users []service.User
apiKeys []service.APIKey
groups []service.Group
accounts []service.Account
proxies []service.Proxy
proxyCounts []service.ProxyWithAccountCount
redeems []service.RedeemCode
boundAuthIdentity *service.AdminBindAuthIdentityInput
boundAuthIdentityFor int64
createdAccounts []*service.CreateAccountInput
createdProxies []*service.CreateProxyInput
updatedProxyIDs []int64
updatedProxies []*service.UpdateProxyInput
testedProxyIDs []int64
getUserErr error
createAccountErr error
updateAccountErr error
bulkUpdateAccountErr error
checkMixedErr error
lastMixedCheck struct {
users []service.User
apiKeys []service.APIKey
groups []service.Group
accounts []service.Account
accountSchedulerScoreFilterAccounts []service.Account
openAISchedulerScorePoolAccounts []service.Account
proxies []service.Proxy
proxyCounts []service.ProxyWithAccountCount
redeems []service.RedeemCode
boundAuthIdentity *service.AdminBindAuthIdentityInput
boundAuthIdentityFor int64
createdAccounts []*service.CreateAccountInput
createdProxies []*service.CreateProxyInput
updatedProxyIDs []int64
updatedProxies []*service.UpdateProxyInput
testedProxyIDs []int64
getUserErr error
createAccountErr error
createSparkShadowErr error
updateAccountErr error
bulkUpdateAccountErr error
checkMixedErr error
lastMixedCheck struct {
accountID int64
platform string
groupIDs []int64
@@ -328,7 +331,56 @@ func (s *stubAdminService) ListAccounts(ctx context.Context, page, pageSize int,
s.lastListAccounts.sortBy = sortBy
s.lastListAccounts.sortOrder = sortOrder
s.lastListAccounts.calls++
return s.accounts, int64(len(s.accounts)), nil
accounts := s.accounts
total := len(accounts)
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = total
}
start := (page - 1) * pageSize
if start >= total {
return []service.Account{}, int64(total), nil
}
end := start + pageSize
if end > total {
end = total
}
return accounts[start:end], int64(total), nil
}
func (s *stubAdminService) ListAccountsForSchedulerScoreFilter(_ context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]service.Account, error) {
if s.accountSchedulerScoreFilterAccounts != nil {
return s.accountSchedulerScoreFilterAccounts, nil
}
return s.accounts, nil
}
func (s *stubAdminService) ListOpenAISchedulableAccountsForSchedulerScore(_ context.Context, groupID *int64) ([]service.Account, error) {
accounts := s.openAISchedulerScorePoolAccounts
if accounts == nil {
accounts = s.accounts
}
out := make([]service.Account, 0, len(accounts))
for _, account := range accounts {
if account.Platform != service.PlatformOpenAI || !account.IsSchedulable() {
continue
}
if groupID == nil {
if len(account.AccountGroups) == 0 && len(account.GroupIDs) == 0 {
out = append(out, account)
}
continue
}
for _, accountGroup := range account.AccountGroups {
if accountGroup.GroupID == *groupID {
out = append(out, account)
break
}
}
}
return out, nil
}
func (s *stubAdminService) GetAccount(ctx context.Context, id int64) (*service.Account, error) {
@@ -636,5 +688,25 @@ func (s *stubAdminService) RevertAccountProxyFallback(ctx context.Context, id in
return nil
}
func (s *stubAdminService) CreateShadow(ctx context.Context, parentID int64, opts service.ShadowOptions) (*service.Account, error) {
if s.createSparkShadowErr != nil {
return nil, s.createSparkShadowErr
}
pid := parentID
return &service.Account{
ID: 9001,
Name: opts.Name,
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Priority: opts.Priority,
Concurrency: opts.Concurrency,
GroupIDs: opts.GroupIDs,
ParentAccountID: &pid,
QuotaDimension: service.QuotaDimensionSpark,
Credentials: map[string]any{},
Extra: map[string]any{},
}, nil
}
// Ensure stub implements interface.
var _ service.AdminService = (*stubAdminService)(nil)
@@ -509,6 +509,7 @@ var platformToLiteLLMProvider = map[string]string{
service.PlatformOpenAI: "openai",
service.PlatformGemini: "google",
service.PlatformAntigravity: "anthropic",
service.PlatformGrok: "xai",
}
// SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表
@@ -46,6 +46,7 @@ type channelMonitorCreateRequest struct {
GroupName string `json:"group_name" binding:"max=100"`
Enabled *bool `json:"enabled"`
IntervalSeconds int `json:"interval_seconds" binding:"required,min=15,max=3600"`
JitterSeconds int `json:"jitter_seconds" binding:"omitempty,min=0,max=3585"`
TemplateID *int64 `json:"template_id"`
ExtraHeaders map[string]string `json:"extra_headers"`
BodyOverrideMode string `json:"body_override_mode" binding:"omitempty,oneof=off merge replace"`
@@ -63,6 +64,7 @@ type channelMonitorUpdateRequest struct {
GroupName *string `json:"group_name" binding:"omitempty,max=100"`
Enabled *bool `json:"enabled"`
IntervalSeconds *int `json:"interval_seconds" binding:"omitempty,min=15,max=3600"`
JitterSeconds *int `json:"jitter_seconds" binding:"omitempty,min=0,max=3585"`
TemplateID *int64 `json:"template_id"`
ClearTemplate bool `json:"clear_template"` // true 时把 template_id 置空,忽略 TemplateID
ExtraHeaders *map[string]string `json:"extra_headers"`
@@ -83,6 +85,7 @@ type channelMonitorResponse struct {
GroupName string `json:"group_name"`
Enabled bool `json:"enabled"`
IntervalSeconds int `json:"interval_seconds"`
JitterSeconds int `json:"jitter_seconds"`
LastCheckedAt *string `json:"last_checked_at"`
CreatedBy int64 `json:"created_by"`
CreatedAt string `json:"created_at"`
@@ -150,6 +153,7 @@ func channelMonitorToResponse(m *service.ChannelMonitor) *channelMonitorResponse
GroupName: m.GroupName,
Enabled: m.Enabled,
IntervalSeconds: m.IntervalSeconds,
JitterSeconds: m.JitterSeconds,
CreatedBy: m.CreatedBy,
CreatedAt: m.CreatedAt.UTC().Format(time.RFC3339),
UpdatedAt: m.UpdatedAt.UTC().Format(time.RFC3339),
@@ -315,6 +319,7 @@ func (h *ChannelMonitorHandler) Create(c *gin.Context) {
GroupName: req.GroupName,
Enabled: enabled,
IntervalSeconds: req.IntervalSeconds,
JitterSeconds: req.JitterSeconds,
CreatedBy: subject.UserID,
TemplateID: req.TemplateID,
ExtraHeaders: req.ExtraHeaders,
@@ -351,6 +356,7 @@ func (h *ChannelMonitorHandler) Update(c *gin.Context) {
GroupName: req.GroupName,
Enabled: req.Enabled,
IntervalSeconds: req.IntervalSeconds,
JitterSeconds: req.JitterSeconds,
TemplateID: req.TemplateID,
ClearTemplate: req.ClearTemplate,
ExtraHeaders: req.ExtraHeaders,
@@ -20,36 +20,39 @@ func NewContentModerationHandler(svc *service.ContentModerationService) *Content
}
type contentModerationConfigRequest struct {
Enabled *bool `json:"enabled"`
Mode *string `json:"mode"`
BaseURL *string `json:"base_url"`
Model *string `json:"model"`
APIKey *string `json:"api_key"`
APIKeys *[]string `json:"api_keys"`
APIKeysMode string `json:"api_keys_mode"`
DeleteAPIKeyHashes *[]string `json:"delete_api_key_hashes"`
ClearAPIKey bool `json:"clear_api_key"`
TimeoutMS *int `json:"timeout_ms"`
SampleRate *int `json:"sample_rate"`
AllGroups *bool `json:"all_groups"`
GroupIDs *[]int64 `json:"group_ids"`
RecordNonHits *bool `json:"record_non_hits"`
Thresholds *map[string]float64 `json:"thresholds"`
WorkerCount *int `json:"worker_count"`
QueueSize *int `json:"queue_size"`
BlockStatus *int `json:"block_status"`
BlockMessage *string `json:"block_message"`
EmailOnHit *bool `json:"email_on_hit"`
AutoBanEnabled *bool `json:"auto_ban_enabled"`
BanThreshold *int `json:"ban_threshold"`
ViolationWindowHours *int `json:"violation_window_hours"`
RetryCount *int `json:"retry_count"`
HitRetentionDays *int `json:"hit_retention_days"`
NonHitRetentionDays *int `json:"non_hit_retention_days"`
PreHashCheckEnabled *bool `json:"pre_hash_check_enabled"`
BlockedKeywords *[]string `json:"blocked_keywords"`
KeywordBlockingMode *string `json:"keyword_blocking_mode"`
ModelFilter *service.ContentModerationModelFilter `json:"model_filter"`
Enabled *bool `json:"enabled"`
Mode *string `json:"mode"`
BaseURL *string `json:"base_url"`
Model *string `json:"model"`
APIKey *string `json:"api_key"`
APIKeys *[]string `json:"api_keys"`
APIKeysMode string `json:"api_keys_mode"`
DeleteAPIKeyHashes *[]string `json:"delete_api_key_hashes"`
ClearAPIKey bool `json:"clear_api_key"`
TimeoutMS *int `json:"timeout_ms"`
SampleRate *int `json:"sample_rate"`
AllGroups *bool `json:"all_groups"`
GroupIDs *[]int64 `json:"group_ids"`
RecordNonHits *bool `json:"record_non_hits"`
Thresholds *map[string]float64 `json:"thresholds"`
WorkerCount *int `json:"worker_count"`
QueueSize *int `json:"queue_size"`
BlockStatus *int `json:"block_status"`
BlockMessage *string `json:"block_message"`
EmailOnHit *bool `json:"email_on_hit"`
AutoBanEnabled *bool `json:"auto_ban_enabled"`
BanThreshold *int `json:"ban_threshold"`
ViolationWindowHours *int `json:"violation_window_hours"`
// cyber_policy 命中是否排除出自动封号计数;前端 RiskControlView 已发送该字段,
// service.UpdateContentModerationConfigInput 已支持,此前 handler 层缺透传导致开关静默失效。
CyberPolicyExcludeFromBanCount *bool `json:"cyber_policy_exclude_from_ban_count"`
RetryCount *int `json:"retry_count"`
HitRetentionDays *int `json:"hit_retention_days"`
NonHitRetentionDays *int `json:"non_hit_retention_days"`
PreHashCheckEnabled *bool `json:"pre_hash_check_enabled"`
BlockedKeywords *[]string `json:"blocked_keywords"`
KeywordBlockingMode *string `json:"keyword_blocking_mode"`
ModelFilter *service.ContentModerationModelFilter `json:"model_filter"`
}
type contentModerationAPIKeyTestRequest struct {
@@ -81,36 +84,37 @@ func (h *ContentModerationHandler) UpdateConfig(c *gin.Context) {
return
}
cfg, err := h.service.UpdateConfig(c.Request.Context(), service.UpdateContentModerationConfigInput{
Enabled: req.Enabled,
Mode: req.Mode,
BaseURL: req.BaseURL,
Model: req.Model,
APIKey: req.APIKey,
APIKeys: req.APIKeys,
APIKeysMode: req.APIKeysMode,
DeleteAPIKeyHashes: req.DeleteAPIKeyHashes,
ClearAPIKey: req.ClearAPIKey,
TimeoutMS: req.TimeoutMS,
SampleRate: req.SampleRate,
AllGroups: req.AllGroups,
GroupIDs: req.GroupIDs,
RecordNonHits: req.RecordNonHits,
Thresholds: req.Thresholds,
WorkerCount: req.WorkerCount,
QueueSize: req.QueueSize,
BlockStatus: req.BlockStatus,
BlockMessage: req.BlockMessage,
EmailOnHit: req.EmailOnHit,
AutoBanEnabled: req.AutoBanEnabled,
BanThreshold: req.BanThreshold,
ViolationWindowHours: req.ViolationWindowHours,
RetryCount: req.RetryCount,
HitRetentionDays: req.HitRetentionDays,
NonHitRetentionDays: req.NonHitRetentionDays,
PreHashCheckEnabled: req.PreHashCheckEnabled,
BlockedKeywords: req.BlockedKeywords,
KeywordBlockingMode: req.KeywordBlockingMode,
ModelFilter: req.ModelFilter,
Enabled: req.Enabled,
Mode: req.Mode,
BaseURL: req.BaseURL,
Model: req.Model,
APIKey: req.APIKey,
APIKeys: req.APIKeys,
APIKeysMode: req.APIKeysMode,
DeleteAPIKeyHashes: req.DeleteAPIKeyHashes,
ClearAPIKey: req.ClearAPIKey,
TimeoutMS: req.TimeoutMS,
SampleRate: req.SampleRate,
AllGroups: req.AllGroups,
GroupIDs: req.GroupIDs,
RecordNonHits: req.RecordNonHits,
Thresholds: req.Thresholds,
WorkerCount: req.WorkerCount,
QueueSize: req.QueueSize,
BlockStatus: req.BlockStatus,
BlockMessage: req.BlockMessage,
EmailOnHit: req.EmailOnHit,
AutoBanEnabled: req.AutoBanEnabled,
BanThreshold: req.BanThreshold,
ViolationWindowHours: req.ViolationWindowHours,
CyberPolicyExcludeFromBanCount: req.CyberPolicyExcludeFromBanCount,
RetryCount: req.RetryCount,
HitRetentionDays: req.HitRetentionDays,
NonHitRetentionDays: req.NonHitRetentionDays,
PreHashCheckEnabled: req.PreHashCheckEnabled,
BlockedKeywords: req.BlockedKeywords,
KeywordBlockingMode: req.KeywordBlockingMode,
ModelFilter: req.ModelFilter,
})
if err != nil {
response.ErrorFrom(c, err)
@@ -0,0 +1,246 @@
package admin
import (
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type GrokOAuthHandler struct {
grokOAuthService *service.GrokOAuthService
adminService service.AdminService
quotaService *service.GrokQuotaService
}
func NewGrokOAuthHandler(
grokOAuthService *service.GrokOAuthService,
adminService service.AdminService,
quotaService *service.GrokQuotaService,
) *GrokOAuthHandler {
return &GrokOAuthHandler{
grokOAuthService: grokOAuthService,
adminService: adminService,
quotaService: quotaService,
}
}
type GrokGenerateAuthURLRequest struct {
ProxyID *int64 `json:"proxy_id"`
RedirectURI string `json:"redirect_uri"`
}
func (h *GrokOAuthHandler) GenerateAuthURL(c *gin.Context) {
var req GrokGenerateAuthURLRequest
if err := c.ShouldBindJSON(&req); err != nil {
req = GrokGenerateAuthURLRequest{}
}
result, err := h.grokOAuthService.GenerateAuthURL(c.Request.Context(), req.ProxyID, req.RedirectURI)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
type GrokExchangeCodeRequest struct {
SessionID string `json:"session_id" binding:"required"`
Code string `json:"code" binding:"required"`
State string `json:"state"`
RedirectURI string `json:"redirect_uri"`
ProxyID *int64 `json:"proxy_id"`
}
func (h *GrokOAuthHandler) ExchangeCode(c *gin.Context) {
var req GrokExchangeCodeRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
tokenInfo, err := h.grokOAuthService.ExchangeCode(c.Request.Context(), &service.GrokExchangeCodeInput{
SessionID: req.SessionID,
Code: req.Code,
State: req.State,
RedirectURI: req.RedirectURI,
ProxyID: req.ProxyID,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, tokenInfo)
}
type GrokRefreshTokenRequest struct {
RefreshToken string `json:"refresh_token"`
RT string `json:"rt"`
ClientID string `json:"client_id"`
ProxyID *int64 `json:"proxy_id"`
}
func (h *GrokOAuthHandler) RefreshToken(c *gin.Context) {
var req GrokRefreshTokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
refreshToken := strings.TrimSpace(req.RefreshToken)
if refreshToken == "" {
refreshToken = strings.TrimSpace(req.RT)
}
if refreshToken == "" {
response.BadRequest(c, "refresh_token is required")
return
}
var proxyURL string
if req.ProxyID != nil {
proxy, err := h.adminService.GetProxy(c.Request.Context(), *req.ProxyID)
if err == nil && proxy != nil {
proxyURL = proxy.URL()
}
}
tokenInfo, err := h.grokOAuthService.RefreshToken(c.Request.Context(), refreshToken, proxyURL, req.ClientID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, tokenInfo)
}
func (h *GrokOAuthHandler) RefreshAccountToken(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
account, err := h.adminService.GetAccount(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
if account.Platform != service.PlatformGrok {
response.BadRequest(c, "Account platform does not match Grok OAuth endpoint")
return
}
if !account.IsOAuth() {
response.BadRequest(c, "Cannot refresh non-OAuth account credentials")
return
}
tokenInfo, err := h.grokOAuthService.RefreshAccountToken(c.Request.Context(), account)
if err != nil {
response.ErrorFrom(c, err)
return
}
newCredentials := h.grokOAuthService.BuildAccountCredentials(tokenInfo)
newCredentials = service.MergeCredentials(account.Credentials, newCredentials)
if baseURL := strings.TrimSpace(account.GetCredential("base_url")); baseURL != "" {
newCredentials["base_url"] = baseURL
}
updatedAccount, err := h.adminService.UpdateAccount(c.Request.Context(), accountID, &service.UpdateAccountInput{
Credentials: newCredentials,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, dto.AccountFromService(updatedAccount))
}
func (h *GrokOAuthHandler) CreateAccountFromOAuth(c *gin.Context) {
var req struct {
SessionID string `json:"session_id" binding:"required"`
Code string `json:"code" binding:"required"`
State string `json:"state"`
RedirectURI string `json:"redirect_uri"`
ProxyID *int64 `json:"proxy_id"`
Name string `json:"name"`
Concurrency int `json:"concurrency"`
Priority int `json:"priority"`
GroupIDs []int64 `json:"group_ids"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
tokenInfo, err := h.grokOAuthService.ExchangeCode(c.Request.Context(), &service.GrokExchangeCodeInput{
SessionID: req.SessionID,
Code: req.Code,
State: req.State,
RedirectURI: req.RedirectURI,
ProxyID: req.ProxyID,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
credentials := h.grokOAuthService.BuildAccountCredentials(tokenInfo)
name := strings.TrimSpace(req.Name)
if name == "" && tokenInfo.Email != "" {
name = tokenInfo.Email
}
if name == "" {
name = "Grok OAuth Account"
}
account, err := h.adminService.CreateAccount(c.Request.Context(), &service.CreateAccountInput{
Name: name,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Credentials: credentials,
ProxyID: req.ProxyID,
Concurrency: req.Concurrency,
Priority: req.Priority,
GroupIDs: req.GroupIDs,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, dto.AccountFromService(account))
}
func (h *GrokOAuthHandler) QueryQuota(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
if h.quotaService == nil {
response.BadRequest(c, "grok quota service is not enabled")
return
}
result, err := h.quotaService.ProbeUsage(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
func (h *GrokOAuthHandler) ResetQuota(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
if h.quotaService == nil {
response.BadRequest(c, "grok quota service is not enabled")
return
}
result, err := h.quotaService.ResetQuota(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
func (h *GrokOAuthHandler) RuntimeSanity(c *gin.Context) {
response.Success(c, xai.RuntimeSanity())
}
@@ -0,0 +1,147 @@
//go:build unit
package admin
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
)
type grokQuotaHandlerAccountRepo struct {
service.AccountRepository
account *service.Account
updates map[int64]map[string]any
}
func (r *grokQuotaHandlerAccountRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
if r.account != nil && r.account.ID == id {
return r.account, nil
}
return nil, service.ErrAccountNotFound
}
func (r *grokQuotaHandlerAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error {
if r.updates == nil {
r.updates = make(map[int64]map[string]any)
}
r.updates[id] = updates
return nil
}
type grokQuotaHandlerUpstream struct {
resp *http.Response
lastReq *http.Request
lastBody []byte
}
func (u *grokQuotaHandlerUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.lastReq = req
if req.Body != nil {
u.lastBody, _ = io.ReadAll(req.Body)
}
return u.resp, nil
}
func (u *grokQuotaHandlerUpstream) DoWithTLS(
req *http.Request,
proxyURL string,
accountID int64,
accountConcurrency int,
_ *tlsfingerprint.Profile,
) (*http.Response, error) {
return u.Do(req, proxyURL, accountID, accountConcurrency)
}
func TestGrokOAuthHandlerQueryQuotaProbesUpstream(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &grokQuotaHandlerAccountRepo{account: &service.Account{
ID: 42,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Concurrency: 1,
Credentials: map[string]any{
"access_token": "access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
},
}}
upstream := &grokQuotaHandlerUpstream{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"X-Ratelimit-Limit-Requests": []string{"10"},
"X-Ratelimit-Remaining-Requests": []string{"8"},
},
Body: io.NopCloser(strings.NewReader(`{"id":"resp_probe"}`)),
}}
quotaService := service.NewGrokQuotaService(repo, nil, service.NewGrokTokenProvider(repo, nil), upstream)
handler := NewGrokOAuthHandler(nil, nil, quotaService)
router := gin.New()
router.GET("/api/v1/admin/grok/accounts/:id/quota", handler.QueryQuota)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/grok/accounts/42/quota", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), `"source":"active_probe"`)
require.Contains(t, rec.Body.String(), `"headers_observed":true`)
require.NotContains(t, rec.Body.String(), "access-token")
require.Equal(t, xai.DefaultBaseURL+"/responses", upstream.lastReq.URL.String())
require.Equal(t, "Bearer access-token", upstream.lastReq.Header.Get("Authorization"))
require.Contains(t, string(upstream.lastBody), `"store":false`)
require.NotNil(t, repo.updates[42])
}
func TestGrokOAuthHandlerResetQuotaReturnsUnsupported(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &grokQuotaHandlerAccountRepo{account: &service.Account{
ID: 43,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
}}
quotaService := service.NewGrokQuotaService(repo, nil, nil, nil)
handler := NewGrokOAuthHandler(nil, nil, quotaService)
router := gin.New()
router.POST("/api/v1/admin/grok/accounts/:id/reset-quota", handler.ResetQuota)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/accounts/43/reset-quota", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusNotImplemented, rec.Code)
require.Contains(t, rec.Body.String(), `"reason":"GROK_QUOTA_RESET_UNSUPPORTED"`)
require.NotContains(t, rec.Body.String(), "access-token")
}
func TestGrokOAuthHandlerRuntimeSanityDoesNotExposeSecrets(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv(xai.EnvBaseURL, "http://127.0.0.1:8080/v1?access_token=secret")
t.Setenv(xai.EnvClientID, "client-secret-like-value")
handler := NewGrokOAuthHandler(nil, nil, nil)
router := gin.New()
router.GET("/api/v1/admin/grok/runtime-sanity", handler.RuntimeSanity)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/grok/runtime-sanity", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), `"public_gateway_scope":"responses_only"`)
require.Contains(t, rec.Body.String(), `"valid":false`)
require.NotContains(t, rec.Body.String(), "access_token")
require.NotContains(t, rec.Body.String(), "secret")
require.NotContains(t, rec.Body.String(), "client-secret-like-value")
}
@@ -84,7 +84,7 @@ func NewGroupHandler(adminService service.AdminService, dashboardService *servic
type CreateGroupRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity"`
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok"`
RateMultiplier float64 `json:"rate_multiplier"`
IsExclusive bool `json:"is_exclusive"`
SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"`
@@ -95,6 +95,10 @@ type CreateGroupRequest struct {
AllowImageGeneration bool `json:"allow_image_generation"`
ImageRateIndependent bool `json:"image_rate_independent"`
ImageRateMultiplier *float64 `json:"image_rate_multiplier"`
PeakRateEnabled bool `json:"peak_rate_enabled"`
PeakStart string `json:"peak_start"`
PeakEnd string `json:"peak_end"`
PeakRateMultiplier *float64 `json:"peak_rate_multiplier"`
ImagePrice1K *float64 `json:"image_price_1k"`
ImagePrice2K *float64 `json:"image_price_2k"`
ImagePrice4K *float64 `json:"image_price_4k"`
@@ -124,7 +128,7 @@ type CreateGroupRequest struct {
type UpdateGroupRequest struct {
Name string `json:"name"`
Description *string `json:"description"`
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity"`
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok"`
RateMultiplier *float64 `json:"rate_multiplier"`
IsExclusive *bool `json:"is_exclusive"`
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
@@ -136,6 +140,10 @@ type UpdateGroupRequest struct {
AllowImageGeneration *bool `json:"allow_image_generation"`
ImageRateIndependent *bool `json:"image_rate_independent"`
ImageRateMultiplier *float64 `json:"image_rate_multiplier"`
PeakRateEnabled *bool `json:"peak_rate_enabled"`
PeakStart *string `json:"peak_start"`
PeakEnd *string `json:"peak_end"`
PeakRateMultiplier *float64 `json:"peak_rate_multiplier"`
ImagePrice1K *float64 `json:"image_price_1k"`
ImagePrice2K *float64 `json:"image_price_2k"`
ImagePrice4K *float64 `json:"image_price_4k"`
@@ -277,6 +285,11 @@ func (h *GroupHandler) Create(c *gin.Context) {
return
}
if err := service.ValidatePeakRateConfig(req.SubscriptionType, req.PeakRateEnabled, req.PeakStart, req.PeakEnd, float64ValueOrDefault(req.PeakRateMultiplier, 1.0)); err != nil {
response.BadRequest(c, err.Error())
return
}
group, err := h.adminService.CreateGroup(c.Request.Context(), &service.CreateGroupInput{
Name: req.Name,
Description: req.Description,
@@ -290,6 +303,10 @@ func (h *GroupHandler) Create(c *gin.Context) {
AllowImageGeneration: req.AllowImageGeneration,
ImageRateIndependent: req.ImageRateIndependent,
ImageRateMultiplier: req.ImageRateMultiplier,
PeakRateEnabled: req.PeakRateEnabled,
PeakStart: req.PeakStart,
PeakEnd: req.PeakEnd,
PeakRateMultiplier: req.PeakRateMultiplier,
ImagePrice1K: req.ImagePrice1K,
ImagePrice2K: req.ImagePrice2K,
ImagePrice4K: req.ImagePrice4K,
@@ -346,6 +363,10 @@ func (h *GroupHandler) Update(c *gin.Context) {
AllowImageGeneration: req.AllowImageGeneration,
ImageRateIndependent: req.ImageRateIndependent,
ImageRateMultiplier: req.ImageRateMultiplier,
PeakRateEnabled: req.PeakRateEnabled,
PeakStart: req.PeakStart,
PeakEnd: req.PeakEnd,
PeakRateMultiplier: req.PeakRateMultiplier,
ImagePrice1K: req.ImagePrice1K,
ImagePrice2K: req.ImagePrice2K,
ImagePrice4K: req.ImagePrice4K,
@@ -1,60 +0,0 @@
package admin
import (
"sort"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/plugin"
"github.com/Wei-Shaw/sub2api/internal/util/logredact"
"github.com/gin-gonic/gin"
)
// moduleStatusSource 提供插件模块状态快照能力(*plugin.Runtime 实现该接口,测试可注入桩)。
type moduleStatusSource interface {
Snapshot() []plugin.ModuleStatus
}
// ModuleHandler handles plugin module observability operations (read-only)
type ModuleHandler struct {
runtime moduleStatusSource
}
// NewModuleHandler creates a new ModuleHandler
func NewModuleHandler(runtime *plugin.Runtime) *ModuleHandler {
return &ModuleHandler{runtime: runtime}
}
// ModuleStatusItem 是单个插件模块状态的响应条目
type ModuleStatusItem struct {
ID string `json:"id"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
State string `json:"state"`
Error string `json:"error"`
}
// List 返回全部已注册插件模块的状态清单(含未启用模块),按模块 ID 字典序排序
// GET /api/v1/admin/modules
func (h *ModuleHandler) List(c *gin.Context) {
statuses := h.runtime.Snapshot()
modules := make([]ModuleStatusItem, 0, len(statuses))
for _, status := range statuses {
errText := status.Err
if errText != "" {
// 错误文本可能包含敏感信息(如上游返回的凭据片段),输出前统一脱敏。
errText = logredact.RedactText(errText)
}
modules = append(modules, ModuleStatusItem{
ID: string(status.ID),
Namespace: status.ID.Namespace(),
Name: status.ID.Name(),
Enabled: status.Enabled,
State: string(status.State),
Error: errText,
})
}
sort.Slice(modules, func(i, j int) bool { return modules[i].ID < modules[j].ID })
response.Success(c, gin.H{"modules": modules})
}
@@ -1,177 +0,0 @@
package admin
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/plugin"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type moduleStatusSourceStub struct {
statuses []plugin.ModuleStatus
}
func (s *moduleStatusSourceStub) Snapshot() []plugin.ModuleStatus {
return s.statuses
}
type moduleListEnvelope struct {
Code int `json:"code"`
Message string `json:"message"`
Data struct {
Modules []struct {
ID string `json:"id"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
State string `json:"state"`
Error string `json:"error"`
} `json:"modules"`
} `json:"data"`
}
func performModuleList(t *testing.T, source moduleStatusSource) (*httptest.ResponseRecorder, moduleListEnvelope) {
t.Helper()
gin.SetMode(gin.TestMode)
router := gin.New()
handler := &ModuleHandler{runtime: source}
router.GET("/admin/modules", handler.List)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/admin/modules", nil)
router.ServeHTTP(w, req)
var envelope moduleListEnvelope
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &envelope))
return w, envelope
}
func TestModuleHandlerListSerializesSnapshot(t *testing.T) {
stub := &moduleStatusSourceStub{statuses: []plugin.ModuleStatus{
{ID: "gateway.platform.anthropic", Enabled: true, State: plugin.StateRunning},
{ID: "job.hello", Enabled: false, State: plugin.StateRegistered},
}}
w, envelope := performModuleList(t, stub)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, 0, envelope.Code)
require.Equal(t, "success", envelope.Message)
require.Len(t, envelope.Data.Modules, 2)
first := envelope.Data.Modules[0]
require.Equal(t, "gateway.platform.anthropic", first.ID)
require.Equal(t, "gateway.platform", first.Namespace)
require.Equal(t, "anthropic", first.Name)
require.True(t, first.Enabled)
require.Equal(t, "running", first.State)
require.Empty(t, first.Error)
// 未启用模块也在列:state=registered、enabled=false
second := envelope.Data.Modules[1]
require.Equal(t, "job.hello", second.ID)
require.Equal(t, "job", second.Namespace)
require.Equal(t, "hello", second.Name)
require.False(t, second.Enabled)
require.Equal(t, "registered", second.State)
require.Empty(t, second.Error)
// snake_case 字段恒定输出(含空 error)
require.Contains(t, w.Body.String(), `"error":""`)
require.Contains(t, w.Body.String(), `"state":"registered"`)
}
func TestModuleHandlerListSortsByID(t *testing.T) {
stub := &moduleStatusSourceStub{statuses: []plugin.ModuleStatus{
{ID: "job.zeta", Enabled: true, State: plugin.StateRunning},
{ID: "gateway.alpha", Enabled: true, State: plugin.StateRunning},
{ID: "job.alpha", Enabled: false, State: plugin.StateRegistered},
}}
_, envelope := performModuleList(t, stub)
ids := make([]string, 0, len(envelope.Data.Modules))
for _, m := range envelope.Data.Modules {
ids = append(ids, m.ID)
}
require.Equal(t, []string{"gateway.alpha", "job.alpha", "job.zeta"}, ids)
}
func TestModuleHandlerListRedactsErrorText(t *testing.T) {
stub := &moduleStatusSourceStub{statuses: []plugin.ModuleStatus{
{ID: "job.bad", Enabled: true, State: plugin.StateErrored, Err: "provision failed: access_token=ya29.secret-value"},
}}
_, envelope := performModuleList(t, stub)
require.Len(t, envelope.Data.Modules, 1)
errText := envelope.Data.Modules[0].Error
require.Contains(t, errText, "provision failed")
require.NotContains(t, errText, "ya29.secret-value")
}
func TestModuleHandlerListEmptySnapshot(t *testing.T) {
w, envelope := performModuleList(t, &moduleStatusSourceStub{})
require.Equal(t, http.StatusOK, w.Code)
require.NotNil(t, envelope.Data.Modules)
require.Empty(t, envelope.Data.Modules)
require.Contains(t, w.Body.String(), `"modules":[]`)
}
type moduleHandlerFakeModule struct {
id plugin.ModuleID
enabledByDefault bool
}
func (m *moduleHandlerFakeModule) ModuleInfo() plugin.ModuleInfo {
id := m.id
enabled := m.enabledByDefault
return plugin.ModuleInfo{
ID: id,
New: func() plugin.Module { return &moduleHandlerFakeModule{id: id, enabledByDefault: enabled} },
EnabledByDefault: enabled,
}
}
// TestModuleHandlerListWithRuntimeSnapshot 用真实 Runtime(隔离注册表)验证
// 接口返回与 Runtime.Snapshot 一致:enabled 模块为 running,
// disabled 模块也在列且 state=registered、enabled=false。
func TestModuleHandlerListWithRuntimeSnapshot(t *testing.T) {
registry := plugin.NewRegistry()
registry.RegisterModule(&moduleHandlerFakeModule{id: "job.enabled", enabledByDefault: true})
registry.RegisterModule(&moduleHandlerFakeModule{id: "job.disabled", enabledByDefault: false})
runtime := plugin.NewRuntimeWithRegistry(nil, nil, registry)
require.NoError(t, runtime.Build())
require.NoError(t, runtime.Start(context.Background()))
t.Cleanup(func() { _ = runtime.Stop(context.Background()) })
gin.SetMode(gin.TestMode)
router := gin.New()
router.GET("/admin/modules", NewModuleHandler(runtime).List)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/admin/modules", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
var envelope moduleListEnvelope
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &envelope))
require.Len(t, envelope.Data.Modules, 2)
disabled := envelope.Data.Modules[0]
require.Equal(t, "job.disabled", disabled.ID)
require.False(t, disabled.Enabled)
require.Equal(t, "registered", disabled.State)
enabled := envelope.Data.Modules[1]
require.Equal(t, "job.enabled", enabled.ID)
require.True(t, enabled.Enabled)
require.Equal(t, "running", enabled.State)
}
@@ -3,6 +3,7 @@ package admin
import (
"strconv"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
@@ -16,6 +17,7 @@ import (
type OpenAIOAuthHandler struct {
openaiOAuthService *service.OpenAIOAuthService
adminService service.AdminService
quotaService *service.OpenAIQuotaService
}
func oauthPlatformFromPath(c *gin.Context) string {
@@ -23,10 +25,15 @@ func oauthPlatformFromPath(c *gin.Context) string {
}
// NewOpenAIOAuthHandler creates a new OpenAI OAuth handler
func NewOpenAIOAuthHandler(openaiOAuthService *service.OpenAIOAuthService, adminService service.AdminService) *OpenAIOAuthHandler {
func NewOpenAIOAuthHandler(
openaiOAuthService *service.OpenAIOAuthService,
adminService service.AdminService,
quotaService *service.OpenAIQuotaService,
) *OpenAIOAuthHandler {
return &OpenAIOAuthHandler{
openaiOAuthService: openaiOAuthService,
adminService: adminService,
quotaService: quotaService,
}
}
@@ -100,6 +107,24 @@ type OpenAIRefreshTokenRequest struct {
ProxyID *int64 `json:"proxy_id"`
}
type OpenAICodexPATCreateRequest struct {
AccessToken string `json:"access_token" binding:"required"`
Name string `json:"name"`
Notes *string `json:"notes"`
GroupIDs []int64 `json:"group_ids"`
ProxyID *int64 `json:"proxy_id"`
Concurrency *int `json:"concurrency"`
Priority *int `json:"priority"`
RateMultiplier *float64 `json:"rate_multiplier"`
LoadFactor *int `json:"load_factor"`
ExpiresAt *int64 `json:"expires_at"`
AutoPauseOnExpired *bool `json:"auto_pause_on_expired"`
CredentialExtras map[string]any `json:"credential_extras"`
Extra map[string]any `json:"extra"`
SkipDefaultGroupBind *bool `json:"skip_default_group_bind"`
ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"`
}
// RefreshToken refreshes an OpenAI OAuth token
// POST /api/v1/admin/openai/refresh-token
func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
@@ -169,6 +194,13 @@ func (h *OpenAIOAuthHandler) RefreshAccountToken(c *gin.Context) {
return
}
// spark 影子账号凭据透传母账号、自身恒空,刷新无意义;在调用上游前早拒,避免先打上游
// 再被凭据写守卫拦下的无谓副作用(外审第6轮)。
if account.IsCredentialShadow() {
response.BadRequest(c, "Cannot refresh spark shadow account; its credentials are managed by the parent account")
return
}
// Use OpenAI OAuth service to refresh token
tokenInfo, err := h.openaiOAuthService.RefreshAccountToken(c.Request.Context(), account)
if err != nil {
@@ -185,6 +217,7 @@ func (h *OpenAIOAuthHandler) RefreshAccountToken(c *gin.Context) {
newCredentials[k] = v
}
}
newCredentials = service.NormalizeOpenAIPersonalAccessTokenCredentials(account, tokenInfo, newCredentials)
updatedAccount, err := h.adminService.UpdateAccount(c.Request.Context(), accountID, &service.UpdateAccountInput{
Credentials: newCredentials,
@@ -262,3 +295,188 @@ func (h *OpenAIOAuthHandler) CreateAccountFromOAuth(c *gin.Context) {
response.Success(c, dto.AccountFromService(account))
}
// CreateAccountFromCodexPAT creates an OpenAI OAuth account from a Codex at-* personal access token.
// POST /api/v1/admin/openai/create-from-codex-pat
func (h *OpenAIOAuthHandler) CreateAccountFromCodexPAT(c *gin.Context) {
var req OpenAICodexPATCreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if req.Concurrency != nil && *req.Concurrency < 0 {
response.BadRequest(c, "concurrency must be >= 0")
return
}
if req.Priority != nil && *req.Priority < 0 {
response.BadRequest(c, "priority must be >= 0")
return
}
if req.RateMultiplier != nil && *req.RateMultiplier < 0 {
response.BadRequest(c, "rate_multiplier must be >= 0")
return
}
if req.LoadFactor != nil && *req.LoadFactor > 10000 {
response.BadRequest(c, "load_factor must be <= 10000")
return
}
var proxyURL string
if req.ProxyID != nil {
proxy, err := h.adminService.GetProxy(c.Request.Context(), *req.ProxyID)
if err != nil {
response.ErrorFrom(c, err)
return
}
if proxy != nil {
proxyURL = proxy.URL()
}
}
tokenInfo, err := h.openaiOAuthService.ValidateCodexPersonalAccessToken(c.Request.Context(), req.AccessToken, proxyURL)
if err != nil {
response.ErrorFrom(c, err)
return
}
credentials := mergeCodexImportMap(
h.openaiOAuthService.BuildAccountCredentials(tokenInfo),
sanitizeCodexImportCredentialExtras(req.CredentialExtras),
)
extra := mergeCodexImportMap(req.Extra, map[string]any{
"import_source": "codex_personal_access_token",
"auth_provider": "codex_personal_access_token",
"imported_at": time.Now().UTC().Format(time.RFC3339),
"access_token_sha256": codexTokenFingerprint(req.AccessToken),
})
concurrency := 3
if req.Concurrency != nil {
concurrency = *req.Concurrency
}
priority := 50
if req.Priority != nil {
priority = *req.Priority
}
skipDefaultGroupBind := false
if req.SkipDefaultGroupBind != nil {
skipDefaultGroupBind = *req.SkipDefaultGroupBind
}
account, err := h.adminService.CreateAccount(c.Request.Context(), &service.CreateAccountInput{
Name: buildOpenAICodexPATAccountName(req.Name, tokenInfo),
Notes: req.Notes,
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: credentials,
Extra: extra,
ProxyID: req.ProxyID,
Concurrency: concurrency,
Priority: priority,
RateMultiplier: req.RateMultiplier,
LoadFactor: req.LoadFactor,
GroupIDs: req.GroupIDs,
ExpiresAt: req.ExpiresAt,
AutoPauseOnExpired: req.AutoPauseOnExpired,
SkipDefaultGroupBind: skipDefaultGroupBind,
SkipMixedChannelCheck: req.ConfirmMixedChannelRisk != nil && *req.ConfirmMixedChannelRisk,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, dto.AccountFromService(account))
}
func buildOpenAICodexPATAccountName(name string, tokenInfo *service.OpenAITokenInfo) string {
name = strings.TrimSpace(name)
if name != "" {
return name
}
if tokenInfo != nil {
for _, candidate := range []string{tokenInfo.Email, tokenInfo.ChatGPTAccountID, tokenInfo.ChatGPTUserID} {
if candidate = strings.TrimSpace(candidate); candidate != "" {
return candidate
}
}
}
return "Codex PAT Account"
}
// QueryQuota queries the rate-limit / quota usage for an OpenAI account.
// GET /api/v1/admin/openai/accounts/:id/quota
func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
if h.quotaService == nil {
response.BadRequest(c, "openai quota service is not enabled")
return
}
usage, err := h.quotaService.QueryUsage(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, usage)
}
// CreateShadowRequest is the request body for CreateShadow.
type CreateShadowRequest struct {
Name string `json:"name"`
Priority int `json:"priority"`
Concurrency int `json:"concurrency"`
GroupIDs []int64 `json:"group_ids"`
}
// CreateShadow creates a spark-dimension shadow account for a parent OpenAI OAuth account.
// POST /api/v1/admin/accounts/:id/shadow
func (h *OpenAIOAuthHandler) CreateShadow(c *gin.Context) {
parentID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
var req CreateShadowRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
shadow, err := h.adminService.CreateShadow(c.Request.Context(), parentID, service.ShadowOptions{
Name: req.Name,
Priority: req.Priority,
Concurrency: req.Concurrency,
GroupIDs: req.GroupIDs,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, dto.AccountFromServiceShallow(shadow))
}
// ResetQuota consumes one rate-limit reset credit for an OpenAI account.
// POST /api/v1/admin/openai/accounts/:id/reset-quota
func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
if h.quotaService == nil {
response.BadRequest(c, "openai quota service is not enabled")
return
}
result, err := h.quotaService.ResetCredit(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
@@ -0,0 +1,106 @@
//go:build unit
package admin
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Wei-Shaw/sub2api/internal/service"
)
func TestCreateShadow_ReturnsCreatedShadow(t *testing.T) {
gin.SetMode(gin.TestMode)
stub := &stubAdminService{}
h := NewOpenAIOAuthHandler(nil, stub, nil)
router := gin.New()
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
body := `{"name":"p-spark","priority":50,"concurrency":2,"group_ids":[10,20]}`
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/shadow", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var resp map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
data, ok := resp["data"].(map[string]any)
require.True(t, ok, "response should have data field")
// parent_account_id must be present and equal to the path param
pid, ok := data["parent_account_id"].(float64)
require.True(t, ok, "parent_account_id should be present")
require.Equal(t, float64(42), pid)
// quota_dimension must be "spark"
require.Equal(t, service.QuotaDimensionSpark, data["quota_dimension"])
// name round-trips
require.Equal(t, "p-spark", data["name"])
}
func TestCreateShadow_InvalidID(t *testing.T) {
gin.SetMode(gin.TestMode)
h := NewOpenAIOAuthHandler(nil, &stubAdminService{}, nil)
router := gin.New()
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/not-a-number/shadow",
strings.NewReader(`{"name":"x"}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestCreateShadow_ServiceError(t *testing.T) {
gin.SetMode(gin.TestMode)
stub := &stubAdminService{createSparkShadowErr: errors.New("database unavailable")}
h := NewOpenAIOAuthHandler(nil, stub, nil)
router := gin.New()
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
body := `{"name":"p-spark","priority":50}`
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/shadow", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
// A generic (non-ApplicationError) service error maps to 500 via response.ErrorFrom.
require.GreaterOrEqual(t, rec.Code, http.StatusBadRequest)
require.Equal(t, http.StatusInternalServerError, rec.Code)
}
func TestCreateShadow_BadBody(t *testing.T) {
gin.SetMode(gin.TestMode)
h := NewOpenAIOAuthHandler(nil, &stubAdminService{}, nil)
router := gin.New()
router.POST("/api/v1/admin/accounts/:id/shadow", h.CreateShadow)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/shadow",
strings.NewReader(`{not valid json`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code)
}
+41 -8
View File
@@ -73,6 +73,13 @@ func NewOpsHandler(opsService *service.OpsService) *OpsHandler {
}
// GetErrorLogs lists ops error logs.
// applyOpsErrorSortParams reads sort_by/sort_order query params into the filter.
// Column whitelist and order normalization live in the repository; unknown
// values degrade to the default (created_at DESC), mirroring the usage list.
func applyOpsErrorSortParams(c *gin.Context, filter *service.OpsErrorLogFilter) {
filter.SetSort(c.Query("sort_by"), c.Query("sort_order"))
}
// GET /api/v1/admin/ops/errors
func (h *OpsHandler) GetErrorLogs(c *gin.Context) {
if h.opsService == nil {
@@ -114,10 +121,17 @@ func (h *OpsHandler) GetErrorLogs(c *gin.Context) {
// buildOpsErrorLogsWhere 以 COALESCE(requested_model, model) 比对。
filter.Model = strings.TrimSpace(c.Query("model"))
// Force request errors: client-visible status >= 400.
// buildOpsErrorLogsWhere already applies this for non-upstream phase.
if strings.EqualFold(strings.TrimSpace(filter.Phase), "upstream") {
filter.Phase = ""
// 请求错误语义:client-visible status>=400 守卫恒生效(未设
// IncludeRecoveredUpstream 时 phase=upstream 不再绕过守卫),故
// phase=upstream 作为普通过滤条件保留——此前这里清空该值,导致
// 错误类型下拉选「上游」等于不过滤。
// 分类(用户侧粗分类码)→ phase/type ANY 条件,与用户端 /usage/errors 同一映射;
// 未知分类返回空切片 = 不过滤。与 phase 参数可同时设置(AND 语义)。
if cat := strings.TrimSpace(c.Query("category")); cat != "" {
phases, types := service.CategoryToFilter(cat)
filter.ErrorPhasesAny = phases
filter.ErrorTypesAny = types
}
if platform := strings.TrimSpace(c.Query("platform")); platform != "" {
@@ -187,6 +201,8 @@ func (h *OpsHandler) GetErrorLogs(c *gin.Context) {
filter.StatusCodes = out
}
applyOpsErrorSortParams(c, filter)
result, err := h.opsService.GetErrorLogs(c.Request.Context(), filter)
if err != nil {
response.ErrorFrom(c, err)
@@ -234,10 +250,17 @@ func (h *OpsHandler) ListRequestErrors(c *gin.Context) {
// buildOpsErrorLogsWhere 以 COALESCE(requested_model, model) 比对。
filter.Model = strings.TrimSpace(c.Query("model"))
// Force request errors: client-visible status >= 400.
// buildOpsErrorLogsWhere already applies this for non-upstream phase.
if strings.EqualFold(strings.TrimSpace(filter.Phase), "upstream") {
filter.Phase = ""
// 请求错误语义:client-visible status>=400 守卫恒生效(未设
// IncludeRecoveredUpstream 时 phase=upstream 不再绕过守卫),故
// phase=upstream 作为普通过滤条件保留——此前这里清空该值,导致
// 错误类型下拉选「上游」等于不过滤。
// 分类(用户侧粗分类码)→ phase/type ANY 条件,与用户端 /usage/errors 同一映射;
// 未知分类返回空切片 = 不过滤。与 phase 参数可同时设置(AND 语义)。
if cat := strings.TrimSpace(c.Query("category")); cat != "" {
phases, types := service.CategoryToFilter(cat)
filter.ErrorPhasesAny = phases
filter.ErrorTypesAny = types
}
if platform := strings.TrimSpace(c.Query("platform")); platform != "" {
@@ -291,6 +314,8 @@ func (h *OpsHandler) ListRequestErrors(c *gin.Context) {
filter.StatusCodes = out
}
applyOpsErrorSortParams(c, filter)
result, err := h.opsService.GetErrorLogs(c.Request.Context(), filter)
if err != nil {
response.ErrorFrom(c, err)
@@ -362,6 +387,8 @@ func (h *OpsHandler) ListRequestErrorUpstreamErrors(c *gin.Context) {
}
filter.View = "all"
filter.Phase = "upstream"
// 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。
filter.IncludeRecoveredUpstream = true
filter.Owner = "provider"
filter.Source = strings.TrimSpace(c.Query("error_source"))
filter.Query = strings.TrimSpace(c.Query("q"))
@@ -377,6 +404,8 @@ func (h *OpsHandler) ListRequestErrorUpstreamErrors(c *gin.Context) {
filter.ClientRequestID = clientRequestID
}
applyOpsErrorSortParams(c, filter)
result, err := h.opsService.GetErrorLogs(c.Request.Context(), filter)
if err != nil {
response.ErrorFrom(c, err)
@@ -442,6 +471,8 @@ func (h *OpsHandler) ListUpstreamErrors(c *gin.Context) {
filter.View = parseOpsViewParam(c)
filter.Phase = "upstream"
// 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。
filter.IncludeRecoveredUpstream = true
filter.Owner = "provider"
filter.Source = strings.TrimSpace(c.Query("error_source"))
filter.Query = strings.TrimSpace(c.Query("q"))
@@ -497,6 +528,8 @@ func (h *OpsHandler) ListUpstreamErrors(c *gin.Context) {
filter.StatusCodes = out
}
applyOpsErrorSortParams(c, filter)
result, err := h.opsService.GetErrorLogs(c.Request.Context(), filter)
if err != nil {
response.ErrorFrom(c, err)
@@ -1,6 +1,8 @@
package admin
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
@@ -47,6 +49,9 @@ func (h *OpsHandler) GetConcurrencyStats(c *gin.Context) {
platform, group, account, collectedAt, err := h.opsService.GetConcurrencyStats(c.Request.Context(), platformFilter, groupID)
if err != nil {
if isOpsRealtimeRequestCanceled(c, err) {
return
}
response.ErrorFrom(c, err)
return
}
@@ -86,6 +91,9 @@ func (h *OpsHandler) GetUserConcurrencyStats(c *gin.Context) {
users, collectedAt, err := h.opsService.GetUserConcurrencyStats(c.Request.Context())
if err != nil {
if isOpsRealtimeRequestCanceled(c, err) {
return
}
response.ErrorFrom(c, err)
return
}
@@ -140,6 +148,9 @@ func (h *OpsHandler) GetAccountAvailability(c *gin.Context) {
platformStats, groupStats, accountStats, collectedAt, err := h.opsService.GetAccountAvailabilityStats(c.Request.Context(), platform, groupID)
if err != nil {
if isOpsRealtimeRequestCanceled(c, err) {
return
}
response.ErrorFrom(c, err)
return
}
@@ -156,6 +167,19 @@ func (h *OpsHandler) GetAccountAvailability(c *gin.Context) {
response.Success(c, payload)
}
func isOpsRealtimeRequestCanceled(c *gin.Context, err error) bool {
if err == nil {
return false
}
if errors.Is(err, context.Canceled) {
return true
}
if c != nil && c.Request != nil && errors.Is(c.Request.Context().Err(), context.Canceled) {
return true
}
return strings.Contains(err.Error(), "canceling statement due to user request")
}
func parseOpsRealtimeWindow(v string) (time.Duration, string, bool) {
switch strings.ToLower(strings.TrimSpace(v)) {
case "", "1min", "1m":
@@ -236,6 +260,9 @@ func (h *OpsHandler) GetRealtimeTrafficSummary(c *gin.Context) {
summary, err := h.opsService.GetRealtimeTrafficSummary(c.Request.Context(), filter)
if err != nil {
if isOpsRealtimeRequestCanceled(c, err) {
return
}
response.ErrorFrom(c, err)
return
}
@@ -21,6 +21,7 @@ type opsSystemLogCleanupRequest struct {
RequestID string `json:"request_id"`
ClientRequestID string `json:"client_request_id"`
UserID *int64 `json:"user_id"`
APIKeyID *int64 `json:"api_key_id"`
AccountID *int64 `json:"account_id"`
Platform string `json:"platform"`
Model string `json:"model"`
@@ -71,6 +72,14 @@ func (h *OpsHandler) ListSystemLogs(c *gin.Context) {
}
filter.UserID = &id
}
if v := strings.TrimSpace(c.Query("api_key_id")); v != "" {
id, parseErr := strconv.ParseInt(v, 10, 64)
if parseErr != nil || id <= 0 {
response.BadRequest(c, "Invalid api_key_id")
return
}
filter.APIKeyID = &id
}
if v := strings.TrimSpace(c.Query("account_id")); v != "" {
id, parseErr := strconv.ParseInt(v, 10, 64)
if parseErr != nil || id <= 0 {
@@ -136,6 +145,10 @@ func (h *OpsHandler) CleanupSystemLogs(c *gin.Context) {
response.BadRequest(c, "Invalid end_time")
return
}
if req.APIKeyID != nil && *req.APIKeyID <= 0 {
response.BadRequest(c, "Invalid api_key_id")
return
}
filter := &service.OpsSystemLogCleanupFilter{
StartTime: start,
@@ -145,6 +158,7 @@ func (h *OpsHandler) CleanupSystemLogs(c *gin.Context) {
RequestID: strings.TrimSpace(req.RequestID),
ClientRequestID: strings.TrimSpace(req.ClientRequestID),
UserID: req.UserID,
APIKeyID: req.APIKeyID,
AccountID: req.AccountID,
Platform: strings.TrimSpace(req.Platform),
Model: strings.TrimSpace(req.Model),
@@ -72,6 +72,19 @@ func TestOpsSystemLogHandler_ListInvalidAccountID(t *testing.T) {
}
}
func TestOpsSystemLogHandler_ListInvalidAPIKeyID(t *testing.T) {
svc := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
h := NewOpsHandler(svc)
r := newOpsSystemLogTestRouter(h, false)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/logs?api_key_id=abc", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status=%d, want 400", w.Code)
}
}
func TestOpsSystemLogHandler_ListMonitoringDisabled(t *testing.T) {
svc := service.NewOpsService(nil, nil, &config.Config{
Ops: config.OpsConfig{Enabled: false},
@@ -178,6 +191,34 @@ func TestOpsSystemLogHandler_CleanupServiceUnavailable(t *testing.T) {
}
}
func TestOpsSystemLogHandler_CleanupAcceptsAPIKeyID(t *testing.T) {
svc := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
h := NewOpsHandler(svc)
r := newOpsSystemLogTestRouter(h, true)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/logs/cleanup", bytes.NewBufferString(`{"api_key_id":123}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("status=%d, want 503", w.Code)
}
}
func TestOpsSystemLogHandler_CleanupInvalidAPIKeyID(t *testing.T) {
svc := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
h := NewOpsHandler(svc)
r := newOpsSystemLogTestRouter(h, true)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/logs/cleanup", bytes.NewBufferString(`{"api_key_id":0}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status=%d, want 400", w.Code)
}
}
func TestOpsSystemLogHandler_CleanupMonitoringDisabled(t *testing.T) {
svc := service.NewOpsService(nil, nil, &config.Config{
Ops: config.OpsConfig{Enabled: false},
+108 -10
View File
@@ -2,6 +2,7 @@ package admin
import (
"strconv"
"time"
dbent "github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
@@ -115,24 +116,105 @@ func (h *PaymentHandler) RetryFulfillment(c *gin.Context) {
response.Success(c, gin.H{"message": "fulfillment retried"})
}
func sanitizeAdminPaymentOrdersForResponse(orders []*dbent.PaymentOrder) []*dbent.PaymentOrder {
if len(orders) == 0 {
return orders
}
out := make([]*dbent.PaymentOrder, 0, len(orders))
type AdminPaymentOrderResult struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
UserEmail string `json:"user_email,omitempty"`
UserName string `json:"user_name,omitempty"`
UserNotes *string `json:"user_notes,omitempty"`
Amount float64 `json:"amount"`
PayAmount float64 `json:"pay_amount"`
FeeRate float64 `json:"fee_rate"`
Currency string `json:"currency"`
RechargeCode string `json:"recharge_code,omitempty"`
OutTradeNo string `json:"out_trade_no"`
PaymentType string `json:"payment_type"`
PaymentTradeNo string `json:"payment_trade_no,omitempty"`
PayURL *string `json:"pay_url,omitempty"`
QRCode *string `json:"qr_code,omitempty"`
QRCodeImg *string `json:"qr_code_img,omitempty"`
OrderType string `json:"order_type"`
PlanID *int64 `json:"plan_id,omitempty"`
SubscriptionGroupID *int64 `json:"subscription_group_id,omitempty"`
SubscriptionDays *int `json:"subscription_days,omitempty"`
ProviderInstanceID *string `json:"provider_instance_id,omitempty"`
ProviderKey *string `json:"provider_key,omitempty"`
Status string `json:"status"`
RefundAmount float64 `json:"refund_amount"`
RefundReason *string `json:"refund_reason,omitempty"`
RefundAt *time.Time `json:"refund_at,omitempty"`
ForceRefund bool `json:"force_refund,omitempty"`
RefundRequestedAt *time.Time `json:"refund_requested_at,omitempty"`
RefundRequestReason *string `json:"refund_request_reason,omitempty"`
RefundRequestedBy *string `json:"refund_requested_by,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
PaidAt *time.Time `json:"paid_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
FailedAt *time.Time `json:"failed_at,omitempty"`
FailedReason *string `json:"failed_reason,omitempty"`
ClientIP string `json:"client_ip,omitempty"`
SrcHost string `json:"src_host,omitempty"`
SrcURL *string `json:"src_url,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func sanitizeAdminPaymentOrdersForResponse(orders []*dbent.PaymentOrder) []*AdminPaymentOrderResult {
out := make([]*AdminPaymentOrderResult, 0, len(orders))
for _, order := range orders {
out = append(out, sanitizeAdminPaymentOrderForResponse(order))
if item := sanitizeAdminPaymentOrderForResponse(order); item != nil {
out = append(out, item)
}
}
return out
}
func sanitizeAdminPaymentOrderForResponse(order *dbent.PaymentOrder) *dbent.PaymentOrder {
func sanitizeAdminPaymentOrderForResponse(order *dbent.PaymentOrder) *AdminPaymentOrderResult {
if order == nil {
return nil
}
cloned := *order
cloned.ProviderSnapshot = nil
return &cloned
return &AdminPaymentOrderResult{
ID: order.ID,
UserID: order.UserID,
UserEmail: order.UserEmail,
UserName: order.UserName,
UserNotes: order.UserNotes,
Amount: order.Amount,
PayAmount: order.PayAmount,
FeeRate: order.FeeRate,
Currency: service.PaymentOrderCurrency(order),
RechargeCode: order.RechargeCode,
OutTradeNo: order.OutTradeNo,
PaymentType: order.PaymentType,
PaymentTradeNo: order.PaymentTradeNo,
PayURL: order.PayURL,
QRCode: order.QrCode,
QRCodeImg: order.QrCodeImg,
OrderType: order.OrderType,
PlanID: order.PlanID,
SubscriptionGroupID: order.SubscriptionGroupID,
SubscriptionDays: order.SubscriptionDays,
ProviderInstanceID: order.ProviderInstanceID,
ProviderKey: order.ProviderKey,
Status: order.Status,
RefundAmount: order.RefundAmount,
RefundReason: order.RefundReason,
RefundAt: order.RefundAt,
ForceRefund: order.ForceRefund,
RefundRequestedAt: order.RefundRequestedAt,
RefundRequestReason: order.RefundRequestReason,
RefundRequestedBy: order.RefundRequestedBy,
ExpiresAt: order.ExpiresAt,
PaidAt: order.PaidAt,
CompletedAt: order.CompletedAt,
FailedAt: order.FailedAt,
FailedReason: order.FailedReason,
ClientIP: order.ClientIP,
SrcHost: order.SrcHost,
SrcURL: order.SrcURL,
CreatedAt: order.CreatedAt,
UpdatedAt: order.UpdatedAt,
}
}
// AdminProcessRefundRequest is the request body for admin refund processing.
@@ -175,6 +257,22 @@ func (h *PaymentHandler) ProcessRefund(c *gin.Context) {
response.Success(c, result)
}
// QueryAndFinalizeRefund queries the provider refund status and finalizes a pending refund.
// POST /api/v1/admin/payment/orders/:id/refund/query
func (h *PaymentHandler) QueryAndFinalizeRefund(c *gin.Context) {
orderID, ok := parseIDParam(c, "id")
if !ok {
return
}
result, err := h.paymentService.QueryAndFinalizeRefund(c.Request.Context(), orderID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
// --- Subscription Plans ---
// ListPlans returns all subscription plans.
@@ -0,0 +1,48 @@
package admin
import (
"encoding/json"
"strings"
"testing"
"time"
dbent "github.com/Wei-Shaw/sub2api/ent"
)
func TestSanitizeAdminPaymentOrderForResponseAddsCurrency(t *testing.T) {
now := time.Now()
order := &dbent.PaymentOrder{
ID: 1,
UserID: 2,
Amount: 100,
PayAmount: 108,
FeeRate: 8,
OutTradeNo: "sub2_202606250001",
PaymentType: "stripe",
OrderType: "subscription",
Status: "COMPLETED",
ExpiresAt: now,
CreatedAt: now,
UpdatedAt: now,
ProviderSnapshot: map[string]any{
"schema_version": 2,
"currency": "USD",
},
}
got := sanitizeAdminPaymentOrderForResponse(order)
if got == nil {
t.Fatal("expected sanitized order")
}
if got.Currency != "USD" {
t.Fatalf("expected currency USD, got %q", got.Currency)
}
body, err := json.Marshal(got)
if err != nil {
t.Fatalf("marshal sanitized order: %v", err)
}
if strings.Contains(string(body), "provider_snapshot") {
t.Fatalf("expected provider_snapshot to be omitted, got %s", string(body))
}
}
@@ -148,7 +148,7 @@ func (h *PromoHandler) Update(c *gin.Context) {
if req.ExpiresAt != nil {
if *req.ExpiresAt == 0 {
// 0 表示清除过期时间
input.ExpiresAt = nil
input.ExpiresAt = &time.Time{}
} else {
t := time.Unix(*req.ExpiresAt, 0)
input.ExpiresAt = &t
File diff suppressed because it is too large. Load diff
@@ -217,12 +217,13 @@ func TestSettingHandler_UpdateSettings_PersistsPaymentVisibleMethodsAndAdvancedS
handler := NewSettingHandler(svc, nil, nil, nil, nil, nil, nil)
body := map[string]any{
"promo_code_enabled": true,
"payment_visible_method_alipay_source": "easypay",
"payment_visible_method_wxpay_source": "wxpay",
"payment_visible_method_alipay_enabled": true,
"payment_visible_method_wxpay_enabled": false,
"openai_advanced_scheduler_enabled": true,
"promo_code_enabled": true,
"payment_visible_method_alipay_source": "easypay",
"payment_visible_method_wxpay_source": "wxpay",
"payment_visible_method_alipay_enabled": true,
"payment_visible_method_wxpay_enabled": false,
"openai_advanced_scheduler_enabled": true,
"openai_advanced_scheduler_subscription_priority_enabled": true,
}
rawBody, err := json.Marshal(body)
require.NoError(t, err)
@@ -240,6 +241,7 @@ func TestSettingHandler_UpdateSettings_PersistsPaymentVisibleMethodsAndAdvancedS
require.Equal(t, "true", repo.values[service.SettingPaymentVisibleMethodAlipayEnabled])
require.Equal(t, "false", repo.values[service.SettingPaymentVisibleMethodWxpayEnabled])
require.Equal(t, "true", repo.values["openai_advanced_scheduler_enabled"])
require.Equal(t, "true", repo.values[service.SettingKeyOpenAIAdvancedSchedulerSubscriptionPriorityEnabled])
var resp response.Response
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
@@ -250,6 +252,7 @@ func TestSettingHandler_UpdateSettings_PersistsPaymentVisibleMethodsAndAdvancedS
require.Equal(t, true, data["payment_visible_method_alipay_enabled"])
require.Equal(t, false, data["payment_visible_method_wxpay_enabled"])
require.Equal(t, true, data["openai_advanced_scheduler_enabled"])
require.Equal(t, true, data["openai_advanced_scheduler_subscription_priority_enabled"])
}
func TestSettingHandler_UpdateSettings_PreservesLegacyBlankPaymentVisibleMethodSource(t *testing.T) {
@@ -0,0 +1,58 @@
//go:build unit
package admin
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// updateSettingsCodexStatus PUT /settings 仅带给定字段,返回 HTTP 状态码(轻量 stub repo,无 DB)。
func updateSettingsCodexStatus(t *testing.T, body map[string]any) int {
t.Helper()
gin.SetMode(gin.TestMode)
repo := &settingHandlerRepoStub{values: map[string]string{service.SettingKeyPromoCodeEnabled: "true"}}
svc := service.NewSettingService(repo, &config.Config{Default: config.DefaultConfig{UserConcurrency: 5}})
handler := NewSettingHandler(svc, nil, nil, nil, nil, nil, nil)
raw, err := json.Marshal(body)
require.NoError(t, err)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPut, "/api/v1/admin/settings", bytes.NewReader(raw))
c.Request.Header.Set("Content-Type", "application/json")
handler.UpdateSettings(c)
return rec.Code
}
// 白名单是双因子 AND:originator-only 条目在运行时永不命中(静默失效)。
// handler 应路由到 ValidateCodexWhitelistEntriesJSON,在写入时即拒(400)。
func TestUpdateSettings_CodexWhitelistRejectsUnmatchable(t *testing.T) {
code := updateSettingsCodexStatus(t, map[string]any{
"codex_cli_only_whitelist": `[{"originator":"opencode"}]`,
})
require.Equal(t, http.StatusBadRequest, code, "白名单 originator-only 应被拒(静默失效防护)")
}
func TestUpdateSettings_CodexWhitelistAcceptsMatchable(t *testing.T) {
code := updateSettingsCodexStatus(t, map[string]any{
"codex_cli_only_whitelist": `[{"originator":"opencode","ua_contains":["opencode/"]}]`,
})
require.Equal(t, http.StatusOK, code, "可命中白名单条目应通过")
}
// 黑名单是 OR 宽 deny:允许 originator-only。非对称——不受白名单收紧影响。
func TestUpdateSettings_CodexBlacklistAllowsOriginatorOnly(t *testing.T) {
code := updateSettingsCodexStatus(t, map[string]any{
"codex_cli_only_blacklist": `[{"originator":"evil"}]`,
})
require.Equal(t, http.StatusOK, code, "黑名单 originator-only 应允许(非对称)")
}
@@ -249,8 +249,9 @@ func (h *SubscriptionHandler) ResetQuota(c *gin.Context) {
response.Success(c, dto.UserSubscriptionFromServiceAdmin(sub))
}
// Revoke handles revoking a subscription
// DELETE /api/v1/admin/subscriptions/:id
// Revoke handles revoking a subscription.
// POST /api/v1/admin/subscriptions/:id/revoke
// DELETE /api/v1/admin/subscriptions/:id is kept for backward compatibility.
func (h *SubscriptionHandler) Revoke(c *gin.Context) {
subscriptionID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
@@ -267,6 +268,24 @@ func (h *SubscriptionHandler) Revoke(c *gin.Context) {
response.Success(c, gin.H{"message": "Subscription revoked successfully"})
}
// Restore handles restoring a revoked subscription.
// POST /api/v1/admin/subscriptions/:id/restore
func (h *SubscriptionHandler) Restore(c *gin.Context) {
subscriptionID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid subscription ID")
return
}
subscription, err := h.subscriptionService.RestoreSubscription(c.Request.Context(), subscriptionID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription))
}
// ListByGroup handles listing subscriptions for a specific group
// GET /api/v1/admin/groups/:id/subscriptions
func (h *SubscriptionHandler) ListByGroup(c *gin.Context) {
@@ -3,6 +3,7 @@ package admin
import (
"context"
"errors"
"fmt"
"log/slog"
"math"
"strconv"
@@ -629,8 +630,8 @@ func (h *UserHandler) UpdateUserPlatformQuotas(c *gin.Context) {
return
}
if len(req.Quotas) > 4 {
response.BadRequest(c, "quotas length must be <= 4")
if len(req.Quotas) > len(service.AllowedQuotaPlatforms) {
response.BadRequest(c, fmt.Sprintf("quotas length must be <= %d", len(service.AllowedQuotaPlatforms)))
return
}
seen := make(map[string]struct{}, len(req.Quotas))
@@ -749,7 +750,7 @@ func (h *UserHandler) UpdateUserPlatformQuotas(c *gin.Context) {
// 失效 cache:对全部允许的 platform 统一 invalidate。
// Trade-off:精确失效(仅 req 涉及平台 + 被软删平台)需 upsert 前额外 ListByUser,
// 增加一次 DB 查询和逻辑复杂度。由于 AllowedQuotaPlatforms 只有 4 个元素,
// 增加一次 DB 查询和逻辑复杂度。由于 AllowedQuotaPlatforms 数量很少,
// 全量 invalidate 的额外开销可接受,且能可靠覆盖软删除场景。
if h.billingCache != nil {
for _, p := range service.AllowedQuotaPlatforms {
Loaded 100 of 824 files, more files were not shown because too many files have changed in this diff. Show more