Compare commits

...
670 Commits
Author SHA1 Message Date
Wesley Liddick cd8bb98c44 Merge pull request #4774 from superman2003/fix/issues-4763-4765-4769-20260723
fix: optimize Codex identity imports and OpenAI account tests
2026-07-23 17:38:05 +08:00
shaw 1be6f30188 fix(ollama): 测试仓储到期查询深拷贝消除数据竞争
ollamaUsageTestRepo.ListDueOllamaCloudUsageAccounts 返回浅拷贝共享
Extra/Credentials map,RunDue 过滤循环的无锁读与组写协程在 r.mu 下的
map 删改构成数据竞争(-race 可复现;无 -race 时也可能触发 runtime
concurrent map read/write fatal 导致 CI 偶发崩溃)。两条返回路径改为
r.mu 下 mergeMap 深拷贝,并补全 ListOllamaCloudUsageGroupAccounts
只拷 Extra 不拷 Credentials 的半克隆,与基类 GetByID 惯例对齐。
生产仓储每次查询返回全新行,不受影响。
2026-07-23 17:14:10 +08:00
shaw 2faa0891e4 fix(ollama): 审计日志不落会话明文并收紧凭证清理守卫
- PUT /admin/accounts/:id/ollama-cloud-usage/session 加入审计整体不入库
  路由,并把裸键 session 纳入键级脱敏兜底,防止浏览器会话 Cookie 明文
  留存 audit_logs.request_body
- UpdateCredentials 的 Ollama 清理分支加顶层 credentials DISTINCT 守卫,
  凭证未变化的持久化不再误清 openai 探测快照或重写 NULL extra
2026-07-23 16:43:18 +08:00
Wesley Liddick 3f03c93bc6 Merge pull request #4776 from alfadb/feature/ollama-cloud-usage
feat(ollama): 支持 Cloud 官方用量自动刷新
2026-07-23 16:36:59 +08:00
alfadb 5ac4a9fac2 feat(ollama): 支持 Cloud 官方用量自动刷新 2026-07-23 15:50:44 +08:00
Wesley Liddick 2c76506e07 Merge pull request #4734 from wjx2951874/feat/alipay-mobile-precreate-deep-link
feat(payment): add mobile Alipay precreate deep link
2026-07-23 14:06:18 +08:00
superman2003 dd5956be5e fix(openai): prefer concrete GPT-5.6 test model 2026-07-23 13:44:15 +08:00
superman2003 5dfe838c21 fix(admin): optimize Codex identity import index 2026-07-23 13:43:57 +08:00
Wesley Liddick 6aeea70ee0 Merge pull request #4749 from heathermhuang/codex/fix-openai-proxy-stream-quarantine
fix(openai): quarantine proxies after incomplete SSE streams
2026-07-23 11:20:01 +08:00
Wesley Liddick 6f7bad3f2f Merge pull request #4751 from heathermhuang/codex/fix-grok-402-account-cooldown
fix(grok): cool down accounts after upstream 402
2026-07-23 11:19:30 +08:00
Wesley Liddick fbc88edf90 Merge pull request #4750 from heathermhuang/codex/fix-simple-default-grok-image
fix(simple-mode): enable images for auto-created Grok default
2026-07-23 11:19:20 +08:00
Wesley Liddick da5c80e113 Merge pull request #4724 from fengshao1227/fix/passthrough-input-normalize
fix(openai): OAuth 透传路径补齐 input 规范化,修复 Input must be a list
2026-07-23 11:19:12 +08:00
Wesley Liddick 09b1309c91 Merge pull request #4755 from wucm667/fix/issue-4754-channel-pricing-model-normalization
fix(billing): normalize channel pricing model names
2026-07-23 11:18:10 +08:00
Wesley Liddick aee9ab36cb Merge pull request #4721 from superman2003/fix/ccswitch-grokbuild-4720
fix(frontend): import Grok keys into Grok Build
2026-07-23 11:18:02 +08:00
Wesley Liddick 31e7ae8195 Merge pull request #4726 from feitianbubu/fix/model-rate-limit-reset-format
fix(admin): 模型限流恢复时间进位到天并在提示中补全日期
2026-07-23 11:17:54 +08:00
shaw ba88cc239c fix(billing): bill composite alias requests by the concrete forwarded model
Composite public aliases (e.g. all/claude) reach the Anthropic/Gemini
billing core via OriginalModel/ChannelMappedModel source overrides.
Unknown aliases resolved to no pricing and silently recorded $0 cost,
while family-word aliases were mispriced by the fallback family match
(Opus traffic billed at the Sonnet fallback rate). The OpenAI path
already guards this via usageBillingModelCandidates; the shared
recordUsageCore had neither the guard nor a fallback.

- composite groups: unless the admin explicitly configured channel
  pricing for the alias (OpenRouter-style custom pricing), bill by the
  concrete forwarded model
- general safety net: when the selected billing model has no resolvable
  pricing at all, fall back to the concrete forwarded model instead of
  silently recording $0
- grok media usage records now attribute OriginalModel to the client
  requested public alias, consistent with every other endpoint
  (billing unaffected: empty BillingModelSource never triggers source
  overrides)

Priced traffic and non-composite groups are unaffected.
2026-07-23 10:26:58 +08:00
shaw 90c4f50a5e fix(admin): restore currency and timestamps in admin plan list response
The composite-groups PR (#3581) replaced the raw ent SubscriptionPlan
response of GET /admin/payment/plans with a projection struct but
dropped the currency field added by #4323. PlanEditDialog then read an
undefined currency, sent an empty string on save, and silently wiped
the stored plan currency. Restore currency plus created_at/updated_at
so the projection preserves the full original response shape.
2026-07-23 10:26:46 +08:00
Wesley Liddick 3e5d4af411 Merge pull request #3581 from heathermhuang/codex/composite-groups
feat: Add composite group route registry
2026-07-23 10:09:39 +08:00
Heatherm Huang ca6b192728 fix: preserve composite video content routing 2026-07-23 09:26:43 +08:00
Heatherm Huang cb81e17fea test: align composite route contracts after rebase 2026-07-23 09:20:52 +08:00
Heatherm Huang 1c7959d0de fix: allow composite grok chat completions 2026-07-23 09:20:52 +08:00
Heatherm Huang 1d2dfab86d fix: allow composite grok messages routing 2026-07-23 09:20:52 +08:00
Heatherm Huang 06e7d12640 Fix composite Grok video status routing 2026-07-23 09:20:52 +08:00
Heatherm Huang ee332cee64 Fix composite model defaults for linked platforms 2026-07-23 09:20:52 +08:00
Heatherm Huang 2e774a48b3 Align Grok composite example with live model 2026-07-23 09:20:52 +08:00
Heatherm Huang ce3272c41b Build composite subscription bucket two 2026-07-23 09:20:52 +08:00
Heatherm Huang 3a683fff55 Fix composite route alias attribution 2026-07-23 09:20:52 +08:00
Heatherm Huang ff666be530 Fix composite route lint issues 2026-07-23 09:20:18 +08:00
Heatherm Huang a008b63c16 Add composite group route registry 2026-07-23 09:20:18 +08:00
Heatherm Huang c8d1e2e16f Harden composite group product surfaces 2026-07-23 09:19:25 +08:00
Heatherm Huang ebc1028771 Add composite group routing 2026-07-23 09:19:24 +08:00
shaw fa2da0409e chore: update sponsors 2026-07-23 09:04:08 +08:00
wucm667 44093579e9 fix(billing): normalize channel pricing model names 2026-07-22 20:25:27 +00:00
Heatherm Huang 47ad29db3e fix(openai): quarantine proxies after stream disconnects 2026-07-23 00:12:28 +08:00
Heatherm Huang 33d694b89b fix(simple-mode): enable images for auto Grok default 2026-07-23 00:08:23 +08:00
Heatherm Huang ca0d3314cf fix(grok): cool down accounts after 402 2026-07-23 00:06:04 +08:00
shaw 63cef60594 chore: update sponsors 2026-07-22 22:21:43 +08:00
wjx2951874 7914433011 feat(payment): add mobile Alipay precreate deep link 2026-07-22 19:18:04 +08:00
github-actions[bot] 60013c5f10 chore: sync VERSION to 0.1.163 [skip ci] 2026-07-22 09:08:53 +00:00
feitianbubu 48d58d72ff fix(admin): 模型限流恢复时间进位到天并在提示中补全日期 2026-07-22 16:57:51 +08:00
li 3e26dfa5bb style: 统一 input 包装类型为 []any,与正常 OAuth 路径一致 2026-07-22 16:49:31 +08:00
li 851436c552 fix(openai): OAuth 透传路径补齐 input 规范化,修复 Input must be a list
openai_passthrough=true 的 OAuth 账号透传路径
(normalizeOpenAIPassthroughOAuthBody) 未对 input 字段做
string→array 转换,导致上游拒绝 "Input must be a list"。

正常 OAuth 路径 (openai_codex_transform.go:290) 已有此逻辑,
透传路径遗漏。补齐三种非数组 input 的规范化:
- string → [{type:"message",role:"user",content:<text>}]
- 空白 string → []
- 单 object → [<object>]
2026-07-22 16:46:29 +08:00
superman2003 a3a1575e9d fix(frontend): import Grok keys into Grok Build 2026-07-22 16:12:47 +08:00
shaw d0bdd7e771 fix(usage): keep significant decimals in cost tooltip rate multiplier
formatMultiplier rounded any value >= 0.01 with toFixed(2), so a
configured multiplier like 0.035 displayed as 0.04x in the /usage and
/admin/usage cost tooltips. Format with up to 4 decimals and trim
trailing zeros while keeping at least 2 decimals; display-only fix,
billing amounts were already computed from the true multiplier.
2026-07-22 14:57:43 +08:00
Wesley Liddick cffea2979b Merge pull request #4701 from nagi330/fix/records-model-filter-0721
fix(usage): 统一后台使用记录模型筛选口径,解决 grok 相关模型无法过滤问题
2026-07-22 14:51:15 +08:00
Wesley Liddick 5e9d75b863 Merge pull request #4719 from superman2003/fix/grok-403-model-sync-4713-4715
fix(grok): sync OAuth models and isolate policy 403s
2026-07-22 14:26:07 +08:00
Wesley Liddick 4126c4c091 Merge pull request #4716 from superman2003/fix/grok-codex-tool-protocol-4710
fix(grok): round-trip Codex client tools on Responses
2026-07-22 14:25:53 +08:00
superman2003 ef8275aede fix(grok): sync OAuth models and isolate policy 403s 2026-07-22 13:32:35 +08:00
superman2003 f8445a241b fix(grok): round-trip Codex client tools on Responses 2026-07-22 12:15:48 +08:00
nagi330 fde95fcd0f fix(usage): 统一后台使用记录模型筛选口径 2026-07-22 09:51:04 +08:00
Wesley Liddick ebfaf2496b Merge pull request #4674 from AdrianZhaoDev/main
feat(groups): add OpenAI reasoning policy
2026-07-22 09:37:06 +08:00
Wesley Liddick 8e078534c2 Merge pull request #4648 from creamtea47/codex/fix-mobile-account-actions-menu
fix: 修复账号管理移动端更多操作菜单溢出
2026-07-22 09:36:54 +08:00
Wesley Liddick a185705d19 Merge pull request #4684 from superman2003/fix/opencode-codebuddy-cache
fix(grok): preserve OpenCode and CodeBuddy cache sessions
2026-07-22 09:36:41 +08:00
Wesley Liddick 003deac540 Merge pull request #4696 from tylzh97/fix/issue-4694-codex-relay
fix(codex): 保留级联中继的客户端指纹
2026-07-22 09:36:28 +08:00
Wesley Liddick 3f7beb4679 Merge pull request #4676 from superman2003/fix/channel-monitor-decrypt-scheduling
fix(monitor): stop retrying monitors with undecryptable API keys
2026-07-22 09:35:54 +08:00
Wesley Liddick 7905d02ce5 Merge pull request #4679 from superman2003/fix/scheduler-last-used-side-key
fix(scheduler): isolate LastUsedAt cache writes
2026-07-22 09:35:42 +08:00
Wesley Liddick 134a2c0bd3 Merge pull request #4670 from wucm667/fix/issue-4669-scheduler-quota-metadata
fix: preserve quota state in scheduler metadata
2026-07-22 09:35:29 +08:00
Wesley Liddick ec413f7802 Merge pull request #4709 from Su-cyber-art/agent/fix-ops-mobile-overflow
fix: prevent ops dashboard overflow on mobile
2026-07-22 09:34:53 +08:00
Wesley Liddick 30371e64cd Merge pull request #4671 from yan9651688/fix/issue-4551-usage-user-search-race
fix(frontend): ignore stale usage user search responses
2026-07-22 09:34:40 +08:00
Wesley Liddick 793f62357f Merge pull request #4700 from feitianbubu/fix/promo-expiry-local-time
fix(promo): 优惠码编辑弹窗过期时间改用本地时间预填
2026-07-22 09:34:27 +08:00
Wesley Liddick d1613ef020 Merge pull request #4697 from feitianbubu/fix/ops-system-log-cleanup-error-toast
fix(ops): 系统日志清理被拒绝时展示具体原因
2026-07-22 09:34:14 +08:00
shaw c5971a6fcb fix(deps): bump golang.org/x/text to v0.39.0 to resolve GO-2026-5970
govulncheck newly flags GO-2026-5970 (infinite loop on invalid input in
golang.org/x/text < v0.39.0), causing every fresh backend-security CI run
to fail. Upgrading x/text pulls sibling golang.org/x/* modules
(crypto/mod/net/sync/sys/term/tools) to their matching minor versions.
2026-07-22 09:33:47 +08:00
cyber-art a8bfdc6f36 fix ops dashboard mobile overflow 2026-07-22 03:11:19 +08:00
feitianbubu eba7289a8e fix(promo): 优惠码编辑弹窗过期时间改用本地时间预填 2026-07-21 21:38:00 +08:00
feitianbubu 61a80114eb fix(ops): surface backend reason when system log cleanup is rejected 2026-07-21 20:28:01 +08:00
Chenhao 8ffa2a31ff fix(codex): 保留级联中继的客户端指纹 2026-07-21 05:02:30 -07:00
Wesley Liddick 5a8d6c4e41 Merge pull request #4689 from moonfunjohn/codex/docs-payment-kyren-details
docs(payment): update Kyren Topup provider details
2026-07-21 17:27:06 +08:00
moonfunjohn c05b2311d8 docs(payment): update Kyren Topup provider details
Update Kyren Topup links, payment fees, and withdrawal fee details

in the English and Chinese payment guides.
2026-07-21 17:09:49 +08:00
superman2003 e31783e443 fix(grok): preserve OpenCode and CodeBuddy cache sessions 2026-07-21 15:22:12 +08:00
Wesley Liddick a978d56c7b Merge pull request #4661 from J606y/fix/mobile-adaptation
fix(mobile): 修复 iOS 页面自动缩放并完善运维监控及全站移动端适配
2026-07-21 14:43:30 +08:00
superman2003 81e7397770 fix(scheduler): isolate LastUsedAt cache writes 2026-07-21 13:27:23 +08:00
superman2003 bd62c6f66c fix(monitor): stop scheduling after API key decryption failure 2026-07-21 11:55:38 +08:00
zhaozewu 6c93f01c97 fix(groups): tighten reasoning policy
Remove unsupported none handling, align the auth cache version with the current baseline, consolidate the unshipped migrations, and update the public API contract.
2026-07-21 11:16:04 +08:00
zhaozewu 6af622c340 feat(groups): add OpenAI reasoning policy
Persist reasoning ceilings and exact mappings for OpenAI groups, enforce them across HTTP and WebSocket forwarding, and invalidate cached auth snapshots.
2026-07-21 11:02:43 +08:00
yan9651688 4696ed7d0b Keep usage user search aligned with the latest query
Debounced requests can finish out of order, allowing an earlier response to replace newer results or repopulate a cleared field. Track a request generation and gate state updates, with deterministic regression coverage.

Constraint: Preserve the existing 300 ms debounce and admin usage API contract
Rejected: Add AbortController plumbing | sequence invalidation matches repository patterns without changing API signatures
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep async filter results gated against superseded queries
Tested: Focused Vitest (4 tests), vue-tsc, ESLint, and full frontend suite except two pre-existing rollback assertion failures
Not-tested: Live browser against production-sized user data
Related: https://github.com/Wei-Shaw/sub2api/issues/4551
2026-07-21 10:52:55 +08:00
Wesley Liddick b8b72e1b18 Merge pull request #4666 from TTopoo/redis-username-support
fix(config): support Redis ACL username
2026-07-21 10:43:54 +08:00
Wesley Liddick 04a61ee6ad Merge pull request #4667 from jianjianai/new/perf-scheduler-snapshot-id-members-upstream
优化快照发布临时分配
2026-07-21 10:43:37 +08:00
Wesley Liddick 1f9eac4fbd Merge pull request #4660 from superman2003/fix/openai-scheduler-exclusion-observability-20260720
fix(scheduler): 高级调度器无可用账号错误补充排除原因统计,可自诊断静默剔除 (#4599)
2026-07-21 10:43:21 +08:00
Wesley Liddick 0b9d44545b Merge pull request #4641 from abbzbb/pr/grok-responses-compact
feat(grok): 基于 Grok Responses 实现 /responses/compact 适配 (#4554)
2026-07-21 10:43:04 +08:00
Wesley Liddick 927fcbc1e3 Merge pull request #4645 from fengshao1227/fix/responses-hosted-image-gen-billing
fix(billing): 合并 hosted image_generation 工具的图片 token 到 /responses 计费
2026-07-21 10:42:46 +08:00
Wesley Liddick 14701ff070 Merge pull request #4664 from wucm667/fix/issue-4656-sync-cache-billing
fix: align sync cache billing after failover
2026-07-21 10:42:07 +08:00
Wesley Liddick e85878624a Merge pull request #4657 from suuuuuu-1/fix/sse-field-parsing-compatibility
fix(gateway): support compact SSE format in Anthropic /responses bridge
2026-07-21 10:41:50 +08:00
Wesley Liddick 8b4c8823d9 Merge pull request #4658 from superman2003/fix/cc-bridge-compact-sse
fix(gateway): Chat Completions 桥接受 Anthropic 上游的 SSE 紧凑格式
2026-07-21 10:41:33 +08:00
Wesley Liddick d1dd512bef Merge pull request #4650 from superman2003/fix/plan-validity-unit-display
fix(frontend): 用户侧套餐有效期单位不再把「月/周」显示成「天」
2026-07-21 10:41:16 +08:00
wucm667 e51e61008a [verified] fix: preserve scheduler quota metadata 2026-07-21 10:41:11 +08:00
Wesley Liddick 7b934d6888 Merge pull request #4649 from superman2003/fix/preserve-call-id-length-20260720
fix(openai): preserve 路径 call_id 超长时压缩至 64 字符上限
2026-07-21 10:40:37 +08:00
Wesley Liddick a753e91e2c Merge pull request #4662 from Milesians/fix/proxy-probe-dual-stack
fix: use dual-stack fallback for proxy probe
2026-07-21 10:40:20 +08:00
Wesley Liddick e5384ac13b Merge pull request #4659 from feitianbubu/fix/graceful-shutdown-cleanup
fix: 优雅关停超时不再跳过 Cleanup,避免缓冲的用量/计费记录丢失
2026-07-21 10:40:03 +08:00
Wesley Liddick 0738eadcb5 Merge pull request #4652 from suuuuuu-1/refactor/clean-zh-accounts-redundant-keys
refactor(i18n): 清理 zh/admin/accounts.ts 中重构遗留的冗余 keys
2026-07-21 10:39:46 +08:00
shaw ef3c770d95 fix(deps): 升级 axios 至 1.18.1 修复 GHSA-gcfj-64vw-6mp9 前端安全审计失败 2026-07-21 10:30:41 +08:00
Wesley Liddick 9da816154e Merge pull request #4654 from yyyyyzc/main
docs (dcoker-cpmpose): 修正示例 compose 中错误的镜像地址
2026-07-21 10:01:02 +08:00
jjaw af3b6bbd68 优化快照发布临时分配 2026-07-21 03:07:01 +08:00
Jingru Shi 49200d4747 fix(config): support Redis ACL username 2026-07-21 01:31:46 +08:00
wucm667 addd5ef1dc [verified] fix: align sync cache billing after failover 2026-07-20 22:43:11 +08:00
milesians de094fb63e fix: use dual-stack fallback for proxy probe 2026-07-20 22:33:08 +08:00
J606yandClaude Fable 5 442323928d fix(mobile): 运维监控骨架屏固定宽度占位条窄屏溢出
加载骨架屏中 w-80(320px) 占位条在 375px 视口下超出容器,加载期间会把
页面撑宽出横向空白,补 max-w-full 收敛。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 22:14:32 +08:00
J606yandClaude Fable 5 64ab08e4aa fix(mobile): 修复全站排查发现的移动端布局问题
全站排查各页面移动端表现,修复以下确认会溢出/挤压的布局:

- 分组用户倍率/RPM 上限弹窗:7 列宽表滚动容器补横向滚动(min-w-max)
- 设置页联盟自定义用户表:容器 overflow-hidden 改为 overflow-x-auto
- 模型/分组/端点分布、消费排行、用户仪表盘 5 处甜甜圈图例表:
  移动端纵向堆叠(flex-col sm:flex-row),图例表全宽并支持横向滚动
- 安装向导:步骤指示器移动端只显示序号圆点(hidden sm:inline)避免
  硬溢出,表单两列栅格移动端折叠为单列
- 设置页:支付商品名三列、Beta 策略与帮助图片两列输入行移动端折叠
- 分组创建/编辑弹窗:三个 time 输入的三列行移动端折叠(时间控件有
  固有宽度,窄屏弹窗内会硬溢出)
- 密钥页分组选择浮层:min-w-[380px] 改为视口限宽 + JS 夹取 left,
  对齐 AccountGroupsCell 的定位收敛做法

桌面端布局均保持不变。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 22:10:19 +08:00
J606yandClaude Fable 5 0df490961b fix(mobile): 运维监控界面适配移动端
运维监控多处使用裸 table 且无移动端处理,小屏下内容被截断无法查看:

- 系统日志、告警事件、告警规则、OpenAI Token 统计、请求明细五处宽表
  参照 DataTable 的做法,在 < 768px 视口切换为卡片视图(useMediaQuery,
  避免挂载隐藏表格)
- 告警事件工具栏移动端纵向堆叠、筛选器自动换行
- 错误详情弹窗筛选栏 grid-cols-8 改为移动端两列折叠

桌面端布局保持不变;卡片视图完整支持深色模式,告警事件的无限滚动
在卡片视图下同样生效。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 21:58:57 +08:00
J606yandClaude Fable 5 9e072cefec fix(ios): 修复 iOS 端输入框聚焦导致页面自动缩放
iOS Safari 在输入框字号小于 16px 时聚焦会自动放大页面,且失焦后不会恢复,
导致布局错位。启动时仅对 iOS 设备为 viewport 注入 maximum-scale=1 阻止该
行为;iOS 10+ 用户仍可双指手动缩放,Android 不受影响。

- utils/device.ts 新增 detectIOSDevice/isIOSDevice(含 iPadOS 桌面模式识别)
- main.ts 启动阶段执行 initIOSViewportZoomFix
- 补充 detectIOSDevice 单元测试

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 21:58:46 +08:00
superman2003andCursor a319333161 fix(lint): summary 检查 strings.Builder WriteString 返回值 (errcheck)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-20 21:52:46 +08:00
superman2003andCursor 29bea0a758 fix(scheduler): 高级调度器无可用账号错误补充排除原因统计
问题背景(Refs #4599):OpenAI OAuth 账号请求 /v1/responses 全模型 503,
日志仅有 no available OpenAI accounts supporting model 且
excluded_account_count=0。selectByLoadBalance 初筛循环的每个过滤分支
(配额自动暂停、渠道上游模型限制、运行时熔断等)都是静默 continue,
最多只有 Debug 级日志,用户与维护者都无法定位候选账号被哪个隐式
过滤点剔除。

修改:
- selectByLoadBalance 初筛循环为每个 continue 分支记录原因计数
  (excluded/not_schedulable/platform_mismatch/runtime_blocked/
  privacy_not_set/transport_incompatible 及请求兼容性细分原因)
- isAccountRequestCompatible 新增 isAccountRequestCompatibleReason
  变体,细分 runtime_blocked/quota_auto_pause_<窗口>/
  shadow_parent_unhealthy/model_not_supported/
  channel_upstream_restricted/capability_mismatch;原 bool 函数改为
  包装变体,其余调用点行为不变
- noAvailableOpenAISelectionError 增加 details 参数,初筛全灭时输出
  如 (pool=3, filtered: excluded=1 model_not_supported=1
  quota_auto_pause_7d=1),原因按字典序排序保证输出确定;快照池为空
  时输出 (pool=0);选择序列耗尽路径追加 selection_order_exhausted
  标注;legacy 调用点传空保持原消息不变

兼容性:错误仍通过 Unwrap 匹配 ErrNoAvailableAccounts,分类与 ops
标记逻辑不变;客户端可见错误仍为通用分类消息,统计仅进服务端日志;
happy path 原因 map 惰性分配,无额外开销。

Refs #4599

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-20 21:44:42 +08:00
feitianbubu 304fcb04e3 fix: 优雅关停超时不再跳过 Cleanup,避免缓冲的用量/计费记录丢失 2026-07-20 21:31:25 +08:00
superman2003 2707f2793d fix(gateway): CC 桥接受 Anthropic 上游的 SSE 紧凑格式
SSE 规范允许字段冒号后省略空格(event:message_start / data:{...})。
Kimi 等 Anthropic 兼容上游返回紧凑格式时,Anthropic → Chat Completions
桥按 "event: " / "data: " 严格匹配会丢弃全部事件,且 dataLine[6:] 按带
空格前缀硬切载荷,最终流式/缓冲两条路径都报 "Upstream stream ended
without a response"(与 #4653 同根因;#4657 只修了 /v1/responses 桥,
本补丁补齐对称的 /v1/chat/completions 桥)。

复用 OpenAI 链路既有的 extractOpenAISSEEventLine / extractOpenAISSEDataLine
(正确处理可选空格/tab),流式与缓冲两处统一替换;补充紧凑格式的
缓冲/流式回归测试,原带空格格式用例保持通过。
2026-07-20 21:00:29 +08:00
suuuuuu-1 e5ad287843 fix(gateway): support compact SSE format in Anthropic /responses bridge
Fixes #4653

## Problem

The /v1/responses endpoint (Responses → Anthropic bridge) failed when
upstream providers returned SSE events in compact format without spaces
after colons (e.g. 'event:message_start' instead of 'event: message_start').

This affected Kimi API (api.kimi.com) and potentially other upstreams,
causing 'Upstream stream ended without a response' errors.

## Root Cause

The SSE parser in gateway_forward_as_responses.go used strict prefix
matching with hardcoded spaces:

    if !strings.HasPrefix(line, "event: ") { ... }
    if !strings.HasPrefix(dataLine, "data: ") { ... }

According to the SSE spec
(https://html.spec.whatwg.org/multipage/server-sent-events.html),
the space after the colon is optional. Both formats are valid:

    event: message_start  ✓
    event:message_start   ✓

## Solution

Introduced parseAnthropicSSEField() helper that:
- Accepts both 'field: value' and 'field:value' formats
- Uses TrimSpace() to handle optional/multiple spaces
- Returns (value, ok) for consistent error handling

Applied to both streaming handlers:
- handleResponsesBufferedStreamingResponse
- handleResponsesStreamingResponse

## Testing

Added comprehensive unit tests:
- TestParseAnthropicSSEField: validates parser with 8 edge cases
- TestHandleResponsesBufferedStreamingResponse_CompactSSEFormat
- TestHandleResponsesStreamingResponse_CompactSSEFormat

All existing tests pass, confirming backward compatibility.
2026-07-20 20:40:08 +08:00
yyyyyzc 106043fd9a docs (dcoker-cpmpose): 修正示例 compose 中错误的镜像地址 2026-07-20 19:28:49 +08:00
suuuuuu-1 3258f7c620 refactor(i18n): 清理 zh/admin/accounts.ts 中重构遗留的 29 个冗余 keys
在 d9e514f98 (2026-07-07) 重构拆分语言包时,部分中文 keys 被错误保留
在 admin/accounts.ts 中。这些 keys 在英文文件中不存在,且代码中无引用。

删除的冗余 keys:
- form 对象(13 个子 keys):nameLabel, platformLabel, typeLabel 等
- filters 对象(6 个子 keys):platform, type, status 等
- 独立 keys(10 个):
  * accountCreatedSuccess, accountUpdatedSuccess, accountDeletedSuccess
  * noAccounts, noAccountsDescription
  * saving, refreshing, testSuccess
  * cookieRefreshedSuccess, failedToSave
  * deleteConfirmMessage, refreshCookie, testAccount
  * api_key, cookie

验证:
- 英文 keys: 1184, 中文 keys: 1184 (修复前: 1220)
- 差异: 0 (修复前: -36)
- 已确认代码中无对 admin.accounts.* 路径的引用
- 正确的翻译在 common.ts 等文件中已存在
2026-07-20 19:11:21 +08:00
superman2003andCursor c401595e01 fix(openai): preserve 路径 call_id 超长时压缩至 64 字符上限
生产环境真实报错:客户端走 /v1/messages(Anthropic Messages 格式)入站,
OAuth 账号转发上游 OpenAI /v1/responses 时(PreserveToolCallIDs=true),
客户端历史中出现超长工具 ID(如嵌套代理拼接产生的 78 字符 srvtoolu_ ID)
会被原样透传,上游 400 拒绝:
"Invalid 'input[614].call_id': string too long. Expected a string with
maximum length 64, but got a string with length 78 instead."

#4612 为非 preserve 路径增加了 call_id 归一化与压缩,但有意将
PreserveToolCallIDs=true 的路径排除在外。本次在 preserve 路径补上长度护栏:
- len(id) <= 64 时仍原样透传,保持 #4612 承诺的"保持原样"语义;
- 超过 64 时复用已有的 compactCodexCallID 做确定性 SHA-256 压缩。

由于压缩是确定性的,同一逻辑 ID 在 function_call 与 function_call_output
两侧结果一致,tool_use/tool_result 配对不破坏;OAuth 路径 store=false
每轮全量重放历史,跨轮结果亦一致。改写点 fixCallIDPrefix 是
filterCodexInputWithOptions 内所有 call_id 修正的单一入口(含 item_reference
的 call_* 引用),同时覆盖 Messages 桥接(openai_gateway_messages.go)与
/v1/responses 透传(openai_gateway_forward.go)两条 preserve 路径。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-20 18:49:24 +08:00
superman2003 a6ecc202f0 fix(frontend): 用户侧套餐有效期单位不再把「月/周」显示成「天」
管理端表单保存的有效期单位是复数(days/weeks/months),数据库默认值
与历史数据是单数(day)。用户侧套餐卡片与订单确认面板此前只匹配单数
'month'(以及计费根本不支持的 'year'),管理端存的 'months' 永远落进
默认分支:「1 个月」的套餐被显示成「1天」(#4607),'weeks' 则会把
周数错标成天数。

后端计费 psComputeValidityDays 对 week/weeks、month/months 单复数均
按 ×7/×30 天换算,实扣是对的——这是纯显示缺陷,但直接造成「显示 1 天、
实付 1 个月」的定价误解。

修复:抽出与计费语义一一对应的 planValiditySuffix 辅助函数(单复数
归一化;month→「月/N个月」、week→「N周」、其余含未知单位一律按天,
与后端兜底一致),SubscriptionPlanCard 与 PaymentView 两处共用;
补充 zh/en 的 weeks 文案与单元/组件测试。
2026-07-20 18:40:42 +08:00
NellPoi 53c8ab5b00 fix: 修复账号管理移动端更多操作菜单溢出 2026-07-20 17:18:42 +08:00
github-actions[bot] e625ce3b3b chore: sync VERSION to 0.1.162 [skip ci] 2026-07-20 08:43:19 +00:00
li 865128998c fix(billing): 合并 hosted image_generation 工具的图片 token 到 /responses 计费
/v1/responses 端点使用 hosted image_generation 工具时,上游在
response.tool_usage.image_gen 返回图片 token 用量,但
extractOpenAIUsageFromJSONBytes 只读 response.usage,导致
image_output_tokens 和 image_output_cost 始终为 0。

在 extractOpenAIUsageFromJSONBytes 提取完 base usage 后,合并
tool_usage.image_gen 的 image tokens 维度(仅补充不覆盖),
覆盖 SSE 流式、非流式和 WebSocket 三条路径。
2026-07-20 16:29:12 +08:00
Wesley Liddick 27f094e096 Merge pull request #4638 from superman2003/fix/s3-secret-ephemeral-encryption-key
fix(backup): 拒绝用自动生成的临时密钥持久化 S3 SecretAccessKey,修复重启后解密失败
2026-07-20 16:21:46 +08:00
abbzbb 2ae61f3da0 fix(grok): Codex compact 适配与链式视频 content 代理
- #4223/#4554: Grok 模拟 /responses/compact,调度允许 Grok 账号
- #4494/#4626: 支持链式中继的受保护视频 /content 下载
2026-07-20 16:12:56 +08:00
shaw fa402b909a feat(branding): 启用新版 SVG logo 并在 README 头部展示
- 新增 assets/logo.svg 作为项目默认 logo(512x512 深色圆角底 + 渐变 S 标)
- 前端 favicon 与组件兜底 logo 由 logo.png 切换为 frontend/public/logo.svg
- 三个 README(EN/CN/JA)头部新增居中 logo 与标题布局
- 删除旧 logo.png 及多余的 lobe 变体 SVG
2026-07-20 16:06:59 +08:00
Wesley Liddick 2e5973b165 Merge pull request #4575 from Astrenix/feat/batch-image-guide-i18n
feat(frontend): 批量生图页面完整迁移至 vue-i18n
2026-07-20 15:32:21 +08:00
Wesley Liddick ecf199d29d Merge pull request #4573 from Astrenix/fix/dark-palette-slate-consistency
style(frontend): 统一暗色模式表面色板为项目 slate 色系
2026-07-20 15:32:16 +08:00
Wesley Liddick 7cbb0d8552 Merge pull request #4629 from yan9651688/fix/issue-4609-plan-currency-symbol
fix(payment): show plan prices with configured currency symbols
2026-07-20 15:32:11 +08:00
Wesley Liddick c4a8878f1f Merge pull request #4626 from put-go/fix/grok-chained-video-content
fix(grok): support chained video content proxies
2026-07-20 15:30:46 +08:00
Wesley Liddick 95c8b2401e Merge pull request #4616 from zhangxaochen/codex/openai-quota-error
fix(openai): return standard insufficient quota errors
2026-07-20 15:30:41 +08:00
Wesley Liddick e669e51b92 Merge pull request #4565 from abbzbb/fix/prompt-audit-fail-closed-4560
fix(security-audit): 仅在 blocking 意图下 fail-closed,修复无法关闭审计
2026-07-20 15:30:36 +08:00
Wesley Liddick ce9e70d5cf Merge pull request #4569 from Astrenix/fix/codex-models-openai-list-envelope
fix(openai): accept standard OpenAI model list for Codex model discovery
2026-07-20 15:30:31 +08:00
Wesley Liddick deb5e8756a Merge pull request #4572 from catoncat/fix/openai-agent-identity-team-isolation
fix(openai): 按 Team 隔离 Agent Identity 导入
2026-07-20 15:30:26 +08:00
Wesley Liddick 2ee66c401d Merge pull request #4574 from Astrenix/fix/i18n-hardcoded-strings
fix(frontend): 补齐零星硬编码 UI 文案的国际化
2026-07-20 15:29:05 +08:00
Wesley Liddick 3071d41443 Merge pull request #4570 from Astrenix/fix/available-channels-scroll
fix(frontend): 修复可用渠道页面内容过多时无法滚动的问题
2026-07-20 15:29:00 +08:00
Wesley Liddick 58ee0c8d75 Merge pull request #4571 from Astrenix/fix/user-balance-modal-dark-text
fix(frontend): 修复余额弹窗暗色模式下用户邮箱不可读
2026-07-20 15:28:56 +08:00
Wesley Liddick 78f85583ea Merge pull request #4630 from feitianbubu/fix/api-key-update-ip-list-clear
fix: 部分更新 API Key 时不再静默清空 IP 白/黑名单
2026-07-20 15:28:51 +08:00
superman2003 7a7f51a534 fix(backup): 拒绝用自动生成的临时密钥持久化 S3 SecretAccessKey
totp.encryption_key 未配置时,加密密钥每次进程启动都会随机重新生成。
备份/图床把 S3 SecretAccessKey 用这把临时密钥加密落库后,重启或升级
即无法解密(decrypt: cipher: message authentication failed),S3 备份
与图床静默失效(#4524)。

对齐支付(payment.ProvideEncryptionKey)与 TOTP 启用已有的护栏:在
持久化新 secret 之前,若密钥非固定配置则返回可操作的
SECRET_ENCRYPTION_KEY_NOT_CONFIGURED(400),提示配置固定
TOTP_ENCRYPTION_KEY。不带 secret 的更新(沿用已存值)与
ReuseBackupS3 模式不受影响;已配置固定密钥的部署无感。
2026-07-20 15:20:51 +08:00
Wesley Liddick db4295d646 Merge pull request #4591 from huangjunsen0406/fix/grok-claude-messages-prompt-cache
fix(grok): improve Claude Messages prompt-cache round-trip
2026-07-20 11:57:36 +08:00
shaw 3c41984733 style(apicompat): gofmt types.go after merge 2026-07-20 11:47:13 +08:00
shaw 04617cc0ff Merge branch 'main' into fix/grok-claude-messages-prompt-cache
Resolve const-block conflict in openai_gateway_grok_cache.go:
keep #4590 client tool cache constants and #4585 xai-package limit
(grokFreeRolling24hTokenLimit removed), add claudeCodeSessionHeader.
2026-07-20 11:39:37 +08:00
Wesley Liddick dabca7ca79 Merge pull request #4585 from superman2003/fix/issues-4561-4562-4566-4582
fix(grok): improve token counting, quota probes, and proxy checks
2026-07-20 11:37:02 +08:00
shaw a90c18cbea Merge branch 'main' into fix/issues-4561-4562-4566-4582
Resolve const-block conflict in openai_gateway_grok_cache.go:
keep #4590's client tool cache constants, drop grokFreeRolling24hTokenLimit
(moved to pkg/xai as IsGrokFreeRolling24hTokenLimit with legacy 2M support).
2026-07-20 11:25:11 +08:00
feitianbubu e502766170 fix: 部分更新 API Key 时不再静默清空 IP 白/黑名单 2026-07-20 11:15:37 +08:00
Wesley Liddick b8e844f4ee Merge pull request #4612 from catoncat/fix/codex-call-id-length
fix(openai): 限制 Codex call_id 归一化后的长度
2026-07-20 11:05:18 +08:00
Wesley Liddick 80a533c890 Merge pull request #4606 from orchief/codex/issue-4603-dedupe-oauth-system-prompt
fix(openai): 避免 OAuth Chat 转译重复 system 前缀
2026-07-20 11:03:00 +08:00
Wesley Liddick 6d152893ff Merge pull request #4590 from superman2003/fix/grok-client-cache-codex-trae
fix(grok): cache client tools from Codex, Trae, and Claude Desktop
2026-07-20 10:47:05 +08:00
shaw 97afb4089c fix(lint): check strings.Builder WriteString return value (errcheck) 2026-07-20 10:46:37 +08:00
put-go 48fad26433 fix(grok): support chained video content proxies 2026-07-20 10:40:18 +08:00
yan9651688 a05b873215 fix(payment): prevent configured currencies from looking like USD
Subscription plans can carry a display-only ISO currency code, but the admin plan table and user plan cards still used a hard-coded dollar sign. Resolve the symbol through the shared currency helper while retaining existing number formatting, the currency code label, and legacy blank-currency behavior.

Constraint: Plans without a currency must keep the legacy USD display

Rejected: Reformat complete prices with Intl.NumberFormat | it would change existing decimals and remove the explicit currency code

Confidence: high

Scope-risk: narrow

Reversibility: clean

Directive: Keep plan currency symbols aligned across admin and user displays

Tested: targeted Vitest 4 tests; targeted ESLint; vue-tsc; Vite production build; full Vitest 1222 tests passed

Not-tested: Full Vitest has 2 unrelated upstream failures in admin.system.rollback.spec.ts

Related: https://github.com/Wei-Shaw/sub2api/issues/4609
2026-07-20 10:33:04 +08:00
Wesley Liddick 1b4029b050 Merge pull request #4595 from kinsolee/fix/http-bridge-failover-terminal-safety
fix(openai): make HTTP bridge failover safe
2026-07-20 10:29:00 +08:00
Wesley Liddick 139a3d4346 Merge pull request #4589 from huangjunsen0406/fix/anthropic-message-start-stop-reason-null
fix(apicompat): emit null stop_reason on Anthropic message_start
2026-07-20 10:28:52 +08:00
Wesley Liddick 8c9cda1803 Merge pull request #4583 from BenjaminAaron196/codex/ops-report-email-template
(feat) 运维定时报表支持可编辑摘要模板与多语言展示
2026-07-20 10:28:44 +08:00
Wesley Liddick 0a8831777b Merge pull request #4619 from superman2003/fix/grok-manual-test-scheduling-gate
fix(grok): let manual connection tests bypass the scheduling gate
2026-07-20 10:26:55 +08:00
Wesley Liddick 34c8dbd604 Merge pull request #4618 from superman2003/fix/system-update-detach-request-ctx
fix(update): detach in-place update from the HTTP request lifetime
2026-07-20 10:26:47 +08:00
Wesley Liddick e311d368d3 Merge pull request #4611 from superman2003/fix/codex-models-manifest-401-unschedulable
fix(openai): mark OAuth accounts unschedulable on Codex models manifest 401
2026-07-20 10:26:39 +08:00
Wesley Liddick f133fde643 Merge pull request #4602 from jianjianai/new/perf-responses-image-intent
perf(openai): 复用 Responses 生图意图判定
2026-07-20 10:26:31 +08:00
Wesley Liddick c0b8f6b0a8 Merge pull request #4601 from jianjianai/new/perf-responses-sse-type
perf(openai): 复用 Responses SSE 事件类型解析
2026-07-20 10:26:23 +08:00
Wesley Liddick 9ccc9077cc Merge pull request #4581 from wucm667/feat/issue-4375-github-release-token
feat: support GitHub token for update checks
2026-07-20 10:26:15 +08:00
Wesley Liddick f5e484aa70 Merge pull request #4625 from wucm667/fix/issue-4624-sticky-force-cache-billing
fix(handler): avoid cache billing on same-account retry
2026-07-20 10:24:38 +08:00
Wesley Liddick aa615c2677 Merge pull request #4620 from cugxuan/codex/show-subscription-expiry-minute
feat(subscription): show expiry times to minute
2026-07-20 10:24:30 +08:00
Wesley Liddick 032001598a Merge pull request #4617 from wucm667/fix/issue-4610-anthropic-json-content-type
fix(openai): correct buffered messages content type
2026-07-20 10:24:22 +08:00
Wesley Liddick 6def36a171 Merge pull request #4614 from cugxuan/codex/fix-subscription-expiry-days
fix(subscription): round remaining days up
2026-07-20 10:24:14 +08:00
Wesley Liddick d2ef0cb151 Merge pull request #4587 from coo1white/fix-compose-redis-dev-local
fix(deploy): make the redis command flags take effect in dev and local compose
2026-07-20 10:24:07 +08:00
Wesley Liddick 25bd4956f0 Merge pull request #4588 from coo1white/wire-postgres-tuning-vars
fix(deploy): pass the documented postgres tuning values to postgres
2026-07-20 10:23:59 +08:00
shaw 2518691dbc fix(config): 为 trusted_proxies 与 forwarded_client_ip_headers 注册 BindEnv,修复 env 可达性守卫测试
#4593 引入的 TestConfigKeysAreEnvReachable 与 #4604 新增的两个配置键语义相撞:
两键在 setDefaults 中无注册,守卫测试判定其环境变量不可达。

不能按守卫注释直接 SetDefault:viper 的 IsSet 会连同 defaults 一起上报,
任何已注册默认值都会让 load() 中 trustedProxiesConfigured 的显式配置探测
永远为真,摧毁 #4600 的 absent/empty 区分。改用 BindEnv 注册——绑定键同样
进入 AllKeys()(守卫测试与 Unmarshal 均可见),而变量缺席时不影响 IsSet。
两个环境变量本就由 load() 中 os.LookupEnv 手工解析,行为不变。
2026-07-20 09:41:02 +08:00
Wesley Liddick bfabfe60c8 Merge pull request #4593 from StarryKira/fix/image-storage-env-unreachable
fix: 异步生图开关配了却不生效(环境变量被静默丢弃 + 迁移到后台开关)
2026-07-20 09:20:15 +08:00
Wesley Liddick f3312cf7d9 Merge pull request #4604 from BenjaminAaron196/codex/fix-issue-4600-client-ip
fix: 修复客户端 IP 回退并支持自定义 CDN 请求头
2026-07-20 09:20:02 +08:00
shaw 30202f8266 chore: update sponsors 2026-07-20 08:55:15 +08:00
wucm667 a2acbf553b fix(handler): avoid cache billing on same-account retry 2026-07-20 02:20:58 +08:00
JlypxandSisyphus dd0cbe91c9 fix: 避免复制客户端 IP 原子状态
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:22:45 +08:00
JlypxandSisyphus 0cc382e331 docs: 补充客户端 IP 请求头配置说明
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:10:41 +08:00
JlypxandSisyphus 6becd11e39 docs: 更新客户端 IP 边缘安全配置
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:10:32 +08:00
JlypxandSisyphus 80dd2929a3 docs: 本地化客户端 IP 请求头设置
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:10:18 +08:00
JlypxandSisyphus 4990ca0b2c feat: 添加客户端 IP 请求头设置界面
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:10:05 +08:00
JlypxandSisyphus 344f303919 feat: 扩展前端客户端 IP 设置类型
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:09:57 +08:00
JlypxandSisyphus ff5b0e6254 test: 更新客户端 IP 设置响应契约
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:09:47 +08:00
JlypxandSisyphus fedeba2568 feat: 审计客户端 IP 请求头变更
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:09:37 +08:00
JlypxandSisyphus 3c86e249f4 feat: 接入客户端 IP 请求头管理接口
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:09:21 +08:00
JlypxandSisyphus f72958d530 feat: 持久化客户端 IP 请求头设置
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:09:11 +08:00
JlypxandSisyphus 8b8b6b3132 feat: 定义客户端 IP 请求头系统设置
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:09:00 +08:00
JlypxandSisyphus 9bc7d10c08 fix: 快照自定义客户端 IP 请求头
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:08:48 +08:00
JlypxandSisyphus 496005d688 fix: 按自定义请求头解析客户端 IP
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:08:36 +08:00
JlypxandSisyphus 041db5d824 feat: 支持自定义客户端 IP 请求头配置
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-20 00:08:26 +08:00
cugxuan 3379603022 feat(subscription): show expiry times to minute 2026-07-19 22:43:35 +08:00
superman2003 4a97491be6 fix(grok): let manual connection tests bypass the scheduling gate
Grok OAuth 'test connection' reused the production GrokTokenProvider
request path, whose eligibility gate rejects any account that is not
currently schedulable (manual switch off, rate limited, overloaded,
temporarily cooled down). Every such test failed before reaching xAI
with the generic 'oauth refresh account state changed', while
Codex/OpenAI account tests read credentials regardless of scheduling
state (#4598).

Add GetAccessTokenForManualTest and use it from the account test
service:

- skips the request-path scheduling eligibility gate so admins can
  probe excluded accounts; credential integrity checks (configured
  proxy present, refresh token present) still apply
- refreshes expired tokens through the shared OAuthRefreshAPI without
  the request-path marker, so the lock protocol and DB re-read keep
  working while scheduling state no longer blocks the refresh;
  credential rotation for non-active accounts stays blocked inside
  RefreshIfNeeded
- falls back to the still-valid current token when a refresh attempt
  fails or another worker holds the refresh lock, and otherwise
  surfaces the concrete refresh error instead of the generic message

Fixes #4598
2026-07-19 22:40:58 +08:00
superman2003 35b5edb24c fix(update): detach in-place update from the HTTP request lifetime
The in-place update ran entirely inside c.Request.Context(). Browsers and
reverse proxies commonly abort long-idle requests (axios global timeout
30s, nginx proxy_read_timeout 60s by default), which canceled the request
context mid-download and killed every slow update with
'download failed: context canceled' while the version stayed unchanged.
Users behind slow GitHub links saw the update button fail at a wall-clock
ceiling (~60s) on every attempt (#4504).

- Run PerformUpdate and RollbackToVersion on a context detached from the
  request (context.WithoutCancel) and bounded by a 15-minute deadline so
  the 10-minute GitHub download client owns its own timeout. A client
  disconnect no longer aborts the binary swap; retries then hit the
  system operation lock or report 'Already up to date'.
- Raise the frontend timeout for the update/rollback calls from the
  global 30s axios default to 15 minutes so the browser can actually
  wait for the result.

Fixes #4504
2026-07-19 22:40:44 +08:00
wucm667 01062c3244 fix(openai): correct buffered messages content type 2026-07-19 22:28:49 +08:00
zhangxaochen 604b764cf5 fix(openai): return standard insufficient quota errors 2026-07-19 21:59:45 +08:00
JlypxandSisyphus f69042ca6e docs: 更新客户端 IP 配置索引
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:42:54 +08:00
JlypxandSisyphus 41b58b640a docs: 更新可信代理部署说明
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:42:33 +08:00
JlypxandSisyphus 5da3325a30 feat: 在安全设置中配置客户端 IP 模式
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:42:12 +08:00
JlypxandSisyphus 93717394b2 fix: 迁移客户端 IP 兼容开关
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:41:45 +08:00
JlypxandSisyphus 6aa6b3a968 fix: 将客户端 IP 模式注入请求上下文
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:41:12 +08:00
JlypxandSisyphus 39107ca457 fix: 安全初始化 Gin 可信代理
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:40:32 +08:00
JlypxandSisyphus 6e2ba0e4cd fix: 统一请求级客户端 IP 模式
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:39:49 +08:00
JlypxandSisyphus 8a147fcc51 fix: 解析显式可信代理配置
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-07-19 21:39:24 +08:00
cugxuan d0fa8c63f1 fix(subscription): round remaining days up 2026-07-19 21:37:26 +08:00
cat 3a4966f786 fix(openai): 限制 Codex call_id 归一化长度 2026-07-19 21:28:47 +08:00
superman2003andCursor 3ed2873f14 fix(openai): mark OAuth accounts unschedulable on Codex models manifest 401
The Codex models manifest path returned upstream 401s straight to the
client without feeding them into the account state machinery. A revoked
or invalidated OAuth account therefore stayed active and schedulable,
kept being selected for subsequent /models requests, and produced
repeated 502s until an admin ran a manual connection test (#4544).

- Route ChatGPT-backend manifest 401s through the shared upstream-error
  handling: token cache invalidation, temp-unschedulable cooldown for
  refreshable OAuth accounts, permanent disable for
  token_revoked/token_invalidated, plus the runtime scheduling block.
- Treat ChatGPT-backend manifest 401s as failover-eligible so the
  current /models request can switch to a healthy account instead of
  returning 502. Custom API key upstream 401s keep the existing
  no-failover, no-disable behavior since their /models auth is not
  authoritative for the account.
- Skip Agent Identity accounts: their 401s can be task-scoped and have
  a dedicated recovery flow.
- Attach the selected account to the ops error-log context so /models
  failures record the account_id.

Fixes #4544

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 21:13:27 +08:00
orchief c044d5c1f1 fix(openai): avoid duplicate OAuth system prompts
Root cause: Chat bridge system messages were mirrored to instructions while remaining in input as developer messages.

Fix: omit only losslessly promoted system messages for non-JSON-object OAuth Chat requests while preserving compatibility paths.

Closes #4603
2026-07-19 19:48:25 +08:00
Jlypx 732aeef880 fix: 兼容反代和 Docker 客户端 IP 解析 2026-07-19 19:41:01 +08:00
superman2003 3dcf412b65 fix(grok): preserve Trae cache routing across turns 2026-07-19 19:00:08 +08:00
superman2003 c8ff478876 fix(grok): default client tool caching on for Free accounts 2026-07-19 18:59:50 +08:00
jjaw f7979ae8ff 优化 Responses SSE 事件类型解析 2026-07-19 18:50:33 +08:00
jjaw 8fd6f91b7e 优化 Responses 生图意图复用 2026-07-19 18:49:08 +08:00
Kinso 7840eb1c49 [verified] fix(openai): make HTTP bridge failover safe
Route first-turn pre-response transport, HTTP, and SSE failures through the existing account failover path without replaying later turns. Require a real Responses terminal event and preserve platform-specific OpenAI/Grok error side effects.
2026-07-19 17:13:27 +08:00
harukaandClaude Opus 4.8 6102d64274 fix(wire): 补上 PromptAdminService 的绑定,恢复 wire 代码生成
ProviderSet 提供了 NewPromptAdminHandler,也绑定了 PromptEngine,却没有为
PromptAdminService 绑定实现,导致 go generate ./cmd/server 直接失败:

  no provider found for securityaudit.PromptAdminService
  needed by *securityaudit.PromptAdminHandler

*PromptService 本就实现了该接口的全部方法,wire_gen.go 也一直是手工维护到位的
(补上绑定后重新生成的结果与现有文件逐字节一致),只是生成这条路被堵死了,
后续任何依赖改动都无法再靠 go generate 同步。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHreE5pzCkSYz7J45fmd2Y
2026-07-19 01:03:41 -07:00
superman2003 eea02c38fc fix(grok): cache Claude Desktop client tools 2026-07-19 16:03:18 +08:00
harukaandClaude Opus 4.8 0343dba916 feat(admin): 备份页新增异步生图对象存储配置卡片
对应后端 /admin/backups/image-storage。放在备份页而非系统设置页,是因为它与
数据库备份共用同一套 S3 客户端与凭证——用户的心智就是"在备份的 S3 上加个开关"。

- 默认勾选"复用备份 S3",此时隐藏端点/密钥字段,只留 bucket 与 prefix,
  bucket 留空则沿用备份桶。
- 保存走 useStepUp,与备份 S3 配置的保存路径一致。
- 补中英文案。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHreE5pzCkSYz7J45fmd2Y
2026-07-19 00:56:33 -07:00
harukaandClaude Opus 4.8 b08cab91a9 feat(image-storage): 异步生图对象存储改为后台配置,保存即生效
此前开启异步生图必须改服务器上的 config.yaml 并重启容器(#4542),且若想
复用已配置的备份 S3,还得把同一套凭证再填一遍(#4458)。

- 新增 ImageStorageSettingService:配置存 settings 表,SecretAccessKey 经
  SecretEncryptor 加密落库、读回脱敏、留空表示沿用旧值,与备份 S3 配置同一套做法。
- reuse_backup_s3(默认开)直接借用 backup_s3_config 的端点与密钥,只用自己的
  bucket/prefix 区分对象,因此备份走 backups/、图片走 images/,且密钥不会在库里存两份。
- ImageTaskService 的启用状态改由 ImageStorageResolver 在运行时解析并缓存,
  保存设置后 Invalidate 使下次请求重建客户端——不再需要重启。
- repository 侧由提供实例改为提供工厂,客户端才可能在运行期重建。
- 轮询接口的门控从 enabled() 放宽为 Pollable():关掉开关只拒绝新提交,
  已受理的任务仍可取回结果,不再被中途吞掉。
- config.yaml 的 image_storage 保留为回落,后台从未保存过时沿用,
  升级前已用配置文件开启的部署不受影响。
- 管理端 GET/PUT/POST /admin/backups/image-storage,PUT 与备份 S3 配置一样要求
  step-up 2FA:改写存储目标同样能把生成内容导向外部账号。

注:go generate ./cmd/server 在当前 upstream 基线上即失败(securityaudit.
PromptAdminService 缺 provider),故 wire_gen.go 为手工同步。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHreE5pzCkSYz7J45fmd2Y
2026-07-19 00:56:21 -07:00
huangjunsen ef88cf3f89 fix(grok): improve Claude Messages prompt-cache round-trip
Round-trip Grok encrypted reasoning via Anthropic thinking.signature and
seed cache identity from Claude Code session IDs, so multi-turn /v1/messages
traffic can hit xAI prompt cache more like CLIProxyAPI. Also strip invalid
encrypted_content and retry on the Messages path when decrypt fails after
account switches.
2026-07-19 15:00:09 +08:00
superman2003 9d79b42729 feat(admin): expose Grok client tool cache opt-in 2026-07-19 14:42:06 +08:00
cat 7a05a7cdcc test(openai): 检查 Agent Identity 测试类型断言 2026-07-19 14:42:01 +08:00
superman2003 752b2eaa9b fix(grok): bridge Trae tool requests through responses 2026-07-19 14:41:55 +08:00
superman2003 026d2a8083 fix(grok): promote Codex Lite tools for caching 2026-07-19 14:41:47 +08:00
superman2003 5af38ccf41 fix(grok): add guarded client tool cache routing 2026-07-19 14:41:38 +08:00
NickandClaude Fable 5 340dc99e02 fix(deploy): pass the documented postgres tuning values to postgres
deploy/.env.example documents POSTGRES_MAX_CONNECTIONS,
POSTGRES_SHARED_BUFFERS, POSTGRES_EFFECTIVE_CACHE_SIZE and
POSTGRES_MAINTENANCE_WORK_MEM, with notes on how to size them — but no
compose file ever passes them to the postgres container. A user who sets
them in .env gets nothing, silently.

Wire them into the postgres command in deploy/docker-compose.yml. The
fallbacks are the postgres:18 stock defaults (100 / 128MB / 4GB / 64MB),
so a deploy that does not set the variables behaves exactly as before.

Checked with postgres:18-alpine: with the variables unset, SHOW gives
the stock values; with them set (1024 / 1GB / 6GB / 128MB), SHOW gives
the set values.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 12:17:31 +07:00
NickandClaude Fable 5 8a2d7c5bd3 fix(deploy): make the redis command flags take effect in dev and local compose
PR #4506 fixed this in deploy/docker-compose.yml, but the same broken
form is still in docker-compose.dev.yml and docker-compose.local.yml.
The redis command is one quoted script given to the inner sh -c, and
compose keeps the newlines inside the quoted string, so redis-server on
the first line runs as a complete command with no flags at all. The
--save / --appendonly / --appendfsync lines are silently never applied,
and ${REDIS_PASSWORD:+--requirepass ...} is dead too — redis takes no
password even when REDIS_PASSWORD is set.

The fix is the same trailing `\` line continuations as #4506, with the
same comment, so the three compose files read the same way.

Checked with both files on redis:8-alpine, REDIS_PASSWORD set. Before:
PING with no auth said PONG, appendonly was "no", save was the stock
"3600 1 300 100 60 10000". After: no-auth PING gets NOAUTH, appendonly
is "yes", save is "60 1". With REDIS_PASSWORD unset the server still
starts open, as before.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 12:16:27 +07:00
huangjunsen ba2b0044e3 fix(apicompat): emit null stop_reason on Anthropic message_start
Use *string for AnthropicResponse.StopReason so streaming message_start
serializes as JSON null instead of "", matching official Anthropic wire
format and avoiding strict client turn-finalization failures.
2026-07-19 13:05:24 +08:00
superman2003 d2753dc2e2 fix(grok): serve current free quota policy 2026-07-19 12:17:52 +08:00
superman2003 c99e479bcc fix(grok): retry transient billing probes 2026-07-19 12:17:42 +08:00
superman2003 b8c640d218 fix(proxy): include Grok in quality checks 2026-07-19 12:17:31 +08:00
superman2003 1433fbc44d fix(grok): estimate messages count tokens locally 2026-07-19 12:17:23 +08:00
Jlypx 2cff4bf169 fix: 修复 golangci-lint 检查错误 2026-07-19 11:39:20 +08:00
Jlypx 361983cf4d feat: 优化运维定时报表邮件模板 2026-07-19 11:23:26 +08:00
wucm667 510ee451bd feat: support GitHub token for update checks 2026-07-19 11:02:56 +08:00
AstrenixandClaude Fable 5 7bbe170405 feat(frontend): migrate batch image page to vue-i18n
BatchImageGuideView carried ~140 user-visible strings outside vue-i18n:
hardcoded Chinese template strings (buttons, placeholders, tooltips,
table headers, dialog titles, empty states) plus an inline bilingual
batchImageText dictionary switched by isZhLocale() in script.

Move all of it into a new batchImage locale namespace (180 leaf keys
per language, zh/en verified key-aligned) registered in both locale
indexes, reusing 15 existing common.*/pagination.* keys. Column and
filter-option definitions become computed so language switches take
effect immediately; countable strings use vue-i18n plurals and the
three rich-text counters keep their inner bold spans via <i18n-t>
slots.

The Codex agent-instruction prompt template intentionally stays as a
plain string: it is an AI-facing prompt document containing literal
JSON braces that conflict with vue-i18n message syntax.

Verified: eslint, vue-tsc --noEmit, vite build, and the full vitest
suite (175 files / 1219 tests) all pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 03:12:39 +08:00
AstrenixandClaude Fable 5 3401a971a8 fix(frontend): localize stray hardcoded UI strings
Move the last few user-visible hardcoded strings into vue-i18n:

- AppHeader: "Toggle Menu" / "User Menu" aria-labels (screen readers
  read these in English regardless of locale)
- CustomPageView: "Page not found" error body
- PaymentProviderDialog: display-name example placeholder hardcoded in
  Chinese for all locales

Adds common.toggleMenu / common.userMenu / common.pageNotFound and
admin.settings.payment.customMethodDisplayNamePlaceholder to both zh
and en locales, and registers the new placeholder key in the
PaymentProviderDialog spec's i18n mock.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 02:55:50 +08:00
AstrenixandClaude Fable 5 ed280b81fc style(frontend): align dark-mode surfaces with the slate dark palette
The project's dark theme uses the custom slate-based dark-* palette
(928 dark:bg-dark-* / 787 dark:border-dark-* occurrences), but a
minority of surfaces still used Tailwind's neutral gray-* scale, which
has a visibly cooler hue next to slate cards — most noticeably the
filter dropdown panels on the usage, accounts and subscriptions pages.

Migrate the remaining dark:bg-gray-* / dark:border-gray-* (and their
hover: variants) to the dark-* palette across 12 components: filter
dropdowns, chart card borders, menu separators, and small badges.
49 class-string substitutions, no structural or logic changes;
dark:text-gray-* is untouched since gray text on dark surfaces is the
established project-wide convention.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 02:45:41 +08:00
AstrenixandClaude Fable 5 841544345f fix(frontend): make user email readable in balance modal dark mode
The user info banner in UserBalanceModal renders on a dark:bg-dark-700
container, but the email line kept text-gray-900 and the balance line
text-gray-500 with no dark variants, leaving near-black text on a dark
background. Align both with the pattern already used elsewhere in the
same dialog (text-gray-900 dark:text-gray-100 / text-gray-500
dark:text-gray-400).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 02:41:32 +08:00
AstrenixandClaude Fable 5 4c73149af8 fix(frontend): restore scrolling on the available channels page
The available channels table rendered inside its own
"card overflow-hidden" wrapper instead of the ".table-wrapper" element
that TablePageLayout's scroll chain expects. The outer
.table-scroll-container is overflow-hidden, so when the channel list
grew taller than the viewport the content was simply clipped with no
scrollbar. The extra card wrapper also drew a double border inside the
layout's own card chrome.

Mount the table on .table-wrapper like every other table page so it
receives overflow-y-auto from the layout, and add a source-convention
regression test in the style of TablePageLayout.spec.ts.

Fixes #4555

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 02:18:41 +08:00
AstrenixandClaude Fable 5 a1e1997632 fix(openai): accept standard OpenAI model list for Codex model discovery
Custom API key upstreams that only implement the standard OpenAI
GET /v1/models endpoint return {"object":"list","data":[{"id":...}]},
which the Codex models manifest validation rejected with
"missing top-level models array", surfacing HTTP 502 to Codex clients.

Convert the standard list envelope into the Codex manifest shape
({"models":[{"slug":...}]}) for API key upstreams before validation.
Bodies that already carry a top-level models field, are not the
standard list shape, or yield no usable model IDs are left unchanged
so existing validation and account failover behavior is preserved.

Fixes #4490

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 02:09:57 +08:00
cat a67351caec fix(openai): 按 Team 隔离 Agent Identity 导入 2026-07-19 01:40:49 +08:00
abbzbb 62846bb074 fix(security-audit): 仅在 blocking 意图下 fail-closed,修复无法关闭审计
configUntrusted 不再单独强制 ModeBlocking,避免默认关闭部署在配置
加载失败时对全部请求返回 prompt_guard_unavailable;成功保存配置后
清除 untrusted,确保管理员关闭提示词审计能立即生效。

Fixes #4560
2026-07-18 23:57:45 +08:00
github-actions[bot] d4b9797ff7 chore: sync VERSION to 0.1.161 [skip ci] 2026-07-18 14:18:28 +00:00
Wesley Liddick 19149ca196 Merge pull request #4558 from fengshao1227/fix/antigravity-plan-type-preserve
fix(antigravity): 保留付费 tier 的 PlanType,IneligibleTiers 仅标记异常状态
2026-07-18 21:48:44 +08:00
Wesley Liddick 831812b39d Merge pull request #4556 from superman2003/fix/grok-free-probe-encrypted-recovery
fix(grok): stabilize Free probes and encrypted reasoning recovery
2026-07-18 21:48:31 +08:00
Wesley Liddick d98ac48eb9 Merge pull request #4543 from heathermhuang/codex/secure-protected-video-content-4498
fix(grok): securely proxy protected video content
2026-07-18 21:46:31 +08:00
li 72b29a7d4e fix(antigravity): 保留付费 tier 的 PlanType,IneligibleTiers 仅标记异常状态
Fixes #4519
2026-07-18 21:43:54 +08:00
shaw 14608dc6d4 Merge origin/main into codex/secure-protected-video-content-4498
Reconcile with #4539 (grok media account model mapping), now on main:
- handler/grok_media.go non-failover error path keeps both changes —
  #4539's grokMediaScheduleModel(account, routingModel, nil) schedule
  attribution and this branch's IsResponseCommitted guard
- auto-merged sections verified: routing/classify use #4539's routingModel,
  video lookup owner-binding and no-failover semantics intact, ForwardGrokMedia
  keeps mapping block (skipped for lookup endpoints via RequiresRequestBody),
  empty-image failover, and video-status URL rewrite in order
2026-07-18 21:38:17 +08:00
Wesley Liddick daa4989124 Merge pull request #4539 from heathermhuang/codex/fix-grok-media-model-mapping-4503
fix(grok): apply account model mapping to media
2026-07-18 21:34:10 +08:00
shaw 8a95a46a69 Merge origin/main into codex/secure-protected-video-content-4498
Resolve conflicts with main:
- service/grok_media.go: keep both post-response blocks — #4497's empty
  image-output failover (main) runs first for image endpoints, then this
  branch's video-status content-URL rewrite; the endpoint conditions are
  mutually exclusive
- handler/openai_gateway_credential_failover_loop_test.go: mark the stub
  OAuth accounts media-eligible via the grok_media_eligible extra override,
  because this branch moved grok media failover coverage to the generation
  endpoint, which is now gated by #4540's paid-eligibility probe on main
2026-07-18 21:31:28 +08:00
shaw 9d498c2474 Merge origin/main into codex/fix-grok-media-model-mapping-4503
Resolve conflicts with main:
- handler/grok_media_test.go: keep both new tests (schedule model test from
  this branch, eligibility gating tests from #4540)
- service/openai_gateway_grok_test.go: keep both new tests; update the image
  cases of the mapping table test to return a non-empty image payload because
  #4497 (already on main) now converts empty image responses into an upstream
  failover error
2026-07-18 21:25:43 +08:00
Wesley Liddick a2f802d409 Merge pull request #4541 from wucm667/fix/issue-4532-renew-expired-subscription
fix(subscription): renew expired admin assignments
2026-07-18 21:14:23 +08:00
Wesley Liddick b01196a7a8 Merge pull request #4553 from wp-a/fix/openai-ws-turn-lifecycle
[codex] enforce websocket passthrough turn lifecycle
2026-07-18 21:10:48 +08:00
superman2003 e14fb2b6ff fix(grok): recover invalid encrypted content once 2026-07-18 21:05:50 +08:00
superman2003 dd7a2b22f0 fix(grok): align Free probes with health checks 2026-07-18 21:05:50 +08:00
shaw 4e8ea7d568 fix(test): 池模式临时规则测试适配 #4547 模型级隔离语义
#4496 与 #4547 文本无冲突但语义相撞:#4496 的测试断言规则命中后账号级
跨模型封锁,#4547(issue 4527 第4点)将已知模型的临时不可调度改为按
模型隔离(SetModelRateLimit,不再触发账号级 runtime block)。

按 #4547 的语义更新断言:命中模型 gpt-5.4 记模型级封锁、gpt-5.5 不受
影响、不再调用账号级 SetTempUnschedulable;池模式规则仍生效(停止同
账号重试),issue 4470 的诉求不受影响。未知模型的账号级兜底已由
TestOpenAITempUnschedulable_UnknownModelKeepsAccountRuntimeBlock 覆盖。
2026-07-18 21:02:23 +08:00
Wesley Liddick a3f2b8fd87 Merge pull request #4540 from heathermhuang/codex/investigate-grok-oauth-test-4525
fix(grok): retry CLI chat permission denial
2026-07-18 20:50:07 +08:00
Wesley Liddick 23cdd20606 Merge pull request #4537 from heathermhuang/codex/refresh-anthropic-monitor-1953
fix(monitor): refresh Anthropic text-block extraction
2026-07-18 20:49:40 +08:00
Wesley Liddick a62b821b5f Merge pull request #4478 from yardbirds0/codex/fix-upstream-billing-probe-refresh
fix: 完善上游 Sub2API 倍率探测刷新、展示与账号配置
2026-07-18 20:49:14 +08:00
Wesley Liddick 774ff5d8c8 Merge pull request #4515 from BenjaminAaron196/feat/filter-noise-rejected-requests
(fix) 过滤入口拒绝日志并强化鉴权安全边界
2026-07-18 20:46:50 +08:00
Wesley Liddick d2667393b3 Merge pull request #4522 from wucm667/docs/issue-4518-http-bridge-prerequisite
docs: clarify OpenAI WS mode router prerequisite
2026-07-18 20:43:01 +08:00
Wesley Liddick e002fbb349 Merge pull request #4508 from wucm667/fix/model-not-found-transient-misclassification
fix: 临时账号耗尽时保留 503 错误分类
2026-07-18 20:41:35 +08:00
Wesley Liddick 005bc5c8d4 Merge pull request #4497 from heathermhuang/agent/fix-grok-media-fallback-4471
fix(grok): fail closed for ineligible OAuth media
2026-07-18 20:41:24 +08:00
Wesley Liddick bc4bd118d8 Merge pull request #4547 from heathermhuang/codex/fix-model-scoped-temp-cooldown-4527
fix(routing): isolate temporary cooldowns by model
2026-07-18 20:41:12 +08:00
Wesley Liddick f3925db11b Merge pull request #4496 from StarryKira/agent/fix-4470-pool-temp-unschedulable
fix: honor temp unschedulable rules in pool mode
2026-07-18 20:40:12 +08:00
Wesley Liddick f9a467a4c0 Merge pull request #4520 from StarryKira/codex/fix-4487
fix: report Chat Completions stream transport failures
2026-07-18 20:39:49 +08:00
Wesley Liddick 8ce9288a6a Merge pull request #4489 from fengshao1227/fix/grok-free-cache-tool-injection
fix(grok): 纯客户端函数工具不再注入原生搜索工具
2026-07-18 20:39:37 +08:00
Wesley Liddick c1e702be5e Merge pull request #4505 from cyhhao/fix/claude-1m-model-suffix
fix(gateway): normalize Claude Code 1m model suffix
2026-07-18 20:39:27 +08:00
Wesley Liddick bc6b69289c Merge pull request #4468 from docooler/fix/responses-stream-content-part
fix(apicompat): emit content_part events and full output in Responses stream
2026-07-18 20:39:15 +08:00
Wesley Liddick 5a0492bf88 Merge pull request #4517 from weiness/fix/custom-branding-flash
fix: prevent custom branding flash on initial load
2026-07-18 20:39:00 +08:00
Wesley Liddick fdc9d92fdb Merge pull request #4528 from feitianbubu/fix/plan-validity-label-unit
fix(i18n): 套餐有效期表头与表单标签去掉写死的"天",与动态单位一致
2026-07-18 20:38:47 +08:00
Wesley Liddick 8cdd372b7e Merge pull request #4507 from coo1white/fix-dockerfile-cross-compile
fix(docker): cross-compile the image instead of running Go under QEMU
2026-07-18 20:38:37 +08:00
Wesley Liddick 080a52121a Merge pull request #4506 from coo1white/fix-compose-redis-command
fix(deploy): make the redis command flags take effect
2026-07-18 20:38:27 +08:00
harukaandClaude Opus 4.8 37db8d031b fix(config): 让环境变量能真正配置 image_storage 等凭证
viper.Unmarshal 只解码 AllKeys() 返回的键,而 AllKeys() 只汇总 SetDefault、
配置文件和显式 BindEnv 三个来源。AutomaticEnv 仅能覆盖已在其中的键,无法引入
新键;能兜底的 viper_bind_struct 又被 build tag 排除(我们只用 -tags embed)。

因此任何「没有注册默认值、且不在 config.yaml 里」的配置项,其环境变量会被静默
丢弃。image_storage 的 endpoint/bucket/access_key_id/secret_access_key/
public_base_url 正属此列,于是纯环境变量部署落到最坏组合:IMAGE_STORAGE_ENABLED
生效使 Enabled=true,四个凭证却为空 → Active()=false → 异步生图接口整体 404,
运维看到的却是"凭证不完整"。deploy/docker-compose.yml 默认就是纯环境变量驱动,
且自动生成的 config.yaml 从不写 image_storage 段,必然踩中(见 #4458、#4542)。

同类缺口不止于此:github_oauth、google_oauth、dingtalk_connect 三组第三方登录
配置(含 client_secret)同样完全无法用环境变量设置。

- 为这些键注册零值默认,使其进入 AllKeys() 而可被环境变量覆盖。零值与"键缺失"
  时的解码结果一致,故行为不变。
- sticky_escape_enabled 例外:它的实际默认是 true(靠 IsSet 守卫在解码后补上),
  注册 false 会让 IsSet 恒真而永久关闭该特性,故直接注册 true。
- 启动告警补上 missing_keys 字段,指明到底哪个凭证为空。
- 新增反射守卫测试:Config 结构体上每个可由环境变量表达的字段都必须已注册默认值。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHreE5pzCkSYz7J45fmd2Y
2026-07-18 05:24:32 -07:00
王鹏 f0e0b7e6d8 fix(openai-ws): enforce passthrough turn lifecycle 2026-07-18 19:17:53 +08:00
Heatherm Huang 4c845ca697 test(grok): sanitize security fixtures 2026-07-18 17:50:53 +08:00
Heatherm Huang 95d27f2dce fix(grok): fetch validated signed video content 2026-07-18 17:49:09 +08:00
Heatherm Huang f2e7a55703 fix(grok): proxy signed video status URLs 2026-07-18 17:21:53 +08:00
Heatherm Huang 1ed9f59599 test(grok): keep media failover coverage on generation 2026-07-18 15:54:43 +08:00
Heatherm Huang b4ad7fd363 test(grok): configure multipart media mapping 2026-07-18 15:49:21 +08:00
Heatherm Huang ef2a22be70 fix(routing): isolate temporary cooldowns by model 2026-07-18 15:35:30 +08:00
Heatherm Huang c831bb979f fix(grok): scope video content to request owner 2026-07-18 14:56:15 +08:00
Heatherm Huang 3edcbfd120 fix(grok): keep media content proxy URLs same-origin 2026-07-18 14:43:08 +08:00
wucm667 1db10dc559 fix(subscription): renew expired admin assignments 2026-07-18 14:42:22 +08:00
Vz7797 3f6b5c7bd7 fix(grok): proxy protected video content through upstream account
(cherry picked from commit a01177e294)
2026-07-18 14:37:25 +08:00
Heatherm Huang 2946281a43 fix(grok): retry CLI chat permission denial 2026-07-18 14:32:56 +08:00
Heatherm Huang 335edde9c8 fix(grok): apply account model mapping to media 2026-07-18 14:21:47 +08:00
mark-ly-wang 1a855d3e0e fix(monitor): extract anthropic text blocks
(cherry picked from commit 76cf1ee834)
2026-07-18 13:53:36 +08:00
Wesley Liddick b1a6b80267 Merge pull request #4526 from Wei-Shaw/feat/security-switches-default-off
feat(security): 敏感操作 step-up 2FA 开关化,安全开关默认关闭
2026-07-18 11:32:17 +08:00
feitianbubu c3f759d13a fix(i18n): 套餐有效期表头与表单标签去掉写死的"天",与动态单位一致 2026-07-18 10:59:11 +08:00
shaw 539bfc8bad feat(security): 敏感操作 step-up 2FA 开关化,安全开关默认关闭
新增系统设置 step_up_enabled(默认关闭),把敏感操作 2FA 门控做成可开关;
同时将会话 IP/UA 绑定默认值从开启改为关闭,避免用户因 IP 变动登录后掉线。

## 新增功能
- 敏感操作 step-up 2FA 总开关 step_up_enabled(默认关闭):关闭时账号/代理导出、
  备份创建/下载、S3 配置修改、提升管理员等操作恢复门控引入前的直接放行行为;
  开启后要求当前会话在 15 分钟内完成过 TOTP step-up 验证。

## 优化改进
- 会话 IP/UA 绑定默认改为关闭(功能保留,可在设置页按需开启)。
- 开启 step-up 开关需操作者本人已启用 TOTP(防自锁);关闭开关本身作为敏感操作,
  需通过 step-up 验证(防止攻击者拿到会话后先关闸再导出/备份)。
- 两个安全开关请求字段改为可空指针(省略=保持现值),避免旧客户端全量保存时
  静默重置安全开关。
- 备份恢复(整库覆盖可回滚安全设置)纳入 step-up 门控。
- 审计摘要 diffSettings 补记 step_up_enabled / session_binding_enabled 变更。

## Bug 修复
- 修复 BackupView 恢复操作 409(恢复进行中)判断未适配 apiClient 扁平化错误对象。
2026-07-18 10:46:42 +08:00
wucm667 8b75dd5576 docs: clarify OpenAI WS mode router prerequisite 2026-07-18 08:37:15 +08:00
haruka bd0f2d6405 fix: report chat stream transport failures 2026-07-18 03:24:04 +08:00
benjamin 71afe24710 fix: 修复CI检查问题 2026-07-18 00:42:16 +08:00
weiness 500f241692 fix: prevent custom branding flash on initial load 2026-07-18 00:24:06 +08:00
benjamin b92bbf0299 fix: 过滤入口拒绝日志并强化鉴权边界 2026-07-18 00:11:18 +08:00
wucm667 2594950993 fix: classify transient account exhaustion as 503 instead of 404 2026-07-17 22:10:18 +08:00
Nick 9386ce8a13 fix(docker): cross-compile the image instead of running Go under QEMU
Building the image for linux/amd64 on an arm64 host (Apple Silicon)
kept failing at 'go mod download' with 'unexpected EOF'.

Two changes:

1. The builder stages had no --platform, so the Node and Go toolchains
   ran under QEMU emulation of the target arch. Pin frontend-builder
   and backend-builder to $BUILDPLATFORM and cross-compile: add
   TARGETOS/TARGETARCH args and set them on 'go build'. The binary is
   CGO_ENABLED=0, so this is a clean pure-Go cross-compile - much
   faster, and the emulated networking that dropped module fetches
   with EOF is gone. The frontend output is JS (arch-neutral), so it
   is safe to build on the host arch too.

2. Add go module and build cache mounts, so a retry after a network
   blip goes on from where it stopped instead of starting over.

The runtime image and app behavior are unchanged.
2026-07-17 21:05:42 +07:00
Nick be74deae73 fix(deploy): make the redis command flags take effect
The redis command is one quoted script given to the inner `sh -c`.
Docker compose keeps the newlines inside the quoted string, so
`redis-server` on the first line ran as a complete command with no
flags at all, and --save / --appendonly / --appendfsync after it were
silently never applied (`redis-cli CONFIG GET appendonly` said "no").

Trailing `\` line continuations fold the script back into one command.
Checked with redis:7-alpine: appendonly is now "yes" and save is
"60 1".
2026-07-17 21:04:47 +07:00
cyh 2264a33085 fix(gateway): normalize Claude Code 1m model suffix 2026-07-17 21:59:57 +08:00
Tian Lee d2585097f3 fix: 完善上游 Sub2API 计费倍率探测与账号展示 2026-07-17 20:59:29 +08:00
Heatherm Huang e86063155f fix(grok): gate OAuth media on paid eligibility 2026-07-17 19:15:16 +08:00
haruka 1f7b7b9132 fix: honor temp unschedulable rules in pool mode 2026-07-17 18:12:33 +08:00
li 7043982ae3 fix(grok): 纯客户端函数工具不再注入原生搜索工具
Fixes #4486
2026-07-17 16:59:40 +08:00
github-actions[bot] 57914967cb chore: sync VERSION to 0.1.160 [skip ci] 2026-07-17 08:48:10 +00:00
Wesley Liddick 8bfbc5ca99 Merge pull request #4485 from Sub2API-Devs/dev
feat(security-audit): 新增 OpenAI 兼容提示词审计能力与安全审计控制台
2026-07-17 16:15:26 +08:00
Wesley Liddick cb40288fb8 Merge pull request #4479 from fengshao1227/fix/backup-s3-stepup-totp
fix(frontend): saveS3Config 接入 step-up TOTP 门控
2026-07-17 16:14:49 +08:00
Wesley Liddick 33766c299f Merge pull request #4481 from fengshao1227/fix/passive-image-namespace-capability
fix(gateway): 被动 image_gen namespace 不再强制要求 Responses capability
2026-07-17 16:14:35 +08:00
Wesley Liddick 13468b3fa5 Merge pull request #4484 from heathermhuang/codex/fix-grok-scheduler-media-cache
fix(grok): preserve media eligibility in scheduler cache
2026-07-17 16:13:31 +08:00
mt21625457 e69e46ba02 feat: allow one-click audit event filter deletion 2026-07-17 15:50:31 +08:00
Heatherm Huang eaf0691752 fix(grok): preserve media eligibility in scheduler cache 2026-07-17 15:45:19 +08:00
li 5fd030a01b test: 更新 image permission 测试适配 explicit intent 检查
被动 namespace 不再触发 403,新增 PassiveNamespaceDoesNotTrigger403
测试和 OpenAI native/image model 的正向用例。
2026-07-17 15:29:14 +08:00
li fc3c5a1e0c fix: 权限检查和并发槽也使用显式检查,修复被动 namespace 触发 403
Fixes #4447
2026-07-17 15:15:54 +08:00
li e375623abf fix(gateway): 被动 image_gen namespace 不再强制要求 Responses capability
Fixes #4476
2026-07-17 15:07:41 +08:00
li 288d3a1cce fix(frontend): saveS3Config 接入 step-up TOTP 门控
Fixes #4445
2026-07-17 14:52:54 +08:00
mt21625457 ac685ccaf5 feat(security-audit): persist full prompts on audit events and polish event review UI
- Add prompt_audit_events.full_prompt (migration 182) so admins can review
  the exact unredacted prompt that triggered a finding; blocking mode writes
  it from the snapshot, async mode reconstructs it from the Redis scan
  payload so jobs rows stay redaction-only
- Event detail API returns full_prompt (list endpoint stays lean); text is
  NUL-stripped and capped at 65536 runes
- Detail dialog shows the full prompt in a scrollable pane with fallback to
  the legacy redacted preview; page copy updated to match the new behavior
- Rework filter deletion into a dedicated dialog with time-range presets and
  criteria-change preview invalidation; localize decision/risk/category
  labels across the events workspace
- Fix pre-existing i18n message-compile spec by declaring the
  @intlify/message-compiler dev dependency
2026-07-17 14:38:10 +08:00
shaw bc50c9d013 chore: update sponsors 2026-07-17 14:05:59 +08:00
Wesley Liddick dda20ae9a6 Merge pull request #4474 from heathermhuang/codex/fix-grok-media-image-url-4420
v0.1.159 fix(grok): normalize media payloads and quarantine ineligible accounts
2026-07-17 13:49:09 +08:00
Heatherm HuangandOpenAI Codex c34dcd3700 docs: document Grok media eligibility
Co-Authored-By: OpenAI Codex <noreply@openai.com>
2026-07-17 12:18:46 +08:00
mt21625457 7ed4e7e5e3 fix(security-audit): isolate latest user prompt chunk 2026-07-17 12:12:41 +08:00
Heatherm Huang d2ac6b2c97 fix(grok): harden media quarantine edge cases 2026-07-17 12:08:50 +08:00
Heatherm Huang 8f9296140f Merge remote-tracking branch 'origin/main' into codex/fix-grok-media-image-url-4420 2026-07-17 11:51:46 +08:00
Heatherm Huang 8bc0a277f2 fix(grok): quarantine ineligible media accounts 2026-07-17 11:51:16 +08:00
Heatherm Huang 456c619379 fix(grok): normalize media reference image payloads 2026-07-17 11:51:08 +08:00
mt21625457andCursor 18e698bed6 feat(security-audit): allow admin-managed audit node targets and polish pool UI
Let admins configure private/intranet Guard endpoints without destination-class blocking, and fix prompt-audit switch layout so thumbs and labels no longer overlap.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-17 11:45:14 +08:00
docooler 26b5e87457 fix(apicompat): emit content_part events and full output in Responses stream
The Anthropic→Responses streaming converter omits two things the OpenAI
Responses wire format requires, which breaks clients that reconstruct the
response from the event stream (rather than just reading deltas).

1. response.content_part.added is never emitted.

   A message item is opened with content: [], and the OpenAI SDK's
   accumulating stream helper (client.responses.stream) only appends a
   content part when it sees content_part.added. Without it, the next
   output_text.delta indexes output.content[content_index] and raises:

     File "openai/lib/streaming/responses/_responses.py", line 352,
       in accumulate_event
         content = output.content[event.content_index]
     IndexError: list index out of range

   Raw iteration (responses.create(stream=True)) does not accumulate and is
   unaffected, which is why this went unnoticed.

2. response.completed carries Output: []ResponsesOutput{}.

   get_final_response() and tracing integrations parse the terminal event's
   response directly, so callers see an empty output_text even though the
   deltas streamed correctly. This one is invisible when only watching the
   stream render.

Also carries the full text on output_text.done / content_part.done (deltas
carry increments only, done events carry the whole part) and fills in
content/arguments/summary on output_item.done, which had the same
empty-payload issue.

Reproduced against a live Anthropic-platform group with the openai Python
SDK 2.46.0; Arize Phoenix's playground hits the same path. Verified before
(IndexError) and after (full text via get_final_response()).

Adds regression tests covering event ordering, done-event payloads, and the
terminal event's output for both text and tool calls.
2026-07-17 03:35:26 +00:00
github-actions[bot] c2c19a7cbe chore: sync VERSION to 0.1.159 [skip ci] 2026-07-17 02:00:12 +00:00
Wesley Liddick 2a75d7d238 Merge pull request #4462 from Wei-Shaw/fix/unify-security-client-ip
fix(security): unify audit log & session binding client IP with API key ACL trust toggle
2026-07-17 09:42:43 +08:00
Wesley Liddick 1c3f2810af Merge pull request #4461 from yardbirds0/feat/account-homepage-link
feat: 支持从 API Key 账号名称跳转上游站点主页
2026-07-17 09:34:50 +08:00
shawandClaude 7c48f9a85f fix(security): unify audit log & session binding client IP with API key ACL trust toggle
Behind a reverse proxy (e.g. nginx with X-Real-IP), admin audit logs and
session IP/UA binding always recorded 127.0.0.1 because they hardcoded
the gin trusted_proxies chain, while API key IP restriction already
honored the "trust forwarded client IP" system setting.

- add ip.GetSecurityClientIP(c, trustForwarded) as the single source of
  truth for security-sensitive client IP selection; API key auth
  middlewares (main + google) refactored onto it with zero behavior change
- SessionBindingContext(cfg) now resolves the client IP via the same
  toggle and injects it into the request context; token issuance,
  binding enforcement and its mismatch audit record all read the
  injected value, so issue/verify can never diverge
- audit log middleware and audit-log clear trace record the same
  security client IP (middleware.SecurityClientIP), falling back to the
  trusted proxy chain when the injection is absent
- settings UI hint (zh/en) documents the broadened toggle scope and the
  one-time re-login after toggling while session binding is enabled

With the toggle off (default) behavior is byte-for-byte unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-17 09:33:18 +08:00
shawandClaude 980a46ffb0 fix(i18n): add missing OpenAI account entry labels
- admin.accounts.oauth.openai.mobileRefreshTokenAuth was referenced by
  OAuthAuthorizationFlow.vue since 9f8cffe88 (Mobile RT entry) but never
  added to zh/en locales, rendering the raw key in the add-account wizard
- admin.accounts.oauth.openai.accessTokenAuth has the same latent issue
  since 26060e702 (Sora AT import); currently hidden but fixed alongside

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-17 09:32:48 +08:00
yardbirds0 824f763a77 feat: 支持从 API Key 账号名称跳转上游站点 2026-07-17 09:15:32 +08:00
Wesley Liddick 9b3c96dc68 Merge pull request #4451 from rurucxk/fix/grok-free-responses-function-tool-cache
fix(grok): enable free prompt cache for Responses function tools
2026-07-17 09:04:47 +08:00
Wesley Liddick 52f2bc69fb Merge pull request #4450 from wucm667/fix/issue-4442-lazy-stripe-loader
fix(frontend): lazy-load Stripe payment dependency
2026-07-17 09:04:33 +08:00
Wesley Liddick 067cf8b46e Merge pull request #4459 from Wei-Shaw/fix/openai-alpha-search-apikey-scheduling
fix(openai): restore APIKey account scheduling for alpha/search
2026-07-17 09:04:17 +08:00
mt21625457andCursor df9d9e2e40 fix(security-audit): harden role scan, startup, probe, and localhost dial
Scan client-injected assistant/tool/model turns, fail closed when config cannot
be trusted after startup or stale invalidation, reuse probe tokens only for the
same base URL, and restrict localhost dials to loopback addresses.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-17 09:00:14 +08:00
mt21625457andCursor 0f7f8a317e fix(security-audit): close prompt-audit bypass and privacy gaps
Stop WebSocket follow-up turns from reusing a request-wide audit cache, scan
client-controlled instruction fields, fail closed on stale weaker configs, and
tighten preview/SSRF controls including persisted request stage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-17 08:46:57 +08:00
shaw d2b080e88b fix(openai): restore APIKey account scheduling for alpha/search
PR #4394 (776f3f0de) 在新增 alpha_search 调度能力时加入了 OAuth-only
门控,把 APIKey 账号从 /alpha/search 候选池整体剔除;但转发层自
52071d391 起就支持 APIKey 走 {base_url}/v1/alpha/search,门控注释中
「API key 会被发往 chatgpt.com 导致 401」与实际路由不符。结果是纯
APIKey 分组自 v0.1.157 起独立搜索在选号阶段即失败(无可用账号)。

修复:
- SupportsOpenAIEndpointCapability 的 alpha_search 门控放行
  AccountTypeAPIKey(OAuth/APIKey 均可,Grok 等仍拒绝);显式能力集
  语义不变,chat_completions 继续隐含放行 alpha_search。
- ForwardAlphaSearch 对 APIKey 账号的 404/405 按端点级 failover 处理
  (换号、不写账号错误状态),避免混合分组里请求死在不支持该端点的
  APIKey 上游;OAuth 账号 404 透传行为保持不变。
- 更新固化旧门控行为的用例,并在调度层新增 APIKey 放行回归锁。
2026-07-17 08:44:23 +08:00
mt21625457 d11bdb13f5 feat(security-audit): add OpenAI-compatible prompt auditing 2026-07-17 00:39:39 +08:00
rurucxk 29e39b96e5 fix(grok): enable free prompt cache for Responses function tools
Reuse applyGrokFreeMessagesFunctionToolCacheRoute on native /v1/responses
and the Grok WS HTTP bridge so Free OAuth requests with client function
tools get the same mixed-tools cache route as the Messages bridge
(append/convert web_search and x_search).

Also dedupe: Grok Build already declares function tools named web_search,
so naive append caused "Duplicate tool names: web_search". Convert those
function entries to native tool types and skip duplicates.

Only Free OAuth accounts (isKnownGrokFreeAccount); paid/unknown unchanged.
2026-07-17 00:23:19 +08:00
wucm667 08e994ad86 fix(frontend): lazy-load Stripe payment dependency 2026-07-16 23:21:58 +08:00
github-actions[bot] bc2244c83f chore: sync VERSION to 0.1.158 [skip ci] 2026-07-16 12:37:21 +00:00
Wesley Liddick 26abd19a28 Merge pull request #4433 from heathermhuang/codex/fix-grok-regressions-4412-4421
fix(grok): repair OAuth media and compatibility regressions
2026-07-16 20:16:46 +08:00
shaw c29b50394f Merge main (fix batch-limits test typecheck breaking CI) 2026-07-16 20:05:48 +08:00
shaw 3d23cc399f fix(admin): align batch-limits test with expanded NewUserHandler signature
PR #4425 was authored before #4429 widened NewUserHandler with the
step-up TOTP and user services, and merged without a rebase, breaking
typecheck on main.
2026-07-16 20:05:31 +08:00
shaw c1fd1cb44e Merge origin/main into codex/fix-grok-regressions-4412-4421
Reconcile the OAuth media route with the manual endpoint-switch redesign
(7f5d067af): media leaves for api.x.ai only when text traffic resolves to
the CLI gateway host; manually selected official/regional/custom endpoints
keep serving media as-is.
2026-07-16 19:57:48 +08:00
Wesley Liddick 7e13b6d039 Merge pull request #4425 from AdrianZhaoDev/agent/admin-users-batch-limits
feat(admin): batch update user concurrency and RPM
2026-07-16 19:33:32 +08:00
Wesley Liddick c993490a82 Merge pull request #4434 from yan9651688/feat/group-one-click-copy
feat(group): add safe one-click duplication
2026-07-16 19:33:18 +08:00
Wesley Liddick 4d91f39474 Merge pull request #4431 from linyqh/codex/fix-codex-image-handoff
fix(openai): 修复 Codex 生图网关侧交接问题
2026-07-16 19:32:33 +08:00
Wesley Liddick af6bd44d2a Merge pull request #4435 from superman2003/fix/grok-codex-wsv2-template
fix(grok): enable Codex Responses WebSocket v2 in setup template
2026-07-16 19:32:14 +08:00
Wesley Liddick 541ca3bc27 Merge pull request #4430 from feitianbubu/fix/proxy-fallback-label
fix(i18n): 代理"失败回退"改名"到期回退",与实际行为一致
2026-07-16 19:32:04 +08:00
shaw 7f5d067af2 feat(grok): 支持上游端点手动切换与快捷端点,修复 SSO 建号自定义地址被覆盖
官方端点(api.x.ai / cli-chat-proxy.grok.com)偶发不可用,运营方需要在
端点间手动切换。旧语义把 OAuth 账号存储的官方 host 一律视同"未定制"并
回落默认 CLI 网关:填了官方地址保存成功却不生效、重新编辑开关回到关闭、
再次保存直接删值,形成"修改不生效"的静默循环。

后端:
- GetGrokBaseURL OAuth 分支改为"存了什么用什么":官方 API / 区域 API /
  第三方转发地址一律按填写值转发与探测,仅空值或无法解析的脏数据回落
  默认 CLI 网关;删除官方变体运行时迁移逻辑
- *.api.x.ai 区域端点(us-east-1/us-west-2/eu-west-1 等)纳入可信 host,
  OAuth 使用时不受运营方 URL 白名单限制,官方 host 仍强制 /v1 path
- 修复 SSO 批量建号 MergeCredentials 方向缺陷:BuildAccountCredentials
  恒写官方 base_url,会覆盖导入请求指定的自定义转发地址;抽出
  grokSSOImportCredentials 显式保留请求值(与 RefreshAccountToken 对齐)

前端:
- isCustomGrokBaseUrl 仅默认 CLI 网关 host 视同未定制:api.x.ai 与区域
  端点保存后正常回显(开关开启 + 显示地址),不再被静默吞掉
- 新增 GrokBaseUrlPresets 快捷端点组件(Grok Build CLI / 官方 API /
  us-east-1 / us-west-2 / eu-west-1),接入编辑(OAuth 自定义区 + apikey
  Base URL)、新增(同前)与批量编辑(所选平台全为 grok 时显示,点击
  自动勾选 base_url);仅快速填充,输入框仍可自由填写任意第三方地址
2026-07-16 19:10:21 +08:00
superman2003 174ea22eeb fix(grok): enable Codex Responses WebSocket v2 2026-07-16 18:30:59 +08:00
yan9651688 9fc006546c Make repeated group setup safer
Admins often recreate groups with the same pricing, routing, and account membership. A server-side duplicate creates an inactive copy for review, preserves eligible account priorities, and recovers ambiguous retries without creating extra groups.

Constraint: Group has no neutral JSON metadata field for durable operation recovery
Constraint: Model routing references account IDs, so copied configuration requires matching bindings
Rejected: Rebuild from the list response | it omits configuration and account priority details
Rejected: Store operation identity in business configuration | it would pollute real group settings
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: Keep duplicated groups inactive until an administrator reviews the copied configuration
Tested: Go unit and full tests, go vet, integration-tag compile, frontend Vitest, lint, typecheck, production build, and Playwright duplicate flow
Not-tested: PostgreSQL container integration locally because Docker is unavailable; CI will execute the database-backed suite
2026-07-16 18:18:28 +08:00
shaw b960ec1980 chore: update sponsors 2026-07-16 17:45:13 +08:00
github-actions[bot] 60732a2e8c chore: sync VERSION to 0.1.157 [skip ci] 2026-07-16 09:12:44 +00:00
viccyandOmX 9d1064badd 澄清 Codex 图片桥接与本地执行器边界
配置界面现在区分非 Responses Lite 的 hosted 桥接与客户端本地 image_gen,并准确描述账号 strip 策略。API Key Mode 同时提示完全重启 Codex 后新建 task,以重建客户端工具注册表。

Constraint: 兼容模式继续保持默认,Responses Lite 的本地工具由客户端与账号策略决定
Rejected: 写入 features.image_generation | 当前 Codex 已默认启用且仓库既有配置刻意省略该项
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: 图片桥接文案必须区分 hosted 注入、客户端声明和 image-only 路由
Tested: 前端 lint、typecheck、关键套件 93 项、定向套件 43 项
Not-tested: Codex Desktop 真实工具注册表重建

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-07-16 17:11:17 +08:00
viccyandOmX 2b5944fd6c 防止 WebSocket 生图结果停留在进行中状态
HTTP/SSE 已会在终态事件中修正带结果的图片 item,但 WebSocket 下行路径缺少同一处理。现在四条文本帧出口复用现有归一化,并原样保留 result 数据。

Constraint: 仅修改终态事件中带非空 result 的 image_generation_call
Rejected: 解码并改写二进制帧 | 二进制帧不属于 JSON 事件契约
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: 保持 HTTP、SSE 与 WebSocket 的图片终态规则一致
Tested: 后端 unit、integration、go vet
Not-tested: 真实 Codex WebSocket 生图会话

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-07-16 17:11:00 +08:00
viccyandOmX 43e95dfa45 避免无效模型清单破坏 Codex 能力发现
自定义 API-key 上游可能将普通 OpenAI 模型列表作为 2xx 响应返回。现在只校验稳定 envelope,并把结构错误归类为可重试,以便冷缓存时换号且不污染缓存。

Constraint: Codex manifest schema 会随客户端演进,仅校验顶层 models 数组
Rejected: 在网关合成完整 manifest | 容易与上游 schema 漂移
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: 不要在此处校验 models 元素的易变字段
Tested: 后端 unit、integration、go vet
Not-tested: 真实第三方 API-key 上游的在线 failover

Co-authored-by: OmX <omx@oh-my-codex.dev>
2026-07-16 17:10:44 +08:00
feitianbubu ca82fd6e98 fix(i18n): rename proxy fallback label to expiry fallback 2026-07-16 17:09:23 +08:00
Wesley Liddick a2779cd5f3 Merge pull request #4428 from alfadb/fix/anthropic-haiku-full-mimicry
fix(gateway): 修复 Haiku OAuth 请求被归入额外用量
2026-07-16 16:55:11 +08:00
Wesley Liddick dbef64bb45 Merge pull request #4427 from yan9651688/feat/channel-monitor-one-click-copy
feat(channel-monitor): add safe one-click duplication
2026-07-16 16:54:22 +08:00
Wesley Liddick 3ecfcc48ae Merge pull request #4429 from Wei-Shaw/feat/role-stepup-admin-2fa-password
feat(security): 角色提升纳入 step-up 2FA + 管理员 2FA 密码验证 + 审计日志页优化
2026-07-16 16:53:51 +08:00
Heatherm Huang 115116e8bf fix(grok): repair OAuth routing regressions 2026-07-16 16:52:25 +08:00
shaw 35748d8c51 feat(security): gate admin role promotion behind step-up 2FA and harden admin TOTP verification
- 提升用户为管理员 / 创建管理员账号纳入敏感操作:handler 级 EnforceStepUp 门控
  (admin API key 拒绝、未启用 TOTP 拒绝、无 grant 返回 STEP_UP_REQUIRED),
  目标已是管理员的日常编辑不触发
- 管理员启用/停用 2FA 一律使用密码验证(默认通知邮箱常收不到验证码),
  verification-method 按用户角色返回;普通用户行为不变
- 用户编辑/创建弹窗接入 useStepUp:命中 STEP_UP_REQUIRED 弹 TOTP 验证并自动重试
- 审计日志清理入口与其他敏感操作对齐:未启用 2FA 时直接提示先启用 TOTP,
  不再弹出无法完成的验证码输入框(后端强制现场 TOTP 语义不变)
- 审计日志页重构:DataTable 布局、详情弹窗分区展示、时间范围改为 ops 同款
  下拉(预设窗口 + 自定义起止支持时分)
2026-07-16 16:49:08 +08:00
yan9651688 e2e375d694 Make repeated channel-monitor setup safer
Admins often recreate monitors with the same endpoint, model, and request settings. A server-side duplicate keeps the stored API key out of the browser, creates a disabled copy for review, and uses stable operation identity to recover ambiguous retries without creating extra rows.

Constraint: Stored monitor API keys must never be returned to the browser
Constraint: Applying a request template must preserve internal duplicate recovery metadata
Rejected: Rebuild the monitor from list data | list responses only contain a masked API key
Rejected: Copy runtime state and history | a duplicate should start as an unverified configuration
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: Keep duplicated monitors disabled until an administrator reviews and enables them
Tested: Go unit tests for repository, service, and admin handler; integration-tag compile; go vet; golangci-lint v2.9; frontend Vitest, ESLint, typecheck, production build; Playwright duplicate flow
Not-tested: PostgreSQL container integration locally because Docker is unavailable; CI will execute the database-backed suite
2026-07-16 16:30:19 +08:00
alfadb 1f5ee8123f fix(gateway): apply full Claude Code mimicry to Haiku 2026-07-16 15:45:22 +08:00
zhaozewu 7947619cc3 feat(admin): batch update user limits 2026-07-16 15:37:35 +08:00
Wesley Liddick 393a8fe56a Merge pull request #4424 from StarryKira/fix/4417-responses-image-account-capability
fix(gateway): route image-intent /v1/responses only to Responses-capable accounts (#4417)
2026-07-16 15:35:45 +08:00
Wesley Liddick 09729ba54c Merge pull request #4406 from StarryKira/agent/fix-4326-async-image-object-storage
feat: 异步生图任务与结果轮询(重新引入 #4381)+ 结果落对象存储
2026-07-16 15:35:04 +08:00
shaw 590efe29a5 Merge remote-tracking branch 'origin/main' into agent/fix-4326-async-image-object-storage
# Conflicts:
#	backend/cmd/server/wire_gen.go
2026-07-16 15:32:38 +08:00
Wesley Liddick 813920607e Merge pull request #4418 from Wei-Shaw/feat/audit-log-and-credential-hardening
feat(security): 操作审计日志 + 会话IP/UA绑定 + 敏感操作 step-up 2FA
2026-07-16 15:27:13 +08:00
harukaandClaude Opus 4.8 605b026cc4 fix(gateway): route image-intent /v1/responses only to Responses-capable accounts (#4417)
For OpenAI-compatible API-key accounts, /v1/responses requests with
image-generation intent could be scheduled to accounts whose upstream
does not support the Responses API (extra.openai_responses_supported=false).
The flag was only consulted at forward time, where such accounts are
silently downgraded to a Chat-Completions path that cannot produce images,
causing upstream 4xx/5xx or canceled requests.

Fix:
- Add endpoint capability OpenAIEndpointCapabilityResponses. Its check in
  SupportsOpenAIEndpointCapability excludes only OpenAI API-key accounts
  probed as unsupported (mirroring the forward-time downgrade condition);
  OAuth/Grok/unprobed accounts keep existing behavior, and a responses-
  capable upstream must still pass the chat_completions gate. Reusing the
  existing requiredCapability plumbing makes every scheduler filter path
  enforce it with no scheduler signature changes.
- Request the responses capability at the HTTP Responses and
  ResponsesWebSocket call sites only when imageIntent && platform==openai,
  so non-image requests keep the downgrade path and Grok's own image path
  is untouched.
- Normalize max_tokens -> max_output_tokens on the native responses
  forward path (PlatformOpenAI), and strip prompt_cache_options alongside
  prompt_cache_retention/safety_identifier.

/v1/images/generations continues to use native image capability (unchanged).

Tests: capability truth table, scheduler exclusion of unsupported accounts,
and forward-path transform behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KXpzKKvsb5jW2GvgBQqnnZ
2026-07-16 00:23:40 -07:00
shaw 2d97207d41 fix(settings): 审计日志保留天数清空时回退默认值避免保存 400
audit_log_retention_days 用 v-model.number 绑定数字框,管理员清空输入框时
得到空串,后端 int 字段 ShouldBindJSON 解析空串失败返回 400,导致整次系统
设置保存被拒。payload 构建时对空/非法值回退默认 180(与后端
parseAuditLogRetentionDays("") 语义一致;显式 0 仍表示永久保留)。
2026-07-16 15:19:19 +08:00
shaw d67a2cad2b fix(lint): 检查 audit 键归一化中 WriteRune 返回值 (errcheck)
golangci-lint errcheck 报 audit_log.go:115 未检查 (*strings.Builder).WriteRune
返回值。Builder.WriteRune 永不返回错误,按仓库惯例以 _, _ = 显式丢弃。
2026-07-16 15:05:19 +08:00
shaw 2de6ccb071 fix(security): 补齐审计日志脱敏缺口 + step-up 下载/取消体验修复
审计发现修复:

高危——审计日志请求体脱敏不全(audit_logs 沦为明文凭证聚合点):
- 键名归一化比对(小写+去分隔符),覆盖 privateKey/apiv3key 等无分隔符与 camelCase 写法
- 程序化并入 SensitiveCredentialKeys 与 providerSensitiveConfigFields 两份权威敏感表,防清单漂移
- 补齐 proxy_key(内嵌代理密码)、custom_key(自设 API Key 明文)精确键
- Codex session 导入路由 body 整体由粘贴的 auth JSON 构成,键级脱敏无法覆盖,整体不入库
- 新增守卫测试:两份权威表的每个键必须被审计脱敏命中;provider_key 等渠道标识保留以便追责

中危——step-up 前端体验:
- 备份下载改同页 anchor 导航(预签名 URL 后端强制 attachment disposition),
  避免 step-up 弹窗 await 耗尽瞬态激活后 window.open 被浏览器拦截
- useStepUp.run 用户取消时抛 StepUpCancelledError sentinel,
  三个调用点静默处理,不再把取消误报为红色错误 toast

低危:
- 修正审计中间件挂载位置的陈旧注释(实际挂在认证之后)
- 审计 body 捕获改 LimitReader 按 256KB 上限截断读取,超出部分拼接回填,
  避免大体积导入请求被完整复制进内存两次
- TOTP step-up 弹窗验证成功后即时清空验证码输入
2026-07-16 14:38:16 +08:00
shaw a1af031969 fix(test): gofmt 审计日志测试 + 补齐 settings 契约 golden 两新字段
- audit_log_test.go: gofmt map 对齐
- api_contract_test.go: GET /admin/settings 两处 golden 补 session_binding_enabled/audit_log_retention_days
2026-07-16 13:58:50 +08:00
shaw 0ddd58aaf9 feat(security): 操作审计日志 + 会话IP/UA绑定 + 敏感操作 step-up 2FA
应对管理员访问凭证失守导致的数据外泄风险,新增三层防护:

审计日志(admin-only 可见,用户不可见)
- 新增 append-only audit_logs 表(migration 180)+ 异步批量写入 + 保留期清理
- 审计中间件挂在 admin/user/auth/admin-payment 组认证之后:记录所有变更类
  请求 + 白名单敏感读取(账号/代理导出、备份下载、admin/user API key 读取)
- 请求头凭证首尾掩码;请求体 JSON 递归脱敏(api_key/password 等擦除,base_url
  保留以便追责);非 JSON body 不入库
- 无单条删除;全量清空需现场 TOTP 校验、拒绝 admin API key、未启用 2FA 不允许,
  清空后同步写入留痕记录

会话 IP/UA 绑定(默认开启,可在系统设置关闭)
- JWT 携带 session id + IP/UA 指纹哈希;IP 或 UA 任一变化即撤销会话家族并要求
  重新登录;旧 token 无指纹时放行以平滑升级

敏感操作 step-up 2FA(sudo 窗口 15 分钟)
- 账号/代理导出、DB 备份创建/下载、S3 目标修改要求近期 TOTP 二次验证;admin API
  key 一律拒绝;前端 useStepUp 组合式 + TotpStepUpDialog 弹码后自动重试
- API key 查看按需求暂不加强管控

前端:新增 /admin/audit-logs 操作日志页面(筛选/详情/2FA 清空)、侧边栏入口、
step-up 弹窗接入导出与备份流程、安全设置项(绑定开关 + 日志保留天数)、zh/en i18n
2026-07-16 13:47:50 +08:00
harukaandClaude Opus 4.8 0eb6e21aaa feat: 异步图片任务结果落对象存储
为异步生图任务增加 S3 兼容对象存储支持,任务结果不再把大图内联存进 Redis:

- 新增可插拔接口 service.ImageStorage(Save -> url),适配别的厂商只需实现它
- S3 实现 S3ImageStorage(AWS S3 / R2 / 阿里云 OSS / MinIO),与备份共用 S3 客户端构造
- 新增 image_storage 配置(config.yaml + IMAGE_STORAGE_* 环境变量),默认关闭
- enabled 同时作为总开关:关闭或未配置对象存储时,异步生图接口返回 404 且不写
  Redis,从根上避免几 MB 的 b64_json 结果撑爆 Redis
- 完成时把图片上传对象存储并把结果改写为短链接(公开直链或 presigned),
  上传失败则任务标记为失败

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SM1tf3CFVRzC7guuhBXvMd
2026-07-15 19:57:37 -07:00
haruka e5e94d1eb1 docs: document async image task API 2026-07-15 19:57:37 -07:00
haruka 1fb942dd77 feat: add async image generation tasks 2026-07-15 19:57:37 -07:00
Wesley Liddick 09c6c6d740 Merge pull request #4387 from yardbirds0/feat/upstream-rate-scheduling
feat: 按上游计费倍率调度 OpenAI 账号
2026-07-16 10:46:29 +08:00
shaw 0408bdb34f Merge remote-tracking branch 'origin/main' into feat/upstream-rate-scheduling
# Conflicts:
#	backend/internal/handler/openai_gateway_handler.go
2026-07-16 10:31:21 +08:00
Wesley Liddick ab978e615e Merge pull request #4385 from yardbirds0/feat/upstream-billing-probe
feat: 增加上游 Sub2API 计费倍率探测与账号展示
2026-07-16 10:27:45 +08:00
Wesley Liddick 8d36ce3d20 Merge pull request #4108 from yardbirds0/feat/key-billing-info
feat: 增加 API Key 计费倍率自省接口
2026-07-16 10:27:35 +08:00
shaw e2bb90a80d fix(test): tls.peet.ws 站点故障时跳过 TLS 指纹集成测试
skipIfExternalServiceUnavailable 的不可用特征清单漏掉 EOF/connection
reset/broken pipe,站点半死返回空响应断开时测试走 Fatalf 导致 CI 必红。
补齐特征清单,并把读体失败、非 200 状态码、响应体非法 JSON 一并归为
外部服务不可用跳过;站点健康时指纹校验行为不变。
2026-07-16 09:51:41 +08:00
Wesley Liddick 08828293b7 Merge pull request #4404 from Wei-Shaw/revert-4381-agent/fix-4326-async-image-tasks
Revert "feat: 支持异步生图任务与结果轮询"
2026-07-16 09:48:09 +08:00
Wesley Liddick 502097026f Revert "feat: 支持异步生图任务与结果轮询" 2026-07-16 09:47:27 +08:00
Wesley Liddick a3a227c858 Merge pull request #4381 from StarryKira/agent/fix-4326-async-image-tasks
feat: 支持异步生图任务与结果轮询
2026-07-16 09:44:26 +08:00
Wesley Liddick 51f2b0e3ee Merge pull request #4382 from wp-a/fix/openai-responses-rejected-field-retries
[codex] retry explicitly rejected Responses fields
2026-07-16 09:37:36 +08:00
Wesley Liddick 531ae04a0b Merge pull request #4395 from wp-a/fix/openai-body-limit-failover
[codex] fail over account-specific OpenAI body limits
2026-07-16 09:33:48 +08:00
Wesley Liddick e4329a04e8 Merge pull request #4393 from superman2003/fix/grok-codex-compatibility
fix(grok): improve Codex compatibility and key setup
2026-07-16 09:33:20 +08:00
Wesley Liddick f3138ceb43 Merge pull request #4384 from wp-a/fix/openai-model-scoped-transient-cooldown
[codex] scope OpenAI transient cooldowns by model
2026-07-16 09:33:09 +08:00
Wesley Liddick 1c5c42c183 Merge pull request #4394 from siyuan-123/codex/pr-gpt56-pat-alpha-search
fix(openai): route PAT alpha search via responses web_search
2026-07-16 09:32:59 +08:00
Wesley Liddick 3fc0336e1d Merge pull request #4377 from wp-a/fix/openai-ws-ingress-lifecycle
[codex] close OpenAI WS ingress reads cleanly
2026-07-16 09:32:50 +08:00
Wesley Liddick 807850769f Merge pull request #4396 from StarryKira/fix/4386-image-input-pricing
fix(billing): 图像输入 token 按独立单价计费(gpt-image-2 图片编辑)
2026-07-16 09:32:29 +08:00
Wesley Liddick 8852194670 Merge pull request #4402 from wucm667/fix/issue-4399-oauth-image-usage
fix(openai): 修复 OAuth 生图工具用量计费
2026-07-16 09:32:18 +08:00
Wesley Liddick 4226ff8e3a Merge pull request #4392 from jianjianai/new/perf-bulk-account-platform-scope
perf(scheduler): 按平台收窄批量账户事件重建
2026-07-16 09:31:59 +08:00
Wesley Liddick ff08694d79 Merge pull request #4400 from jianjianai/new/perf-scheduler-payload-reuse
perf: 复用同批次调度快照账号载荷写入
2026-07-16 09:31:51 +08:00
Wesley Liddick 7e43ebc792 Merge pull request #4369 from wp-a/fix/openai-wsv2-malformed-json
[codex] reject malformed OpenAI WS v2 events
2026-07-16 09:31:39 +08:00
Wesley Liddick 4a50d05393 Merge pull request #4380 from wucm667/fix/issue-4357-responses-lite-context
fix(openai): normalize Responses Lite reasoning context
2026-07-16 09:31:29 +08:00
Wesley Liddick ba01199812 Merge pull request #4376 from drgnchan/hotfix/find-n6-table-scroll
fix(frontend): preserve horizontal table scrolling on tablets
2026-07-16 09:31:16 +08:00
Wesley Liddick 25d7797d83 Merge pull request #4379 from wucm667/fix/issue-4348-reject-image-chat-models
fix(openai): reject image models on chat completions
2026-07-16 09:31:05 +08:00
wucm667 d22f4d9b5b fix(openai): use image tool usage for OAuth billing 2026-07-16 08:48:43 +08:00
jjaw f552448fb2 复用调度快照账号载荷写入 2026-07-16 04:07:15 +08:00
harukaandClaude Opus 4.8 62d57c02d8 feat(billing): usage_logs 单独记录图片输入 token 与费用
图片编辑/图生图请求的图片输入 token 此前并入 input_tokens/input_cost,
无法对账。拆分上报口径,total_cost 保持不变。

后端:
- CostBreakdown 新增 ImageInputCost;computeTokenBreakdown 将图片输入费用
  从 InputCost 拆出(InputCost 从此仅含文本输入),并纳入 tier 倍率与总额;
  长上下文合并路径同步携带 ImageInputCost
- 迁移 179:usage_logs 新增 image_input_tokens / image_input_cost 列
- UsageLog、insert/query 仓储(含定位参数数组、CTE 列表、扫描顺序)、
  DTO 与 mapper 补齐两列
- openai_gateway_usage 从 usage 与 cost 落库图片输入 token/费用

前端:
- UsageLog 类型、imageUsage 工具(hasImageInputTokens/Cost、textInputTokens)
- 用量表 token 徽标、Token/费用 tooltip 与单价行按图/文输入拆分展示
- zh/en usage.* i18n

测试:
- 新增 gpt-image-2 图片编辑复现用例(复现 #4386 的 $0.016081 期望值)
- 新增 usage 提取器图片输入 token 解析用例(input_tokens_details.image_tokens)
- 更新 doubao 图文分价用例与仓储/契约测试以匹配新的 input/image 拆分口径

相关 #4386。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015wcJTKDddxXSQrepSs3wrU
2026-07-15 10:03:38 -07:00
王鹏 ad5e2a85b7 test(openai): validate body-limit error envelope 2026-07-16 00:52:26 +08:00
Tian Lee 90ee85f3ef feat: 按上游计费倍率调度 OpenAI 账号 2026-07-16 00:40:46 +08:00
siyuan 72fada40f6 fix(lint): check alpha search builder writes 2026-07-16 00:36:38 +08:00
siyuan 695665cbc8 fix(openai): fallback PAT alpha search to responses web_search 2026-07-16 00:36:38 +08:00
siyuan 776f3f0de7 fix(openai): align alpha search PAT forwarding 2026-07-16 00:36:38 +08:00
harukaandClaude Opus 4.8 06e03f467a feat(billing): 渠道自定义定价支持图片输入 token 单价 image_input_price
渠道 token 计费模式此前无法为图片输入 token 单独定价,gpt-image-2
图片编辑等请求的图像输入被按文本 input_price 计费。新增
channel_model_pricing.image_input_price 列及全链路支持。

后端:
- 迁移 178:channel_model_pricing 新增 image_input_price 列
- ChannelModelPricing 新增 ImageInputPrice 字段,repo 读写、校验补齐
- model_pricing_resolver / GetModelPricingWithChannel 映射到
  ImageInputPricePerToken;未配置时归零,由 computeTokenBreakdown
  回退文本输入价(向后兼容,与 image_output_price 的渠道权威规则一致)
- admin / 用户侧定价 DTO 与 model-pricing 自动填充接口补充该字段

前端:
- 渠道定价表单新增「图片输入」价格输入(token 模式)
- API 类型、表单模型、form↔API 换算、自动填充、用户侧模型定价卡展示
- zh/en i18n 标签

相关 #4386。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015wcJTKDddxXSQrepSs3wrU
2026-07-15 09:35:34 -07:00
harukaandClaude Opus 4.8 7c43b7327d feat(billing): 解析 usage.input_tokens_details 拆分图/文输入 token
/v1/images/edits 等带图请求,上游在 input_tokens_details.image_tokens
单独回传图片输入 token,此前被合并进 input_tokens 整体按文本输入价计费。

- openAIUsageFromGJSON 读取 input_tokens_details.image_tokens
  (回退 prompt_tokens_details.image_tokens)写入 OpenAIUsage.ImageInputTokens
- mergeOpenAIUsage 补充 ImageInputTokens 的流式合并

配合全局定价的 input_cost_per_image_token,gpt-image-2 图片编辑请求的
图像输入即按独立单价计费。相关 #4386。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015wcJTKDddxXSQrepSs3wrU
2026-07-15 09:24:44 -07:00
harukaandClaude Opus 4.8 10cb2ca42c feat(billing): 全局定价解析 input_cost_per_image_token
LiteLLM 定价数据中 gpt-image-2 等模型已含 input_cost_per_image_token
(图片输入 token 单价),但此前未被解析,导致图片编辑/图生图请求的
图像输入 token 被按文本输入价计费。

- LiteLLMModelPricing / LiteLLMRawEntry 新增 InputCostPerImageToken 字段并解析
- GetModelPricing 将其映射到 ModelPricing.ImageInputPricePerToken

计费拆分算术(computeTokenBreakdown)已支持图/文输入分价,本提交补齐
全局定价路径的数据来源。相关 #4386。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015wcJTKDddxXSQrepSs3wrU
2026-07-15 09:23:35 -07:00
王鹏 3db00d3fee fix(openai): fail over account-specific body limits 2026-07-16 00:19:20 +08:00
superman2003 e8cc1fe26b feat(frontend): add Grok key setup templates 2026-07-16 00:16:21 +08:00
superman2003 410ea8490c fix(grok): allow passive Codex image tool declarations 2026-07-16 00:16:21 +08:00
jjaw a8a8a58f65 优化批量账户事件的调度重建范围 2026-07-16 00:11:17 +08:00
Tian Lee 0765d10c1d feat: 增加上游 Sub2API 计费倍率探测与账号展示 2026-07-15 23:58:46 +08:00
王鹏 40b8f04a6a fix(openai): scope transient cooldowns by model 2026-07-15 22:52:35 +08:00
Tian Lee f59a6ed74c feat: 增加 API Key 计费倍率自省接口 2026-07-15 22:42:53 +08:00
王鹏 5e4da92dec fix(openai): retry explicitly rejected Responses fields 2026-07-15 22:37:30 +08:00
wucm667 56650d6aed fix(openai): normalize Responses Lite reasoning context 2026-07-15 22:23:57 +08:00
wucm667 2fe7df9b81 fix(openai): reject image models on chat completions 2026-07-15 22:22:51 +08:00
王鹏 4f641208a0 fix(openai-ws): close ingress reads cleanly 2026-07-15 22:15:44 +08:00
haruka df247b4364 docs: document async image task API 2026-07-15 22:14:34 +08:00
haruka 134179085c feat: add async image generation tasks 2026-07-15 22:13:37 +08:00
shaw eb2b8632de fix(frontend): 修复 Grok OAuth 建号缺上游配置入口与 JSON 导入渲染崩溃
- CreateAccountModal 为 Grok OAuth 新增自定义上游地址与请求头覆写区块,
  经统一校验注入授权码兑换/RT 批量/SSO 批量三条创建路径(授权码路径
  在兑换前校验,避免烧掉一次性 code)
- JSON 导入示例文案内嵌花括号被 vue-i18n 消息编译器当占位符解析,
  渲染时抛 Invalid token in placeholder 炸掉面板:示例移出 i18n 硬编码;
  同类修复 settings 的死键 claudeOAuthSystemPromptBlocksPlaceholder(删)
  与 Hint 中被吞掉的 {billing_header}(字面量转义)
- 新增 localesMessageCompile 守卫测试:预编译中英全部文案,拦截非法占位符
- 面板打开后 scrollIntoView + 聚焦,避免在弹窗滚动容器视野外展开
- 删除「填入模板」按钮及三平台模板常量(产品决策:无意义)
- 抽取 HeaderOverrideEditor 共享组件,消除 Create/Edit/BulkEdit 三处重复
2026-07-15 22:05:59 +08:00
drgnchan 858f3e4a78 fix(frontend): preserve horizontal table scrolling on tablets 2026-07-15 21:57:08 +08:00
王鹏 716fcc6f3d fix(openai): reject malformed WS v2 events 2026-07-15 21:20:41 +08:00
Wesley Liddick be6cd1250c Merge pull request #4367 from Wei-Shaw/feat/grok-custom-base-url-and-headers
feat(grok): 支持账号级自定义上游地址与请求头覆写
2026-07-15 20:55:16 +08:00
Wesley Liddick 34015a1791 Merge pull request #4359 from catoncat/agent/fix-agent-identity-import-expiry
fix(openai): make Agent Identity usable end to end
2026-07-15 20:55:05 +08:00
Wesley Liddick a733e66330 Merge pull request #4358 from DanisJiang/feat/admin-recharge-affiliate-rebate
feat(affiliate): support rebates for admin balance deposits
2026-07-15 20:54:48 +08:00
Wesley Liddick 960d1886f3 Merge pull request #4323 from turingcat/feat/plan-currency-label
feat(payment): 订阅套餐支持币种标注,区分 $ 符号对应币种
2026-07-15 20:54:34 +08:00
shaw 221581400b feat(grok): 支持账号级自定义上游地址与请求头覆写
将账号级请求头覆写从 anthropic/openai 的 api_key 账号扩展到 Grok 的
api_key 与 oauth 账号,并放开 Grok OAuth 账号的自定义上游地址(仅作用于
转发端点,授权与 token 刷新链路不变)。

后端:
- IsHeaderOverrideEligible 扩展到 Grok(api_key+oauth),禁止名单新增
  x-grok-conv-id(逐请求会话路由头)。
- 所有 Grok 上游请求路径接线 ApplyHeaderOverrides(Responses/Chat 桥/
  媒体/配额探测/billing 探测/连通性测试),统一置于内置默认头之后。
- GetGrokBaseURL/GetGrokMediaBaseURL 放开 OAuth 自定义地址:官方地址
  视同未定制回落官方网关,仅显式第三方 host 改发转发流量。
- 非官方 host 允许任意 path 前缀,官方 host 仍强制 /v1。
- OAuth base_url 校验按 host 判定官方/自定义,自定义 host 恒受运营方
  URL 策略约束,不受 XAI_ALLOW_UNSAFE_URL_OVERRIDES 调试开关放宽。
- 给 GrokQuotaService 注入 config,使配额/billing 探测与转发共用同一
  URL 策略。

前端:
- Edit 模态为 Grok OAuth 账号新增「自定义上游地址」开关。
- 请求头表单新增 JSON 快速导入与按 JSON 一键复制(复用 useClipboard,
  兼容非安全上下文 HTTP 页面)。
- 门控改为平台×类型判定,Bulk 批量 base_url 增加格式校验,zh/en 文案同步。
2026-07-15 20:30:23 +08:00
cat c352d99d92 fix(openai): 调整 Agent Identity 授权入口层级 2026-07-15 20:03:47 +08:00
cat 2147da682b fix(openai): 修复 Agent Identity 审查问题 2026-07-15 18:30:16 +08:00
cat 12e6e70775 fix(openai): 补全 Agent Identity Codex 能力 2026-07-15 17:52:10 +08:00
cat 3b5072187a feat(openai): 增加 Agent Identity 独立导入入口 2026-07-15 17:52:10 +08:00
cat 529744c7c7 fix(openai): 修复 Agent Identity 导入过期校验 2026-07-15 17:52:10 +08:00
Yuhao Jiang 736824dd7a feat(affiliate): add admin recharge rebate option 2026-07-15 04:28:55 -05:00
turingcatandClaude Fable 5 705da4f610 feat(payment): 补充订阅套餐币种字段的 SQL 迁移文件
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 16:59:00 +08:00
github-actions[bot] d515c3045c chore: sync VERSION to 0.1.156 [skip ci] 2026-07-15 08:51:27 +00:00
Wesley Liddick 12f991dde8 Merge pull request #4241 from heathermhuang/codex/fix-grok-admin-refresh-routing
fix(grok): route generic admin refresh through Grok OAuth
2026-07-15 16:22:26 +08:00
shaw 4e4ce440b3 fix(test): align duplicate account test with new NewAccountHandler signature 2026-07-15 16:13:22 +08:00
shaw bdb5be1c42 Merge remote-tracking branch 'origin/main' into pr4241-fix 2026-07-15 16:11:28 +08:00
Wesley Liddick 0de768e8be Merge pull request #4221 from heathermhuang/codex/fix-grok-oauth-pool-health
fix(grok): refresh OAuth pools proactively
2026-07-15 16:07:09 +08:00
Wesley Liddick d348193179 Merge pull request #4262 from wucm667/fix/issue-4245-root-models-alias
fix(codex): add root models compatibility alias
2026-07-15 16:06:59 +08:00
Wesley Liddick bac925624f Merge pull request #4289 from Tiantianr/fix/openai-ws-first-message-timeout
fix(openai-ws): make first-message timeout configurable
2026-07-15 15:45:24 +08:00
Wesley Liddick 651bb019d5 Merge pull request #4346 from xiaohei210509/agent/handle-codex-image-function-tool
fix(openai): preserve Codex image function tools during bridge injection
2026-07-15 15:35:07 +08:00
Wesley Liddick 4de53b61b8 Merge pull request #4339 from wp-a/codex/read-tool-stream-finalization
fix(apicompat): sanitize complete Read tool argument streams
2026-07-15 15:16:24 +08:00
Wesley Liddick dba6cefb6b Merge pull request #4340 from wp-a/codex/anthropic-incomplete-finalization
fix(apicompat): preserve incomplete stream finalization
2026-07-15 15:16:12 +08:00
Wesley Liddick 80560e48d2 Merge pull request #4341 from wp-a/codex/additional-tools-discriminator
fix(apicompat): scope additional tools parsing
2026-07-15 15:15:58 +08:00
xiaohei210509 ade5944201 fix(openai): preserve Codex image function tools 2026-07-15 15:10:43 +08:00
Wesley Liddick 44452d4a9d Merge pull request #4334 from lenzhang/fix/grok-vision-image-bridge
fix(grok): bridge image_url content parts through Responses API for vision models
2026-07-15 14:43:44 +08:00
Wesley Liddick 8e84071f21 Merge pull request #4307 from wp-a/fix/openai-first-output-timeout
fix(openai): bound native responses first output wait
2026-07-15 14:41:11 +08:00
Wesley Liddick 788b1cebf1 Merge pull request #4333 from superman2003/fix/grok-free-messages-function-cache
fix(grok): cache Free Messages function tools
2026-07-15 14:40:14 +08:00
王鹏 9b4a7d5d47 fix(apicompat): sanitize complete Read tool argument streams 2026-07-15 14:31:26 +08:00
王鹏 d6d9f6ea4f fix(apicompat): preserve incomplete stream finalization 2026-07-15 14:31:26 +08:00
王鹏 c3a425837c fix(apicompat): scope additional tools parsing 2026-07-15 14:31:26 +08:00
shaw 986310d0bd fix(lint): apply De Morgan's law to grok vision bridge gate (QF1001) 2026-07-15 14:30:47 +08:00
Wesley Liddick 2d218fbe61 Merge pull request #4317 from yan9651688/feat/account-one-click-copy
feat(accounts): add safe one-click account duplication
2026-07-15 14:23:35 +08:00
Wesley Liddick 9d1b44e6a0 Merge pull request #4324 from superman2003/fix/responses-lite-tool-compat
fix(openai): normalize Responses Lite tool declarations
2026-07-15 14:22:15 +08:00
Wesley Liddick 601a1d1662 Merge pull request #4305 from wp-a/fix/outbox-degraded-rebuild-latch
fix(scheduler): latch degraded outbox rebuilds
2026-07-15 14:22:03 +08:00
Wesley Liddick 83ef20bf8b Merge pull request #4299 from wp-a/fix/xai-oauth-unsafe-base-url-components
fix(xai): reject empty base URL queries
2026-07-15 14:21:42 +08:00
superman2003 3170c110a0 fix(openai): surface Messages stream error events 2026-07-15 14:07:01 +08:00
superman2003 08ea29428d fix(grok): recognize probed Free cache accounts 2026-07-15 14:07:01 +08:00
Wesley Liddick e4a0e69424 Merge pull request #4280 from bestony/feat/keys-id-column
feat(keys): add optional ID column on /keys page
2026-07-15 13:50:37 +08:00
Wesley Liddick 156cabd260 Merge pull request #4316 from fengshao1227/fix/grok-image-model-responses-reject
fix(grok): 拦截图片模型发往 Responses 端点,返回明确错误
2026-07-15 13:49:25 +08:00
Wesley Liddick febc5cbdd8 Merge pull request #4319 from feeeei/main
统一gork使用模板中的名称风格
2026-07-15 13:49:07 +08:00
Wesley Liddick 3e30862ddd Merge pull request #4295 from caigee-cmd/perf/direct-anthropic-chatcompletions-bridge
perf(apicompat): force-chat 路径直转 Anthropic↔ChatCompletions,跳过 Responses 中间层
2026-07-15 13:46:56 +08:00
王鹏 9950f4a2e2 fix(scheduler): latch degraded outbox rebuilds 2026-07-15 13:24:08 +08:00
lenzhang d5bc576b4f fix(grok): bridge image_url content parts through Responses API for vision models
The eligibility gate in grokChatResponsesBridgeEligibility rejected any
structured content (arrays), including standard OpenAI image_url parts.
This forced image-bearing requests to fall back to raw Chat Completions
forwarding, where non-Composer models have no image bridge — silently
dropping the images or causing upstream errors.

Changes:
- Allow content arrays containing only text and image_url parts to pass
  eligibility, so ChatCompletionsToResponses can convert them to
  input_image parts that Grok vision models natively support.
- Force image-bearing requests to use Responses even when no prompt
  cache identity is available, since the raw path cannot forward images
  for non-Composer models.
- Add grokChatStructuredContentBridgeable helper with conservative
  validation: unknown part types (e.g. input_audio) still fall back.
- Update tests: image_url content is now bridgeable; add cases for
  text+image, text-only arrays, unknown parts, and empty arrays.
2026-07-14 22:24:03 -07:00
superman2003 f041b5cf0a fix(grok): cache Free Messages function tools 2026-07-15 13:05:13 +08:00
王鹏 fc4089f292 fix(openai): bound native responses first output wait
Add an opt-in first semantic output budget for native HTTP Responses, including response-header wait. Keep preamble and keepalive bytes non-semantic so a stalled account can fail over once without replaying its response IDs. Defaults remain disabled.

Related to #4201, #4185, and #4248. Complements the HTTP/2 dead-connection fix in #4207.
2026-07-15 13:01:16 +08:00
王鹏 e8e360c802 fix(xai): reject unsafe base URL components 2026-07-15 12:50:15 +08:00
shaw 7b51271a84 fix(apicompat): default stop_reason for empty-choices responses
Adversarial re-verification found one more divergence from the
double-conversion chain: an upstream 200 with empty choices (or a nil
response) left stop_reason as an empty string, while the old chain
reports end_turn. Derive the fallback from the content blocks — the
guard never fires when choices exist, since every finish_reason maps to
a non-empty stop_reason.

Also strengthen the equivalence tests: compare tool_use Content[].Input
and tool_call Function.Arguments across bridges, and add an
empty-choices stop_reason parity case.
2026-07-15 11:44:47 +08:00
superman2003 bc6d9c47d2 fix(openai): normalize Responses Lite tool declarations 2026-07-15 11:37:38 +08:00
shaw 430fd8f20a fix(apicompat): align direct bridge edge semantics with double conversion
Adversarial review of the direct bridge found divergences from the
double-conversion chain it replaces; all are now aligned and covered by
tests that fail against the previous implementation:

- flush argument fragments buffered before a deferred tool announcement,
  and announce name-less tools at finalize, so no tool arguments are lost
  when upstreams stream arguments before the name
- fold text-only user array content into a single string; parts form only
  when an image requires it (strict chat upstreams reject array content)
- drop tool_choice pointing at undeclared tools and unknown choice types
- treat cache_write_tokens/cache_creation_tokens as alternate spellings
  (prefer write), not additive
- generate a response id when the upstream omits one
- derive stop_reason from blocks for content_filter/unknown finish reasons
- emit input_json_delta "{}" when a tool block closes without argument
  deltas
2026-07-15 11:29:22 +08:00
turingcatandClaude Fable 5 2bbdd47002 feat(payment): 订阅套餐支持币种标注,区分 $ 符号对应币种
后台配置与用户端展示的套餐价格统一使用 $ 符号,而实际扣款币种随
支付渠道配置漂移(如 Stripe 配置 NZD 时按新西兰元扣款),用户易
误认为美元。本次为套餐新增可选的展示性币种标注:

- SubscriptionPlan 新增 currency 字段(ISO 4217 三字母码,默认空)
- 空值不展示任何标注,存量套餐行为完全不变
- 非空值复用 payment.NormalizePaymentCurrency 校验并规范化为大写
- 后台套餐编辑弹窗新增可选币种输入,列表价格列展示币种小字
- 用户端套餐卡片价格与划线原价旁展示币种小字
- 纯展示性质,不影响任何支付/扣款逻辑

Closes #4315

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 11:17:45 +08:00
li 6a61b2daca fix(grok): 拦截图片模型发往 Responses 端点,返回明确错误
Fixes #4301
2026-07-15 11:16:07 +08:00
Wesley Liddick 3f605c3543 Merge pull request #4303 from wp-a/fix/web-fingerprinted-asset-caching
fix(web): limit immutable caching to fingerprinted assets
2026-07-15 11:12:50 +08:00
Wesley Liddick 23796a1b34 Merge pull request #4291 from bestony/agent/user-server-timing/bes-26
feat: extend Server-Timing to authenticated user web APIs
2026-07-15 11:12:37 +08:00
Wesley Liddick 5b5e41450c Merge pull request #4310 from jianjianai/codex/perf-scheduler-final
perf(scheduler): 完善缓存桶生命周期并复用重建批次查询
2026-07-15 11:09:47 +08:00
Wesley Liddick 10798abe4f Merge pull request #4300 from wp-a/fix/frontend-datatable-row-cache
fix(frontend): clear stale DataTable row caches
2026-07-15 11:08:58 +08:00
Wesley Liddick 4344f6afb0 Merge pull request #4298 from wp-a/fix/openai-images-json-completion-boundary
fix(images): preserve JSON completion boundaries
2026-07-15 11:08:47 +08:00
Wesley Liddick ab369c363f Merge pull request #4290 from wucm667/fix/issue-4287-preserve-antigravity-rt
fix(antigravity): 保留手动输入的 refresh token
2026-07-15 11:08:37 +08:00
Wesley Liddick 6460b9895c Merge pull request #4297 from wp-a/fix/openai-reset-credit-malformed-details
fix(openai): preserve reset count on malformed details
2026-07-15 11:08:25 +08:00
yan9651688 f7da6e2bc6 fix(accounts): prevent duplicate retries from crossing admins
Ambiguous idempotency-store failures can occur after the account transaction commits. Scope durable recovery markers to the authenticated admin, retain the operation key across reloads, and recover only an already committed copy without rerunning active work.

Constraint: Generic idempotent handlers may legitimately remain active while a recovery lookup is attempted

Rejected: Reclaim or rerun an in-progress duplicate request | can execute account creation concurrently

Rejected: Recover by source account and key alone | allows another admin to observe the committed copy

Confidence: high

Scope-risk: narrow

Reversibility: clean

Directive: Keep ambiguous-response recovery read-only and bind durable operation markers to the authenticated actor

Tested: Full Go unit suite, go vet, server build, integration-test compilation; frontend lint, typecheck, 1,030 Vitest tests, and production build

Not-tested: Docker-backed PostgreSQL integration runtime because Docker is unavailable

Related: Wei-Shaw/sub2api#1379

Related: Wei-Shaw/sub2api#2928
2026-07-15 10:51:13 +08:00
yan9651688 60ff61132d feat(accounts): make repeated static account setup safer
Admins often need another account with the same provider and routing configuration. Duplicate on the server so credentials never return to the browser, preserve exact group priorities atomically, start the copy paused, and recover the same copy after ambiguous idempotency-store failures.

Constraint: Admin account responses redact credentials, so duplication must remain server-side

Constraint: OAuth and setup-token credentials rotate and must not be shared across account rows

Rejected: Copy raw account JSON to the clipboard | exposes credentials outside the server

Rejected: Duplicate rotating credentials | account-scoped refresh locks can race token rotation

Confidence: high

Scope-risk: moderate

Reversibility: clean

Directive: Keep copies paused, avoid automatic upstream probes, and exclude rotating credential types unless token ownership is redesigned

Tested: Targeted Go tests, Go vet, server build; frontend lint, typecheck, Vitest suite, production build; integration test compiled

Not-tested: Docker-backed PostgreSQL execution because Docker is unavailable

Related: Wei-Shaw/sub2api#1379

Related: Wei-Shaw/sub2api#2928
2026-07-15 10:51:13 +08:00
feeeei 1acbb12c65 统一gork使用模板中的名称风格 2026-07-15 10:51:08 +08:00
shaw cf6aa1a5c3 fix(openai): 和解 #4304 与 #4306 的透传错误语义冲突
两个 PR 分别合并后在 main 上语义相撞(文本无冲突,CI 才暴露):
- #4306 把所有非 failover 透传错误重建为通用净化信封;
- #4304 要求确定性 context-window 错误不切号且文案对客户端可见
  (如触发客户端自动压缩),其测试断言原文可达。

和解方案(保留双方意图):
- 净化器拆出 writeOpenAIPassthroughErrorEnvelope;context-window 错误
  仍走本地 JSON 信封 + 净化头策略,但 message 使用脱敏后的上游消息,
  不再抹成通用文案;其余错误净化行为不变。
- RebuildsUpstreamErrors 的两个 5xx 用例改用非瞬时状态码(530/501):
  瞬时 5xx 对 API-key 账号已按 #4304 契约走 failover(由
  APIKeyPassthrough_Transient5xxTriggersFailover 覆盖),净化重建
  路径的 5xx 覆盖由非瞬时状态码继续承担。
2026-07-15 10:40:14 +08:00
Wesley Liddick 40a59c9e86 Merge pull request #4275 from jianjianai/codex/perf-u17-response-sse-flush
优化 Responses 流式事件边界刷新
2026-07-15 10:30:31 +08:00
Wesley Liddick 65d744d0e1 Merge pull request #4294 from caigee-cmd/fix/parallel-tool-use-ghost-delta
fix(apicompat): 并行 tool_use 幽灵 content_block_delta(index 错误)
2026-07-15 10:26:02 +08:00
Wesley Liddick 2381b6c104 Merge pull request #4304 from wp-a/fix/openai-passthrough-5xx-failover
fix(openai): fail over API-key passthrough 5xx
2026-07-15 10:20:44 +08:00
shaw a38220ebdc Merge origin/main into fix/openai-passthrough-5xx-failover (resolve #4269 conflicts)
# Conflicts:
#	backend/internal/service/openai_gateway_passthrough.go
2026-07-15 10:18:55 +08:00
Wesley Liddick 2ceaa4783c Merge pull request #4311 from jianjianai/codex/perf-openai-forwarding-final
perf(openai): 优化 Responses 图片意图判定与透传流式刷新
2026-07-15 10:12:05 +08:00
Wesley Liddick 9b86585909 Merge pull request #4296 from wp-a/fix/openai-responses-sse-json-boundaries
fix(openai): repair concatenated Responses stream events
2026-07-15 10:11:55 +08:00
Wesley Liddick 42d1bf298d Merge pull request #4306 from wp-a/fix/openai-passthrough-error-sanitization
fix(openai): sanitize passthrough upstream errors
2026-07-15 10:11:41 +08:00
shaw eb7933af4c fix(openai): 移除 #4269 合并时复活的旧版 Grok 错误路径处理
#4269 分支基于 #4212 之前的 main(merge-base da85cc7e),合并后把
ForwardAsAnthropic 错误路径上已被 #4212 重构移除的 Grok 块带了回来:
- xai.ParseQuotaHeaders 的 import 已被 main 删除,导致 main 编译失败;
- 该块与 failoverOpenAIUpstreamHTTPError 内部的 handleGrokAccountUpstreamError
  重复(后者第一步就用新解析器 parseGrokQuotaSnapshot 更新配额快照),
  保留会造成 Grok 错误双重处置。

删除整块,恢复 #4212 语义;#4269 的 agent identity 恢复逻辑保留不动。
2026-07-15 10:01:31 +08:00
Wesley Liddick 4355861ef2 Merge pull request #4269 from catoncat/agent/sub2api-agent-identity
feat(openai): support Codex Agent Identity authentication
2026-07-15 09:47:00 +08:00
Heatherm Huang 0c80d52573 test(grok): wire reconciliation in import probe fixture 2026-07-15 09:40:08 +08:00
Heatherm Huang 3a3b962de3 fix(grok): normalize refresh errors 2026-07-15 09:40:08 +08:00
Heatherm Huang b245ab5848 fix(grok): satisfy pool health lint 2026-07-15 09:40:08 +08:00
Heatherm Huang 6a62ea1b1d test(grok): synchronize refresh candidate fixture 2026-07-15 09:40:08 +08:00
Heatherm Huang 6b25900403 fix(grok): refresh OAuth pools proactively 2026-07-15 09:40:08 +08:00
Wesley Liddick 30df3f68e4 Merge pull request #4264 from lyon-le/perf/content-moderation-keyword-hot-path
perf(risk): 优化内容审核关键词热路径(优化性能)
2026-07-15 09:39:33 +08:00
Wesley Liddick 1c61225b28 Merge pull request #4271 from jianjianai/codex/perf-u10-ops-projection
优化 Ops 队列深度账号查询
2026-07-15 09:39:09 +08:00
Wesley Liddick 7cb8ece8d3 Merge pull request #4274 from jianjianai/codex/perf-u16-content-seed-scan
优化内容会话种子字段扫描
2026-07-15 09:38:59 +08:00
Wesley Liddick de52f7ba89 Merge pull request #4279 from bestony/agent/0268b42f/bes-21-groups-id-column
feat(admin): /admin/groups 列表设置新增 ID 列
2026-07-15 09:38:46 +08:00
Wesley Liddick 42ea78fb47 Merge pull request #4266 from StarryKira/agent/fix-codex-api-key-image-generation
fix(frontend): update Codex API key snippets for image generation
2026-07-15 09:38:34 +08:00
Wesley Liddick 8d13bbbea5 Merge pull request #4284 from zh239ns/codex/fix-openai-oauth-image-actual-size
fix(images): report decoded OAuth output dimensions
2026-07-15 09:37:34 +08:00
Wesley Liddick 125b03aee6 Merge pull request #4281 from bestony/feat/openai-ws-proxy-failed-host
fix(openai): include proxy host in websocket_proxy_failed logs
2026-07-15 09:37:04 +08:00
Wesley Liddick 65093591cd Merge pull request #4282 from bestony/feat/openai-failover-switching-proxy-host
fix(openai): include proxy host in upstream_failover_switching logs
2026-07-15 09:36:53 +08:00
Wesley Liddick 1f91b69ca6 Merge pull request #4288 from wucm667/fix/issue-4285-gpt56-account-cost
fix: 修复 GPT-5.6 长上下文账号成本统计
2026-07-15 09:36:43 +08:00
Wesley Liddick 9676b19fba Merge pull request #4313 from Wei-Shaw/fix/4257-cancel-aware-failover
fix(gateway): 客户端断开后 failover 静默终止,不再误报 502 账号耗尽
2026-07-15 09:36:13 +08:00
shaw a0593b0bf8 fix(gateway): 客户端断开后 failover 静默终止,不再误报 502 账号耗尽
上游请求经 detachUpstreamContext(WithoutCancel) 有意脱离客户端取消(保
计费),但 failover 循环仍用原始 c.Request.Context() 重新选号:客户端
断开后上游返回 520 等可 failover 错误时,重新选号必然得到 context
canceled,被误判为账号耗尽,记录并返回通用 502。

修复:客户端已断开 ⇒ failover 静默终止。

- 新增 failoverClientGone(c):请求 ctx 已取消时先停 compact 心跳
  (建立 happens-before,对齐其它终结路径),响应未提交则标 499
  (statusClientClosedRequest,与并发槽取消路径同惯例)
- 7 个 OpenAI 内联 failover 循环(Responses/Messages/chat_completions/
  embeddings/images/grok_media/alpha_search)加双 guard:换号前 +
  选号失败分支入口;guard 位于 ReportOpenAIAccountScheduleResult(false)
  之后、RecordOpenAIAccountSwitch/池模式重试之前,账号健康副作用
  (service 层 detached ctx)不受影响
- FailoverState.HandleFailoverError/HandleSelectionExhausted 入口加
  ctx.Err() 检查返回 FailoverCanceled,取消不再改动 failover 状态;
  全部 10 个 FailoverCanceled 分支统一调用 failoverClientGone 归类 499
- 上游 detach 与计费设计不变;真实上游 520 事件仍完整落 ops
  (面板显示码 COALESCE(upstream_status_code,status_code)=520,
  错误率/告警口径不变)

测试:新增 openai_responses_failover_cancel_test.go 复现 issue 场景
(520+取消 ⇒ 不切号、499、无 502 终态)+ 在线客户端对照(正常切换、
耗尽 502);failover_loop_test.go 补入口取消用例并修正取消语义断言。

Fixes #4257
2026-07-15 09:29:05 +08:00
Wesley Liddick accb918eca Merge pull request #4212 from heathermhuang/codex/fix-grok-oauth-credential-failover
fix(grok): fail over OAuth credential errors safely
2026-07-15 08:37:17 +08:00
jjaw 62be9db9df 补充调度缓存并发语义注释 2026-07-15 07:10:22 +08:00
jjaw 4aedbfc4a8 补充 OpenAI 转发复用边界注释 2026-07-15 06:59:00 +08:00
jjaw 143cab7bf5 复用重建批次内的账号查询 2026-07-15 05:31:50 +08:00
王鹏 536865032c fix(openai): sanitize passthrough upstream errors 2026-07-15 04:47:16 +08:00
jjaw 8edad3a455 清理全量重建中的过期调度桶 2026-07-15 04:23:06 +08:00
王鹏 91dc31ef39 fix(openai): fail over API-key passthrough 5xx 2026-07-15 04:21:38 +08:00
jjaw 78e09a0f1a 复用请求级图片生成意图判断 2026-07-15 04:20:11 +08:00
王鹏 60bae26a2f fix(web): limit immutable caching to fingerprinted assets 2026-07-15 04:00:46 +08:00
jjaw 43a2c13173 优化图片生成意图字段扫描 2026-07-15 03:54:32 +08:00
王鹏 f863f664ac fix(frontend): clear stale DataTable row caches 2026-07-15 03:33:35 +08:00
王鹏 2c13ed32e7 fix(images): preserve JSON completion boundaries 2026-07-15 03:15:47 +08:00
王鹏 d4da138cf5 fix(openai): preserve reset count on malformed details 2026-07-15 02:51:56 +08:00
王鹏 b286cca0c4 fix(openai): repair concatenated Responses stream events 2026-07-15 02:41:23 +08:00
jjaw 31a0efc747 退休已停用分组的调度缓存桶 2026-07-15 01:07:26 +08:00
蔡及 22e97898bb fix: gofmt on parallel tool regression test 2026-07-15 00:59:28 +08:00
蔡及 1eb79df0d3 fix: golangci-lint issues (unused helpers, empty branch, errcheck, gofmt) 2026-07-15 00:58:42 +08:00
蔡及 07732a5a35 test: add regression tests for parallel tool_use ghost delta (#4193)
Three tests covering the CC→Responses→Anthropic finalize path:
- TestStreamingParallelToolUseNoGhostDelta: full end-to-end with two
  parallel tool_calls, asserts every content_block_delta targets a
  started block
- TestStreamingParallelToolUseSecondToolPackedArgsDone: focused test
  where tool 1 streams deltas and tool 2 has packed .done args
- TestStreamingThreeParallelToolsAllPackedDone: three tools all with
  packed .done, the most extreme case

All three fail on unfixed code (ghost deltas on wrong indices) and
pass after the fix.
2026-07-15 00:47:04 +08:00
蔡及 3504b8cc88 perf: direct Anthropic↔ChatCompletions bridge for force-chat accounts
Skip the Responses API intermediate representation on the /v1/messages
force-chat path. Previously every streaming token ran through two state
machines (CC→Responses→Anthropic); now it runs through one (CC→Anthropic).

New file backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go:
- AnthropicToChatCompletionsRequest: request-side direct conversion
- ChatCompletionsResponseToAnthropic: non-stream response direct conversion
- ChatCompletionsChunkToAnthropicEvents + Finalize: single streaming state machine

openai_gateway_messages_chat_fallback.go rewired to use the direct bridge.
Existing 7 ForceChatCompletions end-to-end tests pass unchanged; 22 new
unit tests added including equivalence tests vs the double-conversion path.
2026-07-15 00:44:13 +08:00
蔡及 4f3b5110e2 fix: parallel tool_use ghost content_block_delta (index error)
resToAnthHandleFuncArgsDone used state.ContentBlockIndex directly
instead of looking up from OutputIndexToBlockIdx like
resToAnthHandleFuncArgsDelta does. When multiple tool_calls arrive
in parallel and arguments come as a packed .done (no prior delta),
the second+ tool would emit content_block_delta on an index that
was never content_block_start'ed, causing Claude Code to report
"Content block not found".

Fix: resolve block index from OutputIndexToBlockIdx, and skip the
delta if the block is already closed or the index doesn't match
the current open block.

Closes #4193
2026-07-15 00:44:09 +08:00
bestony 324a491671 feat: extend Server-Timing to authenticated user web APIs
Mirror the Admin UI Server-Timing opt-in for user-facing pages so
authenticated callers can inspect total/app/db/redis/deps metrics on
session, profile, keys, usage, payment, and related user APIs.

- Collect when X-User-UI-Request=1 or path is on the user allowlist
- Emit for non-admin only on allowlisted paths (header is not auth)
- Exclude payment public/webhook surfaces
- Mark matching SPA requests and allow the new CORS request header
2026-07-15 00:23:27 +08:00
jjaw 9da4cfbdcc 增加调度分组生命周期租约 2026-07-15 00:12:40 +08:00
jjaw 5e43c7faac 优化透传流事件边界刷新 2026-07-15 00:00:40 +08:00
wucm667 b28ac90364 fix(antigravity): preserve manually entered refresh token 2026-07-14 23:58:00 +08:00
jjaw 8523a52c07 优化调度缓存桶退休原语 2026-07-14 23:08:17 +08:00
haruka ad3522e34b fix(frontend): preserve legacy Codex config mode 2026-07-14 22:41:38 +08:00
Tiantianr 74e296703a fix(openai-ws): make first-message timeout configurable
Add a dedicated client first-message timeout while preserving the legacy 30-second default.

Use the resolved value for both the WebSocket read deadline and structured timeout logs, and document tuning for large requests or slow links.

Add configuration, validation, handler, and resolver regression coverage.

Refs #4158
2026-07-14 22:40:05 +08:00
wucm667 25e6688af6 [verified] fix: apply long-context pricing to account cost 2026-07-14 22:31:39 +08:00
jjaw 92edda2f6e 优化透传图片意图判定复用 2026-07-14 21:57:26 +08:00
zh239ns bef520b191 fix(images): report decoded OAuth output dimensions
ChatGPT OAuth may normalize explicit image size controls to auto while returning smaller raster bytes. Decode final image headers so Images API metadata and tier billing reflect the actual output for both streaming and non-streaming OAuth responses.
2026-07-14 20:31:17 +08:00
bestony ba5b6970be fix(openai): include proxy host in upstream_failover_switching logs
Enrich openai.upstream_failover_switching structured logs with proxy
identity fields (proxy_id, proxy_name, proxy_host, proxy_port) so
operators can see which outbound proxy failed when switching accounts.
Matches the existing gateway.forward_failed / websocket_proxy_failed
logging pattern.
2026-07-14 19:33:56 +08:00
bestony b000aac474 fix(openai): include proxy host in websocket_proxy_failed logs
Add proxy_id/proxy_name/proxy_host/proxy_port fields to openai.websocket_proxy_failed so operators can identify which proxy failed without extra lookups. Matches the existing gateway.forward_failed logging pattern.
2026-07-14 19:32:49 +08:00
cat 6485081122 feat(frontend): 标明 OpenAI 认证模式 2026-07-14 19:25:13 +08:00
cat ec7c1b6f72 fix(openai): 修复 Agent Identity CI 问题 2026-07-14 19:24:56 +08:00
bestony eedd9b147d feat(admin): add optional ID column on groups list
Add a toggleable group ID column in /admin/groups column settings.
It shows the group id (e.g. #1), is hidden by default for new and
existing admins via column-settings version migration, and remains
sortable against the existing backend sort_by=id support.
2026-07-14 19:19:22 +08:00
bestony 2157ee344b feat(keys): add optional ID column on /keys page
Expose API key ID in the keys table column settings so users can show
or hide it. Hidden by default; bump column-settings version so existing
preferences also keep ID hidden until toggled on.
2026-07-14 19:18:53 +08:00
cat d68a2aac1a chore(openai): 同步上游并解决认证冲突 2026-07-14 19:04:04 +08:00
haruka f09d63f54e fix(frontend): address Codex config review feedback 2026-07-14 18:31:06 +08:00
cat f479a5d10c fix(openai): 收紧 Agent Identity task 生命周期 2026-07-14 18:09:59 +08:00
cat bd1399f81e fix(openai): 允许 Agent Identity 无令牌拨号 WS 2026-07-14 17:41:17 +08:00
Lyonle 8b37ba8828 perf(risk): optimize keyword moderation hot path 2026-07-14 17:39:49 +08:00
cat 10aa88aab9 fix(openai): 补齐身份失效恢复路径 2026-07-14 17:19:15 +08:00
wucm667 806bb23053 fix: add root Codex models alias 2026-07-14 17:16:24 +08:00
cat 3fe7b4da78 fix(openai): 闭合直通 WS 恢复与错误脱敏 2026-07-14 17:05:47 +08:00
cat 57cf2df09f fix(openai): 收紧 Agent Identity 恢复与脱敏 2026-07-14 17:05:47 +08:00
cat 1dab126944 feat(openai): 支持 Agent Identity 认证 2026-07-14 17:05:46 +08:00
shaw da85cc7e47 chore: update sponsors 2026-07-14 17:01:39 +08:00
jjaw 86800a8cd0 优化内容会话种子字段扫描 2026-07-14 16:53:21 +08:00
haruka e2028a814e fix(frontend): update Codex API key snippets 2026-07-14 16:41:44 +08:00
jjaw 23f93a9348 优化 Responses 流式事件边界刷新 2026-07-14 16:38:37 +08:00
jjaw a8afc20969 优化 Ops 队列深度账号查询 2026-07-14 16:18:26 +08:00
github-actions[bot] 7c717365ef chore: sync VERSION to 0.1.155 [skip ci] 2026-07-14 07:08:08 +00:00
Heatherm Huang 4c764d3fc9 test(grok): use healthy quota account fixture 2026-07-14 15:07:09 +08:00
Heatherm Huang a13a6113dd fix(grok): route generic account refresh correctly 2026-07-14 15:00:52 +08:00
Heatherm Huang cb7dfea5a9 test(grok): update default model fixture 2026-07-14 14:55:30 +08:00
Heatherm Huang 81b8b78378 fix(grok): resolve upstream OAuth imports 2026-07-14 14:55:30 +08:00
Heatherm Huang b32b815e46 fix(grok): harden OAuth pool recovery 2026-07-14 14:55:30 +08:00
Heatherm Huang 91ae671a58 fix(grok): satisfy lint checks 2026-07-14 14:55:30 +08:00
Heatherm Huang 343390057d fix(grok): fail over OAuth credential errors safely 2026-07-14 14:55:30 +08:00
Wesley Liddick 41cec0db05 Merge pull request #4154 from sir1st/codex/fix-native-responses-namespace
fix: support namespace tools in native responses
2026-07-14 14:51:14 +08:00
shaw fa1641f05f fix: keep namespace verbatim on WSv2 forwards and check test type assertions
WSv2 egress relays upstream events verbatim without the HTTP-path
namespace restore, so flattening requests that take the WSv2 branch
would surface flattened tool names the client cannot match. Resolve
the WS transport decision before flattening and skip flattening only
when the request will actually go WSv2 (passthrough accounts return
via HTTP before the WSv2 branch and still flatten).

Also check all type assertions in responses_namespace_test.go to
satisfy golangci-lint errcheck.
2026-07-14 14:48:22 +08:00
shaw 252ef8b73a Merge origin/main into codex/fix-native-responses-namespace
Resolve conflict in openai_gateway_passthrough.go streaming path: keep
main's normalizeCompletedImageGenerationStatus normalization ahead of
this branch's namespace restore block, mirroring the established order
in openai_gateway_response_handling.go.
2026-07-14 14:45:04 +08:00
Wesley Liddick 53004e2e90 Merge pull request #4238 from superman2003/feat/grok-monitor-auto-probe
feat(grok): add import probes and channel monitoring
2026-07-14 14:23:04 +08:00
Wesley Liddick 11ed22d052 Merge pull request #4240 from chensunlai/fix/openai-responses-lite-image-display
fix(openai): preserve client image tools in Responses Lite
2026-07-14 14:22:50 +08:00
Wesley Liddick 03646e9434 Merge pull request #4239 from fengshao1227/fix/grok-reasoning-content-null
fix(grok): 清洗 reasoning 项中 content: null 避免 xAI 422
2026-07-14 14:22:42 +08:00
li 2e9b8d9a64 fix: resolve golangci-lint errcheck and gofmt violations in reasoning test
Use two-value type assertions with require.True(t, ok) to satisfy
errcheck, and run gofmt to fix alignment.
2026-07-14 13:23:57 +08:00
chensunlai 2f715baf05 fix(openai): preserve client image tools in Responses Lite 2026-07-14 05:19:13 +00:00
li ff639ba757 fix(grok): 清洗 reasoning 项中 content: null 避免 xAI 422
Fixes #4237
2026-07-14 13:13:32 +08:00
superman2003 16d1fbfd4e fix(ci): keep probe scheduler snapshots test-only 2026-07-14 12:45:03 +08:00
superman2003 d2d3fcf57b feat(frontend): show Grok monitoring and Free plan badge 2026-07-14 12:24:42 +08:00
superman2003 0a64a6d8ce feat(monitor): support Grok channel health checks 2026-07-14 12:24:42 +08:00
superman2003 d8a07e91a5 fix(grok): stabilize prompt cache routing identity 2026-07-14 12:24:42 +08:00
superman2003 a1b5c75ca3 feat(grok): probe newly imported OAuth accounts 2026-07-14 12:24:42 +08:00
Wesley Liddick 69bc6a87dd Merge pull request #4231 from superman2003/fix/grok-free-rolling-24h-20260714
fix(grok): use rolling 24h free quota estimate
2026-07-14 11:31:48 +08:00
Wesley Liddick c361b0606d Merge pull request #4219 from zh239ns/codex/fix-openai-images-nonstream-keepalive
fix(images): add opt-in non-stream JSON keepalive
2026-07-14 11:30:28 +08:00
shaw ac7a141a24 fix(images): align OAuth pre-response size snapshot with keepalive-adjusted metric
The snapshot taken before dispatching the OAuth response handler still used
raw c.Writer.Size(), while handleOpenAIImagesOAuthResponseError compares it
against the keepalive-adjusted size. From the second failover round on, the
previous round's heartbeat bytes made the raw snapshot positive while the
adjusted size stayed -1, so a retryable upstream error was misjudged as
'response already written': the failover was swallowed and the client got a
committed 200 with a whitespace-only body.

Snapshot now uses OpenAIImagesJSONKeepaliveAdjustedWrittenSize, matching the
comparison side. Regression test simulates a prior-round heartbeat before
ForwardImages and asserts the retryable error still converts to
UpstreamFailoverError (verified red without the fix, green with it).
2026-07-14 11:24:44 +08:00
Wesley Liddick 527279c953 Merge pull request #4225 from BenjaminAaron196/fix/reset-credit-count-fallback
fix(openai): 提升主动重置次数识别的可靠性
2026-07-14 11:11:54 +08:00
Wesley Liddick 9717699367 Merge pull request #4218 from chensunlai/fix/openai-image-generation-final-status
fix(openai): complete streamed image generation results
2026-07-14 11:00:40 +08:00
Wesley Liddick 2590b86e31 Merge pull request #4204 from jianjianai/codex/fix-scheduler-rebuild-coalescing
修复调度器并发触发重复全量重建
2026-07-14 11:00:09 +08:00
Wesley Liddick 24d908b257 Merge pull request #4203 from jianjianai/codex/fix-scheduler-pending-lag
修复调度器使用已消费事件计算 outbox 延迟
2026-07-14 10:59:57 +08:00
Wesley Liddick 9c3c560d49 Merge pull request #4206 from jianjianai/codex/fix-scheduler-proxy-expiry-event
修复代理到期改投触发全量调度重建
2026-07-14 10:59:43 +08:00
Wesley Liddick 8711882918 Merge pull request #4205 from jianjianai/codex/fix-scheduler-auto-pause-event
修复账号到期暂停触发全量调度重建
2026-07-14 10:59:34 +08:00
Wesley Liddick 27fcbace89 Merge pull request #4207 from hongheshan-svg/upstream-pr/http2-keepalive
fix(openai): 为 Codex HTTP/2 上游启用 PING 健康探测,剔除死连接
2026-07-14 10:59:22 +08:00
superman2003 30d4301bea fix(grok): use rolling 24h free quota estimate 2026-07-14 10:53:43 +08:00
Wesley Liddick 5d1c577cb2 Merge pull request #4217 from jinfeijie/feat/grok-sso-device-oauth
feat(grok): 支持 Web SSO 批量导入并转换为 Build OAuth
2026-07-14 10:25:56 +08:00
shaw d41a10111d Merge remote-tracking branch 'origin/main' into feat/grok-sso-device-oauth
# Conflicts:
#	frontend/src/api/admin/grok.ts
2026-07-14 10:19:16 +08:00
Wesley Liddick 93f2ccf3a5 Merge pull request #4188 from superman2003/fix/grok-free-quota-429-20260713
feat(grok): improve free quota probing and usage display
2026-07-14 10:14:41 +08:00
Wesley Liddick a8927d8ec7 Merge pull request #4214 from bestony/agent/devbox-coding/25c66071-1783957460
feat: add opt-in Server-Timing for Admin UI APIs
2026-07-14 10:14:17 +08:00
Wesley Liddick 623a9647c0 Merge pull request #4110 from gebdalaoli-arch/agent/fix-codex-models-apikey-upstream
fix: proxy Codex model manifests through API key upstreams
2026-07-14 10:13:56 +08:00
Wesley Liddick 41c71a1528 Merge pull request #4216 from bestony/agent/devbox-coding/3ff3c99d
feat(ops): add Host filtering to system logs
2026-07-14 10:13:40 +08:00
Wesley Liddick 1847bdf9fd Merge pull request #4179 from scientist-blockchian/fix/messages-exact-model-mapping
fix(openai): preserve exact messages dispatch mappings
2026-07-14 10:13:27 +08:00
Wesley Liddick 7358810659 Merge pull request #4180 from jianjianai/fix/openai-request-view-single-scan
fix(openai): avoid repeated request body scans
2026-07-14 10:13:11 +08:00
Wesley Liddick 029e5ce9f9 Merge pull request #4104 from gebdalaoli-arch/codex/fix-image-gen-hosted-tool-conflict
[codex] avoid duplicate hosted image tool injection
2026-07-14 10:13:00 +08:00
benjamin 8cd848313c fix(openai): improve reset credit quota detection 2026-07-14 10:07:48 +08:00
jjaw 9033e14bb7 修复账号到期暂停触发全量重建 2026-07-14 09:49:57 +08:00
jjaw 8f328d4ab3 修复代理到期改投触发全量重建 2026-07-14 09:23:02 +08:00
Wesley Liddick 74e78c3de0 Merge pull request #4115 from Arron196/fix/api-double-billing
fix: 按账号控制 OpenAI 长上下文计费
2026-07-14 08:38:57 +08:00
zh239ns 002c0b9fda fix(images): keep non-stream requests alive 2026-07-14 07:39:21 +08:00
chensunlai f2ca16577e fix(openai): complete streamed image generation results 2026-07-13 21:24:53 +00:00
jinfeijie bot 6c441637b0 fix(grok): 移除账号类型页 SSO 卡片入口
SSO 仅作为 OAuth 流程内的输入方式,避免与 OAuth/API Key 卡片风格冲突。
2026-07-14 01:47:53 +08:00
bestonyandmultica-agent 0f2ec134b5 fix(ops): bound indexed log host length
Co-authored-by: multica-agent <github@multica.ai>
2026-07-14 01:29:47 +08:00
bestonyandmultica-agent 2c2e50ba58 feat(ops): add host filtering to system logs
Co-authored-by: multica-agent <github@multica.ai>
2026-07-14 01:29:46 +08:00
bestonyandmultica-agent 966afd1b4b fix: preserve instrumented client contracts
Co-authored-by: multica-agent <github@multica.ai>
2026-07-14 01:29:30 +08:00
bestonyandmultica-agent 54d228dda5 feat(admin): add opt-in server timing metrics
Co-authored-by: multica-agent <github@multica.ai>
2026-07-14 01:29:30 +08:00
jinfeijie bot ad4bf5c60d feat(grok): 支持 Web SSO 批量导入并转换为 Build OAuth
新增 Grok Web SSO → xAI Device Flow → Grok Build OAuth 导入链路,
支持管理员批量粘贴 SSO key 创建 OAuth 账号。

- 后端:ConvertSSOToBuild、ConvertFromSSO、POST /admin/grok/sso-to-oauth
- 批量:3 worker 并发,失败跳过并汇总 created/failed,worker panic recover
- 无 refresh_token 时写入 expires_at 并强制 auto_pause_on_expired
- 前端:SSO Cookie 导入入口、动态超时、中英文案、部分成功不关弹窗
- 测试:pkg/service/handler/前端超时单测;本地 Docker 真实 SSO e2e 通过
2026-07-14 01:09:07 +08:00
benjamin e9fb5983cd fix(billing): 默认关闭 OpenAI 长上下文计费 2026-07-13 23:32:16 +08:00
hongheshan-svgandClaude Opus 4.8 98027cdded fix(openai): enable HTTP/2 keep-alive PING to evict dead Codex connections
Codex/OpenAI upstream switched from a WebSocket pool to HTTP/2. The
outbound H2 transport set neither ReadIdleTimeout nor ResponseHeaderTimeout
(the OpenAI profile forces ResponseHeaderTimeout=0), so a pooled H2
connection silently killed by a proxy/NAT becomes a "dead connection":
both ends believe it is alive and a request assigned to it hangs until the
OS TCP retransmit timeout (minutes) before the first byte — observed as an
8m37s TTFT with an eventual 200. Occasional (only when a request lands on a
dead pooled conn) and across all groups (shared OpenAI transport); worse on
larger idle pools.

Explicitly configure http2 on the openai_h2 transport and enable active
PING health checks (ReadIdleTimeout=15s, PingTimeout=15s) so dead
connections are detected and evicted at the source, instead of relying on
ResponseHeaderTimeout as an after-the-fact backstop. Scoped to the
openai_h2 path only; Claude/Gemini (default) and h1 modes are untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 23:31:18 +08:00
jjaw 831862b924 修复调度全量重建并发合并 2026-07-13 21:59:55 +08:00
jjaw a0778e9a42 修复调度器使用已消费事件计算延迟 2026-07-13 21:56:47 +08:00
gebdalaoli-arch 3c68b2e369 fix: fail over Codex manifest accounts 2026-07-13 20:36:37 +08:00
superman2003 c896cacf6d feat(grok): improve free quota probing and usage 2026-07-13 19:49:56 +08:00
gebdalaoli-arch ed31a52424 fix: stabilize API key Codex manifest refreshes 2026-07-13 19:31:38 +08:00
benjamin f63d168ae0 fix(billing): 检查长上下文开关类型断言 2026-07-13 18:45:06 +08:00
benjamin 3e4d48e010 Merge remote-tracking branch 'upstream/main' into fix/api-double-billing
# Conflicts:
#	frontend/src/components/account/EditAccountModal.vue
2026-07-13 18:06:44 +08:00
zz80900 40ec74b9fc fix(openai): preserve exact messages dispatch mappings
Treat a non-empty messages dispatch model as a caller-approved fallback after account-level mapping, without reclassifying the requested Claude family.\n\nAdd Fable forwarding and endpoint boundary regression coverage.\n\nFixes #4177
2026-07-13 17:57:08 +08:00
benjamin a0ac5e0240 fix(billing): 默认开启 OpenAI 长上下文计费 2026-07-13 17:55:01 +08:00
jjaw 8d5bc448b5 fix(openai): avoid repeated request body scans 2026-07-13 17:43:59 +08:00
Wesley Liddick 7d239d62e8 Merge pull request #4173 from heathermhuang/codex/fix-grok-oauth-media-routing
fix(grok): keep OAuth media on the official API
2026-07-13 17:37:00 +08:00
Wesley Liddick adb5106c1f Merge pull request #4169 from bestony/fix/openai-oauth-model-capability-cooldown
fix(scheduler): cool down Codex plan-gated models per account
2026-07-13 17:19:59 +08:00
Heatherm Huang bb73416733 fix(grok): route OAuth media through official API 2026-07-13 17:08:55 +08:00
github-actions[bot] 55ed0ab0da chore: sync VERSION to 0.1.153 [skip ci] 2026-07-13 08:32:35 +00:00
Bestony 5aeb03018c fix(scheduler): cool down Codex plan-gated models per account
OpenAI OAuth (ChatGPT) accounts deterministically reject plan-gated
models with 400 "The 'X' model is not supported when using Codex with
a ChatGPT account". Account selection had no capability filtering for
this, so the scheduler kept picking the same account for the same model
forever; every attempt burned an upstream call and surfaced to clients
as a retryable 502, sustaining client retry storms.

Treat this 400 like upstream model-not-found: mark the (account, model)
pair via SetModelRateLimit (30min cooldown) so
IsSchedulableForModelWithContext skips the account for that model
during selection, and return true so the in-flight request fails over
to another account through the existing UpstreamFailoverError path.
2026-07-13 16:29:18 +08:00
Wesley Liddick a2bc133747 Merge pull request #4163 from bestony/fix/openai-ws-ingress-lifecycle
fix(openai-ws): bound ingress session lifecycle
2026-07-13 16:07:53 +08:00
Wesley Liddick 540e90ca8b Merge pull request #4162 from heathermhuang/codex/fix-grok-third-party-api
fix(grok): allow third-party API base URLs
2026-07-13 16:07:36 +08:00
Wesley Liddick 4bc7486c3b Merge pull request #4161 from fengshao1227/fix/remove-payment-channels-endpoint
fix(payment): 删除泄露内部 AI 渠道配置的废弃接口
2026-07-13 15:39:32 +08:00
Wesley Liddick 664b7be30f Merge pull request #4055 from iMouseWu/feat/account-plan-type-edit
feat(account): 账号编辑弹窗支持手动覆盖 OpenAI 订阅档位 plan_type(仅 OAuth)
2026-07-13 15:32:57 +08:00
Bestony@Homelab c8cfc93632 fix(openai-ws): bound ingress session lifecycle 2026-07-13 15:32:42 +08:00
Wesley Liddick b4aa3eb023 Merge pull request #4148 from feeeei/fix/retry_count
fix: 池模式同账号重试次数配置对 Anthropic/Gemini/通用转发路径生效
2026-07-13 15:32:40 +08:00
Wesley Liddick 0465540195 Merge pull request #4048 from iMouseWu/fix/datatable-scroll-jank
fix(frontend): 小数据量关闭 DataTable 虚拟化并按行主键缓存行高,消除账号列表滚动抖动
2026-07-13 15:32:08 +08:00
Wesley Liddick b0d0de0547 Merge pull request #4045 from xiaopixiu2019/codex/upstream-gpt56-oauth-test
fix: normalize GPT-5.6 alias in OpenAI OAuth account tests
2026-07-13 15:31:44 +08:00
Heatherm Huang bc5d6ecb46 fix(grok): allow third-party API base URLs 2026-07-13 15:27:57 +08:00
li 03ccb2a08e fix(payment): 删除泄露内部 AI 渠道配置的废弃接口
Fixes #4160
2026-07-13 15:22:39 +08:00
Wesley Liddick 551e2570dd Merge pull request #4118 from badaozhai/feat/grok-video-edit-extension
[codex] support Grok video edits and extensions
2026-07-13 15:04:51 +08:00
shaw 8315defe8e Merge branch 'main' into feat/grok-video-edit-extension 2026-07-13 14:50:18 +08:00
Wesley Liddick fc9b489106 Merge pull request #4125 from adamglin0/feat/apple-container-support
feat(deploy): add Apple container support
2026-07-13 14:43:41 +08:00
Wesley Liddick d774948e09 Merge pull request #4082 from zuelu/agent/fix-codex-additional-tools-chat-bridge
fix(apicompat): 支持 Codex additional_tools 到 Chat Completions 桥接
2026-07-13 14:42:16 +08:00
Wesley Liddick baab0adf7c Merge pull request #4075 from jianjianai/codex/fix-scheduler-cache-invalid-time-upstream
fix(scheduler): skip cache records with unencodable times
2026-07-13 14:42:05 +08:00
Wesley Liddick a60a282473 Merge pull request #4143 from zvensmoluya/fix/alpha-search-frontend-bypass
fix(web): bypass frontend for alpha search
2026-07-13 14:41:55 +08:00
xingzhi 317de9c04b fix: support namespace tools in native responses 2026-07-13 14:38:05 +08:00
Wesley Liddick b8dcae3bcf Merge pull request #4150 from suuuuuu-1/fix/i18n-zh-missing-keys
fix(i18n): 补齐 zh 语言包 overview 和 misc 缺失 key
2026-07-13 14:16:09 +08:00
Wesley Liddick fbc3f42a22 Merge pull request #4138 from fengshao1227/fix/read-tool-args-streaming
fix(apicompat): Read 工具参数实时流式发送,不再依赖 .done 事件
2026-07-13 14:14:08 +08:00
Wesley Liddick 98cc641008 Merge pull request #4134 from yan9651688/fix/usage-window-pagination-local-dates
fix: align usage windows, pagination offsets, and local dates
2026-07-13 14:13:34 +08:00
Wesley Liddick daf0b99dcb Merge pull request #4130 from Drswith/fix/web-static-asset-cache-headers
fix(web): 为嵌入式前端静态资源设置长期 Cache-Control
2026-07-13 14:13:21 +08:00
Wesley Liddick 90bff0ea17 Merge pull request #4050 from bestony/perf/keys-last-used-ip-query
perf(keys): bound latest IP lookup per key
2026-07-13 14:13:11 +08:00
Wesley Liddick d8fa425a27 Merge pull request #4142 from fengshao1227/fix/streaming-stop-reason-and-content-filter
fix(apicompat): 流式 Anthropic max_tokens 截断语义 + content_filter finish_reason
2026-07-13 14:13:00 +08:00
Wesley Liddick 50e5372fed Merge pull request #4139 from heathermhuang/codex/fix-grok-upstream-model-sync
fix(grok): support upstream model sync for API keys
2026-07-13 14:12:17 +08:00
feeeei c7c933776d fix: 池模式同账号重试次数配置对 Anthropic/Gemini/通用转发路径生效
e643fc38 引入 pool_mode_retry_count 账号配置时,只覆盖了 OpenAI 族
handler 的内联重试循环;走 HandleFailoverError 的 Anthropic/
Antigravity/Gemini/通用转发路径仍硬编码同账号重试 3 次,配置不生效。

为 HandleFailoverError 增加 retryLimit 参数,由调用方传入
account.GetPoolModeRetryCount();未配置账号默认仍为 3 次,行为不变。
2026-07-13 12:57:00 +08:00
xingzhi 1d86c1bf81 docs: plan native responses namespace compatibility 2026-07-13 12:13:52 +08:00
li b6427d4ec0 fix(apicompat): 流式 Anthropic max_tokens 映射为 incomplete + content_filter 映射为 finish_reason 2026-07-13 12:08:32 +08:00
Zven b0fa2b352f fix(web): bypass frontend for alpha search 2026-07-13 12:06:51 +08:00
xingzhi 54a8606e2a docs: design native responses namespace compatibility 2026-07-13 12:03:01 +08:00
suuuuuu-1 a7ddca8930 fix(i18n): 补齐 zh 语言包 overview 和 misc 缺失 key
- admin/overview.ts: 添加 12 个缺失的翻译 key
  - newUsersToday, active, ok, err, create
  - userUsageTrend, claudeMaxSimulation 对象
- misc.ts: 添加 allowUserRefund 翻译

改进中文用户体验,确保所有 UI 文本都有对应的中文翻译
2026-07-13 12:01:09 +08:00
li a5d40c9845 fix(apicompat): Read 工具参数实时流式发送,不再依赖 .done 事件
Fixes #4114
2026-07-13 11:47:18 +08:00
Heatherm Huang b0441ca5aa fix(grok): support upstream model sync for API keys 2026-07-13 11:46:52 +08:00
yan9651688 3605a316af Keep usage ranges consistent across API and dashboards
Expose the active weekly subscription window through /v1/usage, calculate offsets with the same normalized page size used by queries, and keep user-facing date ranges on the browser's local calendar date.

Constraint: Preserve existing response fields and avoid new dependencies
Rejected: Keep duplicate inline date formatters | a shared local-date utility prevents the same UTC regression in both views
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep Offset and Limit based on the same normalized page size
Tested: go test ./internal/pkg/pagination ./internal/handler; go vet ./internal/pkg/pagination ./internal/handler; frontend 923 tests; pnpm typecheck; pnpm lint:check; pnpm build
Not-tested: Live API request against a deployed subscription
Related: #4121
2026-07-13 11:35:46 +08:00
Drswith 1e97e4cee4 fix(web): set long-lived Cache-Control for embedded static assets
Direct Go/Docker deployments were serving Vite-hashed /assets without
Cache-Control, so browsers re-downloaded the console on every visit.
Align with deploy/Caddyfile while keeping index.html on no-cache.

Closes #4129
2026-07-13 11:14:15 +08:00
benjamin 0d9c140bc2 Merge upstream/main into fix/api-double-billing 2026-07-13 11:10:33 +08:00
github-actions[bot] a1930ea6f2 chore: sync VERSION to 0.1.152 [skip ci] 2026-07-13 02:53:05 +00:00
chenjian 909b96edd2 feat: support Grok video edits and extensions 2026-07-13 10:50:42 +08:00
adamglin0 83c10133d1 feat(deploy): add Apple container support 2026-07-13 10:45:45 +08:00
benjamin 139f79b85a test(server): 补齐长上下文计费字段契约 2026-07-13 10:02:53 +08:00
benjamin 92dcfb5ebc fix(billing): 按账号控制 OpenAI 长上下文计费 2026-07-13 09:47:19 +08:00
gebdalaoli-arch 0dce07ee8b fix: proxy Codex models through API key upstreams 2026-07-13 03:47:39 +08:00
gebdalaoli-arch b6bb74b6fa fix(openai): avoid duplicate Codex image tool injection 2026-07-12 22:54:56 +08:00
zuelu ff5c216189 fix(apicompat): bridge Codex additional tools 2026-07-12 11:33:09 +08:00
jjaw fe184f8c33 修复调度缓存异常时间阻塞
Refs Wei-Shaw/sub2api#60

Refs Wei-Shaw/sub2api#1608
2026-07-12 05:54:46 +08:00
iMouseWuandClaude Opus 4.8 c56a64fabd feat(account): 账号编辑弹窗支持手动覆盖 OpenAI 订阅档位 plan_type(仅 OAuth)
此前 plan_type(ChatGPT Plus/Pro/Free)只由系统自动写入(OAuth 换码/刷新、
429 同步、导入),UI 无编辑入口。现于 EditAccountModal 为 OpenAI OAuth 非影子
账号新增一个订阅档位下拉,可手动纠正(走既有 PUT /admin/accounts/:id 合并,
plan_type 非敏感字段无需改后端)。

- 仅 OAuth 非影子账号显示/提交:setup-token 无订阅调度语义
  (IsOpenAIChatGPTSubscription 要求 oauth),影子账号凭据由母账号管理
- 下拉:清空 + Plus/Pro/Free;别名(chatgptpro→Pro)与自定义值(team 等)
  友好显示并保留 canonical 值,避免编辑丢失或写脏
- readPlanType 仅接受字符串,挡住脏数据;清空则删除该键(恢复自动识别)
- 抽 buildPlanTypeOptions/applyPlanType/readPlanType/planTypeDisplayLabel 为
  纯函数入 credentialsBuilder.ts,并补 12 个单测(别名去重、保留其余凭据键、
  set/delete 语义)
- 文案(zh/en)注明:令牌临期刷新或 429 会用真实档位自动覆盖手改值

经三方评审会(Claude + Codex + 作者)一轮交叉评审达成共识后落地。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 18:31:45 +08:00
Bestony 1c02158c2a perf(migrations): index latest API key IP lookups 2026-07-11 17:32:06 +08:00
Bestony 80b7a8d4cb perf(keys): bound latest IP lookup per key 2026-07-11 17:31:30 +08:00
iMouseWuandClaude Opus 4.8 94a22b62f7 fix(frontend): 小数据量关闭 DataTable 虚拟化并按行主键缓存行高,消除账号列表滚动抖动
账号列表(可变行高)在 @tanstack/vue-virtual 始终开启虚拟化下,估算行高(72)
远小于真实行高(~157),滚动时每行首次测量触发滚动补偿,表现为"一跳一跳"。

- DataTable 新增 virtualizeThreshold(默认 100):行数不超过阈值时全量渲染,
  彻底绕开虚拟器的估算/测量/补偿链路;超过才虚拟化,保留大列表性能
- DataTable 补 getItemKey(与模板 :key 一致的行主键):itemSizeCache 由 index 键
  改为行主键,排序/筛选/跨阈值来回都复用正确的已测行高,连带修复 >阈值 档
  排序即抖的既存问题
- 虚拟/全量两模式统一为 renderRows,共用同一套行与单元格;measure ref 仅虚拟模式绑定
- useSwipeSelect:全量渲染(虚拟窗口为空)时改用真实 DOM 行按坐标二分定位,
  修复关闭虚拟化后滑动多选点错行的隐患;定位逻辑提取为可测的导出函数
- AccountsView:estimate-row-height 72→156 对齐真实行高;virtualize-threshold=50,
  常用分页档全量渲染无抖动,pageSize=100 仍虚拟化以约束每行 AccountUsageCell 的首屏请求扇出
- 新增/强化测试:DataTable 虚拟化决策与 getItemKey、useSwipeSelect DOM 兜底定位

经三方评审会(Claude + Codex + 作者)两轮讨论达成共识后落地。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 17:13:19 +08:00
xiaopixiu2019 51de58b37f fix: normalize GPT-5.6 alias in OpenAI OAuth account tests 2026-07-11 15:39:32 +08:00
1132 changed files with 146630 additions and 6797 deletions
+9
View File
@@ -8,6 +8,15 @@ permissions:
contents: read
jobs:
shell:
runs-on: macos-15
steps:
- uses: actions/checkout@v6
- name: Check deployment scripts
run: |
/bin/bash -n deploy/apple-container.sh
/bin/bash deploy/tests/apple-container-test.sh
test:
runs-on: ubuntu-latest
steps:
+3
View File
@@ -116,6 +116,8 @@ backend/.installed
# 其他
# ===================
tests
!deploy/tests/
!deploy/tests/**
CLAUDE.md
.claude
scripts
@@ -133,6 +135,7 @@ docs/*
!docs/PAYMENT.md
!docs/PAYMENT_CN.md
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
!docs/ASYNC_IMAGE_TASKS.md
!docs/legal/
!docs/legal/*.md
.serena/
+19 -5
View File
@@ -18,7 +18,9 @@ ARG NPM_CONFIG_REGISTRY=
# -----------------------------------------------------------------------------
# Stage 1: Frontend Builder
# -----------------------------------------------------------------------------
FROM ${NODE_IMAGE} AS frontend-builder
# --platform=$BUILDPLATFORM: the frontend output is JS (arch-neutral), so build
# it on the native host arch instead of under QEMU emulation for the target.
FROM --platform=${BUILDPLATFORM} ${NODE_IMAGE} AS frontend-builder
ARG NPM_CONFIG_REGISTRY
WORKDIR /app/frontend
@@ -44,7 +46,11 @@ RUN pnpm run build
# -----------------------------------------------------------------------------
# Stage 2: Backend Builder
# -----------------------------------------------------------------------------
FROM ${GOLANG_IMAGE} AS backend-builder
# --platform=$BUILDPLATFORM: run the Go toolchain on the native host arch and
# cross-compile to the target arch below. The binary is CGO_ENABLED=0, so this
# is a clean pure-Go cross-compile — no QEMU emulation of go mod download / go
# build (emulated networking here was dropping module fetches with EOF).
FROM --platform=${BUILDPLATFORM} ${GOLANG_IMAGE} AS backend-builder
# Build arguments for version info (set by CI)
ARG VERSION=
@@ -52,6 +58,9 @@ ARG COMMIT=docker
ARG DATE
ARG GOPROXY
ARG GOSUMDB
# Populated by buildx from the --platform target (e.g. linux/amd64).
ARG TARGETOS
ARG TARGETARCH
ENV GOPROXY=${GOPROXY}
ENV GOSUMDB=${GOSUMDB}
@@ -63,7 +72,10 @@ WORKDIR /app/backend
# Copy go mod files first (better caching)
COPY backend/go.mod backend/go.sum ./
RUN go mod download
# Cache mount keeps the module cache across builds so a transient CDN blip on
# retry resumes instead of re-fetching every zip from scratch.
RUN --mount=type=cache,id=sub2api-gomod,target=/go/pkg/mod \
go mod download
# Copy backend source first
COPY backend/ ./
@@ -73,10 +85,12 @@ 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 > exact git tag > cmd/server/VERSION
RUN VERSION_VALUE="${VERSION}" && \
RUN --mount=type=cache,id=sub2api-gomod,target=/go/pkg/mod \
--mount=type=cache,id=sub2api-gobuild,target=/root/.cache/go-build \
VERSION_VALUE="${VERSION}" && \
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 \
CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build \
-tags embed \
-ldflags="-s -w -X main.Version=${VERSION_VALUE} -X main.Commit=${COMMIT} -X main.Date=${DATE_VALUE} -X main.BuildType=release" \
-trimpath \
+116 -13
View File
@@ -1,7 +1,9 @@
# Sub2API
<div align="center">
<img src="assets/logo.svg" alt="Sub2API Logo" width="128" />
# Sub2API
[![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/)
@@ -77,8 +79,8 @@ Please read the following carefully before using this project:
</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>Thanks to PPToken.org for sponsoring this project! <a href="https://api.pptoken.org/register?promo=SUB2API">PPToken.org</a> specializes in GPT model API relay services, supporting Codex, Claude Code, OpenAI-compatible clients, and Gemini CLI integration. Top-ups are 1:1 (¥1 = $1 credit); GPT models start at 0.16x rate multiplier, with overall cost at roughly 2.2% of official pricing and first-token latency around 1 second — ideal for developers seeking low-cost, high-speed access to GPT model capabilities. Technical support: 24/7 real human responses (no bots), @tech in the group chat and get a reply within 10 minutes. Sponsor benefit: the first 200 users who register via the <a href="https://api.pptoken.org/register?promo=SUB2API">exclusive registration link</a> and enter promo code `SUB2API` can claim free Codex / Claude Code trial credits — no minimum spend, no card required.
<td width="180"><a href="https://api.pptoken.cc/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
<td>Thanks to PPToken.cc for sponsoring this project! <a href="https://api.pptoken.cc/register?promo=SUB2API">PPToken.cc</a> specializes in GPT model API relay services, supporting Codex, Claude Code, OpenAI-compatible clients, and Gemini CLI integration. Top-ups are 1:1 (¥1 = $1 credit); GPT models start at 0.16x rate multiplier, with overall cost at roughly 2.2% of official pricing and first-token latency around 1 second — ideal for developers seeking low-cost, high-speed access to GPT model capabilities. Technical support: 24/7 real human responses (no bots), @tech in the group chat and get a reply within 10 minutes. Sponsor benefit: the first 200 users who register via the <a href="https://api.pptoken.cc/register?promo=SUB2API">exclusive registration link</a> and enter promo code `SUB2API` can claim free Codex / Claude Code trial credits — no minimum spend, no card required.
</td>
</tr>
@@ -163,6 +165,29 @@ Model authenticity: no content intervention or secondary filtering — experienc
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>Thanks to Aimzoon for sponsoring this project! <a href="http://aimzoon.com">Aimzoon</a> provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. <a href="http://aimzoon.com">Click here</a> to register and try it out!
</td>
</tr>
<tr>
<td width="180"><a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/claudeapi.jpg" alt="claudeapi" width="150"></a></td>
<td>Thanks to Claude API for sponsoring this project! <a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">Claude API</a> is an official-channel API provider focused on Claude models. Built on official Anthropic keys and the official AWS Bedrock channel, it delivers a stable integration experience for Claude Code and Agent applications, supports the full Claude model lineup, and retains official capabilities such as Tool Use and long context. The service involves no reverse engineering and no model degradation, making it a great fit for heavy Claude Code users, Agent engineers, and enterprise engineering teams. Register via the <a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">exclusive link</a> and contact customer support to receive free trial credits; invoicing and team onboarding are also supported.
</td>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/code0.jpg" alt="code0" width="150"></a></td>
<td>Thanks to code0.ai for sponsoring this project! <a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">code0.ai</a> is an AI coding workbench for developers and engineering teams, aggregating mainstream agent coding capabilities such as Claude Code and Codex, and covering common development scenarios including code generation, project understanding, debugging and fixing, code review, and documentation generation. It suits independent developers, Agent engineers, open-source maintainers, and enterprise R&D teams, with invoicing and team onboarding supported. Register via the <a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">exclusive link</a> and contact customer support to receive free trial credits and experience a more efficient AI coding workflow.
</td>
</tr>
<tr>
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
<td><a href="https://nagora.ai/">Nagora</a> is a multi-model AI API gateway built for developers and teams. With a single account and API key, you can access more than 26 leading text and image models through one unified interface. It is compatible with OpenAI, Anthropic, and Gemini protocols and integrates seamlessly with development tools such as Claude Code, Codex, and Gemini CLI. The platform provides intelligent routing, automatic failover, transparent pricing, and consolidated billing, along with budget management, rate limiting, and concurrency controls. This makes AI usage more reliable and manageable across individual development, team collaboration, and production environments. No changes to your existing application are required. Simply replace the Base URL and API key to complete the integration in as little as one minute.</td>
</tr>
</table>
## Overview
@@ -179,6 +204,7 @@ Sub2API is an AI API gateway platform designed to distribute and manage API quot
- **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
- **Composite Groups** - Admin routing layer that resolves requested models to concrete providers for multi-provider groups ([Operator Guide](docs/COMPOSITE_GROUPS.md))
- **External System Integration** - Embed external systems (e.g. ticketing) via iframe to extend the admin dashboard
## Ecosystem
@@ -329,6 +355,7 @@ cd sub2api/deploy
# 2. Copy environment configuration
cp .env.example .env
chmod 600 .env
# 3. Edit configuration (generate secure passwords)
nano .env
@@ -448,7 +475,23 @@ rm -rf data/ postgres_data/ redis_data/
---
### Method 3: Build from Source
### Method 3: Apple container (macOS)
Apple-silicon Macs running macOS 26 can run the full Sub2API, PostgreSQL, and Redis stack with Apple `container` 1.1.0 or newer:
```bash
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api/deploy
./apple-container.sh init
./apple-container.sh up
./apple-container.sh status
```
This is an operator-managed local workflow; Docker Compose remains the recommended production path. See [deploy/APPLE_CONTAINER.md](deploy/APPLE_CONTAINER.md) for lifecycle commands, persistence, upgrades, and runtime limitations.
---
### Method 4: Build from Source
Build and run from source code for development or customization.
@@ -507,6 +550,7 @@ database:
redis:
host: "localhost"
port: 6379
username: ""
password: ""
jwt:
@@ -536,9 +580,18 @@ Additional security-related options are available in `config.yaml`:
- `security.response_headers.enabled` to enable configurable response header filtering (disabled uses default allowlist)
- `security.csp` to control Content-Security-Policy headers
- `billing.circuit_breaker` to fail closed on billing errors
- `server.trusted_proxies` to enable X-Forwarded-For parsing
- `security.trust_forwarded_ip_for_api_key_acl` enables legacy raw forwarded-header takeover (enabled by default for upgrade compatibility); disable it to enforce `server.trusted_proxies`, which should contain only the exact proxy CIDRs that connect directly to Sub2API
- `security.forwarded_client_ip_headers` configures up to 16 third-party CDN client-IP header names; they are checked in order before the built-in headers only while legacy takeover is enabled
- `turnstile.required` to require Turnstile in release mode
Custom client-IP headers can be set in YAML or as a comma-separated environment variable:
```bash
SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
```
Header names are validated, canonicalized, and de-duplicated. The admin security settings can update the list without a restart; new installations persist YAML/environment defaults and existing installations backfill a missing database value. When legacy takeover is disabled, all custom and built-in raw forwarding headers are ignored and Gin uses only `server.trusted_proxies`. While takeover is enabled, firewall the origin to CDN/proxy addresses and make the edge overwrite every trusted client-IP header. See [`deploy/EDGE_SECURITY.md`](deploy/EDGE_SECURITY.md) for the complete migration and trust-boundary rules.
**⚠️ Security Warning: HTTP URL Configuration**
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:
@@ -579,6 +632,46 @@ 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
#### OpenAI Responses WebSocket ingress limits
`gateway.openai_ws` bounds the lifetime and aggregate count of client-facing
Responses WebSocket sessions. These safeguards apply independently from
per-turn user and account concurrency slots, which are released between turns.
```yaml
gateway:
openai_ws:
# Total time to receive and decompress the first client message.
client_first_message_timeout_seconds: 30
# Close a client socket idle between completed turns; 0 disables this safeguard.
ingress_inter_turn_idle_timeout_seconds: 300
# Distributed API-key limit for live client ingress sessions; 0 disables it.
max_ingress_connections_per_api_key: 64
```
The first-message timeout is a total read deadline. Deployments that accept
large contexts or image-heavy requests over slower links can raise it to
120-300 seconds. It expires before HTTP bridge routing, so bridge mode does not
override this limit.
The connection cap is coordinated through Redis using a 60-second lease that
is refreshed every 20 seconds. A process that cannot confirm a lease for a
full lease lifetime closes its local WebSocket rather than continuing outside
the global cap.
Enable the v2 mode router before selecting an account-level WS mode such as
`http_bridge`:
```yaml
gateway:
openai_ws:
mode_router_v2_enabled: true
```
Or set `GATEWAY_OPENAI_WS_MODE_ROUTER_V2_ENABLED=true` in the environment.
Use `http_bridge` for client-WebSocket/upstream-HTTP operation when rolling out
or mitigating upstream WebSocket issues.
#### ⚠️ 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.
@@ -637,6 +730,12 @@ Simple Mode is designed for individual developers or internal teams who want qui
---
## Asynchronous Image Tasks
Long-running OpenAI/Grok image generation and editing can be submitted through `/v1/images/generations/async` or `/v1/images/edits/async`, then polled at `/v1/images/tasks/{task_id}` without holding a CDN connection open. See [Asynchronous Image Tasks](docs/ASYNC_IMAGE_TASKS.md) for request and response examples.
---
## Grok / xAI Support
Sub2API supports both Grok subscription accounts through xAI OAuth and standard xAI API-key accounts. Both account types forward OpenAI-compatible Responses traffic to xAI.
@@ -650,8 +749,9 @@ Sub2API supports both Grok subscription accounts through xAI OAuth and standard
- Public Chat Completions targets: `/v1/chat/completions` and `/chat/completions`, forwarded to the account-type-specific xAI upstream
- Codex CLI style Responses WebSocket ingress is accepted on the Responses targets and bridged to xAI HTTP/SSE Responses upstream
- Text models: `grok-4.5`, `grok-4.3`, `grok-build-0.1`, `grok-composer-2.5-fast`, `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 targets for Grok groups: `/v1/images/generations`, `/images/generations`, `/v1/images/edits`, `/images/edits`, `/v1/videos/generations`, `/videos/generations`, `/v1/videos/edits`, `/videos/edits`, `/v1/videos/extensions`, `/videos/extensions`, `/v1/videos/{request_id}`, and `/videos/{request_id}`. Generation, editing, and extension 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`
- JSON image-edit and video-generation requests accept image references in `image`, `images`, `reference_images`, and `mask` objects. Use `url` for xAI-compatible payloads; the legacy `image_url` field remains accepted and is normalized to `url` before forwarding.
- Out of scope for this provider: TTS, transcription, browser automation, cookies, and Grok web scraping
### OAuth Configuration
@@ -690,14 +790,13 @@ For API-key accounts, select **Grok → API Key** in the create-account dialog.
```toml
[models]
default = "sub2api-grok"
web_search = "sub2api-grok"
default = "grok"
web_search = "grok"
[model."sub2api-grok"]
[model."grok"]
model = "grok-4.5"
base_url = "https://your-sub2api.example.com/v1"
name = "Grok 4.5 via Sub2API"
description = "Grok 4.5 through a Sub2API Grok group"
name = "Grok 4.5"
api_key = "sk-your-sub2api-key"
api_backend = "responses"
context_window = 1000000
@@ -708,7 +807,7 @@ Back up an existing `config.toml` before merging the entry. The file contains a
```bash
grok inspect
grok -p "Reply with sub2api-ok" -m sub2api-grok
grok -p "Reply with sub2api-ok" -m grok
```
The `base_url` above is the public Sub2API URL ending in `/v1`, not `api.x.ai` or the internal xAI OAuth proxy URL.
@@ -719,6 +818,10 @@ xAI quota is passive. Sub2API does not invent subscription quota values; it reco
`401` responses temporarily remove accounts with invalid credentials from scheduling. `403` responses are treated as access or entitlement failures instead of token-refresh loops. `429` responses use `Retry-After` or a short cooldown to temporarily remove the account from scheduling.
New Grok image and video generation requests use a media-specific eligibility check. API-key accounts remain eligible. OAuth accounts require positive paid-entitlement evidence from the xAI billing probe; Free, forbidden, missing, malformed, and inconclusive billing observations are excluded from new media generation. Unobserved OAuth accounts are probed before the first media request is forwarded, and imports run the billing-first quota probe proactively. Chat requests and video status lookups are not affected by this media-only quarantine. If no eligible account remains, the media endpoint returns HTTP `503` with error type `grok_media_no_eligible_account`.
Administrators can override automatic media eligibility through the account create/update API by setting `extra.grok_media_eligible` to `false` (exclude) or `true` (force eligible). On update, set it to `null` to remove the override and return to automatic probe-based behavior; omitting the field preserves the current override. A weekly allowance period alone is not treated as a paid tier signal. Successful image responses must contain at least one actual image output; empty HTTP `200` responses trigger account failover instead of being counted and returned as successful generations.
---
## Antigravity Support
+56 -6
View File
@@ -1,7 +1,9 @@
# Sub2API
<div align="center">
<img src="assets/logo.svg" alt="Sub2API Logo" width="128" />
# Sub2API
[![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/)
@@ -80,8 +82,8 @@
</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 width="180"><a href="https://api.pptoken.cc/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
<td>感谢 PPToken.cc 赞助本项目! <a href="https://api.pptoken.cc/register?promo=SUB2API">PPToken.cc</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.cc/register?promo=SUB2API">[专属注册链接]</a> 注册,输入优惠码 `SUB2API`,可领取 Codex / Claude Code 免费试用额度,无门槛、不绑卡。
</td>
</tr>
@@ -166,6 +168,28 @@
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>感谢 Aimzoon 对本项目的赞助! <a href="http://aimzoon.com">Aimzoon</a> 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。<a href="http://aimzoon.com">点击这里</a>注册体验!
</td>
</tr>
<tr>
<td width="180"><a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/claudeapi.jpg" alt="claudeapi" width="150"></a></td>
<td>感谢 Claude API 对本项目的赞助! <a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">Claude API</a> 是专注 Claude 模型的官方渠道 API 服务商,基于 Anthropic 官方 Key 与 AWS Bedrock 官方渠道,提供稳定的 Claude Code 与 Agent 应用接入体验,支持 Claude 全系列模型,保留 Tool Use、长上下文等官方能力。服务非逆向、非降智,适合 Claude Code 深度用户、Agent 工程师与企业技术团队使用。通过<a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">[专属链接]</a>注册后联系客服,可领取免费测试额度,并支持开票和团队对接。
</td>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/code0.jpg" alt="code0" width="150"></a></td>
<td>感谢 code0.ai 对本项目的赞助! <a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">code0.ai</a> 是面向开发者与技术团队的 AI 编程工作台,聚合 Claude Code、Codex 等主流 Agent 编程能力,支持代码生成、项目理解、调试修复、代码审查与文档生成等常见研发场景。适合独立开发者、Agent 工程师、开源项目维护者和企业研发团队使用,支持开票和团队对接。通过<a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">[专属链接]</a>注册后联系客服,可领取免费测试额度,体验更高效的 AI 编程工作流。
</td>
</tr>
<tr>
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
<td><a href="https://nagora.ai/">Nagora</a> 是专为开发者和团队打造的多模型 AI API 网关。通过一个账户和一枚 API Key,即可统一调用 26+ 款主流文本与图像模型,兼容 OpenAI、Anthropic 与 Gemini 协议,并可无缝接入 Claude Code、Codex、Gemini CLI 等开发工具。平台提供智能路由、自动故障转移、透明计费与统一账单,同时支持预算、限速、并发控制,让个人开发、团队协作和生产环境中的 AI 调用更稳定、更可控。无需改造现有应用,只需替换 Base URL 与 API Key,最快 1 分钟即可完成接入。</td>
</tr>
</table>
@@ -333,6 +357,7 @@ cd sub2api/deploy
# 2. 复制环境配置文件
cp .env.example .env
chmod 600 .env
# 3. 编辑配置(生成安全密码)
nano .env
@@ -464,7 +489,23 @@ rm -rf data/ postgres_data/ redis_data/
---
### 方式三:源码编译
### 方式三:Apple container(macOS)
Apple 芯片 Mac 在 macOS 26 上可使用 Apple `container` 1.1.0 或更高版本运行完整的 Sub2API、PostgreSQL 和 Redis:
```bash
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api/deploy
./apple-container.sh init
./apple-container.sh up
./apple-container.sh status
```
该方式面向本地开发和人工运维,不提供持续重启监管;生产部署仍推荐 Docker Compose。生命周期命令、持久化、升级和运行时限制见 [deploy/APPLE_CONTAINER.md](deploy/APPLE_CONTAINER.md)。
---
### 方式四:源码编译
从源码编译安装,适合开发或定制需求。
@@ -573,9 +614,18 @@ gateway:
- `security.response_headers.enabled` 可启用可配置响应头过滤(关闭时使用默认白名单)
- `security.csp` 配置 Content-Security-Policy
- `billing.circuit_breaker` 计费异常时 fail-closed
- `server.trusted_proxies` 启用可信代理解析 X-Forwarded-For
- `security.trust_forwarded_ip_for_api_key_acl` 控制旧版原始转发头接管(为升级兼容默认开启);关闭后严格使用 `server.trusted_proxies`,其中只应填写直接连接 Sub2API 的精确代理 CIDR
- `security.forwarded_client_ip_headers` 最多配置 16 个第三方 CDN 客户端 IP 请求头;仅在旧版接管开启时按顺序优先于内置请求头解析
- `turnstile.required` 在 release 模式强制启用 Turnstile
自定义客户端 IP 请求头可通过 YAML 配置,也可使用逗号分隔的环境变量:
```bash
SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
```
请求头名称会经过合法性校验、规范化和大小写无关去重。管理员可在安全设置中动态更新列表,无需重启;新安装会持久化 YAML/环境变量默认值,旧安装缺少数据库字段时会自动回填。关闭旧版接管后,自定义头和内置原始转发头均被忽略,只使用 `server.trusted_proxies`。开启接管时必须限制源站仅允许 CDN/代理访问,并确保边缘代理覆盖所有受信客户端 IP 请求头。完整迁移规则和信任边界见 [`deploy/EDGE_SECURITY.md`](deploy/EDGE_SECURITY.md)。
**网关防御纵深建议(重点)**
- `gateway.upstream_response_read_max_bytes`:限制非流式上游响应读取大小(默认 `8MB`),用于防止异常响应导致内存放大。
+57 -6
View File
@@ -1,7 +1,9 @@
# Sub2API
<div align="center">
<img src="assets/logo.svg" alt="Sub2API Logo" width="128" />
# Sub2API
[![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/)
@@ -79,8 +81,8 @@
</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 倍のレート倍率で、総合コストは公式価格の約 2.2% 、最速ファーストトークンは約1秒 — 開発者が低コスト・高速レスポンスで GPT モデル機能にアクセスするのに最適です。テクニカルサポート:24時間365日リアルな人間が対応(ボットではありません)、グループ内で @技術 すれば 10 分以内に返信。スポンサー特典:先着 200 名のユーザーが<a href="https://api.pptoken.org/register?promo=SUB2API">専用登録リンク</a>から登録し、プロモコード `SUB2API` を入力すると、Codex / Claude Code の無料トライアルクレジットを獲得できます — 最低利用額なし、カード登録不要。
<td width="180"><a href="https://api.pptoken.cc/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
<td>PPToken.cc のご支援に感謝します!<a href="https://api.pptoken.cc/register?promo=SUB2API">PPToken.cc</a> は GPT シリーズモデルの API 中継サービスを専門としており、Codex、Claude Code、OpenAI 互換クライアント、Gemini CLI などのツール接続をサポートしています。チャージは 1:1(1元=1ドル分のクレジット)、GPT モデルは最低 0.16 倍のレート倍率で、総合コストは公式価格の約 2.2% 、最速ファーストトークンは約1秒 — 開発者が低コスト・高速レスポンスで GPT モデル機能にアクセスするのに最適です。テクニカルサポート:24時間365日リアルな人間が対応(ボットではありません)、グループ内で @技術 すれば 10 分以内に返信。スポンサー特典:先着 200 名のユーザーが<a href="https://api.pptoken.cc/register?promo=SUB2API">専用登録リンク</a>から登録し、プロモコード `SUB2API` を入力すると、Codex / Claude Code の無料トライアルクレジットを獲得できます — 最低利用額なし、カード登録不要。
</td>
</tr>
@@ -161,6 +163,29 @@
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>Aimzoon のご支援に感謝します!<a href="http://aimzoon.com">Aimzoon</a> は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。<a href="http://aimzoon.com">こちら</a>から登録してお試しください!
</td>
</tr>
<tr>
<td width="180"><a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/claudeapi.jpg" alt="claudeapi" width="150"></a></td>
<td>Claude API のご支援に感謝します!<a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">Claude API</a> は Claude モデルに特化した公式チャネルの API サービスプロバイダーで、Anthropic 公式キーと AWS Bedrock 公式チャネルをベースに、Claude Code や Agent アプリケーションへの安定した接続体験を提供します。Claude 全シリーズのモデルに対応し、Tool Use や長文コンテキストなどの公式機能もそのまま利用可能。リバースエンジニアリングやモデル劣化のないサービスで、Claude Code のヘビーユーザー、Agent エンジニア、企業の技術チームに最適です。<a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">専用リンク</a>から登録後カスタマーサポートへご連絡いただくと、無料お試しクレジットを受け取れます。請求書発行やチーム導入にも対応しています。
</td>
</tr>
<tr>
<td width="180"><a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/code0.jpg" alt="code0" width="150"></a></td>
<td>code0.ai のご支援に感謝します!<a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">code0.ai</a> は開発者と技術チーム向けの AI プログラミングワークベンチで、Claude Code や Codex などの主要な Agent コーディング能力を集約し、コード生成、プロジェクト理解、デバッグと修正、コードレビュー、ドキュメント生成といった一般的な開発シーンをサポートします。個人開発者、Agent エンジニア、OSS メンテナー、企業の開発チームに最適で、請求書発行やチーム導入にも対応。<a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">専用リンク</a>から登録後カスタマーサポートへご連絡いただくと、無料お試しクレジットを受け取り、より効率的な AI プログラミングワークフローを体験できます。
</td>
</tr>
<tr>
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
<td><a href="https://nagora.ai/">Nagora</a>は、開発者やチーム向けに設計されたマルチモデルAI APIゲートウェイです。1つのアカウントと1つのAPIキーだけで、26種類以上の主要なテキストモデルおよび画像モデルを一元的に利用できます。OpenAI、Anthropic、Geminiの各プロトコルに対応し、Claude Code、Codex、Gemini CLIなどの開発ツールにもシームレスに接続できます。 プラットフォームには、インテリジェントルーティング、自動フェイルオーバー、透明性の高い料金体系、請求の一元管理に加え、予算管理、レート制限、同時実行数の制御機能が備わっています。これにより、個人開発、チームでの共同作業、本番環境におけるAI APIの利用を、より安定的かつ柔軟に管理できます。 既存のアプリケーションを改修する必要はありません。Base URLとAPIキーを置き換えるだけで、最短1分で導入を完了できます。</td>
</tr>
</table>
## 概要
@@ -327,6 +352,7 @@ cd sub2api/deploy
# 2. 環境設定ファイルをコピー
cp .env.example .env
chmod 600 .env
# 3. 設定を編集(セキュアなパスワードを生成)
nano .env
@@ -446,7 +472,23 @@ rm -rf data/ postgres_data/ redis_data/
---
### 方法3: ソースからビルド
### 方法3: Apple container(macOS)
Apple シリコン搭載 Mac と macOS 26 では、Apple `container` 1.1.0 以降を使用して Sub2API、PostgreSQL、Redis の完全なスタックを実行できます:
```bash
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api/deploy
./apple-container.sh init
./apple-container.sh up
./apple-container.sh status
```
これはローカル開発および手動運用向けです。本番環境では引き続き Docker Compose を推奨します。ライフサイクル、永続化、アップグレード、制限については [deploy/APPLE_CONTAINER.md](deploy/APPLE_CONTAINER.md) を参照してください。
---
### 方法4: ソースからビルド
開発やカスタマイズのためにソースコードからビルドして実行します。
@@ -534,9 +576,18 @@ default:
- `security.response_headers.enabled` - 設定可能なレスポンスヘッダーフィルタリングを有効化(無効時はデフォルトの許可リストを使用)
- `security.csp` - Content-Security-Policy ヘッダーの制御
- `billing.circuit_breaker` - 課金エラー時にフェイルクローズ
- `server.trusted_proxies` - X-Forwarded-For パースの有効化
- `security.trust_forwarded_ip_for_api_key_acl` - 従来の生転送ヘッダーによる上書きを制御(アップグレード互換性のため既定で有効)。無効にすると `server.trusted_proxies` を厳格に使用し、Sub2API に直接接続するプロキシの正確な CIDR のみを指定
- `security.forwarded_client_ip_headers` - サードパーティ CDN のクライアント IP ヘッダーを最大 16 個指定。従来モードが有効な場合のみ、設定順で組み込みヘッダーより先に評価
- `turnstile.required` - リリースモードでの Turnstile 必須化
カスタムクライアント IP ヘッダーは YAML またはカンマ区切りの環境変数で設定できます:
```bash
SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
```
ヘッダー名は検証、正規化、大小文字を区別しない重複排除が行われます。管理画面のセキュリティ設定から再起動せずに更新でき、新規インストールでは YAML/環境変数の既定値を保存し、既存環境ではデータベース値がない場合に補完します。従来モードを無効にするとカスタムおよび組み込みの生転送ヘッダーはすべて無視され、`server.trusted_proxies` のみを使用します。有効にする場合はオリジンへの接続元を CDN/プロキシに制限し、エッジで信頼する全クライアント IP ヘッダーを上書きしてください。移行規則と信頼境界の詳細は [`deploy/EDGE_SECURITY.md`](deploy/EDGE_SECURITY.md) を参照してください。
**⚠️ セキュリティ警告: HTTP URL 設定**
`security.url_allowlist.enabled=false` の場合、システムは最小限の URL バリデーションのみを行い、**デフォルトで HTTP URL を許可**します(開発フレンドリーモード。Docker Compose デプロイのデフォルトも同じです)。本番環境では、以下のように明示的に HTTPS のみに制限することを推奨します:
+32
View File
@@ -0,0 +1,32 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-labelledby="title desc">
<title id="title">Sub2API</title>
<desc id="desc">An interlocking S symbol representing subscription routing into APIs.</desc>
<defs>
<linearGradient id="s2a-bg" x1="72" y1="44" x2="442" y2="478" gradientUnits="userSpaceOnUse">
<stop stop-color="#142B56"/>
<stop offset=".52" stop-color="#0A1A39"/>
<stop offset="1" stop-color="#061127"/>
</linearGradient>
<radialGradient id="s2a-ambient" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(168 92) rotate(51) scale(342 382)">
<stop stop-color="#3E68B0" stop-opacity=".28"/>
<stop offset="1" stop-color="#3E68B0" stop-opacity="0"/>
</radialGradient>
<linearGradient id="s2a-brand" x1="4" y1="4" x2="20" y2="20" gradientUnits="userSpaceOnUse">
<stop stop-color="#79F4BD"/>
<stop offset=".48" stop-color="#39D9E7"/>
<stop offset="1" stop-color="#3875F6"/>
</linearGradient>
<filter id="s2a-shadow" x="-25%" y="-25%" width="150%" height="165%" color-interpolation-filters="sRGB">
<feDropShadow dx="0" dy=".55" stdDeviation=".65" flood-color="#020817" flood-opacity=".34"/>
</filter>
</defs>
<rect x="16" y="16" width="480" height="480" rx="120" fill="url(#s2a-bg)"/>
<rect x="16" y="16" width="480" height="480" rx="120" fill="url(#s2a-ambient)"/>
<rect x="16.75" y="16.75" width="478.5" height="478.5" rx="119.25" fill="none" stroke="#A5BFFF" stroke-opacity=".16" stroke-width="1.5"/>
<g transform="translate(52 52) scale(17)" fill="none" stroke="url(#s2a-brand)" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.7" filter="url(#s2a-shadow)">
<path d="m19.25 7.65-2.55-3.2a1.33 1.33 0 0 0-1.03-.5H8.58c-.34 0-.67.13-.91.37L4.15 7.65c-.93.88-.6 1.52.65 2.3l9.55 5.97"/>
<path d="m4.75 16.35 2.55 3.2c.25.31.63.5 1.03.5h7.09c.34 0 .67-.13.91-.37l3.52-3.33c.93-.88.6-1.52-.65-2.3L9.65 8.08"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

@@ -0,0 +1,20 @@
# Ingress rejection log cleanup
This maintenance command removes historical admission rejections from
`ops_error_logs` without matching unrelated authentication or upstream errors.
It is a dry run unless `--execute` is supplied, and always requires an explicit
RFC3339 cutoff.
```sh
go run ./cmd/cleanup-ingress-reject-logs --before 2026-07-17T00:00:00Z
go run ./cmd/cleanup-ingress-reject-logs --before 2026-07-17T00:00:00Z --execute
```
Run the execute form only after every application instance has been upgraded so
older instances cannot add new ingress rejection rows below the chosen cutoff.
The classifier intentionally retains invariant failures such as
`USER_NOT_FOUND`, database errors, quota/billing errors, and upstream failures.
After the rollout and cleanup are verified, run
`backend/scripts/finalize-ingress-reject-cleanup.sql` in a maintenance window to
remove the deprecated plaintext-key audit table and attribution columns.
@@ -0,0 +1,218 @@
package main
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"log"
"sort"
"strings"
"time"
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/lib/pq"
)
const classifierVersion = "ingress-reject-v1"
type candidate struct {
id int64
statusCode int
message string
body string
}
func main() {
beforeRaw := flag.String("before", "", "required RFC3339 cutoff; only older rows are considered")
execute := flag.Bool("execute", false, "delete matched rows (default is dry-run)")
batchSize := flag.Int("batch-size", 5000, "scan/delete batch size (1-5000)")
flag.Parse()
if *beforeRaw == "" {
log.Fatal("--before is required")
}
before, err := time.Parse(time.RFC3339, *beforeRaw)
if err != nil {
log.Fatalf("invalid --before: %v", err)
}
if *batchSize < 1 || *batchSize > 5000 {
log.Fatal("--batch-size must be between 1 and 5000")
}
cfg, err := config.LoadForBootstrap()
if err != nil {
log.Fatalf("load config: %v", err)
}
client, db, err := repository.InitEnt(cfg)
if err != nil {
log.Fatalf("initialize database: %v", err)
}
defer func() { _ = client.Close() }()
ctx := context.Background()
counts, scanned, matched, deleted, err := cleanup(ctx, db, before, *batchSize, *execute)
if err != nil {
log.Fatalf("cleanup failed: %v", err)
}
digest := sha256.Sum256([]byte(classifierVersion))
mode := "dry-run"
if *execute {
mode = "execute"
}
fmt.Printf("mode=%s before=%s classifier=%s scanned=%d matched=%d deleted=%d\n",
mode, before.UTC().Format(time.RFC3339), hex.EncodeToString(digest[:]), scanned, matched, deleted)
reasons := make([]string, 0, len(counts))
for reason := range counts {
reasons = append(reasons, reason)
}
sort.Strings(reasons)
for _, reason := range reasons {
fmt.Printf("reason=%s count=%d\n", reason, counts[reason])
}
if *execute && deleted > 0 {
fmt.Println("cleanup complete; schedule VACUUM (ANALYZE) ops_error_logs during normal maintenance")
}
}
func cleanup(ctx context.Context, db *sql.DB, before time.Time, batchSize int, execute bool) (map[string]int64, int64, int64, int64, error) {
counts := make(map[string]int64)
var cursor, scanned, matched, deleted int64
for {
rows, err := db.QueryContext(ctx, `
SELECT id, COALESCE(status_code, 0), COALESCE(error_message, ''), COALESCE(error_body, '')
FROM ops_error_logs
WHERE id > $1
AND created_at < $2
AND error_phase = 'auth'
AND account_id IS NULL
AND upstream_status_code IS NULL
AND COALESCE(upstream_error_message, '') = ''
AND COALESCE(upstream_error_detail, '') = ''
ORDER BY id ASC
LIMIT $3`, cursor, before, batchSize)
if err != nil {
return nil, scanned, matched, deleted, err
}
batch := make([]candidate, 0, batchSize)
for rows.Next() {
var item candidate
if err := rows.Scan(&item.id, &item.statusCode, &item.message, &item.body); err != nil {
_ = rows.Close()
return nil, scanned, matched, deleted, err
}
batch = append(batch, item)
cursor = item.id
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return nil, scanned, matched, deleted, err
}
_ = rows.Close()
if len(batch) == 0 {
break
}
ids := make([]int64, 0, len(batch))
for _, item := range batch {
scanned++
if reason, ok := historicalIngressRejectReason(item); ok {
matched++
counts[reason]++
ids = append(ids, item.id)
}
}
if execute && len(ids) > 0 {
result, err := db.ExecContext(ctx,
`DELETE FROM ops_error_logs WHERE id = ANY($1) AND created_at < $2`, pq.Array(ids), before)
if err != nil {
return nil, scanned, matched, deleted, err
}
n, err := result.RowsAffected()
if err != nil {
return nil, scanned, matched, deleted, err
}
deleted += n
}
}
return counts, scanned, matched, deleted, nil
}
func historicalIngressRejectReason(item candidate) (string, bool) {
code, message := parseErrorIdentity(item.body, item.message)
switch code {
case "API_KEY_REQUIRED":
return "missing_key", true
case "INVALID_API_KEY":
return "invalid_key", true
case "API_KEY_DISABLED":
return "key_disabled", true
case "USER_INACTIVE":
return "user_inactive", true
case "GROUP_DELETED":
return "group_deleted", true
case "GROUP_DISABLED":
return "group_disabled", true
case "GROUP_NOT_ALLOWED":
return "group_forbidden", true
case "ACCESS_DENIED":
return "ip_acl_denied", true
case "api_key_in_query_deprecated":
return "query_key_deprecated", true
}
normalized := strings.TrimSpace(message)
switch {
case normalized == "API key is required":
return "missing_key", true
case normalized == "Invalid API key":
return "invalid_key", true
case normalized == "API key is disabled":
return "key_disabled", true
case normalized == "User account is not active":
return "user_inactive", true
case normalized == "API Key 所属分组已删除":
return "group_deleted", true
case normalized == "API Key 所属分组已停用":
return "group_disabled", true
case normalized == "API Key 所属专属分组不再允许当前用户使用":
return "group_forbidden", true
case normalized == "API Key is not assigned to any group and cannot be used. Please contact the administrator to assign it to a group.":
return "group_unassigned", true
case strings.HasPrefix(normalized, "Access denied. Your IP is "):
return "ip_acl_denied", true
case normalized == "Query parameter api_key is deprecated. Use Authorization header or key instead.":
return "query_key_deprecated", true
default:
return "", false
}
}
func parseErrorIdentity(body, fallbackMessage string) (string, string) {
var payload struct {
Code string `json:"code"`
Message string `json:"message"`
Error struct {
Code json.RawMessage `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal([]byte(body), &payload); err != nil {
return "", fallbackMessage
}
message := payload.Message
if message == "" {
message = payload.Error.Message
}
if message == "" {
message = fallbackMessage
}
return strings.TrimSpace(payload.Code), message
}
@@ -0,0 +1,29 @@
package main
import "testing"
func TestHistoricalIngressRejectReason(t *testing.T) {
tests := []struct {
name string
item candidate
reason string
match bool
}{
{name: "standard invalid key", item: candidate{body: `{"code":"INVALID_API_KEY","message":"Invalid API key"}`}, reason: "invalid_key", match: true},
{name: "google missing key", item: candidate{body: `{"error":{"code":401,"message":"API key is required","status":"UNAUTHENTICATED"}}`}, reason: "missing_key", match: true},
{name: "google group deleted", item: candidate{body: `{"error":{"code":403,"message":"API Key 所属分组已删除","status":"PERMISSION_DENIED"}}`}, reason: "group_deleted", match: true},
{name: "ip acl", item: candidate{body: `{"code":"ACCESS_DENIED","message":"Access denied. Your IP is 192.0.2.1"}`}, reason: "ip_acl_denied", match: true},
{name: "user not found remains", item: candidate{body: `{"code":"USER_NOT_FOUND","message":"User associated with API key not found"}`}, match: false},
{name: "quota remains", item: candidate{body: `{"code":"API_KEY_QUOTA_EXHAUSTED","message":"quota"}`}, match: false},
{name: "database failure remains", item: candidate{statusCode: 500, message: "Failed to validate API key", body: `{"code":"INTERNAL_ERROR","message":"Failed to validate API key"}`}, match: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reason, ok := historicalIngressRejectReason(tt.item)
if ok != tt.match || reason != tt.reason {
t.Fatalf("got (%q, %v), want (%q, %v)", reason, ok, tt.reason, tt.match)
}
})
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ func main() {
log.Fatalf("failed to resolve admin user: %v", err)
}
token, err := authService.GenerateToken(user)
token, err := authService.GenerateToken(ctx, user)
if err != nil {
log.Fatalf("failed to generate token: %v", err)
}
+1 -1
View File
@@ -1 +1 @@
0.1.151
0.1.163
+10 -1
View File
@@ -153,6 +153,15 @@ func runMainServer() {
log.Fatalf("Failed to initialize application: %v", err)
}
defer app.Cleanup()
if app.PromptAudit != nil {
if err := app.PromptAudit.Start(context.Background()); err != nil {
// Startup continues so unrelated APIs stay up. Fail-closed (unavailable)
// applies only when a persisted blocking policy was observed; without
// blocking intent, Prompt Audit stays ModeOff so the gateway remains
// usable and administrators can still disable the feature (#4560).
log.Printf("Prompt Audit started in degraded state: %v", err)
}
}
// 启动服务器
go func() {
@@ -174,7 +183,7 @@ func runMainServer() {
defer cancel()
if err := app.Server.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
log.Printf("Server forced to shutdown: %v", err)
}
log.Println("Server exited")
+62 -3
View File
@@ -15,6 +15,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/handler"
"github.com/Wei-Shaw/sub2api/internal/payment"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
"github.com/Wei-Shaw/sub2api/internal/server"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -24,8 +25,9 @@ import (
)
type Application struct {
Server *http.Server
Cleanup func()
Server *http.Server
PromptAudit *securityaudit.PromptService
Cleanup func()
}
func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
@@ -36,6 +38,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
// Business layer ProviderSets
repository.ProviderSet,
service.ProviderSet,
securityaudit.ProviderSet,
payment.ProviderSet,
middleware.ProviderSet,
handler.ProviderSet,
@@ -53,7 +56,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
provideCleanup,
// Application struct
wire.Struct(new(Application), "Server", "Cleanup"),
wire.Struct(new(Application), "Server", "PromptAudit", "Cleanup"),
)
return nil, nil
}
@@ -78,6 +81,10 @@ func provideCleanup(
opsCleanup *service.OpsCleanupService,
opsScheduledReport *service.OpsScheduledReportService,
opsSystemLogSink *service.OpsSystemLogSink,
opsService *service.OpsService,
opsIngressReject *service.OpsIngressRejectAggregator,
apiKeyService *service.APIKeyService,
authCacheInvalidationWorker *service.AuthCacheInvalidationWorker,
schedulerSnapshot *service.SchedulerSnapshotService,
tokenRefresh *service.TokenRefreshService,
accountExpiry *service.AccountExpiryService,
@@ -103,6 +110,10 @@ func provideCleanup(
paymentOrderExpiry *service.PaymentOrderExpiryService,
channelMonitorRunner *service.ChannelMonitorRunner,
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
upstreamBillingProbe *service.UpstreamBillingProbeService,
ollamaCloudUsage *service.OllamaCloudUsageService,
auditLog *service.AuditLogService,
promptAudit *securityaudit.PromptService,
) func() {
return func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -115,6 +126,36 @@ func provideCleanup(
// 应用层清理步骤可并行执行,基础设施资源(Redis/Ent)最后按顺序关闭。
parallelSteps := []cleanupStep{
{"OpsIngressRejectAggregator", func() error {
if opsIngressReject != nil {
opsIngressReject.Stop()
}
return nil
}},
{"AuthCacheInvalidationWorker", func() error {
if authCacheInvalidationWorker != nil {
authCacheInvalidationWorker.Stop()
}
return nil
}},
{"AuthCacheInvalidationSubscriber", func() error {
if apiKeyService != nil {
apiKeyService.StopAuthCacheInvalidationSubscriber()
}
return nil
}},
{"OpsRuntimeSettingsRefresh", func() error {
if opsService != nil {
opsService.StopRuntimeSettingsRefresh()
}
return nil
}},
{"PromptAuditService", func() error {
if promptAudit != nil {
return promptAudit.Shutdown(ctx)
}
return nil
}},
{"OpsScheduledReportService", func() error {
if opsScheduledReport != nil {
opsScheduledReport.Stop()
@@ -133,6 +174,12 @@ func provideCleanup(
}
return nil
}},
{"AuditLogService", func() error {
if auditLog != nil {
auditLog.Stop()
}
return nil
}},
{"OpsAlertEvaluatorService", func() error {
if opsAlertEvaluator != nil {
opsAlertEvaluator.Stop()
@@ -279,6 +326,18 @@ func provideCleanup(
}
return nil
}},
{"UpstreamBillingProbeService", func() error {
if upstreamBillingProbe != nil {
upstreamBillingProbe.Stop()
}
return nil
}},
{"OllamaCloudUsageService", func() error {
if ollamaCloudUsage != nil {
ollamaCloudUsage.Stop()
}
return nil
}},
}
infraSteps := []cleanupStep{
+122 -35
View File
@@ -14,6 +14,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/handler/admin"
"github.com/Wei-Shaw/sub2api/internal/payment"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
"github.com/Wei-Shaw/sub2api/internal/server"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -96,9 +97,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
usageLogRepository := repository.NewUsageLogRepository(client, db)
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
opsRepository := repository.NewOpsRepository(db)
batchImageRepository := repository.NewBatchImageRepository(db)
batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig)
batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig)
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
gatewayCache := repository.NewGatewayCache(redisClient)
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
@@ -137,14 +135,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelRepository := repository.NewChannelRepository(db)
channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService)
modelPricingResolver := service.NewModelPricingResolver(channelService, billingService)
batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver)
batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig)
batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig)
batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig)
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
compositeModelRouteRepository := repository.NewCompositeModelRouteRepository(client)
compositeRouteResolver := service.NewCompositeRouteResolver(compositeModelRouteRepository)
notificationEmailService := service.NewNotificationEmailService(settingRepository, emailService)
balanceNotifyService := service.ProvideBalanceNotifyService(emailService, settingRepository, accountRepository, notificationEmailService)
gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, balanceNotifyService, serviceUserPlatformQuotaRepository)
gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, compositeRouteResolver, balanceNotifyService, serviceUserPlatformQuotaRepository)
openAIOAuthClient := repository.NewOpenAIOAuthClient()
privacyClientFactory := providePrivacyClientFactory()
openAIOAuthService := service.ProvideOpenAIOAuthService(proxyRepository, openAIOAuthClient, privacyClientFactory)
@@ -164,7 +159,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
antigravityGatewayService := service.NewAntigravityGatewayService(accountRepository, gatewayCache, schedulerSnapshotService, antigravityTokenProvider, rateLimitService, httpUpstream, settingService, internal500CounterCache)
geminiMessagesCompatService := service.NewGeminiMessagesCompatService(accountRepository, groupRepository, gatewayCache, schedulerSnapshotService, geminiTokenProvider, rateLimitService, httpUpstream, antigravityGatewayService, configConfig)
opsSystemLogSink := service.ProvideOpsSystemLogSink(opsRepository)
opsService := service.ProvideOpsService(opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink, settingService)
authCacheInvalidationOutboxRepository := repository.NewAuthCacheInvalidationOutboxRepository(db)
authCacheInvalidationWorker := service.ProvideAuthCacheInvalidationWorker(authCacheInvalidationOutboxRepository, apiKeyCache, apiKeyService)
opsService := service.ProvideOpsService(opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink, settingService, authCacheInvalidationWorker, apiKeyService)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService)
redeemHandler := handler.NewRedeemHandler(redeemService)
subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService)
@@ -181,34 +178,39 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
leaderLockCache := repository.NewLeaderLockCache(redisClient)
dashboardAggregationService := service.ProvideDashboardAggregationService(dashboardAggregationRepository, timingWheelService, leaderLockCache, db, configConfig)
dashboardHandler := admin.NewDashboardHandler(dashboardService, dashboardAggregationService)
adminGroupRepository := repository.NewAdminGroupRepository(client, db)
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
adminService := service.NewAdminService(userRepository, groupRepository, accountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache)
adminService := service.NewAdminService(userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService)
claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream)
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository)
grokQuotaFetcher := service.NewGrokQuotaFetcher()
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory)
grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, configConfig, usageLogRepository)
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService)
usageCache := service.NewUsageCache()
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService)
accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService)
accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService)
accountTestService := service.ProvideAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService, openAIGatewayService)
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)
accountHandler := admin.ProvideAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator, grokQuotaService)
adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService)
dataManagementService := service.NewDataManagementService()
dataManagementHandler := admin.NewDataManagementHandler(dataManagementService)
backupObjectStoreFactory := repository.NewS3BackupStoreFactory()
dbDumper := repository.NewPgDumper(configConfig)
backupService := service.ProvideBackupService(settingRepository, configConfig, secretEncryptor, backupObjectStoreFactory, dbDumper)
backupHandler := admin.NewBackupHandler(backupService, userService)
imageStorageFactory := repository.ProvideImageStorageFactory()
imageStorageSettingService := service.ProvideImageStorageSettingService(settingRepository, secretEncryptor, backupService, imageStorageFactory, configConfig)
backupHandler := admin.NewBackupHandler(backupService, userService, imageStorageSettingService)
oAuthHandler := admin.NewOAuthHandler(oAuthService)
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)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService, tokenRefreshService)
proxyHandler := admin.NewProxyHandler(adminService)
adminRedeemHandler := admin.NewRedeemHandler(adminService, redeemService)
promoHandler := admin.NewPromoHandler(promoService)
@@ -220,7 +222,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
registry := payment.ProvideRegistry()
defaultLoadBalancer := payment.ProvideDefaultLoadBalancer(client, encryptionKey)
paymentService := service.ProvidePaymentService(client, registry, defaultLoadBalancer, redeemService, subscriptionService, paymentConfigService, userRepository, groupRepository, affiliateService, notificationEmailService)
settingHandler := handler.ProvideAdminSettingHandler(settingService, emailService, turnstileService, opsService, paymentConfigService, paymentService, userAttributeService, notificationEmailService)
settingHandler := handler.ProvideAdminSettingHandler(settingService, emailService, turnstileService, opsService, paymentConfigService, paymentService, userAttributeService, notificationEmailService, totpService, userService)
opsHandler := admin.NewOpsHandler(opsService)
updateCache := repository.NewUpdateCache(redisClient)
gitHubReleaseClient := repository.ProvideGitHubReleaseClient(configConfig)
@@ -253,46 +255,74 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
contentModerationHashCache := repository.NewContentModerationHashCache(redisClient)
contentModerationService := service.NewContentModerationService(settingRepository, contentModerationRepository, contentModerationHashCache, groupRepository, userRepository, apiKeyAuthCacheInvalidator, emailService)
contentModerationHandler := admin.NewContentModerationHandler(contentModerationService)
configManager := securityaudit.NewConfigManager(db, settingRepository, redisClient, secretEncryptor)
postgreSQLRepository := securityaudit.NewPostgreSQLRepository(db)
redisPayloadStore := securityaudit.NewRedisPayloadStore(redisClient)
openAICompatibleScanner := securityaudit.NewOpenAICompatibleScanner()
atomicMetrics := securityaudit.NewAtomicMetrics()
promptService := securityaudit.NewPromptService(configManager, postgreSQLRepository, redisPayloadStore, openAICompatibleScanner, atomicMetrics)
promptAdminHandler := securityaudit.NewPromptAdminHandler(promptService)
paymentHandler := admin.NewPaymentHandler(paymentService, paymentConfigService)
affiliateHandler := admin.NewAffiliateHandler(affiliateService, adminService)
complianceHandler := admin.NewComplianceHandler(settingService)
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)
auditLogRepository := repository.NewAuditLogRepository(db)
auditLogService := service.ProvideAuditLogService(auditLogRepository, settingService)
auditLogHandler := admin.NewAuditLogHandler(auditLogService, totpService)
upstreamBillingProbeService := service.ProvideUpstreamBillingProbeService(accountRepository, accountTestService, settingService, leaderLockCache, db)
ollamaCloudUsageService := service.ProvideOllamaCloudUsageService(accountRepository, httpUpstream, settingService, secretEncryptor, configConfig, leaderLockCache, db)
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, promptAdminHandler, paymentHandler, affiliateHandler, complianceHandler, auditLogHandler, upstreamBillingProbeService, ollamaCloudUsageService)
usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig)
userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient)
userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, 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)
legacyEngine := securityaudit.NewLegacyModerationAdapter(contentModerationService)
coordinator := securityaudit.NewCoordinator(legacyEngine, promptService)
gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator)
openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator)
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService)
totpHandler := handler.NewTotpHandler(totpService)
handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService, channelService)
handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService)
paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry)
availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService)
batchImageHandler := handler.NewBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService)
imageTaskStore := repository.NewImageTaskStore(redisClient)
imageTaskService := service.ProvideImageTaskService(imageTaskStore, imageStorageSettingService)
asyncImageHandler := handler.NewAsyncImageHandler(imageTaskService, openAIGatewayHandler)
batchImageRepository := repository.NewBatchImageRepository(db)
batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig)
batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver)
batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig)
batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig)
batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig)
batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig)
batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler)
idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig)
idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig)
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService)
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService)
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService)
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService)
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService)
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService)
apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig)
engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, apiKeyService, subscriptionService, opsService, settingService, redisClient)
auditLogMiddleware := middleware.NewAuditLogMiddleware(auditLogService)
stepUpAuthMiddleware := middleware.NewStepUpAuthMiddleware(totpService, userService, settingService)
engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, auditLogMiddleware, stepUpAuthMiddleware, apiKeyService, subscriptionService, opsService, settingService, compositeRouteResolver, redisClient)
httpServer := server.ProvideHTTPServer(configConfig, engine)
opsMetricsCollector := service.ProvideOpsMetricsCollector(opsRepository, settingRepository, accountRepository, concurrencyService, db, redisClient, configConfig)
opsAggregationService := service.ProvideOpsAggregationService(opsRepository, settingRepository, db, redisClient, configConfig)
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, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
opsIngressRejectAggregator := service.ProvideOpsIngressRejectAggregator(opsRepository, opsService)
accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository)
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db)
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig)
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, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, promptService)
application := &Application{
Server: httpServer,
Cleanup: v,
Server: httpServer,
PromptAudit: promptService,
Cleanup: v,
}
return application, nil
}
@@ -300,8 +330,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
// wire.go:
type Application struct {
Server *http.Server
Cleanup func()
Server *http.Server
PromptAudit *securityaudit.PromptService
Cleanup func()
}
func providePrivacyClientFactory() service.PrivacyClientFactory {
@@ -324,6 +355,10 @@ func provideCleanup(
opsCleanup *service.OpsCleanupService,
opsScheduledReport *service.OpsScheduledReportService,
opsSystemLogSink *service.OpsSystemLogSink,
opsService *service.OpsService,
opsIngressReject *service.OpsIngressRejectAggregator,
apiKeyService *service.APIKeyService,
authCacheInvalidationWorker *service.AuthCacheInvalidationWorker,
schedulerSnapshot *service.SchedulerSnapshotService,
tokenRefresh *service.TokenRefreshService,
accountExpiry *service.AccountExpiryService,
@@ -349,6 +384,10 @@ func provideCleanup(
paymentOrderExpiry *service.PaymentOrderExpiryService,
channelMonitorRunner *service.ChannelMonitorRunner,
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
upstreamBillingProbe *service.UpstreamBillingProbeService,
ollamaCloudUsage *service.OllamaCloudUsageService,
auditLog *service.AuditLogService,
promptAudit *securityaudit.PromptService,
) func() {
return func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -360,6 +399,36 @@ func provideCleanup(
}
parallelSteps := []cleanupStep{
{"OpsIngressRejectAggregator", func() error {
if opsIngressReject != nil {
opsIngressReject.Stop()
}
return nil
}},
{"AuthCacheInvalidationWorker", func() error {
if authCacheInvalidationWorker != nil {
authCacheInvalidationWorker.Stop()
}
return nil
}},
{"AuthCacheInvalidationSubscriber", func() error {
if apiKeyService != nil {
apiKeyService.StopAuthCacheInvalidationSubscriber()
}
return nil
}},
{"OpsRuntimeSettingsRefresh", func() error {
if opsService != nil {
opsService.StopRuntimeSettingsRefresh()
}
return nil
}},
{"PromptAuditService", func() error {
if promptAudit != nil {
return promptAudit.Shutdown(ctx)
}
return nil
}},
{"OpsScheduledReportService", func() error {
if opsScheduledReport != nil {
opsScheduledReport.Stop()
@@ -378,6 +447,12 @@ func provideCleanup(
}
return nil
}},
{"AuditLogService", func() error {
if auditLog != nil {
auditLog.Stop()
}
return nil
}},
{"OpsAlertEvaluatorService", func() error {
if opsAlertEvaluator != nil {
opsAlertEvaluator.Stop()
@@ -524,6 +599,18 @@ func provideCleanup(
}
return nil
}},
{"UpstreamBillingProbeService", func() error {
if upstreamBillingProbe != nil {
upstreamBillingProbe.Stop()
}
return nil
}},
{"OllamaCloudUsageService", func() error {
if ollamaCloudUsage != nil {
ollamaCloudUsage.Stop()
}
return nil
}},
}
infraSteps := []cleanupStep{
+8
View File
@@ -58,6 +58,10 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
&service.OpsCleanupService{},
&service.OpsScheduledReportService{},
opsSystemLogSinkSvc,
nil, // opsService
nil, // opsIngressRejectAggregator
nil, // apiKeyService
nil, // authCacheInvalidationWorker
schedulerSnapshotSvc,
tokenRefreshSvc,
accountExpirySvc,
@@ -83,6 +87,10 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
nil, // paymentOrderExpiry
nil, // channelMonitorRunner
nil, // quotaFlusher
nil, // upstreamBillingProbe
nil, // ollamaCloudUsage
nil, // auditLog
nil, // promptAudit
)
require.NotPanics(t, func() {
+2 -1
View File
@@ -167,6 +167,7 @@ const (
ProviderOpenai Provider = "openai"
ProviderAnthropic Provider = "anthropic"
ProviderGemini Provider = "gemini"
ProviderGrok Provider = "grok"
)
func (pr Provider) String() string {
@@ -176,7 +177,7 @@ func (pr Provider) String() string {
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
func ProviderValidator(pr Provider) error {
switch pr {
case ProviderOpenai, ProviderAnthropic, ProviderGemini:
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok:
return nil
default:
return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr)
@@ -103,6 +103,7 @@ const (
ProviderOpenai Provider = "openai"
ProviderAnthropic Provider = "anthropic"
ProviderGemini Provider = "gemini"
ProviderGrok Provider = "grok"
)
func (pr Provider) String() string {
@@ -112,7 +113,7 @@ func (pr Provider) String() string {
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
func ProviderValidator(pr Provider) error {
switch pr {
case ProviderOpenai, ProviderAnthropic, ProviderGemini:
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok:
return nil
default:
return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr)
+175 -14
View File
@@ -29,6 +29,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/channelmonitordailyrollup"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorhistory"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorrequesttemplate"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/errorpassthroughrule"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/idempotencyrecord"
@@ -90,6 +91,8 @@ type Client struct {
ChannelMonitorHistory *ChannelMonitorHistoryClient
// ChannelMonitorRequestTemplate is the client for interacting with the ChannelMonitorRequestTemplate builders.
ChannelMonitorRequestTemplate *ChannelMonitorRequestTemplateClient
// CompositeModelRoute is the client for interacting with the CompositeModelRoute builders.
CompositeModelRoute *CompositeModelRouteClient
// ErrorPassthroughRule is the client for interacting with the ErrorPassthroughRule builders.
ErrorPassthroughRule *ErrorPassthroughRuleClient
// Group is the client for interacting with the Group builders.
@@ -163,6 +166,7 @@ func (c *Client) init() {
c.ChannelMonitorDailyRollup = NewChannelMonitorDailyRollupClient(c.config)
c.ChannelMonitorHistory = NewChannelMonitorHistoryClient(c.config)
c.ChannelMonitorRequestTemplate = NewChannelMonitorRequestTemplateClient(c.config)
c.CompositeModelRoute = NewCompositeModelRouteClient(c.config)
c.ErrorPassthroughRule = NewErrorPassthroughRuleClient(c.config)
c.Group = NewGroupClient(c.config)
c.IdempotencyRecord = NewIdempotencyRecordClient(c.config)
@@ -293,6 +297,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
ChannelMonitorDailyRollup: NewChannelMonitorDailyRollupClient(cfg),
ChannelMonitorHistory: NewChannelMonitorHistoryClient(cfg),
ChannelMonitorRequestTemplate: NewChannelMonitorRequestTemplateClient(cfg),
CompositeModelRoute: NewCompositeModelRouteClient(cfg),
ErrorPassthroughRule: NewErrorPassthroughRuleClient(cfg),
Group: NewGroupClient(cfg),
IdempotencyRecord: NewIdempotencyRecordClient(cfg),
@@ -350,6 +355,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
ChannelMonitorDailyRollup: NewChannelMonitorDailyRollupClient(cfg),
ChannelMonitorHistory: NewChannelMonitorHistoryClient(cfg),
ChannelMonitorRequestTemplate: NewChannelMonitorRequestTemplateClient(cfg),
CompositeModelRoute: NewCompositeModelRouteClient(cfg),
ErrorPassthroughRule: NewErrorPassthroughRuleClient(cfg),
Group: NewGroupClient(cfg),
IdempotencyRecord: NewIdempotencyRecordClient(cfg),
@@ -407,7 +413,7 @@ func (c *Client) Use(hooks ...Hook) {
c.AuthIdentity, c.AuthIdentityChannel, c.BatchImageEvent, c.BatchImageItem,
c.BatchImageJob, c.ChannelMonitor, c.ChannelMonitorDailyRollup,
c.ChannelMonitorHistory, c.ChannelMonitorRequestTemplate,
c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord,
c.CompositeModelRoute, c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord,
c.IdentityAdoptionDecision, c.PaymentAuditLog, c.PaymentOrder,
c.PaymentProviderInstance, c.PendingAuthSession, c.PromoCode, c.PromoCodeUsage,
c.Proxy, c.RedeemCode, c.SecuritySecret, c.Setting, c.SubscriptionPlan,
@@ -427,7 +433,7 @@ func (c *Client) Intercept(interceptors ...Interceptor) {
c.AuthIdentity, c.AuthIdentityChannel, c.BatchImageEvent, c.BatchImageItem,
c.BatchImageJob, c.ChannelMonitor, c.ChannelMonitorDailyRollup,
c.ChannelMonitorHistory, c.ChannelMonitorRequestTemplate,
c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord,
c.CompositeModelRoute, c.ErrorPassthroughRule, c.Group, c.IdempotencyRecord,
c.IdentityAdoptionDecision, c.PaymentAuditLog, c.PaymentOrder,
c.PaymentProviderInstance, c.PendingAuthSession, c.PromoCode, c.PromoCodeUsage,
c.Proxy, c.RedeemCode, c.SecuritySecret, c.Setting, c.SubscriptionPlan,
@@ -470,6 +476,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.ChannelMonitorHistory.mutate(ctx, m)
case *ChannelMonitorRequestTemplateMutation:
return c.ChannelMonitorRequestTemplate.mutate(ctx, m)
case *CompositeModelRouteMutation:
return c.CompositeModelRoute.mutate(ctx, m)
case *ErrorPassthroughRuleMutation:
return c.ErrorPassthroughRule.mutate(ctx, m)
case *GroupMutation:
@@ -2724,6 +2732,157 @@ func (c *ChannelMonitorRequestTemplateClient) mutate(ctx context.Context, m *Cha
}
}
// CompositeModelRouteClient is a client for the CompositeModelRoute schema.
type CompositeModelRouteClient struct {
config
}
// NewCompositeModelRouteClient returns a client for the CompositeModelRoute from the given config.
func NewCompositeModelRouteClient(c config) *CompositeModelRouteClient {
return &CompositeModelRouteClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `compositemodelroute.Hooks(f(g(h())))`.
func (c *CompositeModelRouteClient) Use(hooks ...Hook) {
c.hooks.CompositeModelRoute = append(c.hooks.CompositeModelRoute, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `compositemodelroute.Intercept(f(g(h())))`.
func (c *CompositeModelRouteClient) Intercept(interceptors ...Interceptor) {
c.inters.CompositeModelRoute = append(c.inters.CompositeModelRoute, interceptors...)
}
// Create returns a builder for creating a CompositeModelRoute entity.
func (c *CompositeModelRouteClient) Create() *CompositeModelRouteCreate {
mutation := newCompositeModelRouteMutation(c.config, OpCreate)
return &CompositeModelRouteCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of CompositeModelRoute entities.
func (c *CompositeModelRouteClient) CreateBulk(builders ...*CompositeModelRouteCreate) *CompositeModelRouteCreateBulk {
return &CompositeModelRouteCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *CompositeModelRouteClient) MapCreateBulk(slice any, setFunc func(*CompositeModelRouteCreate, int)) *CompositeModelRouteCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &CompositeModelRouteCreateBulk{err: fmt.Errorf("calling to CompositeModelRouteClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*CompositeModelRouteCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &CompositeModelRouteCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for CompositeModelRoute.
func (c *CompositeModelRouteClient) Update() *CompositeModelRouteUpdate {
mutation := newCompositeModelRouteMutation(c.config, OpUpdate)
return &CompositeModelRouteUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *CompositeModelRouteClient) UpdateOne(_m *CompositeModelRoute) *CompositeModelRouteUpdateOne {
mutation := newCompositeModelRouteMutation(c.config, OpUpdateOne, withCompositeModelRoute(_m))
return &CompositeModelRouteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *CompositeModelRouteClient) UpdateOneID(id int64) *CompositeModelRouteUpdateOne {
mutation := newCompositeModelRouteMutation(c.config, OpUpdateOne, withCompositeModelRouteID(id))
return &CompositeModelRouteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for CompositeModelRoute.
func (c *CompositeModelRouteClient) Delete() *CompositeModelRouteDelete {
mutation := newCompositeModelRouteMutation(c.config, OpDelete)
return &CompositeModelRouteDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *CompositeModelRouteClient) DeleteOne(_m *CompositeModelRoute) *CompositeModelRouteDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *CompositeModelRouteClient) DeleteOneID(id int64) *CompositeModelRouteDeleteOne {
builder := c.Delete().Where(compositemodelroute.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &CompositeModelRouteDeleteOne{builder}
}
// Query returns a query builder for CompositeModelRoute.
func (c *CompositeModelRouteClient) Query() *CompositeModelRouteQuery {
return &CompositeModelRouteQuery{
config: c.config,
ctx: &QueryContext{Type: TypeCompositeModelRoute},
inters: c.Interceptors(),
}
}
// Get returns a CompositeModelRoute entity by its id.
func (c *CompositeModelRouteClient) Get(ctx context.Context, id int64) (*CompositeModelRoute, error) {
return c.Query().Where(compositemodelroute.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *CompositeModelRouteClient) GetX(ctx context.Context, id int64) *CompositeModelRoute {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryGroup queries the group edge of a CompositeModelRoute.
func (c *CompositeModelRouteClient) QueryGroup(_m *CompositeModelRoute) *GroupQuery {
query := (&GroupClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(compositemodelroute.Table, compositemodelroute.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, compositemodelroute.GroupTable, compositemodelroute.GroupColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *CompositeModelRouteClient) Hooks() []Hook {
hooks := c.hooks.CompositeModelRoute
return append(hooks[:len(hooks):len(hooks)], compositemodelroute.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *CompositeModelRouteClient) Interceptors() []Interceptor {
inters := c.inters.CompositeModelRoute
return append(inters[:len(inters):len(inters)], compositemodelroute.Interceptors[:]...)
}
func (c *CompositeModelRouteClient) mutate(ctx context.Context, m *CompositeModelRouteMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&CompositeModelRouteCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&CompositeModelRouteUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&CompositeModelRouteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&CompositeModelRouteDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown CompositeModelRoute mutation op: %q", m.Op())
}
}
// ErrorPassthroughRuleClient is a client for the ErrorPassthroughRule schema.
type ErrorPassthroughRuleClient struct {
config
@@ -6669,23 +6828,25 @@ type (
APIKey, Account, AccountGroup, Announcement, AnnouncementRead, AuthIdentity,
AuthIdentityChannel, BatchImageEvent, BatchImageItem, BatchImageJob,
ChannelMonitor, ChannelMonitorDailyRollup, ChannelMonitorHistory,
ChannelMonitorRequestTemplate, ErrorPassthroughRule, Group, IdempotencyRecord,
IdentityAdoptionDecision, PaymentAuditLog, PaymentOrder,
PaymentProviderInstance, PendingAuthSession, PromoCode, PromoCodeUsage, Proxy,
RedeemCode, SecuritySecret, Setting, SubscriptionPlan, TLSFingerprintProfile,
UsageCleanupTask, UsageLog, User, UserAllowedGroup, UserAttributeDefinition,
UserAttributeValue, UserPlatformQuota, UserSubscription []ent.Hook
ChannelMonitorRequestTemplate, CompositeModelRoute,
ErrorPassthroughRule, Group, IdempotencyRecord, IdentityAdoptionDecision,
PaymentAuditLog, PaymentOrder, PaymentProviderInstance, PendingAuthSession,
PromoCode, PromoCodeUsage, Proxy, RedeemCode, SecuritySecret, Setting,
SubscriptionPlan, TLSFingerprintProfile, UsageCleanupTask, UsageLog, User,
UserAllowedGroup, UserAttributeDefinition, UserAttributeValue,
UserPlatformQuota, UserSubscription []ent.Hook
}
inters struct {
APIKey, Account, AccountGroup, Announcement, AnnouncementRead, AuthIdentity,
AuthIdentityChannel, BatchImageEvent, BatchImageItem, BatchImageJob,
ChannelMonitor, ChannelMonitorDailyRollup, ChannelMonitorHistory,
ChannelMonitorRequestTemplate, ErrorPassthroughRule, Group, IdempotencyRecord,
IdentityAdoptionDecision, PaymentAuditLog, PaymentOrder,
PaymentProviderInstance, PendingAuthSession, PromoCode, PromoCodeUsage, Proxy,
RedeemCode, SecuritySecret, Setting, SubscriptionPlan, TLSFingerprintProfile,
UsageCleanupTask, UsageLog, User, UserAllowedGroup, UserAttributeDefinition,
UserAttributeValue, UserPlatformQuota, UserSubscription []ent.Interceptor
ChannelMonitorRequestTemplate, CompositeModelRoute,
ErrorPassthroughRule, Group, IdempotencyRecord, IdentityAdoptionDecision,
PaymentAuditLog, PaymentOrder, PaymentProviderInstance, PendingAuthSession,
PromoCode, PromoCodeUsage, Proxy, RedeemCode, SecuritySecret, Setting,
SubscriptionPlan, TLSFingerprintProfile, UsageCleanupTask, UsageLog, User,
UserAllowedGroup, UserAttributeDefinition, UserAttributeValue,
UserPlatformQuota, UserSubscription []ent.Interceptor
}
)
+264
View File
@@ -0,0 +1,264 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/group"
)
// CompositeModelRoute is the model entity for the CompositeModelRoute schema.
type CompositeModelRoute struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt *time.Time `json:"deleted_at,omitempty"`
// GroupID holds the value of the "group_id" field.
GroupID int64 `json:"group_id,omitempty"`
// Client-facing model identifier or prefix.
PublicModel string `json:"public_model,omitempty"`
// exact or prefix.
MatchType string `json:"match_type,omitempty"`
// Concrete provider platform.
TargetPlatform string `json:"target_platform,omitempty"`
// Provider model identifier; empty means public_model.
UpstreamModel string `json:"upstream_model,omitempty"`
// Endpoint scope such as any, messages, responses, chat_completions.
Endpoint string `json:"endpoint,omitempty"`
// Lower values win within the same match strength.
Priority int `json:"priority,omitempty"`
// Enabled holds the value of the "enabled" field.
Enabled bool `json:"enabled,omitempty"`
// Notes holds the value of the "notes" field.
Notes *string `json:"notes,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the CompositeModelRouteQuery when eager-loading is set.
Edges CompositeModelRouteEdges `json:"edges"`
selectValues sql.SelectValues
}
// CompositeModelRouteEdges holds the relations/edges for other nodes in the graph.
type CompositeModelRouteEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e CompositeModelRouteEdges) GroupOrErr() (*Group, error) {
if e.Group != nil {
return e.Group, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: group.Label}
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*CompositeModelRoute) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case compositemodelroute.FieldEnabled:
values[i] = new(sql.NullBool)
case compositemodelroute.FieldID, compositemodelroute.FieldGroupID, compositemodelroute.FieldPriority:
values[i] = new(sql.NullInt64)
case compositemodelroute.FieldPublicModel, compositemodelroute.FieldMatchType, compositemodelroute.FieldTargetPlatform, compositemodelroute.FieldUpstreamModel, compositemodelroute.FieldEndpoint, compositemodelroute.FieldNotes:
values[i] = new(sql.NullString)
case compositemodelroute.FieldCreatedAt, compositemodelroute.FieldUpdatedAt, compositemodelroute.FieldDeletedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the CompositeModelRoute fields.
func (_m *CompositeModelRoute) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case compositemodelroute.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int64(value.Int64)
case compositemodelroute.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case compositemodelroute.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
case compositemodelroute.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = new(time.Time)
*_m.DeletedAt = value.Time
}
case compositemodelroute.FieldGroupID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field group_id", values[i])
} else if value.Valid {
_m.GroupID = value.Int64
}
case compositemodelroute.FieldPublicModel:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field public_model", values[i])
} else if value.Valid {
_m.PublicModel = value.String
}
case compositemodelroute.FieldMatchType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field match_type", values[i])
} else if value.Valid {
_m.MatchType = value.String
}
case compositemodelroute.FieldTargetPlatform:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field target_platform", values[i])
} else if value.Valid {
_m.TargetPlatform = value.String
}
case compositemodelroute.FieldUpstreamModel:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field upstream_model", values[i])
} else if value.Valid {
_m.UpstreamModel = value.String
}
case compositemodelroute.FieldEndpoint:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field endpoint", values[i])
} else if value.Valid {
_m.Endpoint = value.String
}
case compositemodelroute.FieldPriority:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field priority", values[i])
} else if value.Valid {
_m.Priority = int(value.Int64)
}
case compositemodelroute.FieldEnabled:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field enabled", values[i])
} else if value.Valid {
_m.Enabled = value.Bool
}
case compositemodelroute.FieldNotes:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[i])
} else if value.Valid {
_m.Notes = new(string)
*_m.Notes = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the CompositeModelRoute.
// This includes values selected through modifiers, order, etc.
func (_m *CompositeModelRoute) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryGroup queries the "group" edge of the CompositeModelRoute entity.
func (_m *CompositeModelRoute) QueryGroup() *GroupQuery {
return NewCompositeModelRouteClient(_m.config).QueryGroup(_m)
}
// Update returns a builder for updating this CompositeModelRoute.
// Note that you need to call CompositeModelRoute.Unwrap() before calling this method if this CompositeModelRoute
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *CompositeModelRoute) Update() *CompositeModelRouteUpdateOne {
return NewCompositeModelRouteClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the CompositeModelRoute entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *CompositeModelRoute) Unwrap() *CompositeModelRoute {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: CompositeModelRoute is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *CompositeModelRoute) String() string {
var builder strings.Builder
builder.WriteString("CompositeModelRoute(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := _m.DeletedAt; v != nil {
builder.WriteString("deleted_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("group_id=")
builder.WriteString(fmt.Sprintf("%v", _m.GroupID))
builder.WriteString(", ")
builder.WriteString("public_model=")
builder.WriteString(_m.PublicModel)
builder.WriteString(", ")
builder.WriteString("match_type=")
builder.WriteString(_m.MatchType)
builder.WriteString(", ")
builder.WriteString("target_platform=")
builder.WriteString(_m.TargetPlatform)
builder.WriteString(", ")
builder.WriteString("upstream_model=")
builder.WriteString(_m.UpstreamModel)
builder.WriteString(", ")
builder.WriteString("endpoint=")
builder.WriteString(_m.Endpoint)
builder.WriteString(", ")
builder.WriteString("priority=")
builder.WriteString(fmt.Sprintf("%v", _m.Priority))
builder.WriteString(", ")
builder.WriteString("enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.Enabled))
builder.WriteString(", ")
if v := _m.Notes; v != nil {
builder.WriteString("notes=")
builder.WriteString(*v)
}
builder.WriteByte(')')
return builder.String()
}
// CompositeModelRoutes is a parsable slice of CompositeModelRoute.
type CompositeModelRoutes []*CompositeModelRoute
@@ -0,0 +1,200 @@
// Code generated by ent, DO NOT EDIT.
package compositemodelroute
import (
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the compositemodelroute type in the database.
Label = "composite_model_route"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldGroupID holds the string denoting the group_id field in the database.
FieldGroupID = "group_id"
// FieldPublicModel holds the string denoting the public_model field in the database.
FieldPublicModel = "public_model"
// FieldMatchType holds the string denoting the match_type field in the database.
FieldMatchType = "match_type"
// FieldTargetPlatform holds the string denoting the target_platform field in the database.
FieldTargetPlatform = "target_platform"
// FieldUpstreamModel holds the string denoting the upstream_model field in the database.
FieldUpstreamModel = "upstream_model"
// FieldEndpoint holds the string denoting the endpoint field in the database.
FieldEndpoint = "endpoint"
// FieldPriority holds the string denoting the priority field in the database.
FieldPriority = "priority"
// FieldEnabled holds the string denoting the enabled field in the database.
FieldEnabled = "enabled"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// Table holds the table name of the compositemodelroute in the database.
Table = "composite_model_routes"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "composite_model_routes"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
)
// Columns holds all SQL columns for compositemodelroute fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldGroupID,
FieldPublicModel,
FieldMatchType,
FieldTargetPlatform,
FieldUpstreamModel,
FieldEndpoint,
FieldPriority,
FieldEnabled,
FieldNotes,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// Note that the variables below are initialized by the runtime
// package on the initialization of the application. Therefore,
// it should be imported in the main as follows:
//
// import _ "github.com/Wei-Shaw/sub2api/ent/runtime"
var (
Hooks [1]ent.Hook
Interceptors [1]ent.Interceptor
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// PublicModelValidator is a validator for the "public_model" field. It is called by the builders before save.
PublicModelValidator func(string) error
// DefaultMatchType holds the default value on creation for the "match_type" field.
DefaultMatchType string
// MatchTypeValidator is a validator for the "match_type" field. It is called by the builders before save.
MatchTypeValidator func(string) error
// DefaultTargetPlatform holds the default value on creation for the "target_platform" field.
DefaultTargetPlatform string
// TargetPlatformValidator is a validator for the "target_platform" field. It is called by the builders before save.
TargetPlatformValidator func(string) error
// DefaultUpstreamModel holds the default value on creation for the "upstream_model" field.
DefaultUpstreamModel string
// UpstreamModelValidator is a validator for the "upstream_model" field. It is called by the builders before save.
UpstreamModelValidator func(string) error
// DefaultEndpoint holds the default value on creation for the "endpoint" field.
DefaultEndpoint string
// EndpointValidator is a validator for the "endpoint" field. It is called by the builders before save.
EndpointValidator func(string) error
// DefaultPriority holds the default value on creation for the "priority" field.
DefaultPriority int
// DefaultEnabled holds the default value on creation for the "enabled" field.
DefaultEnabled bool
)
// OrderOption defines the ordering options for the CompositeModelRoute queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByGroupID orders the results by the group_id field.
func ByGroupID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGroupID, opts...).ToFunc()
}
// ByPublicModel orders the results by the public_model field.
func ByPublicModel(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPublicModel, opts...).ToFunc()
}
// ByMatchType orders the results by the match_type field.
func ByMatchType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMatchType, opts...).ToFunc()
}
// ByTargetPlatform orders the results by the target_platform field.
func ByTargetPlatform(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTargetPlatform, opts...).ToFunc()
}
// ByUpstreamModel orders the results by the upstream_model field.
func ByUpstreamModel(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpstreamModel, opts...).ToFunc()
}
// ByEndpoint orders the results by the endpoint field.
func ByEndpoint(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEndpoint, opts...).ToFunc()
}
// ByPriority orders the results by the priority field.
func ByPriority(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPriority, opts...).ToFunc()
}
// ByEnabled orders the results by the enabled field.
func ByEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEnabled, opts...).ToFunc()
}
// ByNotes orders the results by the notes field.
func ByNotes(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotes, opts...).ToFunc()
}
// ByGroupField orders the results by group field.
func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
func newGroupStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
}
+754
View File
@@ -0,0 +1,754 @@
// Code generated by ent, DO NOT EDIT.
package compositemodelroute
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldDeletedAt, v))
}
// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ.
func GroupID(v int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldGroupID, v))
}
// PublicModel applies equality check predicate on the "public_model" field. It's identical to PublicModelEQ.
func PublicModel(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldPublicModel, v))
}
// MatchType applies equality check predicate on the "match_type" field. It's identical to MatchTypeEQ.
func MatchType(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldMatchType, v))
}
// TargetPlatform applies equality check predicate on the "target_platform" field. It's identical to TargetPlatformEQ.
func TargetPlatform(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldTargetPlatform, v))
}
// UpstreamModel applies equality check predicate on the "upstream_model" field. It's identical to UpstreamModelEQ.
func UpstreamModel(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldUpstreamModel, v))
}
// Endpoint applies equality check predicate on the "endpoint" field. It's identical to EndpointEQ.
func Endpoint(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldEndpoint, v))
}
// Priority applies equality check predicate on the "priority" field. It's identical to PriorityEQ.
func Priority(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldPriority, v))
}
// Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ.
func Enabled(v bool) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldEnabled, v))
}
// Notes applies equality check predicate on the "notes" field. It's identical to NotesEQ.
func Notes(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldNotes, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v time.Time) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotNull(FieldDeletedAt))
}
// GroupIDEQ applies the EQ predicate on the "group_id" field.
func GroupIDEQ(v int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldGroupID, v))
}
// GroupIDNEQ applies the NEQ predicate on the "group_id" field.
func GroupIDNEQ(v int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldGroupID, v))
}
// GroupIDIn applies the In predicate on the "group_id" field.
func GroupIDIn(vs ...int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldGroupID, vs...))
}
// GroupIDNotIn applies the NotIn predicate on the "group_id" field.
func GroupIDNotIn(vs ...int64) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldGroupID, vs...))
}
// PublicModelEQ applies the EQ predicate on the "public_model" field.
func PublicModelEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldPublicModel, v))
}
// PublicModelNEQ applies the NEQ predicate on the "public_model" field.
func PublicModelNEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldPublicModel, v))
}
// PublicModelIn applies the In predicate on the "public_model" field.
func PublicModelIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldPublicModel, vs...))
}
// PublicModelNotIn applies the NotIn predicate on the "public_model" field.
func PublicModelNotIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldPublicModel, vs...))
}
// PublicModelGT applies the GT predicate on the "public_model" field.
func PublicModelGT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldPublicModel, v))
}
// PublicModelGTE applies the GTE predicate on the "public_model" field.
func PublicModelGTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldPublicModel, v))
}
// PublicModelLT applies the LT predicate on the "public_model" field.
func PublicModelLT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldPublicModel, v))
}
// PublicModelLTE applies the LTE predicate on the "public_model" field.
func PublicModelLTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldPublicModel, v))
}
// PublicModelContains applies the Contains predicate on the "public_model" field.
func PublicModelContains(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContains(FieldPublicModel, v))
}
// PublicModelHasPrefix applies the HasPrefix predicate on the "public_model" field.
func PublicModelHasPrefix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasPrefix(FieldPublicModel, v))
}
// PublicModelHasSuffix applies the HasSuffix predicate on the "public_model" field.
func PublicModelHasSuffix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasSuffix(FieldPublicModel, v))
}
// PublicModelEqualFold applies the EqualFold predicate on the "public_model" field.
func PublicModelEqualFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEqualFold(FieldPublicModel, v))
}
// PublicModelContainsFold applies the ContainsFold predicate on the "public_model" field.
func PublicModelContainsFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContainsFold(FieldPublicModel, v))
}
// MatchTypeEQ applies the EQ predicate on the "match_type" field.
func MatchTypeEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldMatchType, v))
}
// MatchTypeNEQ applies the NEQ predicate on the "match_type" field.
func MatchTypeNEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldMatchType, v))
}
// MatchTypeIn applies the In predicate on the "match_type" field.
func MatchTypeIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldMatchType, vs...))
}
// MatchTypeNotIn applies the NotIn predicate on the "match_type" field.
func MatchTypeNotIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldMatchType, vs...))
}
// MatchTypeGT applies the GT predicate on the "match_type" field.
func MatchTypeGT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldMatchType, v))
}
// MatchTypeGTE applies the GTE predicate on the "match_type" field.
func MatchTypeGTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldMatchType, v))
}
// MatchTypeLT applies the LT predicate on the "match_type" field.
func MatchTypeLT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldMatchType, v))
}
// MatchTypeLTE applies the LTE predicate on the "match_type" field.
func MatchTypeLTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldMatchType, v))
}
// MatchTypeContains applies the Contains predicate on the "match_type" field.
func MatchTypeContains(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContains(FieldMatchType, v))
}
// MatchTypeHasPrefix applies the HasPrefix predicate on the "match_type" field.
func MatchTypeHasPrefix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasPrefix(FieldMatchType, v))
}
// MatchTypeHasSuffix applies the HasSuffix predicate on the "match_type" field.
func MatchTypeHasSuffix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasSuffix(FieldMatchType, v))
}
// MatchTypeEqualFold applies the EqualFold predicate on the "match_type" field.
func MatchTypeEqualFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEqualFold(FieldMatchType, v))
}
// MatchTypeContainsFold applies the ContainsFold predicate on the "match_type" field.
func MatchTypeContainsFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContainsFold(FieldMatchType, v))
}
// TargetPlatformEQ applies the EQ predicate on the "target_platform" field.
func TargetPlatformEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldTargetPlatform, v))
}
// TargetPlatformNEQ applies the NEQ predicate on the "target_platform" field.
func TargetPlatformNEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldTargetPlatform, v))
}
// TargetPlatformIn applies the In predicate on the "target_platform" field.
func TargetPlatformIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldTargetPlatform, vs...))
}
// TargetPlatformNotIn applies the NotIn predicate on the "target_platform" field.
func TargetPlatformNotIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldTargetPlatform, vs...))
}
// TargetPlatformGT applies the GT predicate on the "target_platform" field.
func TargetPlatformGT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldTargetPlatform, v))
}
// TargetPlatformGTE applies the GTE predicate on the "target_platform" field.
func TargetPlatformGTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldTargetPlatform, v))
}
// TargetPlatformLT applies the LT predicate on the "target_platform" field.
func TargetPlatformLT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldTargetPlatform, v))
}
// TargetPlatformLTE applies the LTE predicate on the "target_platform" field.
func TargetPlatformLTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldTargetPlatform, v))
}
// TargetPlatformContains applies the Contains predicate on the "target_platform" field.
func TargetPlatformContains(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContains(FieldTargetPlatform, v))
}
// TargetPlatformHasPrefix applies the HasPrefix predicate on the "target_platform" field.
func TargetPlatformHasPrefix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasPrefix(FieldTargetPlatform, v))
}
// TargetPlatformHasSuffix applies the HasSuffix predicate on the "target_platform" field.
func TargetPlatformHasSuffix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasSuffix(FieldTargetPlatform, v))
}
// TargetPlatformEqualFold applies the EqualFold predicate on the "target_platform" field.
func TargetPlatformEqualFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEqualFold(FieldTargetPlatform, v))
}
// TargetPlatformContainsFold applies the ContainsFold predicate on the "target_platform" field.
func TargetPlatformContainsFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContainsFold(FieldTargetPlatform, v))
}
// UpstreamModelEQ applies the EQ predicate on the "upstream_model" field.
func UpstreamModelEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldUpstreamModel, v))
}
// UpstreamModelNEQ applies the NEQ predicate on the "upstream_model" field.
func UpstreamModelNEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldUpstreamModel, v))
}
// UpstreamModelIn applies the In predicate on the "upstream_model" field.
func UpstreamModelIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldUpstreamModel, vs...))
}
// UpstreamModelNotIn applies the NotIn predicate on the "upstream_model" field.
func UpstreamModelNotIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldUpstreamModel, vs...))
}
// UpstreamModelGT applies the GT predicate on the "upstream_model" field.
func UpstreamModelGT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldUpstreamModel, v))
}
// UpstreamModelGTE applies the GTE predicate on the "upstream_model" field.
func UpstreamModelGTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldUpstreamModel, v))
}
// UpstreamModelLT applies the LT predicate on the "upstream_model" field.
func UpstreamModelLT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldUpstreamModel, v))
}
// UpstreamModelLTE applies the LTE predicate on the "upstream_model" field.
func UpstreamModelLTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldUpstreamModel, v))
}
// UpstreamModelContains applies the Contains predicate on the "upstream_model" field.
func UpstreamModelContains(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContains(FieldUpstreamModel, v))
}
// UpstreamModelHasPrefix applies the HasPrefix predicate on the "upstream_model" field.
func UpstreamModelHasPrefix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasPrefix(FieldUpstreamModel, v))
}
// UpstreamModelHasSuffix applies the HasSuffix predicate on the "upstream_model" field.
func UpstreamModelHasSuffix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasSuffix(FieldUpstreamModel, v))
}
// UpstreamModelEqualFold applies the EqualFold predicate on the "upstream_model" field.
func UpstreamModelEqualFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEqualFold(FieldUpstreamModel, v))
}
// UpstreamModelContainsFold applies the ContainsFold predicate on the "upstream_model" field.
func UpstreamModelContainsFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContainsFold(FieldUpstreamModel, v))
}
// EndpointEQ applies the EQ predicate on the "endpoint" field.
func EndpointEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldEndpoint, v))
}
// EndpointNEQ applies the NEQ predicate on the "endpoint" field.
func EndpointNEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldEndpoint, v))
}
// EndpointIn applies the In predicate on the "endpoint" field.
func EndpointIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldEndpoint, vs...))
}
// EndpointNotIn applies the NotIn predicate on the "endpoint" field.
func EndpointNotIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldEndpoint, vs...))
}
// EndpointGT applies the GT predicate on the "endpoint" field.
func EndpointGT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldEndpoint, v))
}
// EndpointGTE applies the GTE predicate on the "endpoint" field.
func EndpointGTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldEndpoint, v))
}
// EndpointLT applies the LT predicate on the "endpoint" field.
func EndpointLT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldEndpoint, v))
}
// EndpointLTE applies the LTE predicate on the "endpoint" field.
func EndpointLTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldEndpoint, v))
}
// EndpointContains applies the Contains predicate on the "endpoint" field.
func EndpointContains(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContains(FieldEndpoint, v))
}
// EndpointHasPrefix applies the HasPrefix predicate on the "endpoint" field.
func EndpointHasPrefix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasPrefix(FieldEndpoint, v))
}
// EndpointHasSuffix applies the HasSuffix predicate on the "endpoint" field.
func EndpointHasSuffix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasSuffix(FieldEndpoint, v))
}
// EndpointEqualFold applies the EqualFold predicate on the "endpoint" field.
func EndpointEqualFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEqualFold(FieldEndpoint, v))
}
// EndpointContainsFold applies the ContainsFold predicate on the "endpoint" field.
func EndpointContainsFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContainsFold(FieldEndpoint, v))
}
// PriorityEQ applies the EQ predicate on the "priority" field.
func PriorityEQ(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldPriority, v))
}
// PriorityNEQ applies the NEQ predicate on the "priority" field.
func PriorityNEQ(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldPriority, v))
}
// PriorityIn applies the In predicate on the "priority" field.
func PriorityIn(vs ...int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldPriority, vs...))
}
// PriorityNotIn applies the NotIn predicate on the "priority" field.
func PriorityNotIn(vs ...int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldPriority, vs...))
}
// PriorityGT applies the GT predicate on the "priority" field.
func PriorityGT(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldPriority, v))
}
// PriorityGTE applies the GTE predicate on the "priority" field.
func PriorityGTE(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldPriority, v))
}
// PriorityLT applies the LT predicate on the "priority" field.
func PriorityLT(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldPriority, v))
}
// PriorityLTE applies the LTE predicate on the "priority" field.
func PriorityLTE(v int) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldPriority, v))
}
// EnabledEQ applies the EQ predicate on the "enabled" field.
func EnabledEQ(v bool) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldEnabled, v))
}
// EnabledNEQ applies the NEQ predicate on the "enabled" field.
func EnabledNEQ(v bool) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldEnabled, v))
}
// NotesEQ applies the EQ predicate on the "notes" field.
func NotesEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEQ(FieldNotes, v))
}
// NotesNEQ applies the NEQ predicate on the "notes" field.
func NotesNEQ(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNEQ(FieldNotes, v))
}
// NotesIn applies the In predicate on the "notes" field.
func NotesIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIn(FieldNotes, vs...))
}
// NotesNotIn applies the NotIn predicate on the "notes" field.
func NotesNotIn(vs ...string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotIn(FieldNotes, vs...))
}
// NotesGT applies the GT predicate on the "notes" field.
func NotesGT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGT(FieldNotes, v))
}
// NotesGTE applies the GTE predicate on the "notes" field.
func NotesGTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldGTE(FieldNotes, v))
}
// NotesLT applies the LT predicate on the "notes" field.
func NotesLT(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLT(FieldNotes, v))
}
// NotesLTE applies the LTE predicate on the "notes" field.
func NotesLTE(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldLTE(FieldNotes, v))
}
// NotesContains applies the Contains predicate on the "notes" field.
func NotesContains(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContains(FieldNotes, v))
}
// NotesHasPrefix applies the HasPrefix predicate on the "notes" field.
func NotesHasPrefix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasPrefix(FieldNotes, v))
}
// NotesHasSuffix applies the HasSuffix predicate on the "notes" field.
func NotesHasSuffix(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldHasSuffix(FieldNotes, v))
}
// NotesIsNil applies the IsNil predicate on the "notes" field.
func NotesIsNil() predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldIsNull(FieldNotes))
}
// NotesNotNil applies the NotNil predicate on the "notes" field.
func NotesNotNil() predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldNotNull(FieldNotes))
}
// NotesEqualFold applies the EqualFold predicate on the "notes" field.
func NotesEqualFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldEqualFold(FieldNotes, v))
}
// NotesContainsFold applies the ContainsFold predicate on the "notes" field.
func NotesContainsFold(v string) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.FieldContainsFold(FieldNotes, v))
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(func(s *sql.Selector) {
step := newGroupStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.CompositeModelRoute) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.CompositeModelRoute) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.CompositeModelRoute) predicate.CompositeModelRoute {
return predicate.CompositeModelRoute(sql.NotPredicates(p))
}
File diff suppressed because it is too large Load Diff
+88
View File
@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// CompositeModelRouteDelete is the builder for deleting a CompositeModelRoute entity.
type CompositeModelRouteDelete struct {
config
hooks []Hook
mutation *CompositeModelRouteMutation
}
// Where appends a list predicates to the CompositeModelRouteDelete builder.
func (_d *CompositeModelRouteDelete) Where(ps ...predicate.CompositeModelRoute) *CompositeModelRouteDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *CompositeModelRouteDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *CompositeModelRouteDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *CompositeModelRouteDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(compositemodelroute.Table, sqlgraph.NewFieldSpec(compositemodelroute.FieldID, field.TypeInt64))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// CompositeModelRouteDeleteOne is the builder for deleting a single CompositeModelRoute entity.
type CompositeModelRouteDeleteOne struct {
_d *CompositeModelRouteDelete
}
// Where appends a list predicates to the CompositeModelRouteDelete builder.
func (_d *CompositeModelRouteDeleteOne) Where(ps ...predicate.CompositeModelRoute) *CompositeModelRouteDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *CompositeModelRouteDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{compositemodelroute.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *CompositeModelRouteDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
+643
View File
@@ -0,0 +1,643 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// CompositeModelRouteQuery is the builder for querying CompositeModelRoute entities.
type CompositeModelRouteQuery struct {
config
ctx *QueryContext
order []compositemodelroute.OrderOption
inters []Interceptor
predicates []predicate.CompositeModelRoute
withGroup *GroupQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the CompositeModelRouteQuery builder.
func (_q *CompositeModelRouteQuery) Where(ps ...predicate.CompositeModelRoute) *CompositeModelRouteQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *CompositeModelRouteQuery) Limit(limit int) *CompositeModelRouteQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *CompositeModelRouteQuery) Offset(offset int) *CompositeModelRouteQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *CompositeModelRouteQuery) Unique(unique bool) *CompositeModelRouteQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *CompositeModelRouteQuery) Order(o ...compositemodelroute.OrderOption) *CompositeModelRouteQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryGroup chains the current query on the "group" edge.
func (_q *CompositeModelRouteQuery) QueryGroup() *GroupQuery {
query := (&GroupClient{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(compositemodelroute.Table, compositemodelroute.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, compositemodelroute.GroupTable, compositemodelroute.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first CompositeModelRoute entity from the query.
// Returns a *NotFoundError when no CompositeModelRoute was found.
func (_q *CompositeModelRouteQuery) First(ctx context.Context) (*CompositeModelRoute, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{compositemodelroute.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) FirstX(ctx context.Context) *CompositeModelRoute {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first CompositeModelRoute ID from the query.
// Returns a *NotFoundError when no CompositeModelRoute ID was found.
func (_q *CompositeModelRouteQuery) FirstID(ctx context.Context) (id int64, err error) {
var ids []int64
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{compositemodelroute.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single CompositeModelRoute entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one CompositeModelRoute entity is found.
// Returns a *NotFoundError when no CompositeModelRoute entities are found.
func (_q *CompositeModelRouteQuery) Only(ctx context.Context) (*CompositeModelRoute, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{compositemodelroute.Label}
default:
return nil, &NotSingularError{compositemodelroute.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) OnlyX(ctx context.Context) *CompositeModelRoute {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only CompositeModelRoute ID in the query.
// Returns a *NotSingularError when more than one CompositeModelRoute ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *CompositeModelRouteQuery) OnlyID(ctx context.Context) (id int64, err error) {
var ids []int64
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{compositemodelroute.Label}
default:
err = &NotSingularError{compositemodelroute.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) OnlyIDX(ctx context.Context) int64 {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of CompositeModelRoutes.
func (_q *CompositeModelRouteQuery) All(ctx context.Context) ([]*CompositeModelRoute, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*CompositeModelRoute, *CompositeModelRouteQuery]()
return withInterceptors[[]*CompositeModelRoute](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) AllX(ctx context.Context) []*CompositeModelRoute {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of CompositeModelRoute IDs.
func (_q *CompositeModelRouteQuery) IDs(ctx context.Context) (ids []int64, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(compositemodelroute.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) IDsX(ctx context.Context) []int64 {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *CompositeModelRouteQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*CompositeModelRouteQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *CompositeModelRouteQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *CompositeModelRouteQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the CompositeModelRouteQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *CompositeModelRouteQuery) Clone() *CompositeModelRouteQuery {
if _q == nil {
return nil
}
return &CompositeModelRouteQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]compositemodelroute.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.CompositeModelRoute{}, _q.predicates...),
withGroup: _q.withGroup.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *CompositeModelRouteQuery) WithGroup(opts ...func(*GroupQuery)) *CompositeModelRouteQuery {
query := (&GroupClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withGroup = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.CompositeModelRoute.Query().
// GroupBy(compositemodelroute.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *CompositeModelRouteQuery) GroupBy(field string, fields ...string) *CompositeModelRouteGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &CompositeModelRouteGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = compositemodelroute.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.CompositeModelRoute.Query().
// Select(compositemodelroute.FieldCreatedAt).
// Scan(ctx, &v)
func (_q *CompositeModelRouteQuery) Select(fields ...string) *CompositeModelRouteSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &CompositeModelRouteSelect{CompositeModelRouteQuery: _q}
sbuild.label = compositemodelroute.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a CompositeModelRouteSelect configured with the given aggregations.
func (_q *CompositeModelRouteQuery) Aggregate(fns ...AggregateFunc) *CompositeModelRouteSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *CompositeModelRouteQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !compositemodelroute.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *CompositeModelRouteQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CompositeModelRoute, error) {
var (
nodes = []*CompositeModelRoute{}
_spec = _q.querySpec()
loadedTypes = [1]bool{
_q.withGroup != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*CompositeModelRoute).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &CompositeModelRoute{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withGroup; query != nil {
if err := _q.loadGroup(ctx, query, nodes, nil,
func(n *CompositeModelRoute, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *CompositeModelRouteQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*CompositeModelRoute, init func(*CompositeModelRoute), assign func(*CompositeModelRoute, *Group)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*CompositeModelRoute)
for i := range nodes {
fk := nodes[i].GroupID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(group.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 "group_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *CompositeModelRouteQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
if len(_q.modifiers) > 0 {
_spec.Modifiers = _q.modifiers
}
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *CompositeModelRouteQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(compositemodelroute.Table, compositemodelroute.Columns, sqlgraph.NewFieldSpec(compositemodelroute.FieldID, field.TypeInt64))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, compositemodelroute.FieldID)
for i := range fields {
if fields[i] != compositemodelroute.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withGroup != nil {
_spec.Node.AddColumnOnce(compositemodelroute.FieldGroupID)
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *CompositeModelRouteQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(compositemodelroute.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = compositemodelroute.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, m := range _q.modifiers {
m(selector)
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (_q *CompositeModelRouteQuery) ForUpdate(opts ...sql.LockOption) *CompositeModelRouteQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForUpdate(opts...)
})
return _q
}
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (_q *CompositeModelRouteQuery) ForShare(opts ...sql.LockOption) *CompositeModelRouteQuery {
if _q.driver.Dialect() == dialect.Postgres {
_q.Unique(false)
}
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
s.ForShare(opts...)
})
return _q
}
// CompositeModelRouteGroupBy is the group-by builder for CompositeModelRoute entities.
type CompositeModelRouteGroupBy struct {
selector
build *CompositeModelRouteQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *CompositeModelRouteGroupBy) Aggregate(fns ...AggregateFunc) *CompositeModelRouteGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *CompositeModelRouteGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*CompositeModelRouteQuery, *CompositeModelRouteGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *CompositeModelRouteGroupBy) sqlScan(ctx context.Context, root *CompositeModelRouteQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// CompositeModelRouteSelect is the builder for selecting fields of CompositeModelRoute entities.
type CompositeModelRouteSelect struct {
*CompositeModelRouteQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *CompositeModelRouteSelect) Aggregate(fns ...AggregateFunc) *CompositeModelRouteSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *CompositeModelRouteSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*CompositeModelRouteQuery, *CompositeModelRouteSelect](ctx, _s.CompositeModelRouteQuery, _s, _s.inters, v)
}
func (_s *CompositeModelRouteSelect) sqlScan(ctx context.Context, root *CompositeModelRouteQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
+767
View File
@@ -0,0 +1,767 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
)
// CompositeModelRouteUpdate is the builder for updating CompositeModelRoute entities.
type CompositeModelRouteUpdate struct {
config
hooks []Hook
mutation *CompositeModelRouteMutation
}
// Where appends a list predicates to the CompositeModelRouteUpdate builder.
func (_u *CompositeModelRouteUpdate) Where(ps ...predicate.CompositeModelRoute) *CompositeModelRouteUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *CompositeModelRouteUpdate) SetUpdatedAt(v time.Time) *CompositeModelRouteUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *CompositeModelRouteUpdate) SetDeletedAt(v time.Time) *CompositeModelRouteUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableDeletedAt(v *time.Time) *CompositeModelRouteUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *CompositeModelRouteUpdate) ClearDeletedAt() *CompositeModelRouteUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *CompositeModelRouteUpdate) SetGroupID(v int64) *CompositeModelRouteUpdate {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableGroupID(v *int64) *CompositeModelRouteUpdate {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// SetPublicModel sets the "public_model" field.
func (_u *CompositeModelRouteUpdate) SetPublicModel(v string) *CompositeModelRouteUpdate {
_u.mutation.SetPublicModel(v)
return _u
}
// SetNillablePublicModel sets the "public_model" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillablePublicModel(v *string) *CompositeModelRouteUpdate {
if v != nil {
_u.SetPublicModel(*v)
}
return _u
}
// SetMatchType sets the "match_type" field.
func (_u *CompositeModelRouteUpdate) SetMatchType(v string) *CompositeModelRouteUpdate {
_u.mutation.SetMatchType(v)
return _u
}
// SetNillableMatchType sets the "match_type" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableMatchType(v *string) *CompositeModelRouteUpdate {
if v != nil {
_u.SetMatchType(*v)
}
return _u
}
// SetTargetPlatform sets the "target_platform" field.
func (_u *CompositeModelRouteUpdate) SetTargetPlatform(v string) *CompositeModelRouteUpdate {
_u.mutation.SetTargetPlatform(v)
return _u
}
// SetNillableTargetPlatform sets the "target_platform" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableTargetPlatform(v *string) *CompositeModelRouteUpdate {
if v != nil {
_u.SetTargetPlatform(*v)
}
return _u
}
// SetUpstreamModel sets the "upstream_model" field.
func (_u *CompositeModelRouteUpdate) SetUpstreamModel(v string) *CompositeModelRouteUpdate {
_u.mutation.SetUpstreamModel(v)
return _u
}
// SetNillableUpstreamModel sets the "upstream_model" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableUpstreamModel(v *string) *CompositeModelRouteUpdate {
if v != nil {
_u.SetUpstreamModel(*v)
}
return _u
}
// SetEndpoint sets the "endpoint" field.
func (_u *CompositeModelRouteUpdate) SetEndpoint(v string) *CompositeModelRouteUpdate {
_u.mutation.SetEndpoint(v)
return _u
}
// SetNillableEndpoint sets the "endpoint" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableEndpoint(v *string) *CompositeModelRouteUpdate {
if v != nil {
_u.SetEndpoint(*v)
}
return _u
}
// SetPriority sets the "priority" field.
func (_u *CompositeModelRouteUpdate) SetPriority(v int) *CompositeModelRouteUpdate {
_u.mutation.ResetPriority()
_u.mutation.SetPriority(v)
return _u
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillablePriority(v *int) *CompositeModelRouteUpdate {
if v != nil {
_u.SetPriority(*v)
}
return _u
}
// AddPriority adds value to the "priority" field.
func (_u *CompositeModelRouteUpdate) AddPriority(v int) *CompositeModelRouteUpdate {
_u.mutation.AddPriority(v)
return _u
}
// SetEnabled sets the "enabled" field.
func (_u *CompositeModelRouteUpdate) SetEnabled(v bool) *CompositeModelRouteUpdate {
_u.mutation.SetEnabled(v)
return _u
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableEnabled(v *bool) *CompositeModelRouteUpdate {
if v != nil {
_u.SetEnabled(*v)
}
return _u
}
// SetNotes sets the "notes" field.
func (_u *CompositeModelRouteUpdate) SetNotes(v string) *CompositeModelRouteUpdate {
_u.mutation.SetNotes(v)
return _u
}
// SetNillableNotes sets the "notes" field if the given value is not nil.
func (_u *CompositeModelRouteUpdate) SetNillableNotes(v *string) *CompositeModelRouteUpdate {
if v != nil {
_u.SetNotes(*v)
}
return _u
}
// ClearNotes clears the value of the "notes" field.
func (_u *CompositeModelRouteUpdate) ClearNotes() *CompositeModelRouteUpdate {
_u.mutation.ClearNotes()
return _u
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *CompositeModelRouteUpdate) SetGroup(v *Group) *CompositeModelRouteUpdate {
return _u.SetGroupID(v.ID)
}
// Mutation returns the CompositeModelRouteMutation object of the builder.
func (_u *CompositeModelRouteUpdate) Mutation() *CompositeModelRouteMutation {
return _u.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *CompositeModelRouteUpdate) ClearGroup() *CompositeModelRouteUpdate {
_u.mutation.ClearGroup()
return _u
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *CompositeModelRouteUpdate) Save(ctx context.Context) (int, error) {
if err := _u.defaults(); err != nil {
return 0, err
}
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *CompositeModelRouteUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *CompositeModelRouteUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *CompositeModelRouteUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *CompositeModelRouteUpdate) defaults() error {
if _, ok := _u.mutation.UpdatedAt(); !ok {
if compositemodelroute.UpdateDefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized compositemodelroute.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := compositemodelroute.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_u *CompositeModelRouteUpdate) check() error {
if v, ok := _u.mutation.PublicModel(); ok {
if err := compositemodelroute.PublicModelValidator(v); err != nil {
return &ValidationError{Name: "public_model", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.public_model": %w`, err)}
}
}
if v, ok := _u.mutation.MatchType(); ok {
if err := compositemodelroute.MatchTypeValidator(v); err != nil {
return &ValidationError{Name: "match_type", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.match_type": %w`, err)}
}
}
if v, ok := _u.mutation.TargetPlatform(); ok {
if err := compositemodelroute.TargetPlatformValidator(v); err != nil {
return &ValidationError{Name: "target_platform", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.target_platform": %w`, err)}
}
}
if v, ok := _u.mutation.UpstreamModel(); ok {
if err := compositemodelroute.UpstreamModelValidator(v); err != nil {
return &ValidationError{Name: "upstream_model", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.upstream_model": %w`, err)}
}
}
if v, ok := _u.mutation.Endpoint(); ok {
if err := compositemodelroute.EndpointValidator(v); err != nil {
return &ValidationError{Name: "endpoint", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.endpoint": %w`, err)}
}
}
if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "CompositeModelRoute.group"`)
}
return nil
}
func (_u *CompositeModelRouteUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(compositemodelroute.Table, compositemodelroute.Columns, sqlgraph.NewFieldSpec(compositemodelroute.FieldID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(compositemodelroute.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(compositemodelroute.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(compositemodelroute.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.PublicModel(); ok {
_spec.SetField(compositemodelroute.FieldPublicModel, field.TypeString, value)
}
if value, ok := _u.mutation.MatchType(); ok {
_spec.SetField(compositemodelroute.FieldMatchType, field.TypeString, value)
}
if value, ok := _u.mutation.TargetPlatform(); ok {
_spec.SetField(compositemodelroute.FieldTargetPlatform, field.TypeString, value)
}
if value, ok := _u.mutation.UpstreamModel(); ok {
_spec.SetField(compositemodelroute.FieldUpstreamModel, field.TypeString, value)
}
if value, ok := _u.mutation.Endpoint(); ok {
_spec.SetField(compositemodelroute.FieldEndpoint, field.TypeString, value)
}
if value, ok := _u.mutation.Priority(); ok {
_spec.SetField(compositemodelroute.FieldPriority, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedPriority(); ok {
_spec.AddField(compositemodelroute.FieldPriority, field.TypeInt, value)
}
if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(compositemodelroute.FieldEnabled, field.TypeBool, value)
}
if value, ok := _u.mutation.Notes(); ok {
_spec.SetField(compositemodelroute.FieldNotes, field.TypeString, value)
}
if _u.mutation.NotesCleared() {
_spec.ClearField(compositemodelroute.FieldNotes, field.TypeString)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: compositemodelroute.GroupTable,
Columns: []string{compositemodelroute.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: compositemodelroute.GroupTable,
Columns: []string{compositemodelroute.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{compositemodelroute.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// CompositeModelRouteUpdateOne is the builder for updating a single CompositeModelRoute entity.
type CompositeModelRouteUpdateOne struct {
config
fields []string
hooks []Hook
mutation *CompositeModelRouteMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *CompositeModelRouteUpdateOne) SetUpdatedAt(v time.Time) *CompositeModelRouteUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *CompositeModelRouteUpdateOne) SetDeletedAt(v time.Time) *CompositeModelRouteUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableDeletedAt(v *time.Time) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *CompositeModelRouteUpdateOne) ClearDeletedAt() *CompositeModelRouteUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetGroupID sets the "group_id" field.
func (_u *CompositeModelRouteUpdateOne) SetGroupID(v int64) *CompositeModelRouteUpdateOne {
_u.mutation.SetGroupID(v)
return _u
}
// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableGroupID(v *int64) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetGroupID(*v)
}
return _u
}
// SetPublicModel sets the "public_model" field.
func (_u *CompositeModelRouteUpdateOne) SetPublicModel(v string) *CompositeModelRouteUpdateOne {
_u.mutation.SetPublicModel(v)
return _u
}
// SetNillablePublicModel sets the "public_model" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillablePublicModel(v *string) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetPublicModel(*v)
}
return _u
}
// SetMatchType sets the "match_type" field.
func (_u *CompositeModelRouteUpdateOne) SetMatchType(v string) *CompositeModelRouteUpdateOne {
_u.mutation.SetMatchType(v)
return _u
}
// SetNillableMatchType sets the "match_type" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableMatchType(v *string) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetMatchType(*v)
}
return _u
}
// SetTargetPlatform sets the "target_platform" field.
func (_u *CompositeModelRouteUpdateOne) SetTargetPlatform(v string) *CompositeModelRouteUpdateOne {
_u.mutation.SetTargetPlatform(v)
return _u
}
// SetNillableTargetPlatform sets the "target_platform" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableTargetPlatform(v *string) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetTargetPlatform(*v)
}
return _u
}
// SetUpstreamModel sets the "upstream_model" field.
func (_u *CompositeModelRouteUpdateOne) SetUpstreamModel(v string) *CompositeModelRouteUpdateOne {
_u.mutation.SetUpstreamModel(v)
return _u
}
// SetNillableUpstreamModel sets the "upstream_model" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableUpstreamModel(v *string) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetUpstreamModel(*v)
}
return _u
}
// SetEndpoint sets the "endpoint" field.
func (_u *CompositeModelRouteUpdateOne) SetEndpoint(v string) *CompositeModelRouteUpdateOne {
_u.mutation.SetEndpoint(v)
return _u
}
// SetNillableEndpoint sets the "endpoint" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableEndpoint(v *string) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetEndpoint(*v)
}
return _u
}
// SetPriority sets the "priority" field.
func (_u *CompositeModelRouteUpdateOne) SetPriority(v int) *CompositeModelRouteUpdateOne {
_u.mutation.ResetPriority()
_u.mutation.SetPriority(v)
return _u
}
// SetNillablePriority sets the "priority" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillablePriority(v *int) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetPriority(*v)
}
return _u
}
// AddPriority adds value to the "priority" field.
func (_u *CompositeModelRouteUpdateOne) AddPriority(v int) *CompositeModelRouteUpdateOne {
_u.mutation.AddPriority(v)
return _u
}
// SetEnabled sets the "enabled" field.
func (_u *CompositeModelRouteUpdateOne) SetEnabled(v bool) *CompositeModelRouteUpdateOne {
_u.mutation.SetEnabled(v)
return _u
}
// SetNillableEnabled sets the "enabled" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableEnabled(v *bool) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetEnabled(*v)
}
return _u
}
// SetNotes sets the "notes" field.
func (_u *CompositeModelRouteUpdateOne) SetNotes(v string) *CompositeModelRouteUpdateOne {
_u.mutation.SetNotes(v)
return _u
}
// SetNillableNotes sets the "notes" field if the given value is not nil.
func (_u *CompositeModelRouteUpdateOne) SetNillableNotes(v *string) *CompositeModelRouteUpdateOne {
if v != nil {
_u.SetNotes(*v)
}
return _u
}
// ClearNotes clears the value of the "notes" field.
func (_u *CompositeModelRouteUpdateOne) ClearNotes() *CompositeModelRouteUpdateOne {
_u.mutation.ClearNotes()
return _u
}
// SetGroup sets the "group" edge to the Group entity.
func (_u *CompositeModelRouteUpdateOne) SetGroup(v *Group) *CompositeModelRouteUpdateOne {
return _u.SetGroupID(v.ID)
}
// Mutation returns the CompositeModelRouteMutation object of the builder.
func (_u *CompositeModelRouteUpdateOne) Mutation() *CompositeModelRouteMutation {
return _u.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (_u *CompositeModelRouteUpdateOne) ClearGroup() *CompositeModelRouteUpdateOne {
_u.mutation.ClearGroup()
return _u
}
// Where appends a list predicates to the CompositeModelRouteUpdate builder.
func (_u *CompositeModelRouteUpdateOne) Where(ps ...predicate.CompositeModelRoute) *CompositeModelRouteUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *CompositeModelRouteUpdateOne) Select(field string, fields ...string) *CompositeModelRouteUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated CompositeModelRoute entity.
func (_u *CompositeModelRouteUpdateOne) Save(ctx context.Context) (*CompositeModelRoute, error) {
if err := _u.defaults(); err != nil {
return nil, err
}
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *CompositeModelRouteUpdateOne) SaveX(ctx context.Context) *CompositeModelRoute {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *CompositeModelRouteUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *CompositeModelRouteUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *CompositeModelRouteUpdateOne) defaults() error {
if _, ok := _u.mutation.UpdatedAt(); !ok {
if compositemodelroute.UpdateDefaultUpdatedAt == nil {
return fmt.Errorf("ent: uninitialized compositemodelroute.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
}
v := compositemodelroute.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
return nil
}
// check runs all checks and user-defined validators on the builder.
func (_u *CompositeModelRouteUpdateOne) check() error {
if v, ok := _u.mutation.PublicModel(); ok {
if err := compositemodelroute.PublicModelValidator(v); err != nil {
return &ValidationError{Name: "public_model", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.public_model": %w`, err)}
}
}
if v, ok := _u.mutation.MatchType(); ok {
if err := compositemodelroute.MatchTypeValidator(v); err != nil {
return &ValidationError{Name: "match_type", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.match_type": %w`, err)}
}
}
if v, ok := _u.mutation.TargetPlatform(); ok {
if err := compositemodelroute.TargetPlatformValidator(v); err != nil {
return &ValidationError{Name: "target_platform", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.target_platform": %w`, err)}
}
}
if v, ok := _u.mutation.UpstreamModel(); ok {
if err := compositemodelroute.UpstreamModelValidator(v); err != nil {
return &ValidationError{Name: "upstream_model", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.upstream_model": %w`, err)}
}
}
if v, ok := _u.mutation.Endpoint(); ok {
if err := compositemodelroute.EndpointValidator(v); err != nil {
return &ValidationError{Name: "endpoint", err: fmt.Errorf(`ent: validator failed for field "CompositeModelRoute.endpoint": %w`, err)}
}
}
if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 {
return errors.New(`ent: clearing a required unique edge "CompositeModelRoute.group"`)
}
return nil
}
func (_u *CompositeModelRouteUpdateOne) sqlSave(ctx context.Context) (_node *CompositeModelRoute, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(compositemodelroute.Table, compositemodelroute.Columns, sqlgraph.NewFieldSpec(compositemodelroute.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "CompositeModelRoute.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, compositemodelroute.FieldID)
for _, f := range fields {
if !compositemodelroute.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != compositemodelroute.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(compositemodelroute.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(compositemodelroute.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(compositemodelroute.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.PublicModel(); ok {
_spec.SetField(compositemodelroute.FieldPublicModel, field.TypeString, value)
}
if value, ok := _u.mutation.MatchType(); ok {
_spec.SetField(compositemodelroute.FieldMatchType, field.TypeString, value)
}
if value, ok := _u.mutation.TargetPlatform(); ok {
_spec.SetField(compositemodelroute.FieldTargetPlatform, field.TypeString, value)
}
if value, ok := _u.mutation.UpstreamModel(); ok {
_spec.SetField(compositemodelroute.FieldUpstreamModel, field.TypeString, value)
}
if value, ok := _u.mutation.Endpoint(); ok {
_spec.SetField(compositemodelroute.FieldEndpoint, field.TypeString, value)
}
if value, ok := _u.mutation.Priority(); ok {
_spec.SetField(compositemodelroute.FieldPriority, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedPriority(); ok {
_spec.AddField(compositemodelroute.FieldPriority, field.TypeInt, value)
}
if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(compositemodelroute.FieldEnabled, field.TypeBool, value)
}
if value, ok := _u.mutation.Notes(); ok {
_spec.SetField(compositemodelroute.FieldNotes, field.TypeString, value)
}
if _u.mutation.NotesCleared() {
_spec.ClearField(compositemodelroute.FieldNotes, field.TypeString)
}
if _u.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: compositemodelroute.GroupTable,
Columns: []string{compositemodelroute.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: compositemodelroute.GroupTable,
Columns: []string{compositemodelroute.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &CompositeModelRoute{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{compositemodelroute.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
+2
View File
@@ -26,6 +26,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/channelmonitordailyrollup"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorhistory"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorrequesttemplate"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/errorpassthroughrule"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/idempotencyrecord"
@@ -124,6 +125,7 @@ func checkColumn(t, c string) error {
channelmonitordailyrollup.Table: channelmonitordailyrollup.ValidColumn,
channelmonitorhistory.Table: channelmonitorhistory.ValidColumn,
channelmonitorrequesttemplate.Table: channelmonitorrequesttemplate.ValidColumn,
compositemodelroute.Table: compositemodelroute.ValidColumn,
errorpassthroughrule.Table: errorpassthroughrule.ValidColumn,
group.Table: group.ValidColumn,
idempotencyrecord.Table: idempotencyrecord.ValidColumn,
+40 -2
View File
@@ -43,6 +43,8 @@ type Group struct {
IsExclusive bool `json:"is_exclusive,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// 内部幂等恢复标识,不对 API 暴露
DuplicateOperationID *string `json:"duplicate_operation_id,omitempty"`
// Platform holds the value of the "platform" field.
Platform string `json:"platform,omitempty"`
// SubscriptionType holds the value of the "subscription_type" field.
@@ -115,6 +117,10 @@ type Group struct {
ModelsListConfig domain.GroupModelsListConfig `json:"models_list_config,omitempty"`
// 分组 RPM 上限,0 表示不限制;设置后接管该分组用户的限流
RpmLimit int `json:"rpm_limit,omitempty"`
// OpenAI reasoning effort 上限;可选 minimal/low/medium/high/xhigh/max
MaxReasoningEffort string `json:"max_reasoning_effort,omitempty"`
// OpenAI reasoning effort 自定义精确映射;先映射再应用上限
ReasoningEffortMappings []domain.ReasoningEffortMapping `json:"reasoning_effort_mappings,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
@@ -221,7 +227,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelsListConfig:
case group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelsListConfig, group.FieldReasoningEffortMappings:
values[i] = new([]byte)
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet:
values[i] = new(sql.NullBool)
@@ -229,7 +235,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
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.FieldPeakStart, group.FieldPeakEnd, group.FieldStatus, group.FieldPlatform, group.FieldSubscriptionType, group.FieldDefaultMappedModel:
case group.FieldName, group.FieldDescription, group.FieldPeakStart, group.FieldPeakEnd, group.FieldStatus, group.FieldDuplicateOperationID, group.FieldPlatform, group.FieldSubscriptionType, group.FieldDefaultMappedModel, group.FieldMaxReasoningEffort:
values[i] = new(sql.NullString)
case group.FieldCreatedAt, group.FieldUpdatedAt, group.FieldDeletedAt:
values[i] = new(sql.NullTime)
@@ -328,6 +334,13 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.Status = value.String
}
case group.FieldDuplicateOperationID:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field duplicate_operation_id", values[i])
} else if value.Valid {
_m.DuplicateOperationID = new(string)
*_m.DuplicateOperationID = value.String
}
case group.FieldPlatform:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field platform", values[i])
@@ -564,6 +577,20 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.RpmLimit = int(value.Int64)
}
case group.FieldMaxReasoningEffort:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field max_reasoning_effort", values[i])
} else if value.Valid {
_m.MaxReasoningEffort = value.String
}
case group.FieldReasoningEffortMappings:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field reasoning_effort_mappings", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.ReasoningEffortMappings); err != nil {
return fmt.Errorf("unmarshal field reasoning_effort_mappings: %w", err)
}
}
default:
_m.selectValues.Set(columns[i], values[i])
}
@@ -680,6 +707,11 @@ func (_m *Group) String() string {
builder.WriteString("status=")
builder.WriteString(_m.Status)
builder.WriteString(", ")
if v := _m.DuplicateOperationID; v != nil {
builder.WriteString("duplicate_operation_id=")
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("platform=")
builder.WriteString(_m.Platform)
builder.WriteString(", ")
@@ -811,6 +843,12 @@ func (_m *Group) String() string {
builder.WriteString(", ")
builder.WriteString("rpm_limit=")
builder.WriteString(fmt.Sprintf("%v", _m.RpmLimit))
builder.WriteString(", ")
builder.WriteString("max_reasoning_effort=")
builder.WriteString(_m.MaxReasoningEffort)
builder.WriteString(", ")
builder.WriteString("reasoning_effort_mappings=")
builder.WriteString(fmt.Sprintf("%v", _m.ReasoningEffortMappings))
builder.WriteByte(')')
return builder.String()
}
+27
View File
@@ -40,6 +40,8 @@ const (
FieldIsExclusive = "is_exclusive"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldDuplicateOperationID holds the string denoting the duplicate_operation_id field in the database.
FieldDuplicateOperationID = "duplicate_operation_id"
// FieldPlatform holds the string denoting the platform field in the database.
FieldPlatform = "platform"
// FieldSubscriptionType holds the string denoting the subscription_type field in the database.
@@ -112,6 +114,10 @@ const (
FieldModelsListConfig = "models_list_config"
// FieldRpmLimit holds the string denoting the rpm_limit field in the database.
FieldRpmLimit = "rpm_limit"
// FieldMaxReasoningEffort holds the string denoting the max_reasoning_effort field in the database.
FieldMaxReasoningEffort = "max_reasoning_effort"
// FieldReasoningEffortMappings holds the string denoting the reasoning_effort_mappings field in the database.
FieldReasoningEffortMappings = "reasoning_effort_mappings"
// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.
EdgeAPIKeys = "api_keys"
// EdgeRedeemCodes holds the string denoting the redeem_codes edge name in mutations.
@@ -199,6 +205,7 @@ var Columns = []string{
FieldPeakRateMultiplier,
FieldIsExclusive,
FieldStatus,
FieldDuplicateOperationID,
FieldPlatform,
FieldSubscriptionType,
FieldDailyLimitUsd,
@@ -235,6 +242,8 @@ var Columns = []string{
FieldMessagesDispatchModelConfig,
FieldModelsListConfig,
FieldRpmLimit,
FieldMaxReasoningEffort,
FieldReasoningEffortMappings,
}
var (
@@ -292,6 +301,8 @@ var (
DefaultStatus string
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
// DuplicateOperationIDValidator is a validator for the "duplicate_operation_id" field. It is called by the builders before save.
DuplicateOperationIDValidator func(string) error
// DefaultPlatform holds the default value on creation for the "platform" field.
DefaultPlatform string
// PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
@@ -344,6 +355,12 @@ var (
DefaultModelsListConfig domain.GroupModelsListConfig
// DefaultRpmLimit holds the default value on creation for the "rpm_limit" field.
DefaultRpmLimit int
// DefaultMaxReasoningEffort holds the default value on creation for the "max_reasoning_effort" field.
DefaultMaxReasoningEffort string
// MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
MaxReasoningEffortValidator func(string) error
// DefaultReasoningEffortMappings holds the default value on creation for the "reasoning_effort_mappings" field.
DefaultReasoningEffortMappings []domain.ReasoningEffortMapping
)
// OrderOption defines the ordering options for the Group queries.
@@ -414,6 +431,11 @@ func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByDuplicateOperationID orders the results by the duplicate_operation_id field.
func ByDuplicateOperationID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDuplicateOperationID, opts...).ToFunc()
}
// ByPlatform orders the results by the platform field.
func ByPlatform(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPlatform, opts...).ToFunc()
@@ -574,6 +596,11 @@ func ByRpmLimit(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRpmLimit, opts...).ToFunc()
}
// ByMaxReasoningEffort orders the results by the max_reasoning_effort field.
func ByMaxReasoningEffort(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMaxReasoningEffort, opts...).ToFunc()
}
// ByAPIKeysCount orders the results by api_keys count.
func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
+150
View File
@@ -115,6 +115,11 @@ func Status(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldStatus, v))
}
// DuplicateOperationID applies equality check predicate on the "duplicate_operation_id" field. It's identical to DuplicateOperationIDEQ.
func DuplicateOperationID(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDuplicateOperationID, v))
}
// Platform applies equality check predicate on the "platform" field. It's identical to PlatformEQ.
func Platform(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPlatform, v))
@@ -275,6 +280,11 @@ func RpmLimit(v int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldRpmLimit, v))
}
// MaxReasoningEffort applies equality check predicate on the "max_reasoning_effort" field. It's identical to MaxReasoningEffortEQ.
func MaxReasoningEffort(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldMaxReasoningEffort, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
@@ -840,6 +850,81 @@ func StatusContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldStatus, v))
}
// DuplicateOperationIDEQ applies the EQ predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDNEQ applies the NEQ predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDIn applies the In predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldDuplicateOperationID, vs...))
}
// DuplicateOperationIDNotIn applies the NotIn predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldDuplicateOperationID, vs...))
}
// DuplicateOperationIDGT applies the GT predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDGTE applies the GTE predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDLT applies the LT predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDLTE applies the LTE predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDContains applies the Contains predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDHasPrefix applies the HasPrefix predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDHasSuffix applies the HasSuffix predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDIsNil applies the IsNil predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDIsNil() predicate.Group {
return predicate.Group(sql.FieldIsNull(FieldDuplicateOperationID))
}
// DuplicateOperationIDNotNil applies the NotNil predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldDuplicateOperationID))
}
// DuplicateOperationIDEqualFold applies the EqualFold predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldDuplicateOperationID, v))
}
// DuplicateOperationIDContainsFold applies the ContainsFold predicate on the "duplicate_operation_id" field.
func DuplicateOperationIDContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldDuplicateOperationID, v))
}
// PlatformEQ applies the EQ predicate on the "platform" field.
func PlatformEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPlatform, v))
@@ -2025,6 +2110,71 @@ func RpmLimitLTE(v int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldRpmLimit, v))
}
// MaxReasoningEffortEQ applies the EQ predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortNEQ applies the NEQ predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortIn applies the In predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldMaxReasoningEffort, vs...))
}
// MaxReasoningEffortNotIn applies the NotIn predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldMaxReasoningEffort, vs...))
}
// MaxReasoningEffortGT applies the GT predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortGTE applies the GTE predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortLT applies the LT predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortLTE applies the LTE predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortContains applies the Contains predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortHasPrefix applies the HasPrefix predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortHasSuffix applies the HasSuffix predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortEqualFold applies the EqualFold predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldMaxReasoningEffort, v))
}
// MaxReasoningEffortContainsFold applies the ContainsFold predicate on the "max_reasoning_effort" field.
func MaxReasoningEffortContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldMaxReasoningEffort, v))
}
// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.
func HasAPIKeys() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
+156
View File
@@ -189,6 +189,20 @@ func (_c *GroupCreate) SetNillableStatus(v *string) *GroupCreate {
return _c
}
// SetDuplicateOperationID sets the "duplicate_operation_id" field.
func (_c *GroupCreate) SetDuplicateOperationID(v string) *GroupCreate {
_c.mutation.SetDuplicateOperationID(v)
return _c
}
// SetNillableDuplicateOperationID sets the "duplicate_operation_id" field if the given value is not nil.
func (_c *GroupCreate) SetNillableDuplicateOperationID(v *string) *GroupCreate {
if v != nil {
_c.SetDuplicateOperationID(*v)
}
return _c
}
// SetPlatform sets the "platform" field.
func (_c *GroupCreate) SetPlatform(v string) *GroupCreate {
_c.mutation.SetPlatform(v)
@@ -677,6 +691,26 @@ func (_c *GroupCreate) SetNillableRpmLimit(v *int) *GroupCreate {
return _c
}
// SetMaxReasoningEffort sets the "max_reasoning_effort" field.
func (_c *GroupCreate) SetMaxReasoningEffort(v string) *GroupCreate {
_c.mutation.SetMaxReasoningEffort(v)
return _c
}
// SetNillableMaxReasoningEffort sets the "max_reasoning_effort" field if the given value is not nil.
func (_c *GroupCreate) SetNillableMaxReasoningEffort(v *string) *GroupCreate {
if v != nil {
_c.SetMaxReasoningEffort(*v)
}
return _c
}
// SetReasoningEffortMappings sets the "reasoning_effort_mappings" field.
func (_c *GroupCreate) SetReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupCreate {
_c.mutation.SetReasoningEffortMappings(v)
return _c
}
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.
func (_c *GroupCreate) AddAPIKeyIDs(ids ...int64) *GroupCreate {
_c.mutation.AddAPIKeyIDs(ids...)
@@ -938,6 +972,14 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultRpmLimit
_c.mutation.SetRpmLimit(v)
}
if _, ok := _c.mutation.MaxReasoningEffort(); !ok {
v := group.DefaultMaxReasoningEffort
_c.mutation.SetMaxReasoningEffort(v)
}
if _, ok := _c.mutation.ReasoningEffortMappings(); !ok {
v := group.DefaultReasoningEffortMappings
_c.mutation.SetReasoningEffortMappings(v)
}
return nil
}
@@ -993,6 +1035,11 @@ func (_c *GroupCreate) check() error {
return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Group.status": %w`, err)}
}
}
if v, ok := _c.mutation.DuplicateOperationID(); ok {
if err := group.DuplicateOperationIDValidator(v); err != nil {
return &ValidationError{Name: "duplicate_operation_id", err: fmt.Errorf(`ent: validator failed for field "Group.duplicate_operation_id": %w`, err)}
}
}
if _, ok := _c.mutation.Platform(); !ok {
return &ValidationError{Name: "platform", err: errors.New(`ent: missing required field "Group.platform"`)}
}
@@ -1077,6 +1124,17 @@ func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.RpmLimit(); !ok {
return &ValidationError{Name: "rpm_limit", err: errors.New(`ent: missing required field "Group.rpm_limit"`)}
}
if _, ok := _c.mutation.MaxReasoningEffort(); !ok {
return &ValidationError{Name: "max_reasoning_effort", err: errors.New(`ent: missing required field "Group.max_reasoning_effort"`)}
}
if v, ok := _c.mutation.MaxReasoningEffort(); ok {
if err := group.MaxReasoningEffortValidator(v); err != nil {
return &ValidationError{Name: "max_reasoning_effort", err: fmt.Errorf(`ent: validator failed for field "Group.max_reasoning_effort": %w`, err)}
}
}
if _, ok := _c.mutation.ReasoningEffortMappings(); !ok {
return &ValidationError{Name: "reasoning_effort_mappings", err: errors.New(`ent: missing required field "Group.reasoning_effort_mappings"`)}
}
return nil
}
@@ -1152,6 +1210,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldStatus, field.TypeString, value)
_node.Status = value
}
if value, ok := _c.mutation.DuplicateOperationID(); ok {
_spec.SetField(group.FieldDuplicateOperationID, field.TypeString, value)
_node.DuplicateOperationID = &value
}
if value, ok := _c.mutation.Platform(); ok {
_spec.SetField(group.FieldPlatform, field.TypeString, value)
_node.Platform = value
@@ -1296,6 +1358,14 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldRpmLimit, field.TypeInt, value)
_node.RpmLimit = value
}
if value, ok := _c.mutation.MaxReasoningEffort(); ok {
_spec.SetField(group.FieldMaxReasoningEffort, field.TypeString, value)
_node.MaxReasoningEffort = value
}
if value, ok := _c.mutation.ReasoningEffortMappings(); ok {
_spec.SetField(group.FieldReasoningEffortMappings, field.TypeJSON, value)
_node.ReasoningEffortMappings = value
}
if nodes := _c.mutation.APIKeysIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -2232,6 +2302,30 @@ func (u *GroupUpsert) AddRpmLimit(v int) *GroupUpsert {
return u
}
// SetMaxReasoningEffort sets the "max_reasoning_effort" field.
func (u *GroupUpsert) SetMaxReasoningEffort(v string) *GroupUpsert {
u.Set(group.FieldMaxReasoningEffort, v)
return u
}
// UpdateMaxReasoningEffort sets the "max_reasoning_effort" field to the value that was provided on create.
func (u *GroupUpsert) UpdateMaxReasoningEffort() *GroupUpsert {
u.SetExcluded(group.FieldMaxReasoningEffort)
return u
}
// SetReasoningEffortMappings sets the "reasoning_effort_mappings" field.
func (u *GroupUpsert) SetReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpsert {
u.Set(group.FieldReasoningEffortMappings, v)
return u
}
// UpdateReasoningEffortMappings sets the "reasoning_effort_mappings" field to the value that was provided on create.
func (u *GroupUpsert) UpdateReasoningEffortMappings() *GroupUpsert {
u.SetExcluded(group.FieldReasoningEffortMappings)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
@@ -2246,6 +2340,9 @@ func (u *GroupUpsertOne) UpdateNewValues() *GroupUpsertOne {
if _, exists := u.create.mutation.CreatedAt(); exists {
s.SetIgnore(group.FieldCreatedAt)
}
if _, exists := u.create.mutation.DuplicateOperationID(); exists {
s.SetIgnore(group.FieldDuplicateOperationID)
}
}))
return u
}
@@ -3187,6 +3284,34 @@ func (u *GroupUpsertOne) UpdateRpmLimit() *GroupUpsertOne {
})
}
// SetMaxReasoningEffort sets the "max_reasoning_effort" field.
func (u *GroupUpsertOne) SetMaxReasoningEffort(v string) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetMaxReasoningEffort(v)
})
}
// UpdateMaxReasoningEffort sets the "max_reasoning_effort" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateMaxReasoningEffort() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateMaxReasoningEffort()
})
}
// SetReasoningEffortMappings sets the "reasoning_effort_mappings" field.
func (u *GroupUpsertOne) SetReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetReasoningEffortMappings(v)
})
}
// UpdateReasoningEffortMappings sets the "reasoning_effort_mappings" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateReasoningEffortMappings() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateReasoningEffortMappings()
})
}
// Exec executes the query.
func (u *GroupUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
@@ -3366,6 +3491,9 @@ func (u *GroupUpsertBulk) UpdateNewValues() *GroupUpsertBulk {
if _, exists := b.mutation.CreatedAt(); exists {
s.SetIgnore(group.FieldCreatedAt)
}
if _, exists := b.mutation.DuplicateOperationID(); exists {
s.SetIgnore(group.FieldDuplicateOperationID)
}
}
}))
return u
@@ -4308,6 +4436,34 @@ func (u *GroupUpsertBulk) UpdateRpmLimit() *GroupUpsertBulk {
})
}
// SetMaxReasoningEffort sets the "max_reasoning_effort" field.
func (u *GroupUpsertBulk) SetMaxReasoningEffort(v string) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetMaxReasoningEffort(v)
})
}
// UpdateMaxReasoningEffort sets the "max_reasoning_effort" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateMaxReasoningEffort() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateMaxReasoningEffort()
})
}
// SetReasoningEffortMappings sets the "reasoning_effort_mappings" field.
func (u *GroupUpsertBulk) SetReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetReasoningEffortMappings(v)
})
}
// UpdateReasoningEffortMappings sets the "reasoning_effort_mappings" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateReasoningEffortMappings() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateReasoningEffortMappings()
})
}
// Exec executes the query.
func (u *GroupUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
+90
View File
@@ -913,6 +913,32 @@ func (_u *GroupUpdate) AddRpmLimit(v int) *GroupUpdate {
return _u
}
// SetMaxReasoningEffort sets the "max_reasoning_effort" field.
func (_u *GroupUpdate) SetMaxReasoningEffort(v string) *GroupUpdate {
_u.mutation.SetMaxReasoningEffort(v)
return _u
}
// SetNillableMaxReasoningEffort sets the "max_reasoning_effort" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableMaxReasoningEffort(v *string) *GroupUpdate {
if v != nil {
_u.SetMaxReasoningEffort(*v)
}
return _u
}
// SetReasoningEffortMappings sets the "reasoning_effort_mappings" field.
func (_u *GroupUpdate) SetReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpdate {
_u.mutation.SetReasoningEffortMappings(v)
return _u
}
// AppendReasoningEffortMappings appends value to the "reasoning_effort_mappings" field.
func (_u *GroupUpdate) AppendReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpdate {
_u.mutation.AppendReasoningEffortMappings(v)
return _u
}
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.
func (_u *GroupUpdate) AddAPIKeyIDs(ids ...int64) *GroupUpdate {
_u.mutation.AddAPIKeyIDs(ids...)
@@ -1213,6 +1239,11 @@ func (_u *GroupUpdate) check() error {
return &ValidationError{Name: "default_mapped_model", err: fmt.Errorf(`ent: validator failed for field "Group.default_mapped_model": %w`, err)}
}
}
if v, ok := _u.mutation.MaxReasoningEffort(); ok {
if err := group.MaxReasoningEffortValidator(v); err != nil {
return &ValidationError{Name: "max_reasoning_effort", err: fmt.Errorf(`ent: validator failed for field "Group.max_reasoning_effort": %w`, err)}
}
}
return nil
}
@@ -1273,6 +1304,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(group.FieldStatus, field.TypeString, value)
}
if _u.mutation.DuplicateOperationIDCleared() {
_spec.ClearField(group.FieldDuplicateOperationID, field.TypeString)
}
if value, ok := _u.mutation.Platform(); ok {
_spec.SetField(group.FieldPlatform, field.TypeString, value)
}
@@ -1482,6 +1516,17 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.AddedRpmLimit(); ok {
_spec.AddField(group.FieldRpmLimit, field.TypeInt, value)
}
if value, ok := _u.mutation.MaxReasoningEffort(); ok {
_spec.SetField(group.FieldMaxReasoningEffort, field.TypeString, value)
}
if value, ok := _u.mutation.ReasoningEffortMappings(); ok {
_spec.SetField(group.FieldReasoningEffortMappings, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedReasoningEffortMappings(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, group.FieldReasoningEffortMappings, value)
})
}
if _u.mutation.APIKeysCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@@ -2673,6 +2718,32 @@ func (_u *GroupUpdateOne) AddRpmLimit(v int) *GroupUpdateOne {
return _u
}
// SetMaxReasoningEffort sets the "max_reasoning_effort" field.
func (_u *GroupUpdateOne) SetMaxReasoningEffort(v string) *GroupUpdateOne {
_u.mutation.SetMaxReasoningEffort(v)
return _u
}
// SetNillableMaxReasoningEffort sets the "max_reasoning_effort" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableMaxReasoningEffort(v *string) *GroupUpdateOne {
if v != nil {
_u.SetMaxReasoningEffort(*v)
}
return _u
}
// SetReasoningEffortMappings sets the "reasoning_effort_mappings" field.
func (_u *GroupUpdateOne) SetReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpdateOne {
_u.mutation.SetReasoningEffortMappings(v)
return _u
}
// AppendReasoningEffortMappings appends value to the "reasoning_effort_mappings" field.
func (_u *GroupUpdateOne) AppendReasoningEffortMappings(v []domain.ReasoningEffortMapping) *GroupUpdateOne {
_u.mutation.AppendReasoningEffortMappings(v)
return _u
}
// AddAPIKeyIDs adds the "api_keys" edge to the APIKey entity by IDs.
func (_u *GroupUpdateOne) AddAPIKeyIDs(ids ...int64) *GroupUpdateOne {
_u.mutation.AddAPIKeyIDs(ids...)
@@ -2986,6 +3057,11 @@ func (_u *GroupUpdateOne) check() error {
return &ValidationError{Name: "default_mapped_model", err: fmt.Errorf(`ent: validator failed for field "Group.default_mapped_model": %w`, err)}
}
}
if v, ok := _u.mutation.MaxReasoningEffort(); ok {
if err := group.MaxReasoningEffortValidator(v); err != nil {
return &ValidationError{Name: "max_reasoning_effort", err: fmt.Errorf(`ent: validator failed for field "Group.max_reasoning_effort": %w`, err)}
}
}
return nil
}
@@ -3063,6 +3139,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.Status(); ok {
_spec.SetField(group.FieldStatus, field.TypeString, value)
}
if _u.mutation.DuplicateOperationIDCleared() {
_spec.ClearField(group.FieldDuplicateOperationID, field.TypeString)
}
if value, ok := _u.mutation.Platform(); ok {
_spec.SetField(group.FieldPlatform, field.TypeString, value)
}
@@ -3272,6 +3351,17 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.AddedRpmLimit(); ok {
_spec.AddField(group.FieldRpmLimit, field.TypeInt, value)
}
if value, ok := _u.mutation.MaxReasoningEffort(); ok {
_spec.SetField(group.FieldMaxReasoningEffort, field.TypeString, value)
}
if value, ok := _u.mutation.ReasoningEffortMappings(); ok {
_spec.SetField(group.FieldReasoningEffortMappings, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedReasoningEffortMappings(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, group.FieldReasoningEffortMappings, value)
})
}
if _u.mutation.APIKeysCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
+12
View File
@@ -177,6 +177,18 @@ func (f ChannelMonitorRequestTemplateFunc) Mutate(ctx context.Context, m ent.Mut
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ChannelMonitorRequestTemplateMutation", m)
}
// The CompositeModelRouteFunc type is an adapter to allow the use of ordinary
// function as CompositeModelRoute mutator.
type CompositeModelRouteFunc func(context.Context, *ent.CompositeModelRouteMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f CompositeModelRouteFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.CompositeModelRouteMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CompositeModelRouteMutation", m)
}
// The ErrorPassthroughRuleFunc type is an adapter to allow the use of ordinary
// function as ErrorPassthroughRule mutator.
type ErrorPassthroughRuleFunc func(context.Context, *ent.ErrorPassthroughRuleMutation) (ent.Value, error)
+30
View File
@@ -22,6 +22,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/channelmonitordailyrollup"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorhistory"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorrequesttemplate"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/errorpassthroughrule"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/idempotencyrecord"
@@ -483,6 +484,33 @@ func (f TraverseChannelMonitorRequestTemplate) Traverse(ctx context.Context, q e
return fmt.Errorf("unexpected query type %T. expect *ent.ChannelMonitorRequestTemplateQuery", q)
}
// The CompositeModelRouteFunc type is an adapter to allow the use of ordinary function as a Querier.
type CompositeModelRouteFunc func(context.Context, *ent.CompositeModelRouteQuery) (ent.Value, error)
// Query calls f(ctx, q).
func (f CompositeModelRouteFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) {
if q, ok := q.(*ent.CompositeModelRouteQuery); ok {
return f(ctx, q)
}
return nil, fmt.Errorf("unexpected query type %T. expect *ent.CompositeModelRouteQuery", q)
}
// The TraverseCompositeModelRoute type is an adapter to allow the use of ordinary function as Traverser.
type TraverseCompositeModelRoute func(context.Context, *ent.CompositeModelRouteQuery) error
// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline.
func (f TraverseCompositeModelRoute) Intercept(next ent.Querier) ent.Querier {
return next
}
// Traverse calls f(ctx, q).
func (f TraverseCompositeModelRoute) Traverse(ctx context.Context, q ent.Query) error {
if q, ok := q.(*ent.CompositeModelRouteQuery); ok {
return f(ctx, q)
}
return fmt.Errorf("unexpected query type %T. expect *ent.CompositeModelRouteQuery", q)
}
// The ErrorPassthroughRuleFunc type is an adapter to allow the use of ordinary function as a Querier.
type ErrorPassthroughRuleFunc func(context.Context, *ent.ErrorPassthroughRuleQuery) (ent.Value, error)
@@ -1162,6 +1190,8 @@ func NewQuery(q ent.Query) (Query, error) {
return &query[*ent.ChannelMonitorHistoryQuery, predicate.ChannelMonitorHistory, channelmonitorhistory.OrderOption]{typ: ent.TypeChannelMonitorHistory, tq: q}, nil
case *ent.ChannelMonitorRequestTemplateQuery:
return &query[*ent.ChannelMonitorRequestTemplateQuery, predicate.ChannelMonitorRequestTemplate, channelmonitorrequesttemplate.OrderOption]{typ: ent.TypeChannelMonitorRequestTemplate, tq: q}, nil
case *ent.CompositeModelRouteQuery:
return &query[*ent.CompositeModelRouteQuery, predicate.CompositeModelRoute, compositemodelroute.OrderOption]{typ: ent.TypeCompositeModelRoute, tq: q}, nil
case *ent.ErrorPassthroughRuleQuery:
return &query[*ent.ErrorPassthroughRuleQuery, predicate.ErrorPassthroughRule, errorpassthroughrule.OrderOption]{typ: ent.TypeErrorPassthroughRule, tq: q}, nil
case *ent.GroupQuery:
+100 -20
View File
@@ -623,7 +623,7 @@ var (
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini"}},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok"}},
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
{Name: "endpoint", Type: field.TypeString, Size: 500},
{Name: "api_key_encrypted", Type: field.TypeString},
@@ -768,7 +768,7 @@ var (
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini"}},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok"}},
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""},
{Name: "extra_headers", Type: field.TypeJSON},
@@ -793,6 +793,68 @@ var (
},
},
}
// CompositeModelRoutesColumns holds the columns for the "composite_model_routes" table.
CompositeModelRoutesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "public_model", Type: field.TypeString, Size: 200},
{Name: "match_type", Type: field.TypeString, Size: 20, Default: "exact"},
{Name: "target_platform", Type: field.TypeString, Size: 50, Default: "openai"},
{Name: "upstream_model", Type: field.TypeString, Size: 200, Default: ""},
{Name: "endpoint", Type: field.TypeString, Size: 50, Default: "any"},
{Name: "priority", Type: field.TypeInt, Default: 100},
{Name: "enabled", Type: field.TypeBool, Default: true},
{Name: "notes", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "group_id", Type: field.TypeInt64},
}
// CompositeModelRoutesTable holds the schema information for the "composite_model_routes" table.
CompositeModelRoutesTable = &schema.Table{
Name: "composite_model_routes",
Columns: CompositeModelRoutesColumns,
PrimaryKey: []*schema.Column{CompositeModelRoutesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "composite_model_routes_groups_group",
Columns: []*schema.Column{CompositeModelRoutesColumns[12]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
},
Indexes: []*schema.Index{
{
Name: "compositemodelroute_group_id",
Unique: false,
Columns: []*schema.Column{CompositeModelRoutesColumns[12]},
},
{
Name: "compositemodelroute_group_id_enabled",
Unique: false,
Columns: []*schema.Column{CompositeModelRoutesColumns[12], CompositeModelRoutesColumns[10]},
},
{
Name: "compositemodelroute_group_id_endpoint",
Unique: false,
Columns: []*schema.Column{CompositeModelRoutesColumns[12], CompositeModelRoutesColumns[8]},
},
{
Name: "compositemodelroute_group_id_target_platform",
Unique: false,
Columns: []*schema.Column{CompositeModelRoutesColumns[12], CompositeModelRoutesColumns[6]},
},
{
Name: "compositemodelroute_deleted_at",
Unique: false,
Columns: []*schema.Column{CompositeModelRoutesColumns[3]},
},
{
Name: "compositemodelroute_priority",
Unique: false,
Columns: []*schema.Column{CompositeModelRoutesColumns[9]},
},
},
}
// ErrorPassthroughRulesColumns holds the columns for the "error_passthrough_rules" table.
ErrorPassthroughRulesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
@@ -845,6 +907,7 @@ var (
{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: "duplicate_operation_id", Type: field.TypeString, Nullable: true, Size: 64},
{Name: "platform", Type: field.TypeString, Size: 50, Default: "anthropic"},
{Name: "subscription_type", Type: field.TypeString, Size: 20, Default: "standard"},
{Name: "daily_limit_usd", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
@@ -881,6 +944,8 @@ var (
{Name: "messages_dispatch_model_config", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "models_list_config", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "rpm_limit", Type: field.TypeInt, Default: 0},
{Name: "max_reasoning_effort", Type: field.TypeString, Size: 20, Default: ""},
{Name: "reasoning_effort_mappings", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
@@ -896,12 +961,12 @@ var (
{
Name: "group_platform",
Unique: false,
Columns: []*schema.Column{GroupsColumns[13]},
Columns: []*schema.Column{GroupsColumns[14]},
},
{
Name: "group_subscription_type",
Unique: false,
Columns: []*schema.Column{GroupsColumns[14]},
Columns: []*schema.Column{GroupsColumns[15]},
},
{
Name: "group_is_exclusive",
@@ -916,7 +981,15 @@ var (
{
Name: "group_sort_order",
Unique: false,
Columns: []*schema.Column{GroupsColumns[41]},
Columns: []*schema.Column{GroupsColumns[42]},
},
{
Name: "idx_groups_duplicate_operation_id_active",
Unique: true,
Columns: []*schema.Column{GroupsColumns[13]},
Annotation: &entsql.IndexAnnotation{
Where: "duplicate_operation_id IS NOT NULL AND deleted_at IS NULL",
},
},
},
}
@@ -1447,6 +1520,7 @@ var (
{Name: "description", Type: field.TypeString, Default: "", SchemaType: map[string]string{"postgres": "text"}},
{Name: "price", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "original_price", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "currency", Type: field.TypeString, Size: 3, Default: ""},
{Name: "validity_days", Type: field.TypeInt, Default: 30},
{Name: "validity_unit", Type: field.TypeString, Size: 10, Default: "day"},
{Name: "features", Type: field.TypeString, Default: "", SchemaType: map[string]string{"postgres": "text"}},
@@ -1470,7 +1544,7 @@ var (
{
Name: "subscriptionplan_for_sale",
Unique: false,
Columns: []*schema.Column{SubscriptionPlansColumns[10]},
Columns: []*schema.Column{SubscriptionPlansColumns[11]},
},
},
}
@@ -1560,6 +1634,7 @@ var (
{Name: "total_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "actual_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "long_context_billing_applied", Type: field.TypeBool, Default: false},
{Name: "account_rate_multiplier", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "billing_type", Type: field.TypeInt8, Default: 0},
{Name: "stream", Type: field.TypeBool, Default: false},
@@ -1592,31 +1667,31 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "usage_logs_api_keys_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[40]},
Columns: []*schema.Column{UsageLogsColumns[41]},
RefColumns: []*schema.Column{APIKeysColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_accounts_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[41]},
Columns: []*schema.Column{UsageLogsColumns[42]},
RefColumns: []*schema.Column{AccountsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_groups_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[43]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "usage_logs_users_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[43]},
Columns: []*schema.Column{UsageLogsColumns[44]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_user_subscriptions_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[44]},
Columns: []*schema.Column{UsageLogsColumns[45]},
RefColumns: []*schema.Column{UserSubscriptionsColumns[0]},
OnDelete: schema.SetNull,
},
@@ -1625,32 +1700,32 @@ var (
{
Name: "usagelog_user_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[43]},
Columns: []*schema.Column{UsageLogsColumns[44]},
},
{
Name: "usagelog_api_key_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[40]},
Columns: []*schema.Column{UsageLogsColumns[41]},
},
{
Name: "usagelog_account_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[41]},
Columns: []*schema.Column{UsageLogsColumns[42]},
},
{
Name: "usagelog_group_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[43]},
},
{
Name: "usagelog_subscription_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[44]},
Columns: []*schema.Column{UsageLogsColumns[45]},
},
{
Name: "usagelog_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[39]},
Columns: []*schema.Column{UsageLogsColumns[40]},
},
{
Name: "usagelog_model",
@@ -1670,17 +1745,17 @@ var (
{
Name: "usagelog_user_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[43], UsageLogsColumns[39]},
Columns: []*schema.Column{UsageLogsColumns[44], UsageLogsColumns[40]},
},
{
Name: "usagelog_api_key_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[40], UsageLogsColumns[39]},
Columns: []*schema.Column{UsageLogsColumns[41], UsageLogsColumns[40]},
},
{
Name: "usagelog_group_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[42], UsageLogsColumns[39]},
Columns: []*schema.Column{UsageLogsColumns[43], UsageLogsColumns[40]},
},
},
}
@@ -2001,6 +2076,7 @@ var (
ChannelMonitorDailyRollupsTable,
ChannelMonitorHistoriesTable,
ChannelMonitorRequestTemplatesTable,
CompositeModelRoutesTable,
ErrorPassthroughRulesTable,
GroupsTable,
IdempotencyRecordsTable,
@@ -2084,6 +2160,10 @@ func init() {
ChannelMonitorRequestTemplatesTable.Annotation = &entsql.Annotation{
Table: "channel_monitor_request_templates",
}
CompositeModelRoutesTable.ForeignKeys[0].RefTable = GroupsTable
CompositeModelRoutesTable.Annotation = &entsql.Annotation{
Table: "composite_model_routes",
}
ErrorPassthroughRulesTable.Annotation = &entsql.Annotation{
Table: "error_passthrough_rules",
}
+1438 -80
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -48,6 +48,9 @@ type ChannelMonitorHistory func(*sql.Selector)
// ChannelMonitorRequestTemplate is the predicate function for channelmonitorrequesttemplate builders.
type ChannelMonitorRequestTemplate func(*sql.Selector)
// CompositeModelRoute is the predicate function for compositemodelroute builders.
type CompositeModelRoute func(*sql.Selector)
// ErrorPassthroughRule is the predicate function for errorpassthroughrule builders.
type ErrorPassthroughRule func(*sql.Selector)
+138 -44
View File
@@ -19,6 +19,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/channelmonitordailyrollup"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorhistory"
"github.com/Wei-Shaw/sub2api/ent/channelmonitorrequesttemplate"
"github.com/Wei-Shaw/sub2api/ent/compositemodelroute"
"github.com/Wei-Shaw/sub2api/ent/errorpassthroughrule"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/idempotencyrecord"
@@ -865,6 +866,75 @@ func init() {
channelmonitorrequesttemplate.DefaultBodyOverrideMode = channelmonitorrequesttemplateDescBodyOverrideMode.Default.(string)
// channelmonitorrequesttemplate.BodyOverrideModeValidator is a validator for the "body_override_mode" field. It is called by the builders before save.
channelmonitorrequesttemplate.BodyOverrideModeValidator = channelmonitorrequesttemplateDescBodyOverrideMode.Validators[0].(func(string) error)
compositemodelrouteMixin := schema.CompositeModelRoute{}.Mixin()
compositemodelrouteMixinHooks1 := compositemodelrouteMixin[1].Hooks()
compositemodelroute.Hooks[0] = compositemodelrouteMixinHooks1[0]
compositemodelrouteMixinInters1 := compositemodelrouteMixin[1].Interceptors()
compositemodelroute.Interceptors[0] = compositemodelrouteMixinInters1[0]
compositemodelrouteMixinFields0 := compositemodelrouteMixin[0].Fields()
_ = compositemodelrouteMixinFields0
compositemodelrouteFields := schema.CompositeModelRoute{}.Fields()
_ = compositemodelrouteFields
// compositemodelrouteDescCreatedAt is the schema descriptor for created_at field.
compositemodelrouteDescCreatedAt := compositemodelrouteMixinFields0[0].Descriptor()
// compositemodelroute.DefaultCreatedAt holds the default value on creation for the created_at field.
compositemodelroute.DefaultCreatedAt = compositemodelrouteDescCreatedAt.Default.(func() time.Time)
// compositemodelrouteDescUpdatedAt is the schema descriptor for updated_at field.
compositemodelrouteDescUpdatedAt := compositemodelrouteMixinFields0[1].Descriptor()
// compositemodelroute.DefaultUpdatedAt holds the default value on creation for the updated_at field.
compositemodelroute.DefaultUpdatedAt = compositemodelrouteDescUpdatedAt.Default.(func() time.Time)
// compositemodelroute.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
compositemodelroute.UpdateDefaultUpdatedAt = compositemodelrouteDescUpdatedAt.UpdateDefault.(func() time.Time)
// compositemodelrouteDescPublicModel is the schema descriptor for public_model field.
compositemodelrouteDescPublicModel := compositemodelrouteFields[1].Descriptor()
// compositemodelroute.PublicModelValidator is a validator for the "public_model" field. It is called by the builders before save.
compositemodelroute.PublicModelValidator = func() func(string) error {
validators := compositemodelrouteDescPublicModel.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(public_model string) error {
for _, fn := range fns {
if err := fn(public_model); err != nil {
return err
}
}
return nil
}
}()
// compositemodelrouteDescMatchType is the schema descriptor for match_type field.
compositemodelrouteDescMatchType := compositemodelrouteFields[2].Descriptor()
// compositemodelroute.DefaultMatchType holds the default value on creation for the match_type field.
compositemodelroute.DefaultMatchType = compositemodelrouteDescMatchType.Default.(string)
// compositemodelroute.MatchTypeValidator is a validator for the "match_type" field. It is called by the builders before save.
compositemodelroute.MatchTypeValidator = compositemodelrouteDescMatchType.Validators[0].(func(string) error)
// compositemodelrouteDescTargetPlatform is the schema descriptor for target_platform field.
compositemodelrouteDescTargetPlatform := compositemodelrouteFields[3].Descriptor()
// compositemodelroute.DefaultTargetPlatform holds the default value on creation for the target_platform field.
compositemodelroute.DefaultTargetPlatform = compositemodelrouteDescTargetPlatform.Default.(string)
// compositemodelroute.TargetPlatformValidator is a validator for the "target_platform" field. It is called by the builders before save.
compositemodelroute.TargetPlatformValidator = compositemodelrouteDescTargetPlatform.Validators[0].(func(string) error)
// compositemodelrouteDescUpstreamModel is the schema descriptor for upstream_model field.
compositemodelrouteDescUpstreamModel := compositemodelrouteFields[4].Descriptor()
// compositemodelroute.DefaultUpstreamModel holds the default value on creation for the upstream_model field.
compositemodelroute.DefaultUpstreamModel = compositemodelrouteDescUpstreamModel.Default.(string)
// compositemodelroute.UpstreamModelValidator is a validator for the "upstream_model" field. It is called by the builders before save.
compositemodelroute.UpstreamModelValidator = compositemodelrouteDescUpstreamModel.Validators[0].(func(string) error)
// compositemodelrouteDescEndpoint is the schema descriptor for endpoint field.
compositemodelrouteDescEndpoint := compositemodelrouteFields[5].Descriptor()
// compositemodelroute.DefaultEndpoint holds the default value on creation for the endpoint field.
compositemodelroute.DefaultEndpoint = compositemodelrouteDescEndpoint.Default.(string)
// compositemodelroute.EndpointValidator is a validator for the "endpoint" field. It is called by the builders before save.
compositemodelroute.EndpointValidator = compositemodelrouteDescEndpoint.Validators[0].(func(string) error)
// compositemodelrouteDescPriority is the schema descriptor for priority field.
compositemodelrouteDescPriority := compositemodelrouteFields[6].Descriptor()
// compositemodelroute.DefaultPriority holds the default value on creation for the priority field.
compositemodelroute.DefaultPriority = compositemodelrouteDescPriority.Default.(int)
// compositemodelrouteDescEnabled is the schema descriptor for enabled field.
compositemodelrouteDescEnabled := compositemodelrouteFields[7].Descriptor()
// compositemodelroute.DefaultEnabled holds the default value on creation for the enabled field.
compositemodelroute.DefaultEnabled = compositemodelrouteDescEnabled.Default.(bool)
errorpassthroughruleMixin := schema.ErrorPassthroughRule{}.Mixin()
errorpassthroughruleMixinFields0 := errorpassthroughruleMixin[0].Fields()
_ = errorpassthroughruleMixinFields0
@@ -995,104 +1065,118 @@ func init() {
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)
// groupDescDuplicateOperationID is the schema descriptor for duplicate_operation_id field.
groupDescDuplicateOperationID := groupFields[9].Descriptor()
// group.DuplicateOperationIDValidator is a validator for the "duplicate_operation_id" field. It is called by the builders before save.
group.DuplicateOperationIDValidator = groupDescDuplicateOperationID.Validators[0].(func(string) error)
// groupDescPlatform is the schema descriptor for platform field.
groupDescPlatform := groupFields[9].Descriptor()
groupDescPlatform := groupFields[10].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[10].Descriptor()
groupDescSubscriptionType := groupFields[11].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[14].Descriptor()
groupDescDefaultValidityDays := groupFields[15].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[15].Descriptor()
groupDescAllowImageGeneration := groupFields[16].Descriptor()
// group.DefaultAllowImageGeneration holds the default value on creation for the allow_image_generation field.
group.DefaultAllowImageGeneration = groupDescAllowImageGeneration.Default.(bool)
// groupDescAllowBatchImageGeneration is the schema descriptor for allow_batch_image_generation field.
groupDescAllowBatchImageGeneration := groupFields[16].Descriptor()
groupDescAllowBatchImageGeneration := groupFields[17].Descriptor()
// group.DefaultAllowBatchImageGeneration holds the default value on creation for the allow_batch_image_generation field.
group.DefaultAllowBatchImageGeneration = groupDescAllowBatchImageGeneration.Default.(bool)
// groupDescImageRateIndependent is the schema descriptor for image_rate_independent field.
groupDescImageRateIndependent := groupFields[17].Descriptor()
groupDescImageRateIndependent := groupFields[18].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[18].Descriptor()
groupDescImageRateMultiplier := groupFields[19].Descriptor()
// group.DefaultImageRateMultiplier holds the default value on creation for the image_rate_multiplier field.
group.DefaultImageRateMultiplier = groupDescImageRateMultiplier.Default.(float64)
// groupDescBatchImageDiscountMultiplier is the schema descriptor for batch_image_discount_multiplier field.
groupDescBatchImageDiscountMultiplier := groupFields[22].Descriptor()
groupDescBatchImageDiscountMultiplier := groupFields[23].Descriptor()
// group.DefaultBatchImageDiscountMultiplier holds the default value on creation for the batch_image_discount_multiplier field.
group.DefaultBatchImageDiscountMultiplier = groupDescBatchImageDiscountMultiplier.Default.(float64)
// groupDescBatchImageHoldMultiplier is the schema descriptor for batch_image_hold_multiplier field.
groupDescBatchImageHoldMultiplier := groupFields[23].Descriptor()
groupDescBatchImageHoldMultiplier := groupFields[24].Descriptor()
// group.DefaultBatchImageHoldMultiplier holds the default value on creation for the batch_image_hold_multiplier field.
group.DefaultBatchImageHoldMultiplier = groupDescBatchImageHoldMultiplier.Default.(float64)
// groupDescVideoRateIndependent is the schema descriptor for video_rate_independent field.
groupDescVideoRateIndependent := groupFields[24].Descriptor()
groupDescVideoRateIndependent := groupFields[25].Descriptor()
// group.DefaultVideoRateIndependent holds the default value on creation for the video_rate_independent field.
group.DefaultVideoRateIndependent = groupDescVideoRateIndependent.Default.(bool)
// groupDescVideoRateMultiplier is the schema descriptor for video_rate_multiplier field.
groupDescVideoRateMultiplier := groupFields[25].Descriptor()
groupDescVideoRateMultiplier := groupFields[26].Descriptor()
// group.DefaultVideoRateMultiplier holds the default value on creation for the video_rate_multiplier field.
group.DefaultVideoRateMultiplier = groupDescVideoRateMultiplier.Default.(float64)
// groupDescClaudeCodeOnly is the schema descriptor for claude_code_only field.
groupDescClaudeCodeOnly := groupFields[30].Descriptor()
groupDescClaudeCodeOnly := groupFields[31].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[34].Descriptor()
groupDescModelRoutingEnabled := groupFields[35].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[35].Descriptor()
groupDescMcpXMLInject := groupFields[36].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[36].Descriptor()
groupDescSupportedModelScopes := groupFields[37].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[37].Descriptor()
groupDescSortOrder := groupFields[38].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[38].Descriptor()
groupDescAllowMessagesDispatch := groupFields[39].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[39].Descriptor()
groupDescRequireOauthOnly := groupFields[40].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[40].Descriptor()
groupDescRequirePrivacySet := groupFields[41].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[41].Descriptor()
groupDescDefaultMappedModel := groupFields[42].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[42].Descriptor()
groupDescMessagesDispatchModelConfig := groupFields[43].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[43].Descriptor()
groupDescModelsListConfig := groupFields[44].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[44].Descriptor()
groupDescRpmLimit := groupFields[45].Descriptor()
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
groupDescMaxReasoningEffort := groupFields[46].Descriptor()
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
groupDescReasoningEffortMappings := groupFields[47].Descriptor()
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
idempotencyrecordMixinFields0 := idempotencyrecordMixin[0].Fields()
_ = idempotencyrecordMixinFields0
@@ -1718,40 +1802,46 @@ func init() {
subscriptionplanDescDescription := subscriptionplanFields[2].Descriptor()
// subscriptionplan.DefaultDescription holds the default value on creation for the description field.
subscriptionplan.DefaultDescription = subscriptionplanDescDescription.Default.(string)
// subscriptionplanDescCurrency is the schema descriptor for currency field.
subscriptionplanDescCurrency := subscriptionplanFields[5].Descriptor()
// subscriptionplan.DefaultCurrency holds the default value on creation for the currency field.
subscriptionplan.DefaultCurrency = subscriptionplanDescCurrency.Default.(string)
// subscriptionplan.CurrencyValidator is a validator for the "currency" field. It is called by the builders before save.
subscriptionplan.CurrencyValidator = subscriptionplanDescCurrency.Validators[0].(func(string) error)
// subscriptionplanDescValidityDays is the schema descriptor for validity_days field.
subscriptionplanDescValidityDays := subscriptionplanFields[5].Descriptor()
subscriptionplanDescValidityDays := subscriptionplanFields[6].Descriptor()
// subscriptionplan.DefaultValidityDays holds the default value on creation for the validity_days field.
subscriptionplan.DefaultValidityDays = subscriptionplanDescValidityDays.Default.(int)
// subscriptionplanDescValidityUnit is the schema descriptor for validity_unit field.
subscriptionplanDescValidityUnit := subscriptionplanFields[6].Descriptor()
subscriptionplanDescValidityUnit := subscriptionplanFields[7].Descriptor()
// subscriptionplan.DefaultValidityUnit holds the default value on creation for the validity_unit field.
subscriptionplan.DefaultValidityUnit = subscriptionplanDescValidityUnit.Default.(string)
// subscriptionplan.ValidityUnitValidator is a validator for the "validity_unit" field. It is called by the builders before save.
subscriptionplan.ValidityUnitValidator = subscriptionplanDescValidityUnit.Validators[0].(func(string) error)
// subscriptionplanDescFeatures is the schema descriptor for features field.
subscriptionplanDescFeatures := subscriptionplanFields[7].Descriptor()
subscriptionplanDescFeatures := subscriptionplanFields[8].Descriptor()
// subscriptionplan.DefaultFeatures holds the default value on creation for the features field.
subscriptionplan.DefaultFeatures = subscriptionplanDescFeatures.Default.(string)
// subscriptionplanDescProductName is the schema descriptor for product_name field.
subscriptionplanDescProductName := subscriptionplanFields[8].Descriptor()
subscriptionplanDescProductName := subscriptionplanFields[9].Descriptor()
// subscriptionplan.DefaultProductName holds the default value on creation for the product_name field.
subscriptionplan.DefaultProductName = subscriptionplanDescProductName.Default.(string)
// subscriptionplan.ProductNameValidator is a validator for the "product_name" field. It is called by the builders before save.
subscriptionplan.ProductNameValidator = subscriptionplanDescProductName.Validators[0].(func(string) error)
// subscriptionplanDescForSale is the schema descriptor for for_sale field.
subscriptionplanDescForSale := subscriptionplanFields[9].Descriptor()
subscriptionplanDescForSale := subscriptionplanFields[10].Descriptor()
// subscriptionplan.DefaultForSale holds the default value on creation for the for_sale field.
subscriptionplan.DefaultForSale = subscriptionplanDescForSale.Default.(bool)
// subscriptionplanDescSortOrder is the schema descriptor for sort_order field.
subscriptionplanDescSortOrder := subscriptionplanFields[10].Descriptor()
subscriptionplanDescSortOrder := subscriptionplanFields[11].Descriptor()
// subscriptionplan.DefaultSortOrder holds the default value on creation for the sort_order field.
subscriptionplan.DefaultSortOrder = subscriptionplanDescSortOrder.Default.(int)
// subscriptionplanDescCreatedAt is the schema descriptor for created_at field.
subscriptionplanDescCreatedAt := subscriptionplanFields[11].Descriptor()
subscriptionplanDescCreatedAt := subscriptionplanFields[12].Descriptor()
// subscriptionplan.DefaultCreatedAt holds the default value on creation for the created_at field.
subscriptionplan.DefaultCreatedAt = subscriptionplanDescCreatedAt.Default.(func() time.Time)
// subscriptionplanDescUpdatedAt is the schema descriptor for updated_at field.
subscriptionplanDescUpdatedAt := subscriptionplanFields[12].Descriptor()
subscriptionplanDescUpdatedAt := subscriptionplanFields[13].Descriptor()
// subscriptionplan.DefaultUpdatedAt holds the default value on creation for the updated_at field.
subscriptionplan.DefaultUpdatedAt = subscriptionplanDescUpdatedAt.Default.(func() time.Time)
// subscriptionplan.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
@@ -1940,56 +2030,60 @@ func init() {
usagelogDescRateMultiplier := usagelogFields[25].Descriptor()
// usagelog.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
usagelog.DefaultRateMultiplier = usagelogDescRateMultiplier.Default.(float64)
// usagelogDescLongContextBillingApplied is the schema descriptor for long_context_billing_applied field.
usagelogDescLongContextBillingApplied := usagelogFields[26].Descriptor()
// usagelog.DefaultLongContextBillingApplied holds the default value on creation for the long_context_billing_applied field.
usagelog.DefaultLongContextBillingApplied = usagelogDescLongContextBillingApplied.Default.(bool)
// usagelogDescBillingType is the schema descriptor for billing_type field.
usagelogDescBillingType := usagelogFields[27].Descriptor()
usagelogDescBillingType := usagelogFields[28].Descriptor()
// usagelog.DefaultBillingType holds the default value on creation for the billing_type field.
usagelog.DefaultBillingType = usagelogDescBillingType.Default.(int8)
// usagelogDescStream is the schema descriptor for stream field.
usagelogDescStream := usagelogFields[28].Descriptor()
usagelogDescStream := usagelogFields[29].Descriptor()
// usagelog.DefaultStream holds the default value on creation for the stream field.
usagelog.DefaultStream = usagelogDescStream.Default.(bool)
// usagelogDescUserAgent is the schema descriptor for user_agent field.
usagelogDescUserAgent := usagelogFields[31].Descriptor()
usagelogDescUserAgent := usagelogFields[32].Descriptor()
// usagelog.UserAgentValidator is a validator for the "user_agent" field. It is called by the builders before save.
usagelog.UserAgentValidator = usagelogDescUserAgent.Validators[0].(func(string) error)
// usagelogDescIPAddress is the schema descriptor for ip_address field.
usagelogDescIPAddress := usagelogFields[32].Descriptor()
usagelogDescIPAddress := usagelogFields[33].Descriptor()
// usagelog.IPAddressValidator is a validator for the "ip_address" field. It is called by the builders before save.
usagelog.IPAddressValidator = usagelogDescIPAddress.Validators[0].(func(string) error)
// usagelogDescImageCount is the schema descriptor for image_count field.
usagelogDescImageCount := usagelogFields[33].Descriptor()
usagelogDescImageCount := usagelogFields[34].Descriptor()
// usagelog.DefaultImageCount holds the default value on creation for the image_count field.
usagelog.DefaultImageCount = usagelogDescImageCount.Default.(int)
// usagelogDescImageSize is the schema descriptor for image_size field.
usagelogDescImageSize := usagelogFields[34].Descriptor()
usagelogDescImageSize := usagelogFields[35].Descriptor()
// usagelog.ImageSizeValidator is a validator for the "image_size" field. It is called by the builders before save.
usagelog.ImageSizeValidator = usagelogDescImageSize.Validators[0].(func(string) error)
// usagelogDescImageInputSize is the schema descriptor for image_input_size field.
usagelogDescImageInputSize := usagelogFields[35].Descriptor()
usagelogDescImageInputSize := usagelogFields[36].Descriptor()
// usagelog.ImageInputSizeValidator is a validator for the "image_input_size" field. It is called by the builders before save.
usagelog.ImageInputSizeValidator = usagelogDescImageInputSize.Validators[0].(func(string) error)
// usagelogDescImageOutputSize is the schema descriptor for image_output_size field.
usagelogDescImageOutputSize := usagelogFields[36].Descriptor()
usagelogDescImageOutputSize := usagelogFields[37].Descriptor()
// usagelog.ImageOutputSizeValidator is a validator for the "image_output_size" field. It is called by the builders before save.
usagelog.ImageOutputSizeValidator = usagelogDescImageOutputSize.Validators[0].(func(string) error)
// usagelogDescImageSizeSource is the schema descriptor for image_size_source field.
usagelogDescImageSizeSource := usagelogFields[37].Descriptor()
usagelogDescImageSizeSource := usagelogFields[38].Descriptor()
// usagelog.ImageSizeSourceValidator is a validator for the "image_size_source" field. It is called by the builders before save.
usagelog.ImageSizeSourceValidator = usagelogDescImageSizeSource.Validators[0].(func(string) error)
// usagelogDescVideoCount is the schema descriptor for video_count field.
usagelogDescVideoCount := usagelogFields[39].Descriptor()
usagelogDescVideoCount := usagelogFields[40].Descriptor()
// usagelog.DefaultVideoCount holds the default value on creation for the video_count field.
usagelog.DefaultVideoCount = usagelogDescVideoCount.Default.(int)
// usagelogDescVideoResolution is the schema descriptor for video_resolution field.
usagelogDescVideoResolution := usagelogFields[40].Descriptor()
usagelogDescVideoResolution := usagelogFields[41].Descriptor()
// usagelog.VideoResolutionValidator is a validator for the "video_resolution" field. It is called by the builders before save.
usagelog.VideoResolutionValidator = usagelogDescVideoResolution.Validators[0].(func(string) error)
// usagelogDescCacheTTLOverridden is the schema descriptor for cache_ttl_overridden field.
usagelogDescCacheTTLOverridden := usagelogFields[42].Descriptor()
usagelogDescCacheTTLOverridden := usagelogFields[43].Descriptor()
// usagelog.DefaultCacheTTLOverridden holds the default value on creation for the cache_ttl_overridden field.
usagelog.DefaultCacheTTLOverridden = usagelogDescCacheTTLOverridden.Default.(bool)
// usagelogDescCreatedAt is the schema descriptor for created_at field.
usagelogDescCreatedAt := usagelogFields[43].Descriptor()
usagelogDescCreatedAt := usagelogFields[44].Descriptor()
// usagelog.DefaultCreatedAt holds the default value on creation for the created_at field.
usagelog.DefaultCreatedAt = usagelogDescCreatedAt.Default.(func() time.Time)
userMixin := schema.User{}.Mixin()
+1 -1
View File
@@ -35,7 +35,7 @@ func (ChannelMonitor) Fields() []ent.Field {
NotEmpty().
MaxLen(100),
field.Enum("provider").
Values("openai", "anthropic", "gemini"),
Values("openai", "anthropic", "gemini", "grok"),
field.String("api_mode").
Default("chat_completions").
MaxLen(32).
@@ -39,7 +39,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field {
NotEmpty().
MaxLen(100),
field.Enum("provider").
Values("openai", "anthropic", "gemini"),
Values("openai", "anthropic", "gemini", "grok"),
field.String("api_mode").
Default("chat_completions").
MaxLen(32).
@@ -0,0 +1,87 @@
package schema
import (
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/domain"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// CompositeModelRoute holds model routing aliases for composite groups.
type CompositeModelRoute struct {
ent.Schema
}
func (CompositeModelRoute) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "composite_model_routes"},
}
}
func (CompositeModelRoute) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.TimeMixin{},
mixins.SoftDeleteMixin{},
}
}
func (CompositeModelRoute) Fields() []ent.Field {
return []ent.Field{
field.Int64("group_id"),
field.String("public_model").
MaxLen(200).
NotEmpty().
Comment("Client-facing model identifier or prefix."),
field.String("match_type").
MaxLen(20).
Default("exact").
Comment("exact or prefix."),
field.String("target_platform").
MaxLen(50).
Default(domain.PlatformOpenAI).
Comment("Concrete provider platform."),
field.String("upstream_model").
MaxLen(200).
Default("").
Comment("Provider model identifier; empty means public_model."),
field.String("endpoint").
MaxLen(50).
Default("any").
Comment("Endpoint scope such as any, messages, responses, chat_completions."),
field.Int("priority").
Default(100).
Comment("Lower values win within the same match strength."),
field.Bool("enabled").
Default(true),
field.String("notes").
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
}
}
func (CompositeModelRoute) Edges() []ent.Edge {
return []ent.Edge{
edge.To("group", Group.Type).
Unique().
Required().
Field("group_id"),
}
}
func (CompositeModelRoute) Indexes() []ent.Index {
return []ent.Index{
index.Fields("group_id"),
index.Fields("group_id", "enabled"),
index.Fields("group_id", "endpoint"),
index.Fields("group_id", "target_platform"),
index.Fields("deleted_at"),
index.Fields("priority"),
}
}
+20
View File
@@ -66,6 +66,12 @@ func (Group) Fields() []ent.Field {
field.String("status").
MaxLen(20).
Default(domain.StatusActive),
field.String("duplicate_operation_id").
MaxLen(64).
Optional().
Nillable().
Immutable().
Comment("内部幂等恢复标识,不对 API 暴露"),
// Subscription-related fields (added by migration 003)
field.String("platform").
@@ -215,6 +221,16 @@ func (Group) Fields() []ent.Field {
field.Int("rpm_limit").
Default(0).
Comment("分组 RPM 上限,0 表示不限制;设置后接管该分组用户的限流"),
// OpenAI/Codex 请求的推理强度上限(空字符串表示不限制)。
field.String("max_reasoning_effort").
MaxLen(20).
Default("").
Comment("OpenAI reasoning effort 上限;可选 minimal/low/medium/high/xhigh/max"),
field.JSON("reasoning_effort_mappings", []domain.ReasoningEffortMapping{}).
Default([]domain.ReasoningEffortMapping{}).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
Comment("OpenAI reasoning effort 自定义精确映射;先映射再应用上限"),
}
}
@@ -244,5 +260,9 @@ func (Group) Indexes() []ent.Index {
index.Fields("is_exclusive"),
index.Fields("deleted_at"),
index.Fields("sort_order"),
index.Fields("duplicate_operation_id").
Unique().
StorageKey("idx_groups_duplicate_operation_id_active").
Annotations(entsql.IndexWhere("duplicate_operation_id IS NOT NULL AND deleted_at IS NULL")),
}
}
+3
View File
@@ -43,6 +43,9 @@ func (SubscriptionPlan) Fields() []ent.Field {
SchemaType(map[string]string{dialect.Postgres: "decimal(20,2)"}).
Optional().
Nillable(),
field.String("currency").
MaxLen(3).
Default(""),
field.Int("validity_days").
Default(30),
field.String("validity_unit").
+3
View File
@@ -100,6 +100,9 @@ func (UsageLog) Fields() []ent.Field {
field.Float("rate_multiplier").
Default(1).
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}),
field.Bool("long_context_billing_applied").
Default(false).
Comment("Whether long-context pricing changed token prices for this request"),
// account_rate_multiplier: 账号计费倍率快照(NULL 表示按 1.0 处理)
field.Float("account_rate_multiplier").
+12 -1
View File
@@ -27,6 +27,8 @@ type SubscriptionPlan struct {
Price float64 `json:"price,omitempty"`
// OriginalPrice holds the value of the "original_price" field.
OriginalPrice *float64 `json:"original_price,omitempty"`
// Currency holds the value of the "currency" field.
Currency string `json:"currency,omitempty"`
// ValidityDays holds the value of the "validity_days" field.
ValidityDays int `json:"validity_days,omitempty"`
// ValidityUnit holds the value of the "validity_unit" field.
@@ -57,7 +59,7 @@ func (*SubscriptionPlan) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullFloat64)
case subscriptionplan.FieldID, subscriptionplan.FieldGroupID, subscriptionplan.FieldValidityDays, subscriptionplan.FieldSortOrder:
values[i] = new(sql.NullInt64)
case subscriptionplan.FieldName, subscriptionplan.FieldDescription, subscriptionplan.FieldValidityUnit, subscriptionplan.FieldFeatures, subscriptionplan.FieldProductName:
case subscriptionplan.FieldName, subscriptionplan.FieldDescription, subscriptionplan.FieldCurrency, subscriptionplan.FieldValidityUnit, subscriptionplan.FieldFeatures, subscriptionplan.FieldProductName:
values[i] = new(sql.NullString)
case subscriptionplan.FieldCreatedAt, subscriptionplan.FieldUpdatedAt:
values[i] = new(sql.NullTime)
@@ -113,6 +115,12 @@ func (_m *SubscriptionPlan) assignValues(columns []string, values []any) error {
_m.OriginalPrice = new(float64)
*_m.OriginalPrice = value.Float64
}
case subscriptionplan.FieldCurrency:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field currency", values[i])
} else if value.Valid {
_m.Currency = value.String
}
case subscriptionplan.FieldValidityDays:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field validity_days", values[i])
@@ -214,6 +222,9 @@ func (_m *SubscriptionPlan) String() string {
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("currency=")
builder.WriteString(_m.Currency)
builder.WriteString(", ")
builder.WriteString("validity_days=")
builder.WriteString(fmt.Sprintf("%v", _m.ValidityDays))
builder.WriteString(", ")
@@ -23,6 +23,8 @@ const (
FieldPrice = "price"
// FieldOriginalPrice holds the string denoting the original_price field in the database.
FieldOriginalPrice = "original_price"
// FieldCurrency holds the string denoting the currency field in the database.
FieldCurrency = "currency"
// FieldValidityDays holds the string denoting the validity_days field in the database.
FieldValidityDays = "validity_days"
// FieldValidityUnit holds the string denoting the validity_unit field in the database.
@@ -51,6 +53,7 @@ var Columns = []string{
FieldDescription,
FieldPrice,
FieldOriginalPrice,
FieldCurrency,
FieldValidityDays,
FieldValidityUnit,
FieldFeatures,
@@ -76,6 +79,10 @@ var (
NameValidator func(string) error
// DefaultDescription holds the default value on creation for the "description" field.
DefaultDescription string
// DefaultCurrency holds the default value on creation for the "currency" field.
DefaultCurrency string
// CurrencyValidator is a validator for the "currency" field. It is called by the builders before save.
CurrencyValidator func(string) error
// DefaultValidityDays holds the default value on creation for the "validity_days" field.
DefaultValidityDays int
// DefaultValidityUnit holds the default value on creation for the "validity_unit" field.
@@ -133,6 +140,11 @@ func ByOriginalPrice(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOriginalPrice, opts...).ToFunc()
}
// ByCurrency orders the results by the currency field.
func ByCurrency(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCurrency, opts...).ToFunc()
}
// ByValidityDays orders the results by the validity_days field.
func ByValidityDays(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValidityDays, opts...).ToFunc()
+70
View File
@@ -79,6 +79,11 @@ func OriginalPrice(v float64) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldEQ(FieldOriginalPrice, v))
}
// Currency applies equality check predicate on the "currency" field. It's identical to CurrencyEQ.
func Currency(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldEQ(FieldCurrency, v))
}
// ValidityDays applies equality check predicate on the "validity_days" field. It's identical to ValidityDaysEQ.
func ValidityDays(v int) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldEQ(FieldValidityDays, v))
@@ -379,6 +384,71 @@ func OriginalPriceNotNil() predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldNotNull(FieldOriginalPrice))
}
// CurrencyEQ applies the EQ predicate on the "currency" field.
func CurrencyEQ(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldEQ(FieldCurrency, v))
}
// CurrencyNEQ applies the NEQ predicate on the "currency" field.
func CurrencyNEQ(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldNEQ(FieldCurrency, v))
}
// CurrencyIn applies the In predicate on the "currency" field.
func CurrencyIn(vs ...string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldIn(FieldCurrency, vs...))
}
// CurrencyNotIn applies the NotIn predicate on the "currency" field.
func CurrencyNotIn(vs ...string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldNotIn(FieldCurrency, vs...))
}
// CurrencyGT applies the GT predicate on the "currency" field.
func CurrencyGT(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldGT(FieldCurrency, v))
}
// CurrencyGTE applies the GTE predicate on the "currency" field.
func CurrencyGTE(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldGTE(FieldCurrency, v))
}
// CurrencyLT applies the LT predicate on the "currency" field.
func CurrencyLT(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldLT(FieldCurrency, v))
}
// CurrencyLTE applies the LTE predicate on the "currency" field.
func CurrencyLTE(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldLTE(FieldCurrency, v))
}
// CurrencyContains applies the Contains predicate on the "currency" field.
func CurrencyContains(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldContains(FieldCurrency, v))
}
// CurrencyHasPrefix applies the HasPrefix predicate on the "currency" field.
func CurrencyHasPrefix(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldHasPrefix(FieldCurrency, v))
}
// CurrencyHasSuffix applies the HasSuffix predicate on the "currency" field.
func CurrencyHasSuffix(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldHasSuffix(FieldCurrency, v))
}
// CurrencyEqualFold applies the EqualFold predicate on the "currency" field.
func CurrencyEqualFold(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldEqualFold(FieldCurrency, v))
}
// CurrencyContainsFold applies the ContainsFold predicate on the "currency" field.
func CurrencyContainsFold(v string) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldContainsFold(FieldCurrency, v))
}
// ValidityDaysEQ applies the EQ predicate on the "validity_days" field.
func ValidityDaysEQ(v int) predicate.SubscriptionPlan {
return predicate.SubscriptionPlan(sql.FieldEQ(FieldValidityDays, v))
+70
View File
@@ -68,6 +68,20 @@ func (_c *SubscriptionPlanCreate) SetNillableOriginalPrice(v *float64) *Subscrip
return _c
}
// SetCurrency sets the "currency" field.
func (_c *SubscriptionPlanCreate) SetCurrency(v string) *SubscriptionPlanCreate {
_c.mutation.SetCurrency(v)
return _c
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (_c *SubscriptionPlanCreate) SetNillableCurrency(v *string) *SubscriptionPlanCreate {
if v != nil {
_c.SetCurrency(*v)
}
return _c
}
// SetValidityDays sets the "validity_days" field.
func (_c *SubscriptionPlanCreate) SetValidityDays(v int) *SubscriptionPlanCreate {
_c.mutation.SetValidityDays(v)
@@ -219,6 +233,10 @@ func (_c *SubscriptionPlanCreate) defaults() {
v := subscriptionplan.DefaultDescription
_c.mutation.SetDescription(v)
}
if _, ok := _c.mutation.Currency(); !ok {
v := subscriptionplan.DefaultCurrency
_c.mutation.SetCurrency(v)
}
if _, ok := _c.mutation.ValidityDays(); !ok {
v := subscriptionplan.DefaultValidityDays
_c.mutation.SetValidityDays(v)
@@ -272,6 +290,14 @@ func (_c *SubscriptionPlanCreate) check() error {
if _, ok := _c.mutation.Price(); !ok {
return &ValidationError{Name: "price", err: errors.New(`ent: missing required field "SubscriptionPlan.price"`)}
}
if _, ok := _c.mutation.Currency(); !ok {
return &ValidationError{Name: "currency", err: errors.New(`ent: missing required field "SubscriptionPlan.currency"`)}
}
if v, ok := _c.mutation.Currency(); ok {
if err := subscriptionplan.CurrencyValidator(v); err != nil {
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.currency": %w`, err)}
}
}
if _, ok := _c.mutation.ValidityDays(); !ok {
return &ValidationError{Name: "validity_days", err: errors.New(`ent: missing required field "SubscriptionPlan.validity_days"`)}
}
@@ -353,6 +379,10 @@ func (_c *SubscriptionPlanCreate) createSpec() (*SubscriptionPlan, *sqlgraph.Cre
_spec.SetField(subscriptionplan.FieldOriginalPrice, field.TypeFloat64, value)
_node.OriginalPrice = &value
}
if value, ok := _c.mutation.Currency(); ok {
_spec.SetField(subscriptionplan.FieldCurrency, field.TypeString, value)
_node.Currency = value
}
if value, ok := _c.mutation.ValidityDays(); ok {
_spec.SetField(subscriptionplan.FieldValidityDays, field.TypeInt, value)
_node.ValidityDays = value
@@ -521,6 +551,18 @@ func (u *SubscriptionPlanUpsert) ClearOriginalPrice() *SubscriptionPlanUpsert {
return u
}
// SetCurrency sets the "currency" field.
func (u *SubscriptionPlanUpsert) SetCurrency(v string) *SubscriptionPlanUpsert {
u.Set(subscriptionplan.FieldCurrency, v)
return u
}
// UpdateCurrency sets the "currency" field to the value that was provided on create.
func (u *SubscriptionPlanUpsert) UpdateCurrency() *SubscriptionPlanUpsert {
u.SetExcluded(subscriptionplan.FieldCurrency)
return u
}
// SetValidityDays sets the "validity_days" field.
func (u *SubscriptionPlanUpsert) SetValidityDays(v int) *SubscriptionPlanUpsert {
u.Set(subscriptionplan.FieldValidityDays, v)
@@ -760,6 +802,20 @@ func (u *SubscriptionPlanUpsertOne) ClearOriginalPrice() *SubscriptionPlanUpsert
})
}
// SetCurrency sets the "currency" field.
func (u *SubscriptionPlanUpsertOne) SetCurrency(v string) *SubscriptionPlanUpsertOne {
return u.Update(func(s *SubscriptionPlanUpsert) {
s.SetCurrency(v)
})
}
// UpdateCurrency sets the "currency" field to the value that was provided on create.
func (u *SubscriptionPlanUpsertOne) UpdateCurrency() *SubscriptionPlanUpsertOne {
return u.Update(func(s *SubscriptionPlanUpsert) {
s.UpdateCurrency()
})
}
// SetValidityDays sets the "validity_days" field.
func (u *SubscriptionPlanUpsertOne) SetValidityDays(v int) *SubscriptionPlanUpsertOne {
return u.Update(func(s *SubscriptionPlanUpsert) {
@@ -1181,6 +1237,20 @@ func (u *SubscriptionPlanUpsertBulk) ClearOriginalPrice() *SubscriptionPlanUpser
})
}
// SetCurrency sets the "currency" field.
func (u *SubscriptionPlanUpsertBulk) SetCurrency(v string) *SubscriptionPlanUpsertBulk {
return u.Update(func(s *SubscriptionPlanUpsert) {
s.SetCurrency(v)
})
}
// UpdateCurrency sets the "currency" field to the value that was provided on create.
func (u *SubscriptionPlanUpsertBulk) UpdateCurrency() *SubscriptionPlanUpsertBulk {
return u.Update(func(s *SubscriptionPlanUpsert) {
s.UpdateCurrency()
})
}
// SetValidityDays sets the "validity_days" field.
func (u *SubscriptionPlanUpsertBulk) SetValidityDays(v int) *SubscriptionPlanUpsertBulk {
return u.Update(func(s *SubscriptionPlanUpsert) {
+44
View File
@@ -125,6 +125,20 @@ func (_u *SubscriptionPlanUpdate) ClearOriginalPrice() *SubscriptionPlanUpdate {
return _u
}
// SetCurrency sets the "currency" field.
func (_u *SubscriptionPlanUpdate) SetCurrency(v string) *SubscriptionPlanUpdate {
_u.mutation.SetCurrency(v)
return _u
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (_u *SubscriptionPlanUpdate) SetNillableCurrency(v *string) *SubscriptionPlanUpdate {
if v != nil {
_u.SetCurrency(*v)
}
return _u
}
// SetValidityDays sets the "validity_days" field.
func (_u *SubscriptionPlanUpdate) SetValidityDays(v int) *SubscriptionPlanUpdate {
_u.mutation.ResetValidityDays()
@@ -277,6 +291,11 @@ func (_u *SubscriptionPlanUpdate) check() error {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.name": %w`, err)}
}
}
if v, ok := _u.mutation.Currency(); ok {
if err := subscriptionplan.CurrencyValidator(v); err != nil {
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.currency": %w`, err)}
}
}
if v, ok := _u.mutation.ValidityUnit(); ok {
if err := subscriptionplan.ValidityUnitValidator(v); err != nil {
return &ValidationError{Name: "validity_unit", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.validity_unit": %w`, err)}
@@ -329,6 +348,9 @@ func (_u *SubscriptionPlanUpdate) sqlSave(ctx context.Context) (_node int, err e
if _u.mutation.OriginalPriceCleared() {
_spec.ClearField(subscriptionplan.FieldOriginalPrice, field.TypeFloat64)
}
if value, ok := _u.mutation.Currency(); ok {
_spec.SetField(subscriptionplan.FieldCurrency, field.TypeString, value)
}
if value, ok := _u.mutation.ValidityDays(); ok {
_spec.SetField(subscriptionplan.FieldValidityDays, field.TypeInt, value)
}
@@ -473,6 +495,20 @@ func (_u *SubscriptionPlanUpdateOne) ClearOriginalPrice() *SubscriptionPlanUpdat
return _u
}
// SetCurrency sets the "currency" field.
func (_u *SubscriptionPlanUpdateOne) SetCurrency(v string) *SubscriptionPlanUpdateOne {
_u.mutation.SetCurrency(v)
return _u
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (_u *SubscriptionPlanUpdateOne) SetNillableCurrency(v *string) *SubscriptionPlanUpdateOne {
if v != nil {
_u.SetCurrency(*v)
}
return _u
}
// SetValidityDays sets the "validity_days" field.
func (_u *SubscriptionPlanUpdateOne) SetValidityDays(v int) *SubscriptionPlanUpdateOne {
_u.mutation.ResetValidityDays()
@@ -638,6 +674,11 @@ func (_u *SubscriptionPlanUpdateOne) check() error {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.name": %w`, err)}
}
}
if v, ok := _u.mutation.Currency(); ok {
if err := subscriptionplan.CurrencyValidator(v); err != nil {
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.currency": %w`, err)}
}
}
if v, ok := _u.mutation.ValidityUnit(); ok {
if err := subscriptionplan.ValidityUnitValidator(v); err != nil {
return &ValidationError{Name: "validity_unit", err: fmt.Errorf(`ent: validator failed for field "SubscriptionPlan.validity_unit": %w`, err)}
@@ -707,6 +748,9 @@ func (_u *SubscriptionPlanUpdateOne) sqlSave(ctx context.Context) (_node *Subscr
if _u.mutation.OriginalPriceCleared() {
_spec.ClearField(subscriptionplan.FieldOriginalPrice, field.TypeFloat64)
}
if value, ok := _u.mutation.Currency(); ok {
_spec.SetField(subscriptionplan.FieldCurrency, field.TypeString, value)
}
if value, ok := _u.mutation.ValidityDays(); ok {
_spec.SetField(subscriptionplan.FieldValidityDays, field.TypeInt, value)
}
+3
View File
@@ -42,6 +42,8 @@ type Tx struct {
ChannelMonitorHistory *ChannelMonitorHistoryClient
// ChannelMonitorRequestTemplate is the client for interacting with the ChannelMonitorRequestTemplate builders.
ChannelMonitorRequestTemplate *ChannelMonitorRequestTemplateClient
// CompositeModelRoute is the client for interacting with the CompositeModelRoute builders.
CompositeModelRoute *CompositeModelRouteClient
// ErrorPassthroughRule is the client for interacting with the ErrorPassthroughRule builders.
ErrorPassthroughRule *ErrorPassthroughRuleClient
// Group is the client for interacting with the Group builders.
@@ -235,6 +237,7 @@ func (tx *Tx) init() {
tx.ChannelMonitorDailyRollup = NewChannelMonitorDailyRollupClient(tx.config)
tx.ChannelMonitorHistory = NewChannelMonitorHistoryClient(tx.config)
tx.ChannelMonitorRequestTemplate = NewChannelMonitorRequestTemplateClient(tx.config)
tx.CompositeModelRoute = NewCompositeModelRouteClient(tx.config)
tx.ErrorPassthroughRule = NewErrorPassthroughRuleClient(tx.config)
tx.Group = NewGroupClient(tx.config)
tx.IdempotencyRecord = NewIdempotencyRecordClient(tx.config)
+12 -1
View File
@@ -75,6 +75,8 @@ type UsageLog struct {
ActualCost float64 `json:"actual_cost,omitempty"`
// RateMultiplier holds the value of the "rate_multiplier" field.
RateMultiplier float64 `json:"rate_multiplier,omitempty"`
// Whether long-context pricing changed token prices for this request
LongContextBillingApplied bool `json:"long_context_billing_applied,omitempty"`
// AccountRateMultiplier holds the value of the "account_rate_multiplier" field.
AccountRateMultiplier *float64 `json:"account_rate_multiplier,omitempty"`
// BillingType holds the value of the "billing_type" field.
@@ -196,7 +198,7 @@ func (*UsageLog) scanValues(columns []string) ([]any, error) {
switch columns[i] {
case usagelog.FieldImageSizeBreakdown:
values[i] = new([]byte)
case usagelog.FieldStream, usagelog.FieldCacheTTLOverridden:
case usagelog.FieldLongContextBillingApplied, usagelog.FieldStream, usagelog.FieldCacheTTLOverridden:
values[i] = new(sql.NullBool)
case usagelog.FieldInputCost, usagelog.FieldOutputCost, usagelog.FieldCacheCreationCost, usagelog.FieldCacheReadCost, usagelog.FieldTotalCost, usagelog.FieldActualCost, usagelog.FieldRateMultiplier, usagelog.FieldAccountRateMultiplier:
values[i] = new(sql.NullFloat64)
@@ -391,6 +393,12 @@ func (_m *UsageLog) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.RateMultiplier = value.Float64
}
case usagelog.FieldLongContextBillingApplied:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field long_context_billing_applied", values[i])
} else if value.Valid {
_m.LongContextBillingApplied = value.Bool
}
case usagelog.FieldAccountRateMultiplier:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field account_rate_multiplier", values[i])
@@ -667,6 +675,9 @@ func (_m *UsageLog) String() string {
builder.WriteString("rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", _m.RateMultiplier))
builder.WriteString(", ")
builder.WriteString("long_context_billing_applied=")
builder.WriteString(fmt.Sprintf("%v", _m.LongContextBillingApplied))
builder.WriteString(", ")
if v := _m.AccountRateMultiplier; v != nil {
builder.WriteString("account_rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", *v))
+10
View File
@@ -66,6 +66,8 @@ const (
FieldActualCost = "actual_cost"
// FieldRateMultiplier holds the string denoting the rate_multiplier field in the database.
FieldRateMultiplier = "rate_multiplier"
// FieldLongContextBillingApplied holds the string denoting the long_context_billing_applied field in the database.
FieldLongContextBillingApplied = "long_context_billing_applied"
// FieldAccountRateMultiplier holds the string denoting the account_rate_multiplier field in the database.
FieldAccountRateMultiplier = "account_rate_multiplier"
// FieldBillingType holds the string denoting the billing_type field in the database.
@@ -180,6 +182,7 @@ var Columns = []string{
FieldTotalCost,
FieldActualCost,
FieldRateMultiplier,
FieldLongContextBillingApplied,
FieldAccountRateMultiplier,
FieldBillingType,
FieldStream,
@@ -251,6 +254,8 @@ var (
DefaultActualCost float64
// DefaultRateMultiplier holds the default value on creation for the "rate_multiplier" field.
DefaultRateMultiplier float64
// DefaultLongContextBillingApplied holds the default value on creation for the "long_context_billing_applied" field.
DefaultLongContextBillingApplied bool
// DefaultBillingType holds the default value on creation for the "billing_type" field.
DefaultBillingType int8
// DefaultStream holds the default value on creation for the "stream" field.
@@ -417,6 +422,11 @@ func ByRateMultiplier(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRateMultiplier, opts...).ToFunc()
}
// ByLongContextBillingApplied orders the results by the long_context_billing_applied field.
func ByLongContextBillingApplied(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLongContextBillingApplied, opts...).ToFunc()
}
// ByAccountRateMultiplier orders the results by the account_rate_multiplier field.
func ByAccountRateMultiplier(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAccountRateMultiplier, opts...).ToFunc()
+15
View File
@@ -185,6 +185,11 @@ func RateMultiplier(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldRateMultiplier, v))
}
// LongContextBillingApplied applies equality check predicate on the "long_context_billing_applied" field. It's identical to LongContextBillingAppliedEQ.
func LongContextBillingApplied(v bool) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldLongContextBillingApplied, v))
}
// AccountRateMultiplier applies equality check predicate on the "account_rate_multiplier" field. It's identical to AccountRateMultiplierEQ.
func AccountRateMultiplier(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldAccountRateMultiplier, v))
@@ -1465,6 +1470,16 @@ func RateMultiplierLTE(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldRateMultiplier, v))
}
// LongContextBillingAppliedEQ applies the EQ predicate on the "long_context_billing_applied" field.
func LongContextBillingAppliedEQ(v bool) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldLongContextBillingApplied, v))
}
// LongContextBillingAppliedNEQ applies the NEQ predicate on the "long_context_billing_applied" field.
func LongContextBillingAppliedNEQ(v bool) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNEQ(FieldLongContextBillingApplied, v))
}
// AccountRateMultiplierEQ applies the EQ predicate on the "account_rate_multiplier" field.
func AccountRateMultiplierEQ(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldAccountRateMultiplier, v))
+65
View File
@@ -351,6 +351,20 @@ func (_c *UsageLogCreate) SetNillableRateMultiplier(v *float64) *UsageLogCreate
return _c
}
// SetLongContextBillingApplied sets the "long_context_billing_applied" field.
func (_c *UsageLogCreate) SetLongContextBillingApplied(v bool) *UsageLogCreate {
_c.mutation.SetLongContextBillingApplied(v)
return _c
}
// SetNillableLongContextBillingApplied sets the "long_context_billing_applied" field if the given value is not nil.
func (_c *UsageLogCreate) SetNillableLongContextBillingApplied(v *bool) *UsageLogCreate {
if v != nil {
_c.SetLongContextBillingApplied(*v)
}
return _c
}
// SetAccountRateMultiplier sets the "account_rate_multiplier" field.
func (_c *UsageLogCreate) SetAccountRateMultiplier(v float64) *UsageLogCreate {
_c.mutation.SetAccountRateMultiplier(v)
@@ -707,6 +721,10 @@ func (_c *UsageLogCreate) defaults() {
v := usagelog.DefaultRateMultiplier
_c.mutation.SetRateMultiplier(v)
}
if _, ok := _c.mutation.LongContextBillingApplied(); !ok {
v := usagelog.DefaultLongContextBillingApplied
_c.mutation.SetLongContextBillingApplied(v)
}
if _, ok := _c.mutation.BillingType(); !ok {
v := usagelog.DefaultBillingType
_c.mutation.SetBillingType(v)
@@ -824,6 +842,9 @@ func (_c *UsageLogCreate) check() error {
if _, ok := _c.mutation.RateMultiplier(); !ok {
return &ValidationError{Name: "rate_multiplier", err: errors.New(`ent: missing required field "UsageLog.rate_multiplier"`)}
}
if _, ok := _c.mutation.LongContextBillingApplied(); !ok {
return &ValidationError{Name: "long_context_billing_applied", err: errors.New(`ent: missing required field "UsageLog.long_context_billing_applied"`)}
}
if _, ok := _c.mutation.BillingType(); !ok {
return &ValidationError{Name: "billing_type", err: errors.New(`ent: missing required field "UsageLog.billing_type"`)}
}
@@ -997,6 +1018,10 @@ func (_c *UsageLogCreate) createSpec() (*UsageLog, *sqlgraph.CreateSpec) {
_spec.SetField(usagelog.FieldRateMultiplier, field.TypeFloat64, value)
_node.RateMultiplier = value
}
if value, ok := _c.mutation.LongContextBillingApplied(); ok {
_spec.SetField(usagelog.FieldLongContextBillingApplied, field.TypeBool, value)
_node.LongContextBillingApplied = value
}
if value, ok := _c.mutation.AccountRateMultiplier(); ok {
_spec.SetField(usagelog.FieldAccountRateMultiplier, field.TypeFloat64, value)
_node.AccountRateMultiplier = &value
@@ -1650,6 +1675,18 @@ func (u *UsageLogUpsert) AddRateMultiplier(v float64) *UsageLogUpsert {
return u
}
// SetLongContextBillingApplied sets the "long_context_billing_applied" field.
func (u *UsageLogUpsert) SetLongContextBillingApplied(v bool) *UsageLogUpsert {
u.Set(usagelog.FieldLongContextBillingApplied, v)
return u
}
// UpdateLongContextBillingApplied sets the "long_context_billing_applied" field to the value that was provided on create.
func (u *UsageLogUpsert) UpdateLongContextBillingApplied() *UsageLogUpsert {
u.SetExcluded(usagelog.FieldLongContextBillingApplied)
return u
}
// SetAccountRateMultiplier sets the "account_rate_multiplier" field.
func (u *UsageLogUpsert) SetAccountRateMultiplier(v float64) *UsageLogUpsert {
u.Set(usagelog.FieldAccountRateMultiplier, v)
@@ -2531,6 +2568,20 @@ func (u *UsageLogUpsertOne) UpdateRateMultiplier() *UsageLogUpsertOne {
})
}
// SetLongContextBillingApplied sets the "long_context_billing_applied" field.
func (u *UsageLogUpsertOne) SetLongContextBillingApplied(v bool) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.SetLongContextBillingApplied(v)
})
}
// UpdateLongContextBillingApplied sets the "long_context_billing_applied" field to the value that was provided on create.
func (u *UsageLogUpsertOne) UpdateLongContextBillingApplied() *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateLongContextBillingApplied()
})
}
// SetAccountRateMultiplier sets the "account_rate_multiplier" field.
func (u *UsageLogUpsertOne) SetAccountRateMultiplier(v float64) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
@@ -3631,6 +3682,20 @@ func (u *UsageLogUpsertBulk) UpdateRateMultiplier() *UsageLogUpsertBulk {
})
}
// SetLongContextBillingApplied sets the "long_context_billing_applied" field.
func (u *UsageLogUpsertBulk) SetLongContextBillingApplied(v bool) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.SetLongContextBillingApplied(v)
})
}
// UpdateLongContextBillingApplied sets the "long_context_billing_applied" field to the value that was provided on create.
func (u *UsageLogUpsertBulk) UpdateLongContextBillingApplied() *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateLongContextBillingApplied()
})
}
// SetAccountRateMultiplier sets the "account_rate_multiplier" field.
func (u *UsageLogUpsertBulk) SetAccountRateMultiplier(v float64) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
+34
View File
@@ -542,6 +542,20 @@ func (_u *UsageLogUpdate) AddRateMultiplier(v float64) *UsageLogUpdate {
return _u
}
// SetLongContextBillingApplied sets the "long_context_billing_applied" field.
func (_u *UsageLogUpdate) SetLongContextBillingApplied(v bool) *UsageLogUpdate {
_u.mutation.SetLongContextBillingApplied(v)
return _u
}
// SetNillableLongContextBillingApplied sets the "long_context_billing_applied" field if the given value is not nil.
func (_u *UsageLogUpdate) SetNillableLongContextBillingApplied(v *bool) *UsageLogUpdate {
if v != nil {
_u.SetLongContextBillingApplied(*v)
}
return _u
}
// SetAccountRateMultiplier sets the "account_rate_multiplier" field.
func (_u *UsageLogUpdate) SetAccountRateMultiplier(v float64) *UsageLogUpdate {
_u.mutation.ResetAccountRateMultiplier()
@@ -1199,6 +1213,9 @@ func (_u *UsageLogUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.AddedRateMultiplier(); ok {
_spec.AddField(usagelog.FieldRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.LongContextBillingApplied(); ok {
_spec.SetField(usagelog.FieldLongContextBillingApplied, field.TypeBool, value)
}
if value, ok := _u.mutation.AccountRateMultiplier(); ok {
_spec.SetField(usagelog.FieldAccountRateMultiplier, field.TypeFloat64, value)
}
@@ -1982,6 +1999,20 @@ func (_u *UsageLogUpdateOne) AddRateMultiplier(v float64) *UsageLogUpdateOne {
return _u
}
// SetLongContextBillingApplied sets the "long_context_billing_applied" field.
func (_u *UsageLogUpdateOne) SetLongContextBillingApplied(v bool) *UsageLogUpdateOne {
_u.mutation.SetLongContextBillingApplied(v)
return _u
}
// SetNillableLongContextBillingApplied sets the "long_context_billing_applied" field if the given value is not nil.
func (_u *UsageLogUpdateOne) SetNillableLongContextBillingApplied(v *bool) *UsageLogUpdateOne {
if v != nil {
_u.SetLongContextBillingApplied(*v)
}
return _u
}
// SetAccountRateMultiplier sets the "account_rate_multiplier" field.
func (_u *UsageLogUpdateOne) SetAccountRateMultiplier(v float64) *UsageLogUpdateOne {
_u.mutation.ResetAccountRateMultiplier()
@@ -2669,6 +2700,9 @@ func (_u *UsageLogUpdateOne) sqlSave(ctx context.Context) (_node *UsageLog, err
if value, ok := _u.mutation.AddedRateMultiplier(); ok {
_spec.AddField(usagelog.FieldRateMultiplier, field.TypeFloat64, value)
}
if value, ok := _u.mutation.LongContextBillingApplied(); ok {
_spec.SetField(usagelog.FieldLongContextBillingApplied, field.TypeBool, value)
}
if value, ok := _u.mutation.AccountRateMultiplier(); ok {
_spec.SetField(usagelog.FieldAccountRateMultiplier, field.TypeFloat64, value)
}
+8 -8
View File
@@ -42,12 +42,12 @@ require (
github.com/wechatpay-apiv3/wechatpay-go v0.2.21
github.com/zeromicro/go-zero v1.9.4
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.51.0
golang.org/x/crypto v0.53.0
golang.org/x/image v0.39.0
golang.org/x/mod v0.35.0
golang.org/x/net v0.55.0
golang.org/x/sync v0.20.0
golang.org/x/term v0.43.0
golang.org/x/mod v0.37.0
golang.org/x/net v0.56.0
golang.org/x/sync v0.21.0
golang.org/x/term v0.44.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.44.3
@@ -177,9 +177,9 @@ require (
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/tools v0.44.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.39.0 // indirect
golang.org/x/tools v0.47.0 // indirect
google.golang.org/grpc v1.75.1 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
+18
View File
@@ -166,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=
@@ -419,16 +421,24 @@ golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww=
golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -440,14 +450,22 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 h1:wpZ8pe2x1Q3f2KyT5f8oP/fa9rHAKgFPr/HZdNuS+PQ=
google.golang.org/genproto/googleapis/api v0.0.0-20250929231259-57b25ae835d4 h1:8XJ4pajGwOlasW+L13MnEGA8W4115jJySQtVfS2/IBU=
+482 -52
View File
@@ -6,6 +6,8 @@ import (
"encoding/hex"
"fmt"
"log/slog"
"math"
"net/textproto"
"net/url"
"os"
"strings"
@@ -13,6 +15,7 @@ import (
"time"
"github.com/spf13/viper"
"golang.org/x/net/http/httpguts"
)
const (
@@ -94,6 +97,7 @@ type Config struct {
Update UpdateConfig `mapstructure:"update"`
Idempotency IdempotencyConfig `mapstructure:"idempotency"`
BatchImage BatchImageConfig `mapstructure:"batch_image"`
ImageStorage ImageStorageConfig `mapstructure:"image_storage"`
}
type LogConfig struct {
@@ -226,6 +230,49 @@ type BatchImageConfig struct {
VertexGCSBaseURL string `mapstructure:"vertex_gcs_base_url"`
}
// ImageStorageConfig 配置异步图片任务结果上传的 S3 兼容对象存储。
// Enabled 同时作为异步图片任务功能的总开关:未启用或未配置完整凭证时,
// 异步生图接口整体禁用,避免把上游返回的大 base64 结果塞进 Redis。
type ImageStorageConfig struct {
Enabled bool `mapstructure:"enabled"`
Endpoint string `mapstructure:"endpoint"` // e.g. https://<account_id>.r2.cloudflarestorage.com
Region string `mapstructure:"region"` // R2 用 "auto"
Bucket string `mapstructure:"bucket"`
AccessKeyID string `mapstructure:"access_key_id"`
SecretAccessKey string `mapstructure:"secret_access_key"`
Prefix string `mapstructure:"prefix"` // S3 key 前缀,如 "images/"
ForcePathStyle bool `mapstructure:"force_path_style"` // MinIO/路径风格桶
PublicBaseURL string `mapstructure:"public_base_url"` // 配了则返回 public_base_url/key 直链;否则 presigned
PresignExpiry int `mapstructure:"presign_expiry_hours"` // public_base_url 为空时的 presigned 过期时长(小时)
MaxDownloadByte int64 `mapstructure:"max_download_bytes"` // 下载上游 url 图片的字节上限
}
// IsConfigured 检查对象存储必要字段是否已配置
func (c *ImageStorageConfig) IsConfigured() bool {
return c.Bucket != "" && c.AccessKeyID != "" && c.SecretAccessKey != ""
}
// Active 返回异步图片任务是否可用:开关打开且凭证齐全
func (c *ImageStorageConfig) Active() bool {
return c.Enabled && c.IsConfigured()
}
// MissingCredentialKeys 返回 IsConfigured 所缺的配置键名。
// 用于启动日志:只说"凭证不完整"会让运维以为自己漏填了,而实际可能是值填了却没被读到。
func (c *ImageStorageConfig) MissingCredentialKeys() []string {
var missing []string
if c.Bucket == "" {
missing = append(missing, "image_storage.bucket")
}
if c.AccessKeyID == "" {
missing = append(missing, "image_storage.access_key_id")
}
if c.SecretAccessKey == "" {
missing = append(missing, "image_storage.secret_access_key")
}
return missing
}
type LinuxDoConnectConfig struct {
Enabled bool `mapstructure:"enabled"`
ClientID string `mapstructure:"client_id"`
@@ -580,6 +627,18 @@ type TokenRefreshConfig struct {
MaxRetries int `mapstructure:"max_retries"`
// 重试退避基础时间(秒)
RetryBackoffSeconds int `mapstructure:"retry_backoff_seconds"`
// 每次从数据库读取的候选账号上限
CandidatePageSize int `mapstructure:"candidate_page_size"`
// 每个平台允许的并发刷新数
ProviderConcurrency int `mapstructure:"provider_concurrency"`
// 每个平台、每个进程允许的刷新请求速率
ProviderQPS int `mapstructure:"provider_qps"`
// 一个周期内连续临时失败达到此值后停止该平台
ProviderFailureThreshold int `mapstructure:"provider_failure_threshold"`
// 单次上游刷新尝试的超时(秒)
AttemptTimeoutSeconds int `mapstructure:"attempt_timeout_seconds"`
// 单个后台刷新周期的总超时(秒)
CycleTimeoutSeconds int `mapstructure:"cycle_timeout_seconds"`
}
type PricingConfig struct {
@@ -598,15 +657,18 @@ type PricingConfig struct {
}
type ServerConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Mode string `mapstructure:"mode"` // debug/release
FrontendURL string `mapstructure:"frontend_url"` // 前端基础 URL,用于生成邮件中的外部链接
ReadHeaderTimeout int `mapstructure:"read_header_timeout"` // 读取请求头超时(秒)
IdleTimeout int `mapstructure:"idle_timeout"` // 空闲连接超时(秒)
TrustedProxies []string `mapstructure:"trusted_proxies"` // 可信代理列表(CIDR/IP)
MaxRequestBodySize int64 `mapstructure:"max_request_body_size"` // 全局最大请求体限制
H2C H2CConfig `mapstructure:"h2c"` // HTTP/2 Cleartext 配置
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Mode string `mapstructure:"mode"` // debug/release
EnableServerTiming bool `mapstructure:"enable_server_timing"` // Admin UI Server-Timing response header
FrontendURL string `mapstructure:"frontend_url"` // 前端基础 URL,用于生成邮件中的外部链接
ReadHeaderTimeout int `mapstructure:"read_header_timeout"` // 读取请求头超时(秒)
MaxHeaderBytes int `mapstructure:"max_header_bytes"` // 请求头最大字节数(HTTP/2 映射为 header-list 上限)
IdleTimeout int `mapstructure:"idle_timeout"` // 空闲连接超时(秒)
TrustedProxies []string `mapstructure:"trusted_proxies"` // 可信代理列表(CIDR/IP)
TrustedProxiesConfigured bool `mapstructure:"-" json:"-" yaml:"-"` // 是否显式配置了可信代理列表
MaxRequestBodySize int64 `mapstructure:"max_request_body_size"` // 全局最大请求体限制
H2C H2CConfig `mapstructure:"h2c"` // HTTP/2 Cleartext 配置
}
// H2CConfig HTTP/2 Cleartext 配置
@@ -624,36 +686,103 @@ type CORSConfig struct {
AllowCredentials bool `mapstructure:"allow_credentials"`
}
const MaxForwardedClientIPHeaders = 16
type ForwardedClientIPSettings struct {
TrustForwardedIP bool
Headers []string
}
type SecurityConfig struct {
URLAllowlist URLAllowlistConfig `mapstructure:"url_allowlist"`
ResponseHeaders ResponseHeaderConfig `mapstructure:"response_headers"`
CSP CSPConfig `mapstructure:"csp"`
ProxyFallback ProxyFallbackConfig `mapstructure:"proxy_fallback"`
ProxyProbe ProxyProbeConfig `mapstructure:"proxy_probe"`
TrustForwardedIPForAPIKeyACL bool `mapstructure:"trust_forwarded_ip_for_api_key_acl"`
trustForwardedIPForAPIKeyACLLive *atomic.Bool `mapstructure:"-"`
URLAllowlist URLAllowlistConfig `mapstructure:"url_allowlist"`
ResponseHeaders ResponseHeaderConfig `mapstructure:"response_headers"`
CSP CSPConfig `mapstructure:"csp"`
ProxyFallback ProxyFallbackConfig `mapstructure:"proxy_fallback"`
ProxyProbe ProxyProbeConfig `mapstructure:"proxy_probe"`
// TrustForwardedIPForAPIKeyACL enables legacy raw forwarded-header takeover.
// When disabled, server.trusted_proxies is authoritative for all client-IP consumers.
TrustForwardedIPForAPIKeyACL bool `mapstructure:"trust_forwarded_ip_for_api_key_acl"`
ForwardedClientIPHeaders []string `mapstructure:"forwarded_client_ip_headers" json:"forwarded_client_ip_headers" yaml:"forwarded_client_ip_headers"`
forwardedClientIPSettingsLive *atomic.Pointer[ForwardedClientIPSettings] `mapstructure:"-" json:"-" yaml:"-"`
}
func NormalizeForwardedClientIPHeaders(headers []string) ([]string, error) {
normalized := make([]string, 0, len(headers))
seen := make(map[string]struct{}, len(headers))
for _, header := range headers {
header = strings.TrimSpace(header)
if !httpguts.ValidHeaderFieldName(header) {
return nil, fmt.Errorf("invalid HTTP header field name %q", header)
}
canonical := textproto.CanonicalMIMEHeaderKey(header)
key := strings.ToLower(canonical)
if _, exists := seen[key]; exists {
continue
}
if len(normalized) == MaxForwardedClientIPHeaders {
return nil, fmt.Errorf("forwarded client IP headers must contain at most %d unique names", MaxForwardedClientIPHeaders)
}
seen[key] = struct{}{}
normalized = append(normalized, canonical)
}
return normalized, nil
}
func cloneForwardedClientIPHeaders(headers []string) []string {
if len(headers) == 0 {
return []string{}
}
return append([]string(nil), headers...)
}
func (c *Config) ForwardedClientIPSettings() ForwardedClientIPSettings {
if c == nil {
return ForwardedClientIPSettings{Headers: []string{}}
}
live := c.Security.forwardedClientIPSettingsLive
if live != nil {
if snapshot := live.Load(); snapshot != nil {
return ForwardedClientIPSettings{
TrustForwardedIP: snapshot.TrustForwardedIP,
Headers: cloneForwardedClientIPHeaders(snapshot.Headers),
}
}
}
return ForwardedClientIPSettings{
TrustForwardedIP: c.Security.TrustForwardedIPForAPIKeyACL,
Headers: cloneForwardedClientIPHeaders(c.Security.ForwardedClientIPHeaders),
}
}
func (c *Config) TrustForwardedIPForAPIKeyACL() bool {
return c.ForwardedClientIPSettings().TrustForwardedIP
}
// ForwardedClientIPTrustEnabled reports whether the legacy forwarded-header
// compatibility mode currently overrides server.trusted_proxies.
func (c *Config) ForwardedClientIPTrustEnabled() bool {
return c != nil && c.TrustForwardedIPForAPIKeyACL()
}
func (c *Config) SetForwardedClientIPSettings(enabled bool, headers []string) {
if c == nil {
return false
return
}
live := c.Security.trustForwardedIPForAPIKeyACLLive
if live == nil {
return c.Security.TrustForwardedIPForAPIKeyACL
headers = cloneForwardedClientIPHeaders(headers)
if c.Security.forwardedClientIPSettingsLive == nil {
c.Security.forwardedClientIPSettingsLive = &atomic.Pointer[ForwardedClientIPSettings]{}
}
return live.Load()
c.Security.forwardedClientIPSettingsLive.Store(&ForwardedClientIPSettings{
TrustForwardedIP: enabled,
Headers: headers,
})
}
func (c *Config) SetTrustForwardedIPForAPIKeyACL(enabled bool) {
if c == nil {
return
}
c.Security.TrustForwardedIPForAPIKeyACL = enabled
if c.Security.trustForwardedIPForAPIKeyACLLive == nil {
c.Security.trustForwardedIPForAPIKeyACLLive = &atomic.Bool{}
}
c.Security.trustForwardedIPForAPIKeyACLLive.Store(enabled)
c.SetForwardedClientIPSettings(enabled, c.ForwardedClientIPSettings().Headers)
}
type URLAllowlistConfig struct {
@@ -747,8 +876,15 @@ type GatewayConfig struct {
// OpenAIResponseHeaderTimeout: OpenAI/Codex 上游等待响应头的超时时间(秒),0表示无超时
// OpenAI/Codex 请求可能在上游排队较久;默认不使用通用响应头超时截断。
OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"`
// OpenAIFirstOutputTimeoutSeconds: native HTTP Responses 首个语义输出超时(秒),0表示禁用。
OpenAIFirstOutputTimeoutSeconds int `mapstructure:"openai_first_output_timeout_seconds"`
// OpenAIHighEffortFirstOutputTimeoutSeconds: high/xhigh/max 推理的首个语义输出超时(秒)。
// 0 表示回退到 OpenAIFirstOutputTimeoutSeconds。
OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"`
// 请求体最大字节数,用于网关请求体大小限制
MaxBodySize int64 `mapstructure:"max_body_size"`
// TextMaxBodySize limits endpoints that cannot carry inline image/video payloads.
TextMaxBodySize int64 `mapstructure:"text_max_body_size"`
// 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大
UpstreamResponseReadMaxBytes int64 `mapstructure:"upstream_response_read_max_bytes"`
// 代理探测响应体读取上限(字节)
@@ -781,6 +917,8 @@ type GatewayConfig struct {
OpenAIScheduler GatewayOpenAISchedulerConfig `mapstructure:"openai_scheduler"`
// OpenAIHTTP2: OpenAI HTTP 上游协议策略(默认启用 HTTP/2,可按代理能力回退 HTTP/1.1)
OpenAIHTTP2 GatewayOpenAIHTTP2Config `mapstructure:"openai_http2"`
// OpenAIProxyStreamCircuit: Responses SSE 代理断流熔断策略。
OpenAIProxyStreamCircuit GatewayOpenAIProxyStreamCircuitConfig `mapstructure:"openai_proxy_stream_circuit"`
// ImageConcurrency: 图片生成独立并发限制配置(默认关闭)
ImageConcurrency ImageConcurrencyConfig `mapstructure:"image_concurrency"`
@@ -818,6 +956,8 @@ type GatewayConfig struct {
ImageStreamDataIntervalTimeout int `mapstructure:"image_stream_data_interval_timeout"`
// ImageStreamKeepaliveInterval: 图片流式 keepalive 间隔(秒),0表示禁用
ImageStreamKeepaliveInterval int `mapstructure:"image_stream_keepalive_interval"`
// ImageNonstreamKeepaliveInterval: 图片非流式 JSON keepalive 间隔(秒),0表示禁用
ImageNonstreamKeepaliveInterval int `mapstructure:"image_nonstream_keepalive_interval"`
// MaxLineSize: 上游 SSE 单行最大字节数(0使用默认值)
MaxLineSize int `mapstructure:"max_line_size"`
@@ -874,6 +1014,17 @@ type GatewayOpenAIHTTP2Config struct {
FallbackTTLSeconds int `mapstructure:"fallback_ttl_seconds"`
}
// GatewayOpenAIProxyStreamCircuitConfig controls the bounded, in-process
// proxy-ID circuit used for incomplete OpenAI Responses SSE streams.
type GatewayOpenAIProxyStreamCircuitConfig struct {
// FailureThreshold: 统计窗口内多少次断流后隔离代理。
FailureThreshold int `mapstructure:"failure_threshold"`
// WindowSeconds: 断流统计窗口(秒)。
WindowSeconds int `mapstructure:"window_seconds"`
// TTLSeconds: 代理隔离持续时间(秒)。
TTLSeconds int `mapstructure:"ttl_seconds"`
}
// UserMessageQueueConfig 用户消息串行队列配置
// 用于 Anthropic OAuth/SetupToken 账号的用户消息串行化发送
type UserMessageQueueConfig struct {
@@ -916,6 +1067,9 @@ func (c *UserMessageQueueConfig) GetEffectiveMode() string {
return ""
}
// DefaultOpenAIWSClientFirstMessageTimeoutSeconds preserves the legacy ingress deadline.
const DefaultOpenAIWSClientFirstMessageTimeoutSeconds = 30
// GatewayOpenAIWSConfig OpenAI Responses WebSocket 配置。
// 注意:默认全局开启;如需回滚可使用 force_http 或关闭 enabled。
type GatewayOpenAIWSConfig struct {
@@ -923,6 +1077,15 @@ type GatewayOpenAIWSConfig struct {
ModeRouterV2Enabled bool `mapstructure:"mode_router_v2_enabled"`
// IngressModeDefault: ingress 默认模式(off/ctx_pool/passthrough/http_bridge)
IngressModeDefault string `mapstructure:"ingress_mode_default"`
// ClientFirstMessageTimeoutSeconds bounds the total time to read and decompress
// the first client response.create message after the WebSocket upgrade.
ClientFirstMessageTimeoutSeconds int `mapstructure:"client_first_message_timeout_seconds"`
// IngressInterTurnIdleTimeoutSeconds bounds the time a client may remain idle
// between completed ingress turns. Zero disables this protection.
IngressInterTurnIdleTimeoutSeconds int `mapstructure:"ingress_inter_turn_idle_timeout_seconds"`
// MaxIngressConnectionsPerAPIKey bounds live client WebSocket ingress sessions
// per API key across all instances. Zero disables this protection.
MaxIngressConnectionsPerAPIKey int `mapstructure:"max_ingress_connections_per_api_key"`
// Enabled: 全局总开关(默认 true)
Enabled bool `mapstructure:"enabled"`
// OAuthEnabled: 是否允许 OpenAI OAuth 账号使用 WS
@@ -1020,11 +1183,35 @@ type GatewayOpenAIWSSchedulerScoreWeights struct {
Reset float64 `mapstructure:"reset"`
// QuotaHeadroom 倾向 7d 剩余额度更健康的账号;默认 0(关闭,不改变原有行为)。
QuotaHeadroom float64 `mapstructure:"quota_headroom"`
// UpstreamCost 倾向上游声明倍率更低的账号;默认 0(关闭,不改变原有行为)。
UpstreamCost float64 `mapstructure:"upstream_cost"`
// PreviousResponse/SessionSticky 仅在开启 OpenAI 高级调度的粘性加权时生效。
PreviousResponse float64 `mapstructure:"previous_response"`
SessionSticky float64 `mapstructure:"session_sticky"`
}
func (w GatewayOpenAIWSSchedulerScoreWeights) BaseWeightSum() float64 {
return w.Priority + w.Load + w.Queue + w.ErrorRate + w.TTFT + w.Reset + w.QuotaHeadroom + w.UpstreamCost
}
func (w GatewayOpenAIWSSchedulerScoreWeights) TotalWeightSum() float64 {
return w.BaseWeightSum() + w.PreviousResponse + w.SessionSticky
}
func (w GatewayOpenAIWSSchedulerScoreWeights) IsValid() bool {
for _, weight := range []float64{
w.Priority, w.Load, w.Queue, w.ErrorRate, w.TTFT, w.Reset,
w.QuotaHeadroom, w.UpstreamCost, w.PreviousResponse, w.SessionSticky,
} {
if weight < 0 || math.IsNaN(weight) || math.IsInf(weight, 0) {
return false
}
}
baseSum := w.BaseWeightSum()
return baseSum > 0 && !math.IsNaN(baseSum) && !math.IsInf(baseSum, 0) &&
!math.IsNaN(w.TotalWeightSum()) && !math.IsInf(w.TotalWeightSum(), 0)
}
// GatewayOpenAISchedulerConfig OpenAI 高级调度器配置。
type GatewayOpenAISchedulerConfig struct {
// StickyEscapeEnabled: 是否允许 session_hash sticky 在账号健康度劣化时临时逃逸
@@ -1229,6 +1416,7 @@ func (d *DatabaseConfig) DSNWithTimezone(tz string) string {
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
// 连接池与超时配置(性能优化:可配置化连接池参数)
@@ -1334,12 +1522,22 @@ type RateLimitConfig struct {
// APIKeyAuthCacheConfig API Key 认证缓存配置
type APIKeyAuthCacheConfig struct {
L1Size int `mapstructure:"l1_size"`
L1TTLSeconds int `mapstructure:"l1_ttl_seconds"`
L2TTLSeconds int `mapstructure:"l2_ttl_seconds"`
NegativeTTLSeconds int `mapstructure:"negative_ttl_seconds"`
JitterPercent int `mapstructure:"jitter_percent"`
Singleflight bool `mapstructure:"singleflight"`
L1Size int `mapstructure:"l1_size"`
L1TTLSeconds int `mapstructure:"l1_ttl_seconds"`
L2TTLSeconds int `mapstructure:"l2_ttl_seconds"`
NegativeTTLSeconds int `mapstructure:"negative_ttl_seconds"`
JitterPercent int `mapstructure:"jitter_percent"`
Singleflight bool `mapstructure:"singleflight"`
LookupConcurrency int `mapstructure:"lookup_concurrency"`
InvalidAbuse InvalidAuthAbuseConfig `mapstructure:"invalid_abuse"`
}
type InvalidAuthAbuseConfig struct {
Enabled bool `mapstructure:"enabled"`
Threshold int `mapstructure:"threshold"`
WindowSeconds int `mapstructure:"window_seconds"`
BlockSeconds int `mapstructure:"block_seconds"`
Capacity int `mapstructure:"capacity"`
}
// SubscriptionCacheConfig 订阅认证 L1 缓存配置
@@ -1453,6 +1651,9 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
// 环境变量支持
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
if err := viper.BindEnv("server.enable_server_timing", "ENABLE_SERVER_TIMING"); err != nil {
return nil, fmt.Errorf("bind ENABLE_SERVER_TIMING: %w", err)
}
// 默认值
setDefaults()
@@ -1463,17 +1664,31 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
}
// 配置文件不存在时使用默认值
}
trustedProxiesEnv, trustedProxiesEnvConfigured := os.LookupEnv("SERVER_TRUSTED_PROXIES")
forwardedClientIPHeadersEnv, forwardedClientIPHeadersEnvConfigured := os.LookupEnv("SECURITY_FORWARDED_CLIENT_IP_HEADERS")
trustedProxiesConfigured := viper.InConfig("server.trusted_proxies") ||
viper.IsSet("server.trusted_proxies") || trustedProxiesEnvConfigured
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("unmarshal config error: %w", err)
}
if trustedProxiesEnvConfigured {
cfg.Server.TrustedProxies = normalizeStringSlice(strings.Split(trustedProxiesEnv, ","))
}
if forwardedClientIPHeadersEnvConfigured {
cfg.Security.ForwardedClientIPHeaders = normalizeStringSlice(strings.Split(forwardedClientIPHeadersEnv, ","))
}
cfg.Server.TrustedProxiesConfigured = trustedProxiesConfigured
if cfg.Gateway.OpenAIScheduler.StickyEscapeTTFTMs == 0 {
cfg.Gateway.OpenAIScheduler.StickyEscapeTTFTMs = 15000
}
if cfg.Gateway.OpenAIScheduler.StickyEscapeErrorRate == 0 {
cfg.Gateway.OpenAIScheduler.StickyEscapeErrorRate = 0.5
}
// Kept as a backstop: setEnvReachableDefaults now registers this key with its
// effective default (true), so IsSet always reports true and this branch no
// longer fires. It still guards the default if that registration is dropped.
if !cfg.Gateway.OpenAIScheduler.StickyEscapeEnabled && !viper.IsSet("gateway.openai_scheduler.sticky_escape_enabled") {
cfg.Gateway.OpenAIScheduler.StickyEscapeEnabled = true
}
@@ -1523,7 +1738,12 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
cfg.Security.ResponseHeaders.AdditionalAllowed = normalizeStringSlice(cfg.Security.ResponseHeaders.AdditionalAllowed)
cfg.Security.ResponseHeaders.ForceRemove = normalizeStringSlice(cfg.Security.ResponseHeaders.ForceRemove)
cfg.Security.CSP.Policy = strings.TrimSpace(cfg.Security.CSP.Policy)
cfg.SetTrustForwardedIPForAPIKeyACL(cfg.Security.TrustForwardedIPForAPIKeyACL)
forwardedClientIPHeaders, err := NormalizeForwardedClientIPHeaders(cfg.Security.ForwardedClientIPHeaders)
if err != nil {
return nil, fmt.Errorf("security.forwarded_client_ip_headers: %w", err)
}
cfg.Security.ForwardedClientIPHeaders = forwardedClientIPHeaders
cfg.SetForwardedClientIPSettings(cfg.Security.TrustForwardedIPForAPIKeyACL, forwardedClientIPHeaders)
cfg.Log.Level = strings.ToLower(strings.TrimSpace(cfg.Log.Level))
cfg.Log.Format = strings.ToLower(strings.TrimSpace(cfg.Log.Format))
cfg.Log.ServiceName = strings.TrimSpace(cfg.Log.ServiceName)
@@ -1608,10 +1828,11 @@ func setDefaults() {
viper.SetDefault("server.host", "0.0.0.0")
viper.SetDefault("server.port", 8080)
viper.SetDefault("server.mode", "release")
viper.SetDefault("server.enable_server_timing", false)
viper.SetDefault("server.frontend_url", "")
viper.SetDefault("server.read_header_timeout", 30) // 30秒读取请求头
viper.SetDefault("server.idle_timeout", 120) // 120秒空闲超时
viper.SetDefault("server.trusted_proxies", []string{})
viper.SetDefault("server.read_header_timeout", 10) // 10秒读取请求头
viper.SetDefault("server.max_header_bytes", 64*1024)
viper.SetDefault("server.idle_timeout", 120) // 120秒空闲超时
viper.SetDefault("server.max_request_body_size", int64(256*1024*1024))
// H2C 默认配置
viper.SetDefault("server.h2c.enabled", false)
@@ -1668,7 +1889,7 @@ func setDefaults() {
viper.SetDefault("security.csp.enabled", true)
viper.SetDefault("security.csp.policy", DefaultCSPPolicy)
viper.SetDefault("security.proxy_probe.insecure_skip_verify", false)
viper.SetDefault("security.trust_forwarded_ip_for_api_key_acl", false)
viper.SetDefault("security.trust_forwarded_ip_for_api_key_acl", true)
// Security - disable direct fallback on proxy error
viper.SetDefault("security.proxy_fallback.allow_direct_on_error", false)
@@ -1774,6 +1995,7 @@ func setDefaults() {
// Redis
viper.SetDefault("redis.host", "localhost")
viper.SetDefault("redis.port", 6379)
viper.SetDefault("redis.username", "")
viper.SetDefault("redis.password", "")
viper.SetDefault("redis.db", 0)
viper.SetDefault("redis.dial_timeout_seconds", 5)
@@ -1830,6 +2052,23 @@ func setDefaults() {
viper.SetDefault("batch_image.vertex_batch_prediction_base_url", "")
viper.SetDefault("batch_image.vertex_gcs_base_url", "")
// Image storage (async image task result offload to S3-compatible object storage)
viper.SetDefault("image_storage.enabled", false)
viper.SetDefault("image_storage.region", "auto")
viper.SetDefault("image_storage.prefix", "images/")
viper.SetDefault("image_storage.force_path_style", false)
viper.SetDefault("image_storage.presign_expiry_hours", 24)
viper.SetDefault("image_storage.max_download_bytes", 33554432)
// Registered with empty defaults so AutomaticEnv can reach them: viper only
// decodes keys present in AllKeys(), so a credential that is supplied purely
// via IMAGE_STORAGE_* and never appears in config.yaml would be dropped and
// silently disable the whole async image feature.
viper.SetDefault("image_storage.endpoint", "")
viper.SetDefault("image_storage.bucket", "")
viper.SetDefault("image_storage.access_key_id", "")
viper.SetDefault("image_storage.secret_access_key", "")
viper.SetDefault("image_storage.public_base_url", "")
// Ops (vNext)
viper.SetDefault("ops.enabled", true)
viper.SetDefault("ops.use_preaggregated_tables", true)
@@ -1886,6 +2125,12 @@ func setDefaults() {
viper.SetDefault("api_key_auth_cache.negative_ttl_seconds", 30)
viper.SetDefault("api_key_auth_cache.jitter_percent", 10)
viper.SetDefault("api_key_auth_cache.singleflight", true)
viper.SetDefault("api_key_auth_cache.lookup_concurrency", 64)
viper.SetDefault("api_key_auth_cache.invalid_abuse.enabled", true)
viper.SetDefault("api_key_auth_cache.invalid_abuse.threshold", 120)
viper.SetDefault("api_key_auth_cache.invalid_abuse.window_seconds", 60)
viper.SetDefault("api_key_auth_cache.invalid_abuse.block_seconds", 60)
viper.SetDefault("api_key_auth_cache.invalid_abuse.capacity", 16384)
// Subscription auth L1 cache
viper.SetDefault("subscription_cache.l1_size", 16384)
@@ -1931,6 +2176,8 @@ func setDefaults() {
// Gateway
viper.SetDefault("gateway.response_header_timeout", 600) // 600秒(10分钟)等待上游响应头,LLM高负载时可能排队较久
viper.SetDefault("gateway.openai_response_header_timeout", 0)
viper.SetDefault("gateway.openai_first_output_timeout_seconds", 0)
viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0)
viper.SetDefault("gateway.log_upstream_error_body", true)
viper.SetDefault("gateway.log_upstream_error_body_max_bytes", 2048)
viper.SetDefault("gateway.inject_beta_for_apikey", false)
@@ -1945,6 +2192,9 @@ func setDefaults() {
viper.SetDefault("gateway.openai_ws.enabled", true)
viper.SetDefault("gateway.openai_ws.mode_router_v2_enabled", false)
viper.SetDefault("gateway.openai_ws.ingress_mode_default", "ctx_pool")
viper.SetDefault("gateway.openai_ws.client_first_message_timeout_seconds", DefaultOpenAIWSClientFirstMessageTimeoutSeconds)
viper.SetDefault("gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds", 300)
viper.SetDefault("gateway.openai_ws.max_ingress_connections_per_api_key", 64)
viper.SetDefault("gateway.openai_ws.oauth_enabled", true)
viper.SetDefault("gateway.openai_ws.apikey_enabled", true)
viper.SetDefault("gateway.openai_ws.force_http", false)
@@ -1992,6 +2242,7 @@ func setDefaults() {
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.upstream_cost", 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
@@ -2000,6 +2251,9 @@ func setDefaults() {
viper.SetDefault("gateway.openai_http2.fallback_error_threshold", 2)
viper.SetDefault("gateway.openai_http2.fallback_window_seconds", 60)
viper.SetDefault("gateway.openai_http2.fallback_ttl_seconds", 600)
viper.SetDefault("gateway.openai_proxy_stream_circuit.failure_threshold", 2)
viper.SetDefault("gateway.openai_proxy_stream_circuit.window_seconds", 60)
viper.SetDefault("gateway.openai_proxy_stream_circuit.ttl_seconds", 600)
viper.SetDefault("gateway.image_concurrency.enabled", false)
viper.SetDefault("gateway.image_concurrency.max_concurrent_requests", 0)
viper.SetDefault("gateway.image_concurrency.overflow_mode", ImageConcurrencyOverflowModeReject)
@@ -2008,6 +2262,7 @@ func setDefaults() {
viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1)
viper.SetDefault("gateway.antigravity_extra_retries", 10)
viper.SetDefault("gateway.max_body_size", int64(256*1024*1024))
viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024))
viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes)
viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024))
viper.SetDefault("gateway.gemini_debug_response_headers", false)
@@ -2024,6 +2279,7 @@ func setDefaults() {
viper.SetDefault("gateway.stream_keepalive_interval", 10)
viper.SetDefault("gateway.image_stream_data_interval_timeout", 900)
viper.SetDefault("gateway.image_stream_keepalive_interval", 10)
viper.SetDefault("gateway.image_nonstream_keepalive_interval", 0)
viper.SetDefault("gateway.max_line_size", 500*1024*1024)
viper.SetDefault("gateway.scheduling.sticky_session_max_waiting", 3)
viper.SetDefault("gateway.scheduling.sticky_session_wait_timeout", 120*time.Second)
@@ -2082,6 +2338,12 @@ func setDefaults() {
viper.SetDefault("token_refresh.refresh_before_expiry_hours", 0.5) // 提前30分钟刷新(适配Google 1小时token)
viper.SetDefault("token_refresh.max_retries", 3) // 最多重试3次
viper.SetDefault("token_refresh.retry_backoff_seconds", 2) // 重试退避基础2秒
viper.SetDefault("token_refresh.candidate_page_size", 200)
viper.SetDefault("token_refresh.provider_concurrency", 4)
viper.SetDefault("token_refresh.provider_qps", 2)
viper.SetDefault("token_refresh.provider_failure_threshold", 3)
viper.SetDefault("token_refresh.attempt_timeout_seconds", 15)
viper.SetDefault("token_refresh.cycle_timeout_seconds", 240)
// Gemini OAuth - configure via environment variables or config file
// GEMINI_OAUTH_CLIENT_ID and GEMINI_OAUTH_CLIENT_SECRET
@@ -2095,9 +2357,140 @@ func setDefaults() {
viper.SetDefault("subscription_maintenance.worker_count", 2)
viper.SetDefault("subscription_maintenance.queue_size", 1024)
setEnvReachableDefaults()
}
// setEnvReachableDefaults registers zero-valued defaults for keys that are
// documented in deploy/config.example.yaml but had no default of their own.
//
// viper.Unmarshal only decodes the keys returned by AllKeys(), which unions
// SetDefault keys, config-file keys and explicitly bound BindEnv keys.
// AutomaticEnv can override a key already in that union, but it never adds one,
// and the viper_bind_struct escape hatch is compiled out (we build with
// -tags embed). So a key that lives only in the example file was unreachable by
// environment variable: the value was read from the process environment and
// then silently dropped. Deployments driven purely by env — which is what
// deploy/docker-compose.yml does — got the zero value with no warning.
//
// The values below are deliberately zero rather than the documented example
// values: an absent key already unmarshalled to the zero value, so registering
// zero keeps behavior identical while making the key addressable from the
// environment. Any subsystem that wants a richer default still applies it after
// unmarshal, exactly as before.
func setEnvReachableDefaults() {
viper.SetDefault("gateway.forced_codex_instructions_template_file", "")
viper.SetDefault("gateway.session_idle_timeout_minutes", 0)
viper.SetDefault("gateway.user_message_queue.mode", "")
viper.SetDefault("update.proxy_url", "")
// sticky_escape_enabled is the one exception to the zero-value rule: its
// effective default is true, applied post-unmarshal via a viper.IsSet guard.
// Registering false would make IsSet always report true and permanently
// disable sticky escape, so register the effective default instead. An
// explicit false in config or env still wins.
viper.SetDefault("gateway.openai_scheduler.sticky_escape_enabled", true)
viper.SetDefault("gateway.openai_scheduler.sticky_escape_error_rate", 0.0)
viper.SetDefault("gateway.openai_scheduler.sticky_escape_ttft_ms", 0)
// server.trusted_proxies and security.forwarded_client_ip_headers are the
// other exception: load() distinguishes explicit configuration from absence
// (issue #4600), and viper.IsSet also reports registered defaults, so a
// SetDefault would make trusted proxies look permanently configured. Both
// environment variables are parsed by hand in load() via os.LookupEnv and
// were never silently dropped; binding them here records that reachability
// where AllKeys() — and the env-reachability guard — can see it, without
// affecting IsSet while the variables are absent. BindEnv only errors when
// called without arguments.
_ = viper.BindEnv("server.trusted_proxies", "SERVER_TRUSTED_PROXIES")
_ = viper.BindEnv("security.forwarded_client_ip_headers", "SECURITY_FORWARDED_CLIENT_IP_HEADERS")
// Third-party login providers. These carry client secrets and are exactly
// the settings an operator expects to inject via the environment, but every
// key here was previously unreachable that way.
for _, provider := range []string{"github_oauth", "google_oauth"} {
viper.SetDefault(provider+".enabled", false)
viper.SetDefault(provider+".client_id", "")
viper.SetDefault(provider+".client_secret", "")
viper.SetDefault(provider+".authorize_url", "")
viper.SetDefault(provider+".token_url", "")
viper.SetDefault(provider+".userinfo_url", "")
viper.SetDefault(provider+".emails_url", "")
viper.SetDefault(provider+".scopes", "")
viper.SetDefault(provider+".redirect_url", "")
viper.SetDefault(provider+".frontend_redirect_url", "")
}
viper.SetDefault("dingtalk_connect.client_id", "")
viper.SetDefault("dingtalk_connect.client_secret", "")
viper.SetDefault("dingtalk_connect.internal_corp_id", "")
viper.SetDefault("dingtalk_connect.redirect_url", "")
viper.SetDefault("dingtalk_connect.bypass_registration", false)
viper.SetDefault("dingtalk_connect.username_attribute_key", "")
viper.SetDefault("dingtalk_connect.enable_attribute_matching", false)
viper.SetDefault("dingtalk_connect.enable_attribute_sync", false)
viper.SetDefault("dingtalk_connect.attribute_sync_fields", []string{})
viper.SetDefault("dingtalk_connect.attribute_sync_overwrite_policy", "")
viper.SetDefault("dingtalk_connect.sync_display_name", false)
viper.SetDefault("dingtalk_connect.sync_display_name_attr_key", "")
viper.SetDefault("dingtalk_connect.sync_display_name_attr_name", "")
viper.SetDefault("dingtalk_connect.sync_dept", false)
viper.SetDefault("dingtalk_connect.sync_dept_attr_key", "")
viper.SetDefault("dingtalk_connect.sync_dept_attr_name", "")
viper.SetDefault("dingtalk_connect.sync_corp_email", false)
viper.SetDefault("dingtalk_connect.sync_corp_email_attr_key", "")
viper.SetDefault("dingtalk_connect.sync_corp_email_attr_name", "")
}
func (c *Config) Validate() error {
forwardedClientIPHeaders, err := NormalizeForwardedClientIPHeaders(c.Security.ForwardedClientIPHeaders)
if err != nil {
return fmt.Errorf("security.forwarded_client_ip_headers: %w", err)
}
c.Security.ForwardedClientIPHeaders = forwardedClientIPHeaders
c.SetForwardedClientIPSettings(c.Security.TrustForwardedIPForAPIKeyACL, forwardedClientIPHeaders)
if c.Server.ReadHeaderTimeout < 1 || c.Server.ReadHeaderTimeout > 60 {
return fmt.Errorf("server.read_header_timeout must be between 1 and 60 seconds")
}
if c.Server.MaxHeaderBytes < 8*1024 || c.Server.MaxHeaderBytes > 1024*1024 {
return fmt.Errorf("server.max_header_bytes must be between 8192 and 1048576 bytes")
}
if c.Server.IdleTimeout <= 0 {
return fmt.Errorf("server.idle_timeout must be positive")
}
if c.Server.MaxRequestBodySize < 0 {
return fmt.Errorf("server.max_request_body_size must be non-negative")
}
if c.Server.H2C.Enabled {
if c.Server.H2C.MaxConcurrentStreams == 0 {
return fmt.Errorf("server.h2c.max_concurrent_streams must be positive")
}
if c.Server.H2C.IdleTimeout <= 0 {
return fmt.Errorf("server.h2c.idle_timeout must be positive")
}
if c.Server.H2C.MaxReadFrameSize < 16*1024 || c.Server.H2C.MaxReadFrameSize > 16*1024*1024-1 {
return fmt.Errorf("server.h2c.max_read_frame_size must be between 16384 and 16777215 bytes")
}
if c.Server.H2C.MaxUploadBufferPerConnection < 65535 {
return fmt.Errorf("server.h2c.max_upload_buffer_per_connection must be at least 65535 bytes")
}
if c.Server.H2C.MaxUploadBufferPerStream <= 0 {
return fmt.Errorf("server.h2c.max_upload_buffer_per_stream must be positive")
}
}
if c.APIKeyAuth.InvalidAbuse.Enabled {
if c.APIKeyAuth.InvalidAbuse.Threshold < 10 {
return fmt.Errorf("api_key_auth_cache.invalid_abuse.threshold must be at least 10")
}
if c.APIKeyAuth.InvalidAbuse.WindowSeconds < 1 || c.APIKeyAuth.InvalidAbuse.WindowSeconds > 3600 {
return fmt.Errorf("api_key_auth_cache.invalid_abuse.window_seconds must be between 1 and 3600")
}
if c.APIKeyAuth.InvalidAbuse.BlockSeconds < 1 || c.APIKeyAuth.InvalidAbuse.BlockSeconds > 3600 {
return fmt.Errorf("api_key_auth_cache.invalid_abuse.block_seconds must be between 1 and 3600")
}
if c.APIKeyAuth.InvalidAbuse.Capacity < 256 || c.APIKeyAuth.InvalidAbuse.Capacity > 1_000_000 {
return fmt.Errorf("api_key_auth_cache.invalid_abuse.capacity must be between 256 and 1000000")
}
}
jwtSecret := strings.TrimSpace(c.JWT.Secret)
if jwtSecret == "" {
return fmt.Errorf("jwt.secret is required")
@@ -2623,6 +3016,9 @@ func (c *Config) Validate() error {
if c.Gateway.MaxBodySize <= 0 {
return fmt.Errorf("gateway.max_body_size must be positive")
}
if c.Gateway.TextMaxBodySize <= 0 || c.Gateway.TextMaxBodySize > c.Gateway.MaxBodySize {
return fmt.Errorf("gateway.text_max_body_size must be positive and no greater than gateway.max_body_size")
}
if c.Gateway.UpstreamResponseReadMaxBytes <= 0 {
return fmt.Errorf("gateway.upstream_response_read_max_bytes must be positive")
}
@@ -2635,6 +3031,14 @@ func (c *Config) Validate() error {
if c.Gateway.OpenAIResponseHeaderTimeout < 0 {
return fmt.Errorf("gateway.openai_response_header_timeout must be non-negative")
}
if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 ||
(c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) {
return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds")
}
if c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds > 1800 ||
(c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds < 30) {
return fmt.Errorf("gateway.openai_high_effort_first_output_timeout_seconds must be 0 or between 30-1800 seconds")
}
if strings.TrimSpace(c.Gateway.ConnectionPoolIsolation) != "" {
switch c.Gateway.ConnectionPoolIsolation {
case ConnectionPoolIsolationProxy, ConnectionPoolIsolationAccount, ConnectionPoolIsolationAccountProxy:
@@ -2710,6 +3114,13 @@ func (c *Config) Validate() error {
(c.Gateway.ImageStreamKeepaliveInterval < 5 || c.Gateway.ImageStreamKeepaliveInterval > 60) {
return fmt.Errorf("gateway.image_stream_keepalive_interval must be 0 or between 5-60 seconds")
}
if c.Gateway.ImageNonstreamKeepaliveInterval < 0 {
return fmt.Errorf("gateway.image_nonstream_keepalive_interval must be non-negative")
}
if c.Gateway.ImageNonstreamKeepaliveInterval != 0 &&
(c.Gateway.ImageNonstreamKeepaliveInterval < 5 || c.Gateway.ImageNonstreamKeepaliveInterval > 60) {
return fmt.Errorf("gateway.image_nonstream_keepalive_interval must be 0 or between 5-60 seconds")
}
// 兼容旧键 sticky_previous_response_ttl_seconds
if c.Gateway.OpenAIWS.StickyResponseIDTTLSeconds <= 0 && c.Gateway.OpenAIWS.StickyPreviousResponseTTLSeconds > 0 {
c.Gateway.OpenAIWS.StickyResponseIDTTLSeconds = c.Gateway.OpenAIWS.StickyPreviousResponseTTLSeconds
@@ -2717,6 +3128,15 @@ func (c *Config) Validate() error {
if c.Gateway.OpenAIWS.MaxConnsPerAccount <= 0 {
return fmt.Errorf("gateway.openai_ws.max_conns_per_account must be positive")
}
if c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds <= 0 {
return fmt.Errorf("gateway.openai_ws.client_first_message_timeout_seconds must be positive")
}
if c.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds < 0 {
return fmt.Errorf("gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds must be non-negative")
}
if c.Gateway.OpenAIWS.MaxIngressConnectionsPerAPIKey < 0 {
return fmt.Errorf("gateway.openai_ws.max_ingress_connections_per_api_key must be non-negative")
}
if c.Gateway.OpenAIWS.MinIdlePerAccount < 0 {
return fmt.Errorf("gateway.openai_ws.min_idle_per_account must be non-negative")
}
@@ -2827,25 +3247,35 @@ func (c *Config) Validate() error {
if c.Gateway.OpenAIHTTP2.FallbackTTLSeconds < 0 {
return fmt.Errorf("gateway.openai_http2.fallback_ttl_seconds must be non-negative")
}
if c.Gateway.OpenAIWS.SchedulerScoreWeights.Priority < 0 ||
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.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")
if c.Gateway.OpenAIProxyStreamCircuit.FailureThreshold < 0 {
return fmt.Errorf("gateway.openai_proxy_stream_circuit.failure_threshold 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.QuotaHeadroom
if c.Gateway.OpenAIProxyStreamCircuit.WindowSeconds < 0 {
return fmt.Errorf("gateway.openai_proxy_stream_circuit.window_seconds must be non-negative")
}
if c.Gateway.OpenAIProxyStreamCircuit.TTLSeconds < 0 {
return fmt.Errorf("gateway.openai_proxy_stream_circuit.ttl_seconds must be non-negative")
}
weights := c.Gateway.OpenAIWS.SchedulerScoreWeights
for _, weight := range []float64{
weights.Priority, weights.Load, weights.Queue, weights.ErrorRate, weights.TTFT,
weights.Reset, weights.QuotaHeadroom, weights.UpstreamCost,
weights.PreviousResponse, weights.SessionSticky,
} {
if weight < 0 || math.IsNaN(weight) || math.IsInf(weight, 0) {
return fmt.Errorf("gateway.openai_ws.scheduler_score_weights.* must be non-negative and finite")
}
}
weightSum := weights.BaseWeightSum()
if weightSum <= 0 {
return fmt.Errorf("gateway.openai_ws.scheduler_score_weights must not all be zero")
}
if math.IsNaN(weightSum) || math.IsInf(weightSum, 0) {
return fmt.Errorf("gateway.openai_ws.scheduler_score_weights base-weight sum must be finite")
}
if totalWeightSum := weights.TotalWeightSum(); math.IsNaN(totalWeightSum) || math.IsInf(totalWeightSum, 0) {
return fmt.Errorf("gateway.openai_ws.scheduler_score_weights total-weight sum must be finite")
}
if c.Gateway.OpenAIScheduler.StickyEscapeTTFTMs <= 0 {
return fmt.Errorf("gateway.openai_scheduler.sticky_escape_ttft_ms must be positive")
}
+482
View File
@@ -1,9 +1,12 @@
package config
import (
"fmt"
"math"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -17,6 +20,239 @@ func resetViperWithJWTSecret(t *testing.T) {
t.Setenv("JWT_SECRET", strings.Repeat("x", 32))
}
func TestLoadServerTimingConfig(t *testing.T) {
t.Run("disabled by default", func(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.False(t, cfg.Server.EnableServerTiming)
})
t.Run("enabled by exact environment variable", func(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("ENABLE_SERVER_TIMING", "true")
cfg, err := Load()
require.NoError(t, err)
require.True(t, cfg.Server.EnableServerTiming)
})
}
func TestLoadRedisUsernameFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("REDIS_USERNAME", "app-user")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, "app-user", cfg.Redis.Username)
}
func TestLoadHTTPIngressSafetyDefaults(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 10, cfg.Server.ReadHeaderTimeout)
require.Equal(t, 64*1024, cfg.Server.MaxHeaderBytes)
require.Empty(t, cfg.Server.TrustedProxies)
require.False(t, cfg.Server.TrustedProxiesConfigured)
require.True(t, cfg.TrustForwardedIPForAPIKeyACL())
require.Equal(t, int64(32*1024*1024), cfg.Gateway.TextMaxBodySize)
require.True(t, cfg.APIKeyAuth.InvalidAbuse.Enabled)
require.Equal(t, 120, cfg.APIKeyAuth.InvalidAbuse.Threshold)
require.Equal(t, 16384, cfg.APIKeyAuth.InvalidAbuse.Capacity)
}
func TestNormalizeForwardedClientIPHeaders(t *testing.T) {
headers, err := NormalizeForwardedClientIPHeaders([]string{
" x-cdn-client-ip ",
"X-CDN-CLIENT-IP",
"true-client-ip",
})
require.NoError(t, err)
require.Equal(t, []string{"X-Cdn-Client-Ip", "True-Client-Ip"}, headers)
_, err = NormalizeForwardedClientIPHeaders([]string{"X Invalid"})
require.ErrorContains(t, err, "invalid HTTP header field name")
}
func TestNormalizeForwardedClientIPHeadersLimit(t *testing.T) {
headers := make([]string, 0, MaxForwardedClientIPHeaders+1)
for i := 0; i <= MaxForwardedClientIPHeaders; i++ {
headers = append(headers, fmt.Sprintf("X-CDN-IP-%d", i))
}
_, err := NormalizeForwardedClientIPHeaders(headers)
require.ErrorContains(t, err, "at most 16 unique names")
}
func TestLoadForwardedClientIPHeadersNormalizesAndSnapshots(t *testing.T) {
resetViperWithJWTSecret(t)
viper.Set("security.forwarded_client_ip_headers", []string{" x-cdn-ip ", "X-CDN-IP", "true-client-ip"})
cfg, err := Load()
require.NoError(t, err)
snapshot := cfg.ForwardedClientIPSettings()
require.Equal(t, []string{"X-Cdn-Ip", "True-Client-Ip"}, snapshot.Headers)
snapshot.Headers[0] = "X-Mutated"
require.Equal(t, []string{"X-Cdn-Ip", "True-Client-Ip"}, cfg.ForwardedClientIPSettings().Headers)
}
func TestForwardedClientIPSettingsConcurrentPublication(t *testing.T) {
cfg := &Config{}
cfg.SetForwardedClientIPSettings(true, []string{"X-Public-A"})
const iterations = 2000
start := make(chan struct{})
errCh := make(chan error, 8)
var wg sync.WaitGroup
for _, settings := range []ForwardedClientIPSettings{
{TrustForwardedIP: true, Headers: []string{"X-Public-A"}},
{TrustForwardedIP: false, Headers: []string{"X-Public-B"}},
} {
settings := settings
wg.Add(1)
go func() {
defer wg.Done()
<-start
for i := 0; i < iterations; i++ {
cfg.SetForwardedClientIPSettings(settings.TrustForwardedIP, settings.Headers)
}
}()
}
for i := 0; i < cap(errCh); i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
for j := 0; j < iterations; j++ {
snapshot := cfg.ForwardedClientIPSettings()
validA := snapshot.TrustForwardedIP && len(snapshot.Headers) == 1 && snapshot.Headers[0] == "X-Public-A"
validB := !snapshot.TrustForwardedIP && len(snapshot.Headers) == 1 && snapshot.Headers[0] == "X-Public-B"
if !validA && !validB {
errCh <- fmt.Errorf("observed inconsistent forwarded IP settings: %+v", snapshot)
return
}
}
}()
}
close(start)
wg.Wait()
close(errCh)
for err := range errCh {
require.NoError(t, err)
}
}
func TestLoadForwardedClientIPHeadersFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("SECURITY_FORWARDED_CLIENT_IP_HEADERS", " x-cdn-ip , X-CDN-IP, true-client-ip ")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, []string{"X-Cdn-Ip", "True-Client-Ip"}, cfg.ForwardedClientIPSettings().Headers)
}
func TestLoadExplicitEmptyForwardedClientIPHeadersFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
viper.Set("security.forwarded_client_ip_headers", []string{"X-Yaml-IP"})
t.Setenv("SECURITY_FORWARDED_CLIENT_IP_HEADERS", "")
cfg, err := Load()
require.NoError(t, err)
require.Empty(t, cfg.ForwardedClientIPSettings().Headers)
}
func TestLoadRejectsInvalidForwardedClientIPHeaderFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("SECURITY_FORWARDED_CLIENT_IP_HEADERS", "X-Valid-IP, X Invalid")
_, err := Load()
require.ErrorContains(t, err, "security.forwarded_client_ip_headers")
}
func TestLoadRejectsInvalidForwardedClientIPHeader(t *testing.T) {
resetViperWithJWTSecret(t)
viper.Set("security.forwarded_client_ip_headers", []string{"X Invalid"})
_, err := Load()
require.ErrorContains(t, err, "security.forwarded_client_ip_headers")
}
func TestLoadExplicitEmptyTrustedProxiesEnablesConfiguredMode(t *testing.T) {
resetViperWithJWTSecret(t)
viper.Set("server.trusted_proxies", []string{})
cfg, err := Load()
require.NoError(t, err)
require.Empty(t, cfg.Server.TrustedProxies)
require.True(t, cfg.Server.TrustedProxiesConfigured)
}
func TestLoadExplicitTrustedProxiesEnablesConfiguredMode(t *testing.T) {
resetViperWithJWTSecret(t)
viper.Set("server.trusted_proxies", []string{"127.0.0.1/32"})
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, []string{"127.0.0.1/32"}, cfg.Server.TrustedProxies)
require.True(t, cfg.Server.TrustedProxiesConfigured)
}
func TestLoadTrustedProxiesFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("SERVER_TRUSTED_PROXIES", "127.0.0.1/32, ::1/128")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, []string{"127.0.0.1/32", "::1/128"}, cfg.Server.TrustedProxies)
require.True(t, cfg.Server.TrustedProxiesConfigured)
}
func TestLoadExplicitEmptyTrustedProxiesFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("SERVER_TRUSTED_PROXIES", "")
cfg, err := Load()
require.NoError(t, err)
require.Empty(t, cfg.Server.TrustedProxies)
require.True(t, cfg.Server.TrustedProxiesConfigured)
}
func TestLoadTrustedProxiesPresenceFromYAML(t *testing.T) {
tests := []struct {
name string
yaml string
want []string
configured bool
}{
{name: "absent", yaml: "server:\n mode: debug\n", configured: false},
{name: "explicit empty", yaml: "server:\n trusted_proxies: []\n", want: []string{}, configured: true},
{
name: "populated",
yaml: "server:\n trusted_proxies:\n - 127.0.0.1/32\n - ::1/128\n",
want: []string{"127.0.0.1/32", "::1/128"},
configured: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
resetViperWithJWTSecret(t)
configDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(configDir, "config.yaml"), []byte(test.yaml), 0o600))
t.Setenv("DATA_DIR", configDir)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, test.want, cfg.Server.TrustedProxies)
require.Equal(t, test.configured, cfg.Server.TrustedProxiesConfigured)
})
}
}
func TestLoadForBootstrapAllowsMissingJWTSecret(t *testing.T) {
viper.Reset()
t.Setenv("JWT_SECRET", "")
@@ -81,6 +317,34 @@ func TestLoadDefaultSchedulingConfig(t *testing.T) {
}
}
func TestLoadDefaultOpenAIFirstOutputTimeoutsDisabled(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Zero(t, cfg.Gateway.OpenAIFirstOutputTimeoutSeconds)
require.Zero(t, cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds)
}
func TestLoadOpenAIFirstOutputTimeoutsFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_FIRST_OUTPUT_TIMEOUT_SECONDS", "90")
t.Setenv("GATEWAY_OPENAI_HIGH_EFFORT_FIRST_OUTPUT_TIMEOUT_SECONDS", "240")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 90, cfg.Gateway.OpenAIFirstOutputTimeoutSeconds)
require.Equal(t, 240, cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds)
}
func TestValidateOpenAIFirstOutputTimeoutMinimum(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
cfg.Gateway.OpenAIFirstOutputTimeoutSeconds = 30
require.NoError(t, cfg.Validate())
}
func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
resetViperWithJWTSecret(t)
@@ -170,6 +434,9 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
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.SchedulerScoreWeights.UpstreamCost != 0 {
t.Fatalf("Gateway.OpenAIWS.SchedulerScoreWeights.UpstreamCost = %v, want 0", cfg.Gateway.OpenAIWS.SchedulerScoreWeights.UpstreamCost)
}
if !cfg.Gateway.OpenAIWS.StoreDisabledForceNewConn {
t.Fatalf("Gateway.OpenAIWS.StoreDisabledForceNewConn = false, want true")
}
@@ -182,6 +449,28 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
if cfg.Gateway.OpenAIWS.IngressModeDefault != "ctx_pool" {
t.Fatalf("Gateway.OpenAIWS.IngressModeDefault = %q, want %q", cfg.Gateway.OpenAIWS.IngressModeDefault, "ctx_pool")
}
if cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds != DefaultOpenAIWSClientFirstMessageTimeoutSeconds {
t.Fatalf(
"Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = %d, want %d",
cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds,
DefaultOpenAIWSClientFirstMessageTimeoutSeconds,
)
}
if cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds != 300 {
t.Fatalf("Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = %d, want 300", cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds)
}
if cfg.Gateway.OpenAIWS.MaxIngressConnectionsPerAPIKey != 64 {
t.Fatalf("Gateway.OpenAIWS.MaxIngressConnectionsPerAPIKey = %d, want 64", cfg.Gateway.OpenAIWS.MaxIngressConnectionsPerAPIKey)
}
}
func TestLoadOpenAIWSClientFirstMessageTimeoutFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_WS_CLIENT_FIRST_MESSAGE_TIMEOUT_SECONDS", "120")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 120, cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds)
}
func TestLoadDefaultOpenAICompactModel(t *testing.T) {
@@ -208,6 +497,22 @@ func TestLoadDefaultOpenAIHTTP2Enabled(t *testing.T) {
require.NoError(t, err)
require.True(t, cfg.Gateway.OpenAIHTTP2.Enabled)
require.True(t, cfg.Gateway.OpenAIHTTP2.AllowProxyFallbackToHTTP1)
require.Equal(t, 2, cfg.Gateway.OpenAIProxyStreamCircuit.FailureThreshold)
require.Equal(t, 60, cfg.Gateway.OpenAIProxyStreamCircuit.WindowSeconds)
require.Equal(t, 600, cfg.Gateway.OpenAIProxyStreamCircuit.TTLSeconds)
}
func TestLoadOpenAIProxyStreamCircuitFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_FAILURE_THRESHOLD", "3")
t.Setenv("GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_WINDOW_SECONDS", "90")
t.Setenv("GATEWAY_OPENAI_PROXY_STREAM_CIRCUIT_TTL_SECONDS", "420")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 3, cfg.Gateway.OpenAIProxyStreamCircuit.FailureThreshold)
require.Equal(t, 90, cfg.Gateway.OpenAIProxyStreamCircuit.WindowSeconds)
require.Equal(t, 420, cfg.Gateway.OpenAIProxyStreamCircuit.TTLSeconds)
}
func TestLoadOpenAIHTTP2DisabledFromEnv(t *testing.T) {
@@ -236,6 +541,15 @@ func TestLoadOpenAIResponseHeaderTimeoutFromEnv(t *testing.T) {
require.Equal(t, 1800, cfg.Gateway.OpenAIResponseHeaderTimeout)
}
func TestLoadImageNonstreamKeepaliveFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_IMAGE_NONSTREAM_KEEPALIVE_INTERVAL", "15")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 15, cfg.Gateway.ImageNonstreamKeepaliveInterval)
}
func TestLoadOpenAIWSStickyTTLCompatibility(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_WS_STICKY_RESPONSE_ID_TTL_SECONDS", "0")
@@ -1105,6 +1419,51 @@ func TestValidateConfigErrors(t *testing.T) {
mutate func(*Config)
wantErr string
}{
{
name: "server read header timeout",
mutate: func(c *Config) { c.Server.ReadHeaderTimeout = 0 },
wantErr: "server.read_header_timeout",
},
{
name: "server max header bytes too small",
mutate: func(c *Config) { c.Server.MaxHeaderBytes = 4096 },
wantErr: "server.max_header_bytes",
},
{
name: "server max request body size",
mutate: func(c *Config) { c.Server.MaxRequestBodySize = -1 },
wantErr: "server.max_request_body_size",
},
{
name: "h2c zero concurrent streams",
mutate: func(c *Config) {
c.Server.H2C.Enabled = true
c.Server.H2C.MaxConcurrentStreams = 0
},
wantErr: "server.h2c.max_concurrent_streams",
},
{
name: "h2c oversized read frame",
mutate: func(c *Config) {
c.Server.H2C.Enabled = true
c.Server.H2C.MaxReadFrameSize = 16 * 1024 * 1024
},
wantErr: "server.h2c.max_read_frame_size",
},
{
name: "invalid auth abuse threshold too small",
mutate: func(c *Config) {
c.APIKeyAuth.InvalidAbuse.Threshold = 9
},
wantErr: "api_key_auth_cache.invalid_abuse.threshold",
},
{
name: "invalid auth abuse capacity too small",
mutate: func(c *Config) {
c.APIKeyAuth.InvalidAbuse.Capacity = 255
},
wantErr: "api_key_auth_cache.invalid_abuse.capacity",
},
{
name: "jwt secret required",
mutate: func(c *Config) { c.JWT.Secret = "" },
@@ -1306,6 +1665,11 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.MaxBodySize = 0 },
wantErr: "gateway.max_body_size",
},
{
name: "gateway text body exceeds media body",
mutate: func(c *Config) { c.Gateway.TextMaxBodySize = c.Gateway.MaxBodySize + 1 },
wantErr: "gateway.text_max_body_size",
},
{
name: "gateway response header timeout",
mutate: func(c *Config) { c.Gateway.ResponseHeaderTimeout = -1 },
@@ -1316,6 +1680,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 },
wantErr: "gateway.openai_response_header_timeout",
},
{
name: "gateway openai first output timeout below minimum",
mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 },
wantErr: "gateway.openai_first_output_timeout_seconds",
},
{
name: "gateway openai high effort first output timeout too large",
mutate: func(c *Config) { c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds = 1801 },
wantErr: "gateway.openai_high_effort_first_output_timeout_seconds",
},
{
name: "gateway max idle conns",
mutate: func(c *Config) { c.Gateway.MaxIdleConns = 0 },
@@ -1386,6 +1760,21 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIHTTP2.FallbackTTLSeconds = -1 },
wantErr: "gateway.openai_http2.fallback_ttl_seconds",
},
{
name: "gateway openai proxy stream circuit threshold",
mutate: func(c *Config) { c.Gateway.OpenAIProxyStreamCircuit.FailureThreshold = -1 },
wantErr: "gateway.openai_proxy_stream_circuit.failure_threshold",
},
{
name: "gateway openai proxy stream circuit window",
mutate: func(c *Config) { c.Gateway.OpenAIProxyStreamCircuit.WindowSeconds = -1 },
wantErr: "gateway.openai_proxy_stream_circuit.window_seconds",
},
{
name: "gateway openai proxy stream circuit ttl",
mutate: func(c *Config) { c.Gateway.OpenAIProxyStreamCircuit.TTLSeconds = -1 },
wantErr: "gateway.openai_proxy_stream_circuit.ttl_seconds",
},
{
name: "gateway stream data interval range",
mutate: func(c *Config) { c.Gateway.StreamDataIntervalTimeout = 5 },
@@ -1406,6 +1795,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.ImageStreamKeepaliveInterval = -1 },
wantErr: "gateway.image_stream_keepalive_interval must be non-negative",
},
{
name: "gateway image nonstream keepalive range",
mutate: func(c *Config) { c.Gateway.ImageNonstreamKeepaliveInterval = 4 },
wantErr: "gateway.image_nonstream_keepalive_interval",
},
{
name: "gateway image nonstream keepalive negative",
mutate: func(c *Config) { c.Gateway.ImageNonstreamKeepaliveInterval = -1 },
wantErr: "gateway.image_nonstream_keepalive_interval must be non-negative",
},
{
name: "gateway image stream data interval range",
mutate: func(c *Config) { c.Gateway.ImageStreamDataIntervalTimeout = 30 },
@@ -1640,6 +2039,26 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIWS.MaxConnsPerAccount = 0 },
wantErr: "gateway.openai_ws.max_conns_per_account",
},
{
name: "client_first_message_timeout_seconds 必须为正数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 0 },
wantErr: "gateway.openai_ws.client_first_message_timeout_seconds",
},
{
name: "client_first_message_timeout_seconds 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = -1 },
wantErr: "gateway.openai_ws.client_first_message_timeout_seconds",
},
{
name: "ingress_inter_turn_idle_timeout_seconds 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = -1 },
wantErr: "gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds",
},
{
name: "max_ingress_connections_per_api_key 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.MaxIngressConnectionsPerAPIKey = -1 },
wantErr: "gateway.openai_ws.max_ingress_connections_per_api_key",
},
{
name: "min_idle_per_account 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.MinIdlePerAccount = -1 },
@@ -1750,6 +2169,42 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
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 upstream_cost 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.SchedulerScoreWeights.UpstreamCost = -0.1 },
wantErr: "gateway.openai_ws.scheduler_score_weights.* must be non-negative",
},
{
name: "scheduler_score_weights reset 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.SchedulerScoreWeights.Reset = -0.1 },
wantErr: "gateway.openai_ws.scheduler_score_weights.* must be non-negative",
},
{
name: "scheduler_score_weights 不能为 NaN",
mutate: func(c *Config) { c.Gateway.OpenAIWS.SchedulerScoreWeights.PreviousResponse = math.NaN() },
wantErr: "gateway.openai_ws.scheduler_score_weights.* must be non-negative and finite",
},
{
name: "scheduler_score_weights 不能为 Inf",
mutate: func(c *Config) { c.Gateway.OpenAIWS.SchedulerScoreWeights.UpstreamCost = math.Inf(1) },
wantErr: "gateway.openai_ws.scheduler_score_weights.* must be non-negative and finite",
},
{
name: "scheduler_score_weights 总和不能溢出",
mutate: func(c *Config) {
c.Gateway.OpenAIWS.SchedulerScoreWeights.Priority = math.MaxFloat64
c.Gateway.OpenAIWS.SchedulerScoreWeights.Load = math.MaxFloat64
},
wantErr: "gateway.openai_ws.scheduler_score_weights base-weight sum must be finite",
},
{
name: "scheduler_score_weights 含 sticky 总和不能溢出",
mutate: func(c *Config) {
c.Gateway.OpenAIWS.SchedulerScoreWeights.Priority = math.MaxFloat64
c.Gateway.OpenAIWS.SchedulerScoreWeights.PreviousResponse = math.MaxFloat64
},
wantErr: "gateway.openai_ws.scheduler_score_weights total-weight sum must be finite",
},
{
name: "scheduler_score_weights 不能全为 0",
mutate: func(c *Config) {
@@ -1801,6 +2256,30 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
require.NoError(t, cfg.Validate())
})
t.Run("upstream_cost 可作为唯一有效调度权重", 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.UpstreamCost = 0.1
require.NoError(t, cfg.Validate())
})
t.Run("reset 可作为唯一有效调度权重", 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.Reset = 0.1
require.NoError(t, cfg.Validate())
})
}
func TestValidateConfig_AutoScaleDisabledIgnoreAutoScaleFields(t *testing.T) {
@@ -1964,6 +2443,9 @@ func TestLoad_DefaultGatewayImageStreamConfig(t *testing.T) {
if cfg.Gateway.ImageStreamKeepaliveInterval != 10 {
t.Fatalf("image_stream_keepalive_interval = %d, want 10", cfg.Gateway.ImageStreamKeepaliveInterval)
}
if cfg.Gateway.ImageNonstreamKeepaliveInterval != 0 {
t.Fatalf("image_nonstream_keepalive_interval = %d, want 0", cfg.Gateway.ImageNonstreamKeepaliveInterval)
}
if cfg.Gateway.ImageConcurrency.Enabled {
t.Fatalf("image_concurrency.enabled = true, want false")
}
@@ -0,0 +1,90 @@
//go:build unit
package config
import (
"reflect"
"sort"
"strings"
"testing"
"github.com/spf13/viper"
)
// collectMapstructureKeys walks a config struct and returns every dotted key
// viper would need in order to populate it.
func collectMapstructureKeys(t reflect.Type, prefix string, out map[string]string) {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" {
continue // unexported
}
tag := field.Tag.Get("mapstructure")
name, _, _ := strings.Cut(tag, ",")
if name == "-" {
continue
}
if name == "" {
name = strings.ToLower(field.Name)
}
key := name
if prefix != "" {
key = prefix + "." + name
}
ft := field.Type
for ft.Kind() == reflect.Ptr {
ft = ft.Elem()
}
if ft.Kind() == reflect.Struct {
collectMapstructureKeys(ft, key, out)
continue
}
if ft.Kind() == reflect.Map {
// A map cannot be expressed in a single environment variable, so it
// is out of scope here — such settings need a config file either way.
continue
}
out[strings.ToLower(key)] = ft.String()
}
}
// TestConfigKeysAreEnvReachable is the systemic guard behind the image_storage
// bug: viper.Unmarshal only decodes keys returned by AllKeys(), which unions
// SetDefault keys, config-file keys and explicit BindEnv keys. AutomaticEnv can
// override a key already in that union but never introduces one, and the
// viper_bind_struct escape hatch is compiled out (we build with -tags embed).
//
// So a Config field with no registered default is unreachable by environment
// variable whenever the deployment has no config.yaml containing it — the
// operator sets the variable, the loader discards it, and the feature behaves
// as if it were never configured. That is exactly how image_storage credentials
// were lost, silently disabling async image tasks for env-driven deployments.
//
// When this fails, register a zero-valued default in setEnvReachableDefaults
// for each reported key.
func TestConfigKeysAreEnvReachable(t *testing.T) {
bound := map[string]string{}
collectMapstructureKeys(reflect.TypeOf(Config{}), "", bound)
viper.Reset()
t.Cleanup(viper.Reset)
setDefaults()
registered := map[string]struct{}{}
for _, key := range viper.AllKeys() {
registered[key] = struct{}{}
}
var unreachable []string
for key, kind := range bound {
if _, ok := registered[key]; !ok {
unreachable = append(unreachable, key+" ("+kind+")")
}
}
sort.Strings(unreachable)
if len(unreachable) > 0 {
t.Fatalf("%d config keys have no default registered, so their environment variables are silently ignored:\n %s",
len(unreachable), strings.Join(unreachable, "\n "))
}
}
@@ -0,0 +1,41 @@
//go:build unit
package config
import (
"testing"
"github.com/stretchr/testify/require"
)
// TestLoadImageStorageFromEnv guards against a viper trap that silently disabled
// asynchronous image tasks for every environment-variable-only deployment.
//
// viper only decodes keys returned by AllKeys(), which unions SetDefault keys,
// config-file keys and explicit BindEnv keys. AutomaticEnv can override a key
// that is already in that list, but it never introduces a new one. Credentials
// such as image_storage.bucket therefore need an (empty) default registered, or
// IMAGE_STORAGE_BUCKET is dropped on the floor and Active() stays false while
// image_storage.enabled reads true — the endpoints 404 with no useful signal.
func TestLoadImageStorageFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("IMAGE_STORAGE_ENABLED", "true")
t.Setenv("IMAGE_STORAGE_ENDPOINT", "https://acct.r2.cloudflarestorage.com")
t.Setenv("IMAGE_STORAGE_BUCKET", "my-images")
t.Setenv("IMAGE_STORAGE_ACCESS_KEY_ID", "ak")
t.Setenv("IMAGE_STORAGE_SECRET_ACCESS_KEY", "sk")
t.Setenv("IMAGE_STORAGE_PUBLIC_BASE_URL", "https://cdn.example.com")
cfg, err := Load()
require.NoError(t, err)
require.True(t, cfg.ImageStorage.Enabled)
require.Equal(t, "https://acct.r2.cloudflarestorage.com", cfg.ImageStorage.Endpoint)
require.Equal(t, "my-images", cfg.ImageStorage.Bucket)
require.Equal(t, "ak", cfg.ImageStorage.AccessKeyID)
require.Equal(t, "sk", cfg.ImageStorage.SecretAccessKey)
require.Equal(t, "https://cdn.example.com", cfg.ImageStorage.PublicBaseURL)
require.True(t, cfg.ImageStorage.IsConfigured())
require.True(t, cfg.ImageStorage.Active(), "async image tasks must be active when every credential is supplied via env")
}
+1
View File
@@ -23,6 +23,7 @@ const (
PlatformGemini = "gemini"
PlatformAntigravity = "antigravity"
PlatformGrok = "grok"
PlatformComposite = "composite"
)
// Account type constants
@@ -0,0 +1,8 @@
package domain
// ReasoningEffortMapping rewrites one explicit OpenAI/Codex reasoning effort
// value to another before the group ceiling is applied.
type ReasoningEffortMapping struct {
From string `json:"from"`
To string `json:"to"`
}
@@ -0,0 +1,177 @@
package admin
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestNormalizeCodexImportEntryAcceptsAgentIdentityAuthJSON(t *testing.T) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
require.NoError(t, err)
privateKeyBase64 := base64.StdEncoding.EncodeToString(der)
item, err := normalizeCodexImportEntry(codexImportEntry{
Index: 1,
Value: map[string]any{
"auth_mode": "agentIdentity",
"agent_identity": map[string]any{
"agent_runtime_id": "runtime-import",
"agent_private_key": privateKeyBase64,
"account_id": "account-import",
"chatgpt_user_id": "user-import",
"email": "agent@example.invalid",
"plan_type": "pro",
"chatgpt_account_is_fedramp": false,
},
},
})
require.NoError(t, err)
require.NotNil(t, item)
require.True(t, item.IsAgentIdentity)
require.Equal(t, service.OpenAIAuthModeAgentIdentity, item.Credentials["auth_mode"])
require.Equal(t, "runtime-import", item.Credentials["agent_runtime_id"])
require.Equal(t, privateKeyBase64, item.Credentials["agent_private_key"])
require.Equal(t, "account-import", item.Credentials["chatgpt_account_id"])
require.Equal(t, "user-import", item.Credentials["chatgpt_user_id"])
require.NotContains(t, item.Credentials, "access_token")
require.NotContains(t, item.Credentials, "refresh_token")
require.NotEmpty(t, item.WarningTexts)
}
func TestBuildCodexAgentIdentityKeysUseChatGPTAccountOnly(t *testing.T) {
keys := buildCodexAgentIdentityKeys("team-a")
require.Equal(t, []string{"account:team-a"}, keys)
}
func TestCodexAgentIdentityIndexSeparatesTeamsForSameUser(t *testing.T) {
existing := service.Account{
ID: 1,
Credentials: map[string]any{
"auth_mode": service.OpenAIAuthModeAgentIdentity,
"chatgpt_account_id": "team-a",
"chatgpt_user_id": "same-user",
"agent_runtime_id": "runtime-a",
},
}
index := buildCodexAccountIndex([]service.Account{existing})
teamBKeys := buildCodexAgentIdentityKeys("team-b")
matched, _ := index.Find(teamBKeys, "same-user")
require.Nil(t, matched)
teamAKeys := buildCodexAgentIdentityKeys("team-a")
matched, matchedKey := index.Find(teamAKeys, "same-user")
require.NotNil(t, matched)
require.Equal(t, int64(1), matched.ID)
require.Equal(t, "account:team-a", matchedKey)
}
func TestImportCodexSessionsKeepsAgentIdentityTeamsSeparate(t *testing.T) {
first := buildAgentIdentityImportValue(t, "runtime-a", "team-a", "same-user", "task-a")
second := buildAgentIdentityImportValue(t, "runtime-b", "team-b", "same-user", "task-b")
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
result, err := handler.importCodexSessions(context.Background(), CodexSessionImportRequest{
SkipDefaultGroupBind: boolPtr(true),
}, []codexImportEntry{{Index: 1, Value: first}, {Index: 2, Value: second}})
require.NoError(t, err)
require.Equal(t, 2, result.Created)
require.Zero(t, result.Updated)
require.Zero(t, result.Skipped)
require.Len(t, svc.createdAccounts, 2)
}
func TestImportCodexSessionsMergesAgentIdentityRuntimesForSameTeam(t *testing.T) {
first := buildAgentIdentityImportValue(t, "runtime-a", "team-a", "same-user", "task-a")
second := buildAgentIdentityImportValue(t, "runtime-b", "team-a", "same-user", "task-b")
firstIdentity, ok := first["agent_identity"].(map[string]any)
require.True(t, ok)
existing := service.Account{
ID: 41,
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"auth_mode": service.OpenAIAuthModeAgentIdentity,
"agent_runtime_id": firstIdentity["agent_runtime_id"],
"agent_private_key": firstIdentity["agent_private_key"],
"task_id": firstIdentity["task_id"],
"chatgpt_account_id": firstIdentity["account_id"],
"chatgpt_user_id": firstIdentity["chatgpt_user_id"],
},
}
svc := newCodexImportMemoryAdminService([]service.Account{existing})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
result, err := handler.importCodexSessions(context.Background(), CodexSessionImportRequest{
SkipDefaultGroupBind: boolPtr(true),
}, []codexImportEntry{{Index: 1, Value: second}})
require.NoError(t, err)
require.Zero(t, result.Created)
require.Equal(t, 1, result.Updated)
require.Len(t, svc.updatedAccounts, 1)
require.Equal(t, "runtime-b", svc.updatedAccounts[0].input.Credentials["agent_runtime_id"])
require.Equal(t, "task-b", svc.updatedAccounts[0].input.Credentials["task_id"])
}
func buildAgentIdentityImportValue(t *testing.T, runtimeID, accountID, userID, taskID string) map[string]any {
t.Helper()
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
require.NoError(t, err)
return map[string]any{
"auth_mode": "agentIdentity",
"agent_identity": map[string]any{
"agent_runtime_id": runtimeID,
"agent_private_key": base64.StdEncoding.EncodeToString(der),
"task_id": taskID,
"account_id": accountID,
"chatgpt_user_id": userID,
},
}
}
func TestImportCodexSessionsCreatesAgentIdentityWithoutOAuthExpiry(t *testing.T) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
require.NoError(t, err)
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
result, err := handler.importCodexSessions(context.Background(), CodexSessionImportRequest{
SkipDefaultGroupBind: boolPtr(true),
}, []codexImportEntry{{
Index: 1,
Value: map[string]any{
"auth_mode": "agentIdentity",
"agent_identity": map[string]any{
"agent_runtime_id": "runtime-import",
"agent_private_key": base64.StdEncoding.EncodeToString(der),
"task_id": "task-import",
"account_id": "account-import",
"chatgpt_user_id": "user-import",
},
},
}})
require.NoError(t, err)
require.Equal(t, 1, result.Created)
require.Zero(t, result.Failed)
require.Len(t, svc.createdAccounts, 1)
created := svc.createdAccounts[0]
require.Nil(t, created.ExpiresAt)
require.Nil(t, created.AutoPauseOnExpired)
require.Equal(t, service.OpenAIAuthModeAgentIdentity, created.Credentials["auth_mode"])
require.NotContains(t, created.Credentials, "access_token")
require.NotContains(t, created.Credentials, "refresh_token")
}
@@ -72,20 +72,25 @@ type codexImportEntry struct {
}
type codexImportAccount struct {
Name string
AccessToken string
RefreshToken string
IDToken string
Email string
AccountID string
UserID string
PlanType string
Organization string
Credentials map[string]any
Extra map[string]any
TokenExpiresAt *time.Time
IdentityKeys []string
WarningTexts []string
Name string
AccessToken string
RefreshToken string
IDToken string
Email string
AccountID string
UserID string
PlanType string
Organization string
AgentRuntimeID string
AgentPrivateKey string
AgentTaskID string
AgentFedRAMP bool
IsAgentIdentity bool
Credentials map[string]any
Extra map[string]any
TokenExpiresAt *time.Time
IdentityKeys []string
WarningTexts []string
}
type codexJWTClaims struct {
@@ -106,7 +111,8 @@ type codexJWTOpenAIClaims struct {
}
type codexAccountIndex struct {
accountsByKey map[string][]service.Account
accountsByKey map[string][]service.Account
keysByAccountID map[int64]map[string]struct{}
}
func (h *AccountHandler) ImportCodexSession(c *gin.Context) {
@@ -115,6 +121,10 @@ func (h *AccountHandler) ImportCodexSession(c *gin.Context) {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := service.ValidateOpenAILongContextBillingExtra(service.PlatformOpenAI, req.Extra); err != nil {
response.ErrorFrom(c, err)
return
}
if req.Concurrency != nil && *req.Concurrency < 0 {
response.BadRequest(c, "concurrency must be >= 0")
return
@@ -492,6 +502,41 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err
case string:
item.AccessToken = strings.TrimSpace(raw)
case map[string]any:
if agentIdentity, ok := firstCodexMap(raw, []string{"agent_identity"}, []string{"agentIdentity"}); ok || strings.EqualFold(firstCodexString(raw, []string{"auth_mode"}, []string{"authMode"}), service.OpenAIAuthModeAgentIdentity) {
if !ok {
agentIdentity = raw
}
item.IsAgentIdentity = true
item.AgentRuntimeID = firstCodexString(agentIdentity, []string{"agent_runtime_id"}, []string{"agentRuntimeId"})
item.AgentPrivateKey = firstCodexString(agentIdentity, []string{"agent_private_key"}, []string{"agentPrivateKey"})
item.AgentTaskID = firstCodexString(agentIdentity, []string{"task_id"}, []string{"taskId"})
item.AccountID = firstCodexString(agentIdentity, []string{"account_id"}, []string{"accountId"})
item.UserID = firstCodexString(agentIdentity, []string{"chatgpt_user_id"}, []string{"chatgptUserId"})
item.Email = firstCodexString(agentIdentity, []string{"email"})
item.PlanType = firstCodexString(agentIdentity, []string{"plan_type"}, []string{"planType"})
item.AgentFedRAMP = firstCodexBool(agentIdentity, []string{"chatgpt_account_is_fedramp"}, []string{"chatgptAccountIsFedramp"})
if item.AgentRuntimeID == "" || item.AgentPrivateKey == "" || item.AccountID == "" || item.UserID == "" {
return nil, errors.New("agent identity 缺少必要字段")
}
if err := service.ValidateOpenAIAgentIdentityPrivateKey(item.AgentPrivateKey); err != nil {
return nil, errors.New("agent identity private key 格式无效")
}
item.Credentials["auth_mode"] = service.OpenAIAuthModeAgentIdentity
item.Credentials["agent_runtime_id"] = item.AgentRuntimeID
item.Credentials["agent_private_key"] = item.AgentPrivateKey
item.Credentials["chatgpt_account_id"] = item.AccountID
item.Credentials["chatgpt_user_id"] = item.UserID
item.Credentials["chatgpt_account_is_fedramp"] = item.AgentFedRAMP
setCodexCredentialIfNotEmpty(item.Credentials, "task_id", item.AgentTaskID)
setCodexCredentialIfNotEmpty(item.Credentials, "email", item.Email)
setCodexCredentialIfNotEmpty(item.Credentials, "plan_type", item.PlanType)
if item.AgentTaskID == "" {
item.WarningTexts = append(item.WarningTexts, "未包含 task_id,首次请求会使用现有 runtime 注册新 task")
}
item.IdentityKeys = buildCodexAgentIdentityKeys(item.AccountID)
item.Name = buildCodexImportAccountName(item, entry.Index)
return item, nil
}
item.AccessToken = firstCodexString(raw,
[]string{"tokens", "access_token"},
[]string{"tokens", "accessToken"},
@@ -573,6 +618,9 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err
return nil, fmt.Errorf("第 %d 条格式不支持", entry.Index)
}
if item.IsAgentIdentity {
return item, nil
}
if item.AccessToken == "" {
return nil, errors.New("缺少 accessToken/access_token")
}
@@ -727,6 +775,12 @@ func resolveCodexImportExpiry(req CodexSessionImportRequest, item *codexImportAc
if item == nil {
return nil, nil, nil, nil, errors.New("导入项为空")
}
// Agent Identity has no OAuth access-token lifetime. Its runtime/task
// lifecycle is handled by the upstream task recovery path, so it must not
// be rejected or auto-paused by the OAuth import expiry policy.
if item.IsAgentIdentity {
return nil, nil, nil, nil, nil
}
var requestExpiresAt *time.Time
if req.ExpiresAt != nil && *req.ExpiresAt > 0 {
@@ -808,6 +862,9 @@ func sanitizeCodexImportCredentialExtras(input map[string]any) map[string]any {
"openai_auth_mode": {},
"token_type": {},
"chatgpt_account_is_fedramp": {},
"agent_runtime_id": {},
"agent_private_key": {},
"task_id": {},
}
out := make(map[string]any, len(input))
for key, value := range input {
@@ -838,6 +895,19 @@ func buildCodexImportIdentityKeys(accountID, userID, email, accessToken, refresh
return buildCodexStoredIdentityKeys(accountID, userID, email, accessToken)
}
func buildCodexAgentIdentityKeys(accountID string) []string {
// Agent Identity credentials belonging to the same ChatGPT account are
// intentionally merged, while the same user may own multiple accounts.
// Do not use user/email/runtime as fallback keys here: user_id is shared
// across Team workspaces and runtime_id changes when a new runtime is
// registered for the same account.
accountID = strings.TrimSpace(accountID)
if accountID == "" {
return nil
}
return []string{"account:" + accountID}
}
// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度,
// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。
func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string {
@@ -863,7 +933,10 @@ func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string)
}
func buildCodexAccountIndex(accounts []service.Account) *codexAccountIndex {
index := &codexAccountIndex{accountsByKey: map[string][]service.Account{}}
index := &codexAccountIndex{
accountsByKey: map[string][]service.Account{},
keysByAccountID: map[int64]map[string]struct{}{},
}
for _, account := range accounts {
index.Add(account)
}
@@ -877,36 +950,71 @@ func (i *codexAccountIndex) Add(account service.Account) {
if i.accountsByKey == nil {
i.accountsByKey = map[string][]service.Account{}
}
i.remove(account.ID)
if i.keysByAccountID == nil {
i.keysByAccountID = map[int64]map[string]struct{}{}
}
keys := buildCodexStoredIdentityKeys(
codexCredentialString(account.Credentials, "chatgpt_account_id"),
codexCredentialString(account.Credentials, "chatgpt_user_id"),
codexCredentialString(account.Credentials, "email"),
codexCredentialString(account.Credentials, "access_token"),
)
orderedKeys := make([]string, 0, len(keys)+1)
accountKeys := make(map[string]struct{}, len(keys)+1)
for _, key := range keys {
i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], 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)
if _, exists := accountKeys[key]; exists {
continue
}
i.accountsByKey[key] = kept
accountKeys[key] = struct{}{}
orderedKeys = append(orderedKeys, key)
}
if runtimeID := codexCredentialString(account.Credentials, "agent_runtime_id"); runtimeID != "" {
key := "agent:" + runtimeID
if _, exists := accountKeys[key]; !exists {
accountKeys[key] = struct{}{}
orderedKeys = append(orderedKeys, key)
}
}
previousKeys := i.keysByAccountID[account.ID]
for key := range previousKeys {
if _, retained := accountKeys[key]; retained {
i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account)
continue
}
i.removeFromKey(key, account.ID)
}
for _, key := range orderedKeys {
if _, retained := previousKeys[key]; retained {
continue
}
i.accountsByKey[key] = append(i.accountsByKey[key], account)
}
if len(accountKeys) > 0 {
i.keysByAccountID[account.ID] = accountKeys
return
}
delete(i.keysByAccountID, account.ID)
}
// upsertCodexAccount 保留同一键下的全部候选账号(共享的 account: 键可对应
// 团队内多个账号),同一账号重复 Add 时原位替换为最新状态。
func (i *codexAccountIndex) removeFromKey(key string, accountID int64) {
accounts := i.accountsByKey[key]
kept := accounts[:0]
for _, account := range accounts {
if account.ID != accountID {
kept = append(kept, account)
}
}
if len(kept) == 0 {
delete(i.accountsByKey, key)
return
}
i.accountsByKey[key] = kept
}
// upsertCodexAccount keeps all candidates for shared keys while replacing an
// existing account in place so ambiguous legacy matches retain their order.
func upsertCodexAccount(accounts []service.Account, account service.Account) []service.Account {
for idx := range accounts {
if accounts[idx].ID == account.ID {
@@ -1039,6 +1147,38 @@ func firstCodexString(obj map[string]any, paths ...[]string) string {
return ""
}
func firstCodexMap(obj map[string]any, paths ...[]string) (map[string]any, bool) {
for _, path := range paths {
value, ok := codexPathValue(obj, path)
if !ok || value == nil {
continue
}
if mapped, ok := value.(map[string]any); ok {
return mapped, true
}
}
return nil, false
}
func firstCodexBool(obj map[string]any, paths ...[]string) bool {
for _, path := range paths {
value, ok := codexPathValue(obj, path)
if !ok {
continue
}
switch value := value.(type) {
case bool:
return value
case string:
parsed, err := strconv.ParseBool(strings.TrimSpace(value))
if err == nil {
return parsed
}
}
}
return false
}
func copyCodexExtraString(obj map[string]any, extra map[string]any, key string, path []string) {
value := firstCodexString(obj, path)
if value != "" {
@@ -509,6 +509,73 @@ func TestCodexAccountIndexUpsertReplacesSameAccount(t *testing.T) {
}
}
func TestCodexAccountIndexUpdateRemovesAllPreviousKeys(t *testing.T) {
legacy := service.Account{
ID: 50,
Credentials: map[string]any{
"chatgpt_account_id": "team-old",
"chatgpt_user_id": "user-old",
"email": "old@example.com",
"access_token": "access-old",
"agent_runtime_id": "runtime-old",
},
}
index := buildCodexAccountIndex([]service.Account{legacy})
updated := service.Account{
ID: 50,
Credentials: map[string]any{
"chatgpt_account_id": "team-new",
"chatgpt_user_id": "user-new",
"email": "new@example.com",
"access_token": "access-new",
"agent_runtime_id": "runtime-new",
},
}
index.Add(updated)
oldKeys := append(buildCodexStoredIdentityKeys("team-old", "user-old", "old@example.com", "access-old"), "agent:runtime-old")
for _, key := range oldKeys {
if got, matchedKey := index.Find([]string{key}, "user-old"); got != nil {
t.Fatalf("stale account matched by %q: account ID %d", matchedKey, got.ID)
}
}
newKeys := append(buildCodexStoredIdentityKeys("team-new", "user-new", "new@example.com", "access-new"), "agent:runtime-new")
for _, key := range newKeys {
got, matchedKey := index.Find([]string{key}, "user-new")
if got == nil || got.ID != updated.ID {
t.Fatalf("updated account not found by %q: account=%v matched=%q", key, got, matchedKey)
}
}
}
func TestCodexAccountIndexUpdatePreservesSharedKeyCandidateOrder(t *testing.T) {
first := service.Account{
ID: 60,
Credentials: map[string]any{
"chatgpt_account_id": "team-shared",
"access_token": "access-first-old",
},
}
second := service.Account{
ID: 61,
Credentials: map[string]any{
"chatgpt_account_id": "team-shared",
"access_token": "access-second",
},
}
index := buildCodexAccountIndex([]service.Account{first, second})
first.Credentials["access_token"] = "access-first-new"
index.Add(first)
got, matchedKey := index.Find([]string{"account:team-shared"}, "")
if got == nil || got.ID != first.ID {
t.Fatalf("shared key candidate order changed after update: account=%v matched=%q", got, matchedKey)
}
}
func TestCodexIdentitySeenDistinguishesTeamMembers(t *testing.T) {
seen := map[string]codexSeenIdentity{}
member1 := buildCodexImportIdentityKeys("team-1", "user-1", "", "token-1", "refresh-1")
@@ -559,7 +626,7 @@ func TestNormalizeCodexImportUsesJWTSubForAccessTokenOnlyIdentity(t *testing.T)
func TestImportCodexSessionsAccessTokenOnlySameWorkspaceDifferentUsersCreatesTwoAccounts(t *testing.T) {
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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")},
@@ -583,7 +650,7 @@ func TestImportCodexSessionsAccessTokenOnlySameWorkspaceDifferentUsersCreatesTwo
func TestImportCodexSessionsAccessTokenOnlySameWorkspaceAndUserDifferentTokensCreatesTwoAccounts(t *testing.T) {
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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{
@@ -630,8 +697,9 @@ func TestImportCodexSessionsAccessTokenOnlySameUserUpdatesExisting(t *testing.T)
"chatgpt_user_id": "user-1",
"access_token": existingToken,
},
Extra: map[string]any{"openai_long_context_billing_enabled": false},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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}},
@@ -650,6 +718,9 @@ func TestImportCodexSessionsAccessTokenOnlySameUserUpdatesExisting(t *testing.T)
if len(svc.updatedAccounts) != 1 || svc.updatedAccounts[0].id != 10 {
t.Fatalf("updated accounts = %+v, want account 10", svc.updatedAccounts)
}
if got := svc.updatedAccounts[0].input.Extra["openai_long_context_billing_enabled"]; got != false {
t.Fatalf("openai_long_context_billing_enabled = %v, want false", got)
}
}
func TestImportCodexSessionsUpgradesAccessTokenOnlyAccountWithRefreshToken(t *testing.T) {
@@ -666,7 +737,7 @@ func TestImportCodexSessionsUpgradesAccessTokenOnlyAccountWithRefreshToken(t *te
"access_token": oldToken,
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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{
@@ -705,7 +776,7 @@ func TestImportCodexSessionsAccessTokenOnlyPreservesExistingRefreshToken(t *test
"client_id": "client-old",
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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}},
@@ -748,7 +819,7 @@ func TestImportCodexSessionsBatchOldAccessTokenDoesNotRollbackRefreshToken(t *te
"refresh_token": "refresh-old",
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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{
@@ -794,7 +865,7 @@ func TestImportCodexSessionsWithRefreshTokenKeepsExistingDedup(t *testing.T) {
"refresh_token": "refresh-old",
},
}})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(svc, nil, 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")},
@@ -460,6 +460,7 @@ func (h *AccountHandler) importData(ctx context.Context, req DataImportRequest)
if created.Platform == service.PlatformAntigravity && created.Type == service.AccountTypeOAuth {
privacyAccounts = append(privacyAccounts, created)
}
h.scheduleGrokImportProbe(created)
result.AccountCreated++
}
@@ -66,6 +66,7 @@ func setupAccountDataRouter() (*gin.Engine, *stubAdminService) {
nil,
nil,
nil,
nil,
)
router.GET("/api/v1/admin/accounts/data", h.ExportData)
@@ -52,6 +52,7 @@ type AccountHandler struct {
openaiOAuthService *service.OpenAIOAuthService
geminiOAuthService *service.GeminiOAuthService
antigravityOAuthService *service.AntigravityOAuthService
grokOAuthService service.GrokOAuthTokenService
rateLimitService *service.RateLimitService
accountUsageService *service.AccountUsageService
accountTestService *service.AccountTestService
@@ -60,6 +61,18 @@ type AccountHandler struct {
sessionLimitCache service.SessionLimitCache
rpmCache service.RPMCache
tokenCacheInvalidator service.TokenCacheInvalidator
grokImportProber grokImportProber
upstreamBillingProbe *service.UpstreamBillingProbeService
ollamaCloudUsage *service.OllamaCloudUsageService
}
// SetUpstreamBillingProbeService attaches the optional remote billing probe service.
func (h *AccountHandler) SetUpstreamBillingProbeService(probe *service.UpstreamBillingProbeService) {
h.upstreamBillingProbe = probe
}
func (h *AccountHandler) SetOllamaCloudUsageService(usage *service.OllamaCloudUsageService) {
h.ollamaCloudUsage = usage
}
// NewAccountHandler creates a new admin account handler
@@ -69,6 +82,7 @@ func NewAccountHandler(
openaiOAuthService *service.OpenAIOAuthService,
geminiOAuthService *service.GeminiOAuthService,
antigravityOAuthService *service.AntigravityOAuthService,
grokOAuthService service.GrokOAuthTokenService,
rateLimitService *service.RateLimitService,
accountUsageService *service.AccountUsageService,
accountTestService *service.AccountTestService,
@@ -84,6 +98,7 @@ func NewAccountHandler(
openaiOAuthService: openaiOAuthService,
geminiOAuthService: geminiOAuthService,
antigravityOAuthService: antigravityOAuthService,
grokOAuthService: grokOAuthService,
rateLimitService: rateLimitService,
accountUsageService: accountUsageService,
accountTestService: accountTestService,
@@ -111,6 +126,7 @@ type CreateAccountRequest struct {
GroupIDs []int64 `json:"group_ids"`
ExpiresAt *int64 `json:"expires_at"`
AutoPauseOnExpired *bool `json:"auto_pause_on_expired"`
ProbeEnabled *bool `json:"upstream_billing_probe_enabled"`
ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险
}
@@ -149,6 +165,7 @@ type BulkUpdateAccountsRequest struct {
GroupIDs *[]int64 `json:"group_ids"`
Credentials map[string]any `json:"credentials"`
Extra map[string]any `json:"extra"`
ProbeEnabled *bool `json:"upstream_billing_probe_enabled"`
ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险
}
@@ -196,9 +213,17 @@ type AccountSchedulerGroupScore struct {
const accountListGroupUngroupedQueryValue = "ungrouped"
func (h *AccountHandler) accountResponseFromService(account *service.Account) *dto.Account {
out := dto.AccountFromService(account)
if h != nil && h.ollamaCloudUsage != nil && out != nil {
h.ollamaCloudUsage.EnrichState(out.OllamaCloudUsage)
}
return out
}
func (h *AccountHandler) buildAccountResponseWithRuntime(ctx context.Context, account *service.Account) AccountWithConcurrency {
item := AccountWithConcurrency{
Account: dto.AccountFromService(account),
Account: h.accountResponseFromService(account),
CurrentConcurrency: 0,
}
if account == nil {
@@ -511,6 +536,16 @@ func (h *AccountHandler) List(c *gin.Context) {
response.ErrorFrom(c, err)
return
}
if h.ollamaCloudUsage != nil && len(accounts) > 0 {
accountPointers := make([]*service.Account, len(accounts))
for index := range accounts {
accountPointers[index] = &accounts[index]
}
if err := h.ollamaCloudUsage.ResolveAccounts(c.Request.Context(), accountPointers); err != nil {
response.ErrorFrom(c, err)
return
}
}
// Get current concurrency counts for all accounts
accountIDs := make([]int64, len(accounts))
@@ -614,7 +649,7 @@ func (h *AccountHandler) List(c *gin.Context) {
for i := range accounts {
acc := &accounts[i]
item := AccountWithConcurrency{
Account: dto.AccountFromService(acc),
Account: h.accountResponseFromService(acc),
CurrentConcurrency: concurrencyCounts[acc.ID],
SchedulerScore: schedulerScores[acc.ID],
SchedulerScores: schedulerGroupScores[acc.ID],
@@ -728,6 +763,12 @@ func (h *AccountHandler) GetByID(c *gin.Context) {
response.ErrorFrom(c, err)
return
}
if h.ollamaCloudUsage != nil {
if err := h.ollamaCloudUsage.ResolveAccounts(c.Request.Context(), []*service.Account{account}); err != nil {
response.ErrorFrom(c, err)
return
}
}
response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), account))
}
@@ -784,6 +825,10 @@ func (h *AccountHandler) Create(c *gin.Context) {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := service.ValidateOpenAILongContextBillingExtra(req.Platform, req.Extra); err != nil {
response.ErrorFrom(c, err)
return
}
if req.RateMultiplier != nil && *req.RateMultiplier < 0 {
response.BadRequest(c, "rate_multiplier must be >= 0")
return
@@ -814,6 +859,7 @@ func (h *AccountHandler) Create(c *gin.Context) {
GroupIDs: req.GroupIDs,
ExpiresAt: req.ExpiresAt,
AutoPauseOnExpired: req.AutoPauseOnExpired,
ProbeEnabled: req.ProbeEnabled,
SkipMixedChannelCheck: skipCheck,
})
if execErr != nil {
@@ -851,6 +897,54 @@ func (h *AccountHandler) Create(c *gin.Context) {
// OpenAI APIKey 账号创建后异步探测上游 /v1/responses 能力。
// 探测失败不影响账号创建响应。
h.scheduleOpenAIResponsesProbe(createdAccount)
h.scheduleGrokImportProbe(createdAccount)
response.Success(c, result.Data)
}
// Duplicate handles creating an independent account from an existing account's configuration.
// POST /api/v1/admin/accounts/:id/duplicate
func (h *AccountHandler) Duplicate(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
actorScope := adminActorScope(c)
result, err := executeAdminIdempotent(
c,
"admin.accounts.duplicate",
struct {
AccountID int64 `json:"account_id"`
}{AccountID: accountID},
service.DefaultWriteIdempotencyTTL(),
func(ctx context.Context) (any, error) {
account, execErr := h.adminService.DuplicateAccount(ctx, accountID, actorScope, c.GetHeader("Idempotency-Key"))
if execErr != nil {
return nil, execErr
}
return h.buildAccountResponseWithRuntime(ctx, account), nil
},
)
if err != nil {
reason := infraerrors.Reason(err)
if reason == infraerrors.Reason(service.ErrIdempotencyInProgress) || reason == infraerrors.Reason(service.ErrIdempotencyStoreUnavail) {
recovered, recoverErr := h.adminService.RecoverDuplicateAccount(c.Request.Context(), accountID, actorScope, c.GetHeader("Idempotency-Key"))
if recoverErr != nil {
slog.Warn("account_duplicate_recovery_failed", "account_id", accountID, "actor_scope", actorScope, "reason", reason, "error", recoverErr)
} else if recovered != nil {
c.Header("X-Idempotency-Recovered", "true")
response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), recovered))
return
}
}
response.ErrorFrom(c, err)
return
}
if result != nil && result.Replayed {
c.Header("X-Idempotency-Replayed", "true")
}
response.Success(c, result.Data)
}
@@ -1173,6 +1267,19 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
return nil, "", fmt.Errorf("failed to clear account error: %w", clearErr)
}
}
} else if account.Platform == service.PlatformGrok {
if h.grokOAuthService == nil {
return nil, "", fmt.Errorf("grok oauth service is not configured")
}
tokenInfo, err := h.grokOAuthService.RefreshAccountToken(ctx, account)
if err != nil {
return nil, "", fmt.Errorf("failed to refresh Grok credentials: %w", err)
}
newCredentials = service.MergeCredentials(account.Credentials, h.grokOAuthService.BuildAccountCredentials(tokenInfo))
if baseURL := strings.TrimSpace(account.GetCredential("base_url")); baseURL != "" {
newCredentials["base_url"] = baseURL
}
} else {
// Use Anthropic/Claude OAuth service to refresh token
tokenInfo, err := h.oauthService.RefreshAccountToken(ctx, account)
@@ -1299,6 +1406,10 @@ func (h *AccountHandler) ApplyOAuthCredentials(c *gin.Context) {
response.ErrorFrom(c, infraerrors.BadRequest("NOT_OAUTH", "cannot apply oauth credentials to non-OAuth account"))
return
}
if err := service.ValidateOpenAILongContextBillingExtra(existing.Platform, req.Extra); err != nil {
response.ErrorFrom(c, err)
return
}
updatedAccount, err := h.adminService.UpdateAccount(ctx, accountID, &service.UpdateAccountInput{
Type: req.Type,
@@ -1592,6 +1703,12 @@ func (h *AccountHandler) BatchCreate(c *gin.Context) {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
for _, item := range req.Accounts {
if err := service.ValidateOpenAILongContextBillingExtra(item.Platform, item.Extra); err != nil {
response.ErrorFrom(c, err)
return
}
}
executeAdminIdempotentJSON(c, "admin.accounts.batch_create", req, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
success := 0
@@ -1653,6 +1770,7 @@ func (h *AccountHandler) BatchCreate(c *gin.Context) {
}
// OpenAI APIKey 账号异步探测 /v1/responses 能力。
h.scheduleOpenAIResponsesProbe(account)
h.scheduleGrokImportProbe(account)
success++
results = append(results, gin.H{
"name": item.Name,
@@ -1821,7 +1939,8 @@ func (h *AccountHandler) BulkUpdate(c *gin.Context) {
req.Schedulable != nil ||
req.GroupIDs != nil ||
len(req.Credentials) > 0 ||
len(req.Extra) > 0
len(req.Extra) > 0 ||
req.ProbeEnabled != nil
if !hasUpdates {
response.BadRequest(c, "No updates provided")
@@ -1842,6 +1961,7 @@ func (h *AccountHandler) BulkUpdate(c *gin.Context) {
GroupIDs: req.GroupIDs,
Credentials: req.Credentials,
Extra: req.Extra,
ProbeEnabled: req.ProbeEnabled,
SkipMixedChannelCheck: skipCheck,
})
if err != nil {
@@ -32,7 +32,7 @@ func (s *availableModelsAdminService) GetAccount(_ context.Context, id int64) (*
func setupAvailableModelsRouter(adminSvc service.AdminService) *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router.GET("/api/v1/admin/accounts/:id/models", handler.GetAvailableModels)
return router
}
@@ -66,7 +66,7 @@ func setupSyncUpstreamModelsRouter(adminSvc service.AdminService, upstream servi
&config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}},
nil,
)
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, accountTestSvc, nil, nil, nil, nil, nil)
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, accountTestSvc, nil, nil, nil, nil, nil)
router.POST("/api/v1/admin/accounts/:id/models/sync-upstream", handler.SyncUpstreamModels)
return router
}
@@ -213,6 +213,38 @@ func TestAccountHandlerGetAvailableModels_OpenAIOAuthPassthroughFallsBackToDefau
require.NotEqual(t, "gpt-5", resp.Data[0].ID)
}
func TestAccountHandlerGetAvailableModels_OpenAIAPIKeyDefaultsToConcreteGPT56Sol(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
account: service.Account{
ID: 46,
Name: "openai-apikey",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Credentials: map[string]any{
"api_key": "test-key",
},
},
}
router := setupAvailableModelsRouter(svc)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/46/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)
require.Equal(t, "gpt-5.6-sol", resp.Data[0].ID)
}
func TestAccountHandlerGetAvailableModels_OpenAISparkShadowReturnsMappingModels(t *testing.T) {
parentID := int64(100)
svc := &availableModelsAdminService{
@@ -0,0 +1,295 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type duplicateAccountAdminServiceStub struct {
service.AdminService
account *service.Account
calls int
recoverCalls int
accountID int64
actorScope string
operationKey string
recoverScope string
recoverKey string
recoverErr error
created bool
}
type blockingDuplicateAdminServiceStub struct {
service.AdminService
account *service.Account
started chan struct{}
release chan struct{}
calls atomic.Int32
recoverCalls atomic.Int32
recoverErr error
}
type failOnceMarkSucceededRepo struct {
*memoryIdempotencyRepoStub
failNext bool
}
func (r *failOnceMarkSucceededRepo) MarkSucceeded(ctx context.Context, id int64, responseStatus int, responseBody string, expiresAt time.Time) error {
if r.failNext {
r.failNext = false
return errors.New("mark succeeded failed")
}
return r.memoryIdempotencyRepoStub.MarkSucceeded(ctx, id, responseStatus, responseBody, expiresAt)
}
func (s *duplicateAccountAdminServiceStub) DuplicateAccount(_ context.Context, accountID int64, actorScope, operationKey string) (*service.Account, error) {
s.calls++
s.accountID = accountID
s.actorScope = actorScope
s.operationKey = operationKey
s.created = true
return s.account, nil
}
func (s *duplicateAccountAdminServiceStub) RecoverDuplicateAccount(_ context.Context, _ int64, actorScope, operationKey string) (*service.Account, error) {
s.recoverCalls++
s.recoverScope = actorScope
s.recoverKey = operationKey
if s.recoverErr != nil {
return nil, s.recoverErr
}
if !s.created {
return nil, nil
}
return s.account, nil
}
func (s *blockingDuplicateAdminServiceStub) DuplicateAccount(_ context.Context, _ int64, _, _ string) (*service.Account, error) {
s.calls.Add(1)
close(s.started)
<-s.release
return s.account, nil
}
func (s *blockingDuplicateAdminServiceStub) RecoverDuplicateAccount(_ context.Context, _ int64, _, _ string) (*service.Account, error) {
s.recoverCalls.Add(1)
return nil, s.recoverErr
}
func setupDuplicateAccountRouter(t *testing.T, svc service.AdminService) *gin.Engine {
t.Helper()
previousCoordinator := service.DefaultIdempotencyCoordinator()
service.SetDefaultIdempotencyCoordinator(nil)
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previousCoordinator) })
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 77})
c.Next()
})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router.POST("/api/v1/admin/accounts/:id/duplicate", handler.Duplicate)
return router
}
func TestDuplicateAccountHandlerRedactsCredentials(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
Credentials: map[string]any{"api_key": "top-secret-key"},
},
}
router := setupDuplicateAccountRouter(t, svc)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, 1, svc.calls)
require.Contains(t, recorder.Body.String(), `"name":"primary (Copy)"`)
require.NotContains(t, recorder.Body.String(), "top-secret-key")
var responseBody struct {
Data struct {
Credentials map[string]any `json:"credentials"`
Schedulable bool `json:"schedulable"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &responseBody))
require.Empty(t, responseBody.Data.Credentials)
require.False(t, responseBody.Data.Schedulable)
}
func TestDuplicateAccountHandlerRejectsInvalidID(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{}
router := setupDuplicateAccountRouter(t, svc)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/not-a-number/duplicate", nil)
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.Zero(t, svc.calls)
}
func TestDuplicateAccountHandlerReplaysSameIdempotencyKey(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
}
router := setupDuplicateAccountRouter(t, svc)
repo := newMemoryIdempotencyRepoStub()
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42")
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, 1, svc.calls)
require.Equal(t, int64(42), svc.accountID)
require.Equal(t, "admin:77", svc.actorScope)
require.Equal(t, "duplicate-account-42", svc.operationKey)
require.Equal(t, "true", second.Header().Get("X-Idempotency-Replayed"))
}
func TestDuplicateAccountHandlerRecoversAfterMarkSucceededFailure(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
}
router := setupDuplicateAccountRouter(t, svc)
repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true}
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42-recovery")
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, "true", first.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, "true", second.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, 1, svc.calls, "ambiguous retries must not repeat the create side effect")
require.Equal(t, 2, svc.recoverCalls)
require.Equal(t, "admin:77", svc.recoverScope)
require.Equal(t, "duplicate-account-42-recovery", svc.recoverKey)
require.Contains(t, second.Body.String(), `"id":43`)
}
func TestDuplicateAccountHandlerPreservesIdempotencyErrorWhenRecoveryLookupFails(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
recoverErr: errors.New("recovery database unavailable"),
}
router := setupDuplicateAccountRouter(t, svc)
repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true}
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42-recovery-error")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Contains(t, recorder.Body.String(), "IDEMPOTENCY_STORE_UNAVAILABLE")
require.Equal(t, 1, svc.calls)
require.Equal(t, 1, svc.recoverCalls)
require.Equal(t, "admin:77", svc.recoverScope)
}
func TestDuplicateAccountHandlerDoesNotReexecuteWhileOriginalIsProcessing(t *testing.T) {
svc := &blockingDuplicateAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
started: make(chan struct{}),
release: make(chan struct{}),
recoverErr: errors.New("recovery database unavailable"),
}
router := setupDuplicateAccountRouter(t, svc)
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42-active")
router.ServeHTTP(recorder, request)
return recorder
}
firstDone := make(chan *httptest.ResponseRecorder, 1)
go func() { firstDone <- call() }()
<-svc.started
second := call()
require.Equal(t, http.StatusConflict, second.Code)
require.Contains(t, second.Body.String(), "IDEMPOTENCY_IN_PROGRESS")
require.Equal(t, int32(1), svc.calls.Load())
require.Equal(t, int32(1), svc.recoverCalls.Load())
close(svc.release)
select {
case first := <-firstDone:
require.Equal(t, http.StatusOK, first.Code)
case <-time.After(time.Second):
t.Fatal("original duplicate request did not finish")
}
}
@@ -0,0 +1,99 @@
//go:build unit
package admin
import (
"context"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
type grokRefreshOAuthStub struct {
account *service.Account
info *service.GrokTokenInfo
calls int
}
func (s *grokRefreshOAuthStub) RefreshAccountToken(_ context.Context, account *service.Account) (*service.GrokTokenInfo, error) {
s.calls++
s.account = account
return s.info, nil
}
func (s *grokRefreshOAuthStub) BuildAccountCredentials(info *service.GrokTokenInfo) map[string]any {
return map[string]any{
"access_token": info.AccessToken,
"refresh_token": info.RefreshToken,
"expires_at": info.ExpiresAt,
"base_url": "https://api.x.ai/v1",
}
}
type grokRefreshAdminService struct {
*stubAdminService
updatedCredentials map[string]any
}
func (s *grokRefreshAdminService) UpdateAccount(_ context.Context, id int64, input *service.UpdateAccountInput) (*service.Account, error) {
s.updatedCredentials = input.Credentials
return &service.Account{
ID: id,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: input.Credentials,
}, nil
}
func TestRefreshSingleAccountRoutesGrokThroughGrokOAuthService(t *testing.T) {
t.Parallel()
adminSvc := &grokRefreshAdminService{stubAdminService: newStubAdminService()}
grokOAuth := &grokRefreshOAuthStub{info: &service.GrokTokenInfo{
AccessToken: "new-access",
RefreshToken: "new-refresh",
ExpiresAt: 1_800_000_000,
}}
handler := NewAccountHandler(
adminSvc,
nil,
nil,
nil,
nil,
grokOAuth,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
)
account := &service.Account{
ID: 4227,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"access_token": "old-access",
"refresh_token": "old-refresh",
"base_url": "https://example.invalid/v1",
"subscription_tier": "SUPER_GROK",
"entitlement_status": "ACTIVE",
},
}
updated, warning, err := handler.refreshSingleAccount(context.Background(), account)
require.NoError(t, err)
require.Empty(t, warning)
require.Equal(t, 1, grokOAuth.calls)
require.Same(t, account, grokOAuth.account)
require.Equal(t, "new-access", adminSvc.updatedCredentials["access_token"])
require.Equal(t, "new-refresh", adminSvc.updatedCredentials["refresh_token"])
require.Equal(t, "https://example.invalid/v1", adminSvc.updatedCredentials["base_url"])
require.Equal(t, "SUPER_GROK", adminSvc.updatedCredentials["subscription_tier"])
require.Equal(t, "ACTIVE", adminSvc.updatedCredentials["entitlement_status"])
require.Equal(t, adminSvc.updatedCredentials, updated.Credentials)
}
@@ -17,7 +17,7 @@ func setupAccountListRouter() (*gin.Engine, *stubAdminService) {
gin.SetMode(gin.TestMode)
router := gin.New()
adminSvc := newStubAdminService()
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router.GET("/api/v1/admin/accounts", handler.List)
return router, adminSvc
}
@@ -0,0 +1,165 @@
package admin
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestAccountAdminBoundariesRejectMalformedOpenAILongContextBillingValue(t *testing.T) {
const malformedExtra = `"extra":{"openai_long_context_billing_enabled":"true"}`
tests := []struct {
name string
method string
path string
body string
mount func(*gin.Engine, *AccountHandler)
setup func(*stubAdminService)
}{
{
name: "create",
method: http.MethodPost,
path: "/accounts",
body: `{"name":"account","platform":"openai","type":"apikey","credentials":{"api_key":"test"},` + malformedExtra + `}`,
mount: func(router *gin.Engine, handler *AccountHandler) { router.POST("/accounts", handler.Create) },
},
{
name: "update",
method: http.MethodPut,
path: "/accounts/1",
body: `{` + malformedExtra + `}`,
mount: func(router *gin.Engine, handler *AccountHandler) { router.PUT("/accounts/:id", handler.Update) },
setup: func(stub *stubAdminService) {
stub.updateAccountErr = infraerrors.BadRequest("OPENAI_LONG_CONTEXT_BILLING_INVALID", "invalid")
},
},
{
name: "bulk update",
method: http.MethodPost,
path: "/accounts/bulk-update",
body: `{"account_ids":[1],` + malformedExtra + `}`,
mount: func(router *gin.Engine, handler *AccountHandler) {
router.POST("/accounts/bulk-update", handler.BulkUpdate)
},
setup: func(stub *stubAdminService) {
stub.bulkUpdateAccountErr = infraerrors.BadRequest("OPENAI_LONG_CONTEXT_BILLING_INVALID", "invalid")
},
},
{
name: "batch create",
method: http.MethodPost,
path: "/accounts/batch",
body: `{"accounts":[{"name":"account","platform":"openai","type":"apikey","credentials":{"api_key":"test"},` + malformedExtra + `}]}`,
mount: func(router *gin.Engine, handler *AccountHandler) { router.POST("/accounts/batch", handler.BatchCreate) },
},
{
name: "Codex session import",
method: http.MethodPost,
path: "/accounts/import-codex-session",
body: `{"content":"token",` + malformedExtra + `}`,
mount: func(router *gin.Engine, handler *AccountHandler) {
router.POST("/accounts/import-codex-session", handler.ImportCodexSession)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gin.SetMode(gin.TestMode)
stub := newStubAdminService()
if tt.setup != nil {
tt.setup(stub)
}
handler := NewAccountHandler(stub, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
tt.mount(router, handler)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(tt.method, tt.path, bytes.NewBufferString(tt.body))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
var responseBody struct {
Reason string `json:"reason"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &responseBody))
require.Equal(t, "OPENAI_LONG_CONTEXT_BILLING_INVALID", responseBody.Reason)
})
}
}
func TestAccountCreateBoundaryDoesNotApplyOpenAIValidationToOtherPlatforms(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := NewAccountHandler(newStubAdminService(), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.POST("/accounts", handler.Create)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/accounts", bytes.NewBufferString(
`{"name":"account","platform":"anthropic","type":"apikey","credentials":{"api_key":"test"},"extra":{"openai_long_context_billing_enabled":"provider-owned"}}`,
))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
}
func TestApplyOAuthCredentialsRejectsMalformedOpenAILongContextBillingBeforeMutation(t *testing.T) {
gin.SetMode(gin.TestMode)
stub := newStubAdminService()
stub.getAccountResult = &service.Account{
ID: 1,
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
}
handler := NewAccountHandler(stub, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.POST("/accounts/:id/apply-oauth-credentials", handler.ApplyOAuthCredentials)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/accounts/1/apply-oauth-credentials", bytes.NewBufferString(
`{"type":"oauth","credentials":{"access_token":"new-token"},"extra":{"openai_long_context_billing_enabled":"true"}}`,
))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
var responseBody struct {
Reason string `json:"reason"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &responseBody))
require.Equal(t, "OPENAI_LONG_CONTEXT_BILLING_INVALID", responseBody.Reason)
require.Zero(t, stub.updateAccountCalls)
require.Zero(t, stub.updateAccountExtraCalls)
}
func TestOpenAIOAuthCodexPATBoundaryRejectsMalformedOpenAILongContextBillingValueBeforeTokenValidation(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := NewOpenAIOAuthHandler(nil, newStubAdminService(), nil)
router := gin.New()
router.Use(gin.Recovery())
router.POST("/openai/create-from-codex-pat", handler.CreateAccountFromCodexPAT)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/openai/create-from-codex-pat", bytes.NewBufferString(
`{"access_token":"token","extra":{"openai_long_context_billing_enabled":1}}`,
))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
var responseBody struct {
Reason string `json:"reason"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &responseBody))
require.Equal(t, "OPENAI_LONG_CONTEXT_BILLING_INVALID", responseBody.Reason)
}
@@ -15,7 +15,7 @@ import (
func setupAccountMixedChannelRouter(adminSvc *stubAdminService) *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
accountHandler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
accountHandler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router.POST("/api/v1/admin/accounts/check-mixed-channel", accountHandler.CheckMixedChannel)
router.POST("/api/v1/admin/accounts", accountHandler.Create)
router.PUT("/api/v1/admin/accounts/:id", accountHandler.Update)
@@ -222,3 +222,22 @@ func TestBulkUpdateAcceptsFilterTargetRequest(t *testing.T) {
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, float64(0), resp["code"])
}
func TestBulkUpdateAcceptsDedicatedUpstreamBillingProbeSetting(t *testing.T) {
adminSvc := newStubAdminService()
router := setupAccountMixedChannelRouter(adminSvc)
body, _ := json.Marshal(map[string]any{
"account_ids": []int64{1, 2},
"upstream_billing_probe_enabled": false,
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/bulk-update", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.NotNil(t, adminSvc.lastBulkUpdateAccountInput)
require.NotNil(t, adminSvc.lastBulkUpdateAccountInput.ProbeEnabled)
require.False(t, *adminSvc.lastBulkUpdateAccountInput.ProbeEnabled)
}
@@ -29,6 +29,7 @@ func TestAccountHandler_Create_AnthropicAPIKeyPassthroughExtraForwarded(t *testi
nil,
nil,
nil,
nil,
)
router := gin.New()
@@ -0,0 +1,162 @@
package admin
import (
"strconv"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type ollamaCloudUsageSessionRequest struct {
Session string `json:"session" binding:"required"`
}
type ollamaCloudUsageAutoRefreshRequest struct {
Enabled *bool `json:"enabled" binding:"required"`
}
func (h *AccountHandler) GetOllamaCloudUsageSettings(c *gin.Context) {
if h.ollamaCloudUsage == nil {
response.ErrorFrom(c, service.ErrOllamaCloudUsageUnavailable)
return
}
settings, err := h.ollamaCloudUsage.GetSettings(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, settings)
}
func (h *AccountHandler) UpdateOllamaCloudUsageSettings(c *gin.Context) {
if h.ollamaCloudUsage == nil {
response.ErrorFrom(c, service.ErrOllamaCloudUsageUnavailable)
return
}
var req service.OllamaCloudUsageSettings
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := h.ollamaCloudUsage.UpdateSettings(c.Request.Context(), &req); err != nil {
response.ErrorFrom(c, err)
return
}
settings, err := h.ollamaCloudUsage.GetSettings(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, settings)
}
func (h *AccountHandler) GetOllamaCloudUsage(c *gin.Context) {
if !h.requireOllamaCloudUsage(c) {
return
}
accountID, ok := ollamaCloudUsageAccountID(c)
if !ok {
return
}
state, err := h.ollamaCloudUsage.GetState(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) SaveOllamaCloudUsageSession(c *gin.Context) {
if !h.requireOllamaCloudUsage(c) {
return
}
accountID, ok := ollamaCloudUsageAccountID(c)
if !ok {
return
}
var req ollamaCloudUsageSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
state, err := h.ollamaCloudUsage.SaveSession(c.Request.Context(), accountID, req.Session)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) DeleteOllamaCloudUsageSession(c *gin.Context) {
if !h.requireOllamaCloudUsage(c) {
return
}
accountID, ok := ollamaCloudUsageAccountID(c)
if !ok {
return
}
state, err := h.ollamaCloudUsage.DeleteSession(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) SetOllamaCloudUsageAutoRefresh(c *gin.Context) {
if !h.requireOllamaCloudUsage(c) {
return
}
accountID, ok := ollamaCloudUsageAccountID(c)
if !ok {
return
}
var req ollamaCloudUsageAutoRefreshRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
state, err := h.ollamaCloudUsage.SetAutoRefresh(c.Request.Context(), accountID, *req.Enabled)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) RefreshOllamaCloudUsage(c *gin.Context) {
if !h.requireOllamaCloudUsage(c) {
return
}
accountID, ok := ollamaCloudUsageAccountID(c)
if !ok {
return
}
state, err := h.ollamaCloudUsage.Refresh(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) requireOllamaCloudUsage(c *gin.Context) bool {
if h != nil && h.ollamaCloudUsage != nil {
return true
}
response.ErrorFrom(c, service.ErrOllamaCloudUsageUnavailable)
return false
}
func ollamaCloudUsageAccountID(c *gin.Context) (int64, bool) {
if c == nil {
return 0, false
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || accountID <= 0 {
response.BadRequest(c, "Invalid account ID")
return 0, false
}
return accountID, true
}
@@ -0,0 +1,276 @@
package admin
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type ollamaCloudUsageHandlerTestRepo struct {
service.AccountRepository
account *service.Account
accounts []*service.Account
groupResolveCalls int
}
func (r *ollamaCloudUsageHandlerTestRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
if r.account != nil && r.account.ID == id {
return r.account, nil
}
for _, account := range r.accounts {
if account.ID == id {
return account, nil
}
}
return nil, service.ErrAccountNotFound
}
func (r *ollamaCloudUsageHandlerTestRepo) ListOllamaCloudUsageGroupAccounts(_ context.Context, _ []*service.Account) ([]service.Account, error) {
r.groupResolveCalls++
result := make([]service.Account, 0, len(r.accounts)+1)
if r.account != nil {
result = append(result, *r.account)
}
for _, account := range r.accounts {
result = append(result, *account)
}
return result, nil
}
func (r *ollamaCloudUsageHandlerTestRepo) SaveOllamaCloudUsageSession(context.Context, *service.Account, string, bool) error {
return nil
}
func (r *ollamaCloudUsageHandlerTestRepo) DeleteOllamaCloudUsageSession(context.Context, *service.Account) error {
return nil
}
func (r *ollamaCloudUsageHandlerTestRepo) SetOllamaCloudUsageAutoRefresh(context.Context, *service.Account, bool) error {
return nil
}
func (r *ollamaCloudUsageHandlerTestRepo) UpdateOllamaCloudUsageSnapshot(context.Context, *service.Account, *service.OllamaCloudUsageSnapshot) error {
return nil
}
func (r *ollamaCloudUsageHandlerTestRepo) DisableOllamaCloudUsageAutoRefresh(context.Context, *service.Account) error {
return nil
}
func (r *ollamaCloudUsageHandlerTestRepo) ListDueOllamaCloudUsageAccounts(context.Context, time.Time, int) ([]service.Account, error) {
return nil, nil
}
func newOllamaCloudUsageHandlerTestService(t *testing.T) *service.OllamaCloudUsageService {
t.Helper()
svc := service.NewOllamaCloudUsageService(nil, nil, nil, nil, false)
t.Cleanup(svc.Stop)
return svc
}
func newOllamaCloudUsageHandlerContext(method, target, body, id string) (*gin.Context, *httptest.ResponseRecorder) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(method, target, bytes.NewBufferString(body))
request.Header.Set("Content-Type", "application/json")
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = request
if id != "" {
ctx.Params = gin.Params{{Key: "id", Value: id}}
}
return ctx, recorder
}
func TestOllamaCloudUsageHandlersValidateRequestsAndDependencies(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := newOllamaCloudUsageHandlerTestService(t)
t.Run("invalid account id", func(t *testing.T) {
ctx, recorder := newOllamaCloudUsageHandlerContext(http.MethodGet, "/admin/accounts/not-an-id/ollama-cloud-usage", "", "not-an-id")
(&AccountHandler{ollamaCloudUsage: svc}).GetOllamaCloudUsage(ctx)
require.Equal(t, http.StatusBadRequest, recorder.Code)
})
t.Run("empty session", func(t *testing.T) {
ctx, recorder := newOllamaCloudUsageHandlerContext(http.MethodPut, "/admin/accounts/7/ollama-cloud-usage/session", `{"session":""}`, "7")
(&AccountHandler{ollamaCloudUsage: svc}).SaveOllamaCloudUsageSession(ctx)
require.Equal(t, http.StatusBadRequest, recorder.Code)
})
t.Run("missing enabled", func(t *testing.T) {
ctx, recorder := newOllamaCloudUsageHandlerContext(http.MethodPut, "/admin/accounts/7/ollama-cloud-usage/auto-refresh", `{}`, "7")
(&AccountHandler{ollamaCloudUsage: svc}).SetOllamaCloudUsageAutoRefresh(ctx)
require.Equal(t, http.StatusBadRequest, recorder.Code)
})
t.Run("service unavailable", func(t *testing.T) {
ctx, recorder := newOllamaCloudUsageHandlerContext(http.MethodGet, "/admin/accounts/7/ollama-cloud-usage", "", "7")
(&AccountHandler{}).GetOllamaCloudUsage(ctx)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Contains(t, recorder.Body.String(), "OLLAMA_CLOUD_USAGE_UNAVAILABLE")
})
}
func TestOllamaCloudUsageEncryptionKeyStateConsistentAcrossAccountResponses(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, configured := range []bool{false, true} {
t.Run("configured="+strconv.FormatBool(configured), func(t *testing.T) {
account := &service.Account{
ID: 7,
Name: "ollama",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Credentials: map[string]any{"base_url": "https://ollama.com", "api_key": "test-key"},
Extra: map[string]any{},
Status: service.StatusActive,
}
adminService := newStubAdminService()
adminService.accounts = []service.Account{*account}
adminService.getAccountResult = account
usageService := service.NewOllamaCloudUsageService(
&ollamaCloudUsageHandlerTestRepo{account: account}, nil, nil, nil, configured,
)
t.Cleanup(usageService.Stop)
handler := NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler.SetOllamaCloudUsageService(usageService)
router := gin.New()
router.GET("/accounts", handler.List)
router.GET("/accounts/:id", handler.GetByID)
router.GET("/accounts/:id/ollama-cloud-usage", handler.GetOllamaCloudUsage)
listRecorder := httptest.NewRecorder()
router.ServeHTTP(listRecorder, httptest.NewRequest(http.MethodGet, "/accounts?page=1&page_size=20", nil))
require.Equal(t, http.StatusOK, listRecorder.Code)
var listPayload struct {
Data struct {
Items []struct {
OllamaCloudUsage *service.OllamaCloudUsageState `json:"ollama_cloud_usage"`
} `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(listRecorder.Body.Bytes(), &listPayload))
require.Len(t, listPayload.Data.Items, 1)
require.NotNil(t, listPayload.Data.Items[0].OllamaCloudUsage)
detailRecorder := httptest.NewRecorder()
router.ServeHTTP(detailRecorder, httptest.NewRequest(http.MethodGet, "/accounts/7", nil))
require.Equal(t, http.StatusOK, detailRecorder.Code)
var detailPayload struct {
Data struct {
OllamaCloudUsage *service.OllamaCloudUsageState `json:"ollama_cloud_usage"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(detailRecorder.Body.Bytes(), &detailPayload))
require.NotNil(t, detailPayload.Data.OllamaCloudUsage)
stateRecorder := httptest.NewRecorder()
router.ServeHTTP(stateRecorder, httptest.NewRequest(http.MethodGet, "/accounts/7/ollama-cloud-usage", nil))
require.Equal(t, http.StatusOK, stateRecorder.Code)
var statePayload struct {
Data service.OllamaCloudUsageState `json:"data"`
}
require.NoError(t, json.Unmarshal(stateRecorder.Body.Bytes(), &statePayload))
listConfigured := listPayload.Data.Items[0].OllamaCloudUsage.EncryptionKeyConfigured
detailConfigured := detailPayload.Data.OllamaCloudUsage.EncryptionKeyConfigured
require.Equal(t, configured, listConfigured)
require.Equal(t, statePayload.Data.EncryptionKeyConfigured, listConfigured)
require.Equal(t, statePayload.Data.EncryptionKeyConfigured, detailConfigured)
})
}
}
func TestOllamaCloudUsageSharedStateMatchesListDetailAndSpecialEndpointWithoutListNPlusOne(t *testing.T) {
gin.SetMode(gin.TestMode)
now := time.Now().UTC()
source := &service.Account{
ID: 7, Name: "source", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Credentials: map[string]any{"base_url": "https://ollama.com", "api_key": "shared-secret-key"},
Extra: map[string]any{
service.OllamaCloudUsageSessionExtraKey: "ciphertext-secret",
service.OllamaCloudUsageAutoRefreshExtraKey: true,
service.OllamaCloudUsageSnapshotExtraKey: &service.OllamaCloudUsageSnapshot{
Status: service.OllamaCloudUsageStatusOK, Data: &service.OllamaCloudUsageData{Plan: "pro"},
LastAttemptAt: now, NextRefreshAt: now.Add(time.Hour),
},
},
Status: service.StatusActive,
}
sibling := &service.Account{
ID: 8, Name: "sibling", Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Credentials: map[string]any{"base_url": "HTTPS://WWW.OLLAMA.COM:443/v1", "api_key": "shared-secret-key"},
Extra: map[string]any{}, Status: service.StatusActive,
}
repo := &ollamaCloudUsageHandlerTestRepo{accounts: []*service.Account{source, sibling}}
adminService := newStubAdminService()
adminService.accounts = []service.Account{*source, *sibling}
adminService.getAccountResult = sibling
usageService := service.NewOllamaCloudUsageService(repo, nil, nil, nil, true)
t.Cleanup(usageService.Stop)
handler := NewAccountHandler(adminService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler.SetOllamaCloudUsageService(usageService)
router := gin.New()
router.GET("/accounts", handler.List)
router.GET("/accounts/:id", handler.GetByID)
router.GET("/accounts/:id/ollama-cloud-usage", handler.GetOllamaCloudUsage)
listRecorder := httptest.NewRecorder()
router.ServeHTTP(listRecorder, httptest.NewRequest(http.MethodGet, "/accounts?page=1&page_size=20", nil))
require.Equal(t, http.StatusOK, listRecorder.Code)
require.Equal(t, 1, repo.groupResolveCalls, "the full list page must use one group-resolution batch")
var listPayload struct {
Data struct {
Items []struct {
ID int64 `json:"id"`
OllamaCloudUsage *service.OllamaCloudUsageState `json:"ollama_cloud_usage"`
} `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(listRecorder.Body.Bytes(), &listPayload))
require.Len(t, listPayload.Data.Items, 2)
for _, item := range listPayload.Data.Items {
require.True(t, item.OllamaCloudUsage.Configured)
require.Equal(t, "pro", item.OllamaCloudUsage.Snapshot.Data.Plan)
}
detailRecorder := httptest.NewRecorder()
router.ServeHTTP(detailRecorder, httptest.NewRequest(http.MethodGet, "/accounts/8", nil))
require.Equal(t, http.StatusOK, detailRecorder.Code)
var detailPayload struct {
Data struct {
OllamaCloudUsage *service.OllamaCloudUsageState `json:"ollama_cloud_usage"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(detailRecorder.Body.Bytes(), &detailPayload))
stateRecorder := httptest.NewRecorder()
router.ServeHTTP(stateRecorder, httptest.NewRequest(http.MethodGet, "/accounts/8/ollama-cloud-usage", nil))
require.Equal(t, http.StatusOK, stateRecorder.Code)
var statePayload struct {
Data service.OllamaCloudUsageState `json:"data"`
}
require.NoError(t, json.Unmarshal(stateRecorder.Body.Bytes(), &statePayload))
require.Equal(t, statePayload.Data.Configured, detailPayload.Data.OllamaCloudUsage.Configured)
require.Equal(t, statePayload.Data.Snapshot, detailPayload.Data.OllamaCloudUsage.Snapshot)
for _, body := range []string{listRecorder.Body.String(), detailRecorder.Body.String(), stateRecorder.Body.String()} {
require.NotContains(t, body, "shared-secret-key")
require.NotContains(t, body, "ciphertext-secret")
}
}
func TestGetOllamaCloudUsageSettingsHandlerSuccess(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx, recorder := newOllamaCloudUsageHandlerContext(http.MethodGet, "/admin/accounts/ollama-cloud-usage/settings", "", "")
handler := &AccountHandler{ollamaCloudUsage: newOllamaCloudUsageHandlerTestService(t)}
handler.GetOllamaCloudUsageSettings(ctx)
require.Equal(t, http.StatusOK, recorder.Code)
require.Contains(t, recorder.Body.String(), `"enabled":false`)
require.Contains(t, recorder.Body.String(), `"interval_minutes":60`)
}
@@ -0,0 +1,122 @@
package admin
import (
"strconv"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type upstreamBillingProbeEnabledRequest struct {
Enabled *bool `json:"enabled" binding:"required"`
}
type upstreamBillingProbeBatchRequest struct {
AccountIDs []int64 `json:"account_ids" binding:"required"`
}
func (h *AccountHandler) GetUpstreamBillingProbeSettings(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
return
}
settings, err := h.upstreamBillingProbe.GetSettings(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, settings)
}
func (h *AccountHandler) UpdateUpstreamBillingProbeSettings(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
return
}
var req service.UpstreamBillingProbeSettings
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := h.upstreamBillingProbe.UpdateSettings(c.Request.Context(), &req); err != nil {
response.ErrorFrom(c, err)
return
}
settings, err := h.upstreamBillingProbe.GetSettings(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, settings)
}
func (h *AccountHandler) SetUpstreamBillingProbeEnabled(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
return
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || accountID <= 0 {
response.BadRequest(c, "Invalid account ID")
return
}
var req upstreamBillingProbeEnabledRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := h.upstreamBillingProbe.SetAccountEnabled(c.Request.Context(), accountID, *req.Enabled); err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, gin.H{"account_id": accountID, "enabled": *req.Enabled})
}
func (h *AccountHandler) ProbeUpstreamBilling(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
return
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || accountID <= 0 {
response.BadRequest(c, "Invalid account ID")
return
}
snapshot, err := h.upstreamBillingProbe.ProbeAccount(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, service.UpstreamBillingProbeResult{AccountID: accountID, Snapshot: snapshot})
}
func (h *AccountHandler) ProbeUpstreamBillingBatch(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
return
}
var req upstreamBillingProbeBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if len(req.AccountIDs) == 0 || len(req.AccountIDs) > service.UpstreamBillingProbeMaxBatchSize {
response.BadRequest(c, "account_ids must contain between 1 and 20 items")
return
}
seen := make(map[int64]struct{}, len(req.AccountIDs))
accountIDs := make([]int64, 0, len(req.AccountIDs))
for _, accountID := range req.AccountIDs {
if accountID <= 0 {
response.BadRequest(c, "account_ids must contain positive IDs")
return
}
if _, exists := seen[accountID]; exists {
continue
}
seen[accountID] = struct{}{}
accountIDs = append(accountIDs, accountID)
}
response.Success(c, gin.H{"results": h.upstreamBillingProbe.ProbeAccounts(c.Request.Context(), accountIDs)})
}
@@ -0,0 +1,71 @@
package admin
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func setupUpstreamBillingProbeRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
handler := NewAccountHandler(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler.SetUpstreamBillingProbeService(service.NewUpstreamBillingProbeService(nil, nil, nil))
router := gin.New()
router.GET("/admin/accounts/upstream-billing-probe/settings", handler.GetUpstreamBillingProbeSettings)
router.POST("/admin/accounts/upstream-billing-probe/batch", handler.ProbeUpstreamBillingBatch)
router.PUT("/admin/accounts/:id/upstream-billing-probe", handler.SetUpstreamBillingProbeEnabled)
return router
}
func TestAccountHandlerGetUpstreamBillingProbeSettingsReturnsDefaults(t *testing.T) {
router := setupUpstreamBillingProbeRouter()
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/admin/accounts/upstream-billing-probe/settings", nil))
require.Equal(t, http.StatusOK, recorder.Code)
var response struct {
Data service.UpstreamBillingProbeSettings `json:"data"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &response))
require.True(t, response.Data.Enabled)
require.Equal(t, 30, response.Data.IntervalMinutes)
}
func TestAccountHandlerProbeUpstreamBillingBatchValidatesIDs(t *testing.T) {
router := setupUpstreamBillingProbeRouter()
for _, body := range []string{`{"account_ids":[]}`, `{"account_ids":[0]}`} {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/admin/accounts/upstream-billing-probe/batch", bytes.NewBufferString(body))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
}
}
func TestAccountHandlerSetUpstreamBillingProbeEnabledRejectsInvalidID(t *testing.T) {
router := setupUpstreamBillingProbeRouter()
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/admin/accounts/not-an-id/upstream-billing-probe", bytes.NewBufferString(`{"enabled":true}`))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
}
func TestAccountHandlerSetUpstreamBillingProbeEnabledRequiresValue(t *testing.T) {
router := setupUpstreamBillingProbeRouter()
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/admin/accounts/1/upstream-billing-probe", bytes.NewBufferString(`{}`))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
}
@@ -16,7 +16,7 @@ func setupAdminRouter() (*gin.Engine, *stubAdminService) {
router := gin.New()
adminSvc := newStubAdminService()
userHandler := NewUserHandler(adminSvc, nil, nil, nil)
userHandler := NewUserHandler(adminSvc, nil, nil, nil, nil, nil, nil)
groupHandler := NewGroupHandler(adminSvc, nil, nil)
proxyHandler := NewProxyHandler(adminSvc)
redeemHandler := NewRedeemHandler(adminSvc, nil)
@@ -34,6 +34,11 @@ func setupAdminRouter() (*gin.Engine, *stubAdminService) {
router.GET("/api/v1/admin/groups", groupHandler.List)
router.GET("/api/v1/admin/groups/all", groupHandler.GetAll)
router.GET("/api/v1/admin/groups/:id/models-list-candidates", groupHandler.GetModelsListCandidates)
router.GET("/api/v1/admin/groups/:id/composite-routes", groupHandler.ListCompositeRoutes)
router.POST("/api/v1/admin/groups/:id/composite-routes", groupHandler.CreateCompositeRoute)
router.POST("/api/v1/admin/groups/:id/composite-routes/preview", groupHandler.PreviewCompositeRoute)
router.PUT("/api/v1/admin/groups/:id/composite-routes/:route_id", groupHandler.UpdateCompositeRoute)
router.DELETE("/api/v1/admin/groups/:id/composite-routes/:route_id", groupHandler.DeleteCompositeRoute)
router.GET("/api/v1/admin/groups/:id", groupHandler.GetByID)
router.POST("/api/v1/admin/groups", groupHandler.Create)
router.PUT("/api/v1/admin/groups/:id", groupHandler.Update)
@@ -184,7 +189,54 @@ func TestGroupHandlerEndpoints(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), "gpt-5.5")
body, _ := json.Marshal(map[string]any{"name": "new", "platform": "anthropic", "subscription_type": "standard"})
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/v1/admin/groups/2/composite-routes", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), "openrouter/gpt-5")
body, _ := json.Marshal(map[string]any{
"public_model": "openrouter/gpt-5",
"match_type": "exact",
"target_platform": "openai",
"upstream_model": "gpt-5",
"endpoint": "chat_completions",
"enabled": true,
})
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups/2/composite-routes", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusCreated, rec.Code)
require.Contains(t, rec.Body.String(), "gpt-5")
body, _ = json.Marshal(map[string]any{
"public_model": "openrouter/gpt-5",
"target_platform": "openai",
"upstream_model": "gpt-5",
"endpoint": "responses",
"enabled": true,
})
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPut, "/api/v1/admin/groups/2/composite-routes/1", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
body, _ = json.Marshal(map[string]any{"model": "gpt-5", "endpoint": "responses"})
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups/2/composite-routes/preview", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), `"source":"detector"`)
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodDelete, "/api/v1/admin/groups/2/composite-routes/1", nil)
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
body, _ = json.Marshal(map[string]any{"name": "new", "platform": "anthropic", "subscription_type": "standard"})
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -33,6 +33,10 @@ type stubAdminService struct {
createSparkShadowErr error
updateAccountErr error
bulkUpdateAccountErr error
lastBulkUpdateAccountInput *service.BulkUpdateAccountsInput
getAccountResult *service.Account
updateAccountCalls int
updateAccountExtraCalls int
checkMixedErr error
lastMixedCheck struct {
accountID int64
@@ -192,6 +196,10 @@ func (s *stubAdminService) BatchUpdateConcurrency(ctx context.Context, userIDs [
return len(userIDs), nil
}
func (s *stubAdminService) BatchUpdateLimits(ctx context.Context, userIDs []int64, concurrency, rpmLimit *int) (int, error) {
return len(userIDs), nil
}
func (s *stubAdminService) GetUserAPIKeys(ctx context.Context, userID int64, page, pageSize int, sortBy, sortOrder string) ([]service.APIKey, int64, error) {
return s.apiKeys, int64(len(s.apiKeys)), nil
}
@@ -285,11 +293,78 @@ func (s *stubAdminService) GetGroupModelsListCandidates(ctx context.Context, id
return []string{"claude-sonnet-4-6"}, nil
}
func (s *stubAdminService) ListCompositeRoutes(ctx context.Context, groupID int64) ([]service.CompositeModelRoute, error) {
return []service.CompositeModelRoute{
{
ID: 1,
GroupID: groupID,
PublicModel: "openrouter/gpt-5",
MatchType: service.CompositeRouteMatchExact,
TargetPlatform: service.PlatformOpenAI,
UpstreamModel: "gpt-5",
Endpoint: service.CompositeRouteEndpointAny,
Priority: 100,
Enabled: true,
},
}, nil
}
func (s *stubAdminService) CreateCompositeRoute(ctx context.Context, groupID int64, input service.CompositeRouteInput) (*service.CompositeModelRoute, error) {
return &service.CompositeModelRoute{
ID: 1,
GroupID: groupID,
PublicModel: input.PublicModel,
MatchType: input.MatchType,
TargetPlatform: input.TargetPlatform,
UpstreamModel: input.UpstreamModel,
Endpoint: input.Endpoint,
Priority: input.Priority,
Enabled: input.Enabled,
Notes: input.Notes,
}, nil
}
func (s *stubAdminService) UpdateCompositeRoute(ctx context.Context, groupID, routeID int64, input service.CompositeRouteInput) (*service.CompositeModelRoute, error) {
return &service.CompositeModelRoute{
ID: routeID,
GroupID: groupID,
PublicModel: input.PublicModel,
MatchType: input.MatchType,
TargetPlatform: input.TargetPlatform,
UpstreamModel: input.UpstreamModel,
Endpoint: input.Endpoint,
Priority: input.Priority,
Enabled: input.Enabled,
Notes: input.Notes,
}, nil
}
func (s *stubAdminService) DeleteCompositeRoute(ctx context.Context, groupID, routeID int64) error {
return nil
}
func (s *stubAdminService) PreviewCompositeRoute(ctx context.Context, groupID int64, input service.CompositeRoutePreviewRequest) (*service.CompositeRouteDecision, error) {
decision, err := service.NewCompositeRouteResolver(nil).Resolve(ctx, groupID, input.Model, input.Endpoint)
if err != nil {
return nil, err
}
return &decision, nil
}
func (s *stubAdminService) CreateGroup(ctx context.Context, input *service.CreateGroupInput) (*service.Group, error) {
group := service.Group{ID: 200, Name: input.Name, Status: service.StatusActive}
return &group, nil
}
func (s *stubAdminService) DuplicateGroup(ctx context.Context, id int64, actorScope, operationKey string) (*service.Group, error) {
group := service.Group{ID: 201, Name: "group (Copy)", Status: "inactive"}
return &group, nil
}
func (s *stubAdminService) RecoverDuplicateGroup(ctx context.Context, id int64, actorScope, operationKey string) (*service.Group, error) {
return nil, nil
}
func (s *stubAdminService) UpdateGroup(ctx context.Context, id int64, input *service.UpdateGroupInput) (*service.Group, error) {
group := service.Group{ID: id, Name: input.Name, Status: service.StatusActive}
return &group, nil
@@ -388,6 +463,9 @@ func (s *stubAdminService) ListOpenAISchedulableAccountsForSchedulerScore(_ cont
}
func (s *stubAdminService) GetAccount(ctx context.Context, id int64) (*service.Account, error) {
if s.getAccountResult != nil {
return s.getAccountResult, nil
}
account := service.Account{ID: id, Name: "account", Status: service.StatusActive}
return &account, nil
}
@@ -412,7 +490,17 @@ func (s *stubAdminService) CreateAccount(ctx context.Context, input *service.Cre
return &account, nil
}
func (s *stubAdminService) DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*service.Account, error) {
account := service.Account{ID: 301, Name: "account (Copy)", Status: service.StatusActive, Schedulable: false}
return &account, nil
}
func (s *stubAdminService) RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*service.Account, error) {
return nil, nil
}
func (s *stubAdminService) UpdateAccount(ctx context.Context, id int64, input *service.UpdateAccountInput) (*service.Account, error) {
s.updateAccountCalls++
if s.updateAccountErr != nil {
return nil, s.updateAccountErr
}
@@ -421,6 +509,7 @@ func (s *stubAdminService) UpdateAccount(ctx context.Context, id int64, input *s
}
func (s *stubAdminService) UpdateAccountExtra(ctx context.Context, id int64, updates map[string]any) error {
s.updateAccountExtraCalls++
return nil
}
@@ -448,6 +537,7 @@ func (s *stubAdminService) SetAccountSchedulable(ctx context.Context, id int64,
}
func (s *stubAdminService) BulkUpdateAccounts(ctx context.Context, input *service.BulkUpdateAccountsInput) (*service.BulkUpdateAccountsResult, error) {
s.lastBulkUpdateAccountInput = input
if s.bulkUpdateAccountErr != nil {
return nil, s.bulkUpdateAccountErr
}
@@ -0,0 +1,169 @@
package admin
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// AuditLogHandler 操作审计日志管理接口。
// 审计日志仅管理员可见;不提供单条删除,仅支持带 TOTP 验证的全量清空。
type AuditLogHandler struct {
auditService *service.AuditLogService
totpService *service.TotpService
}
// NewAuditLogHandler 创建审计日志处理器。
func NewAuditLogHandler(auditService *service.AuditLogService, totpService *service.TotpService) *AuditLogHandler {
return &AuditLogHandler{
auditService: auditService,
totpService: totpService,
}
}
// List 分页查询审计日志。
// GET /api/v1/admin/audit-logs
func (h *AuditLogHandler) List(c *gin.Context) {
page, pageSize := response.ParsePagination(c)
if pageSize > 200 {
pageSize = 200
}
filter := &service.AuditLogFilter{
Page: page,
PageSize: pageSize,
ActorEmail: strings.TrimSpace(c.Query("actor_email")),
AuthMethod: strings.TrimSpace(c.Query("auth_method")),
Action: strings.TrimSpace(c.Query("action")),
Method: strings.TrimSpace(c.Query("method")),
ClientIP: strings.TrimSpace(c.Query("client_ip")),
Query: strings.TrimSpace(c.Query("q")),
}
if v := strings.TrimSpace(c.Query("actor_user_id")); v != "" {
id, err := strconv.ParseInt(v, 10, 64)
if err != nil || id <= 0 {
response.BadRequest(c, "Invalid actor_user_id")
return
}
filter.ActorUserID = &id
}
if v := strings.TrimSpace(c.Query("start_time")); v != "" {
t, err := time.Parse(time.RFC3339, v)
if err != nil {
response.BadRequest(c, "Invalid start_time, expect RFC3339")
return
}
filter.StartTime = &t
}
if v := strings.TrimSpace(c.Query("end_time")); v != "" {
t, err := time.Parse(time.RFC3339, v)
if err != nil {
response.BadRequest(c, "Invalid end_time, expect RFC3339")
return
}
filter.EndTime = &t
}
if v := strings.TrimSpace(c.Query("success")); v != "" {
success := v == "true"
filter.Success = &success
}
result, err := h.auditService.List(c.Request.Context(), filter)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Paginated(c, result.Logs, int64(result.Total), result.Page, result.PageSize)
}
// Get 查询单条审计日志详情(含脱敏后的请求体)。
// GET /api/v1/admin/audit-logs/:id
func (h *AuditLogHandler) Get(c *gin.Context) {
id, err := strconv.ParseInt(strings.TrimSpace(c.Param("id")), 10, 64)
if err != nil || id <= 0 {
response.BadRequest(c, "Invalid audit log id")
return
}
item, err := h.auditService.GetByID(c.Request.Context(), id)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, item)
}
type auditLogClearRequest struct {
TotpCode string `json:"totp_code" binding:"required"`
}
// Clear 全量清空审计日志。
// POST /api/v1/admin/audit-logs/clear
//
// 安全要求(与需求对齐):
// 1. 每次清空都必须现场验证 TOTP 码(不复用 step-up sudo 窗口)
// 2. 未启用 TOTP 的管理员不允许清空
// 3. admin API key(机器凭证)不允许清空
// 4. 清空完成后同步写入一条留痕记录(操作者、IP、UA、删除行数)
func (h *AuditLogHandler) Clear(c *gin.Context) {
if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey {
response.ErrorWithDetails(c, http.StatusForbidden,
"Admin API key cannot clear audit logs; a two-factor verified admin session is required",
"STEP_UP_ADMIN_API_KEY_FORBIDDEN", nil)
return
}
subject, ok := middleware.GetAuthSubjectFromContext(c)
if !ok || subject.UserID <= 0 {
response.Unauthorized(c, "Unauthorized")
return
}
var req auditLogClearRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWithDetails(c, http.StatusBadRequest,
"TOTP code is required to clear audit logs", "TOTP_CODE_REQUIRED", nil)
return
}
// 校验 TOTP:未启用(ErrTotpNotSetup)、码错误、尝试过多均在此拦截。
if err := h.totpService.VerifyCode(c.Request.Context(), subject.UserID, strings.TrimSpace(req.TotpCode)); err != nil {
response.ErrorFrom(c, err)
return
}
uid := subject.UserID
role, _ := middleware.GetUserRoleFromContext(c)
trace := &service.AuditLog{
ActorUserID: &uid,
ActorEmail: c.GetString(middleware.ContextKeyAuthEmail),
ActorRole: role,
AuthMethod: c.GetString("auth_method"),
CredentialMasked: middleware.MaskedRequestCredential(c),
Method: http.MethodPost,
Path: c.FullPath(),
ClientIP: middleware.SecurityClientIP(c),
UserAgent: c.Request.UserAgent(),
StatusCode: http.StatusOK,
}
if requestID := c.Writer.Header().Get("X-Request-ID"); requestID != "" {
trace.RequestID = requestID
}
deleted, err := h.auditService.ClearAll(c.Request.Context(), trace)
if err != nil {
response.ErrorFrom(c, err)
return
}
// 留痕记录已同步落库,跳过异步审计中间件的重复记录。
middleware.SkipAudit(c)
response.Success(c, gin.H{"deleted": deleted})
}
@@ -10,12 +10,14 @@ import (
type BackupHandler struct {
backupService *service.BackupService
userService *service.UserService
imageStorage *service.ImageStorageSettingService
}
func NewBackupHandler(backupService *service.BackupService, userService *service.UserService) *BackupHandler {
func NewBackupHandler(backupService *service.BackupService, userService *service.UserService, imageStorage *service.ImageStorageSettingService) *BackupHandler {
return &BackupHandler{
backupService: backupService,
userService: userService,
imageStorage: imageStorage,
}
}
@@ -203,3 +205,48 @@ func (h *BackupHandler) RestoreBackup(c *gin.Context) {
}
response.Accepted(c, record)
}
// ─── 异步生图对象存储配置 ───
//
// 与备份共用一套 S3 客户端构造,因此放在同一个页面下:勾选"复用备份 S3"即可直接
// 借用备份已配置的端点与密钥,只用不同的前缀区分对象(备份走 backups/,图片走 images/)。
func (h *BackupHandler) GetImageStorageConfig(c *gin.Context) {
ctx := c.Request.Context()
cfg, err := h.imageStorage.Get(ctx)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, gin.H{
"config": cfg,
"secret_configured": h.imageStorage.SecretConfigured(ctx),
})
}
func (h *BackupHandler) UpdateImageStorageConfig(c *gin.Context) {
var req service.ImageStorageSettings
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
cfg, err := h.imageStorage.Update(c.Request.Context(), req)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, cfg)
}
func (h *BackupHandler) TestImageStorageConnection(c *gin.Context) {
var req service.ImageStorageSettings
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := h.imageStorage.TestConnection(c.Request.Context(), req); err != nil {
response.Success(c, gin.H{"ok": false, "message": err.Error()})
return
}
response.Success(c, gin.H{"ok": true, "message": "connection successful"})
}
@@ -36,7 +36,7 @@ func (f *failingAdminService) UpdateAccount(ctx context.Context, id int64, input
func setupAccountHandlerWithService(adminSvc service.AdminService) (*gin.Engine, *AccountHandler) {
gin.SetMode(gin.TestMode)
router := gin.New()
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router.POST("/api/v1/admin/accounts/batch-update-credentials", handler.BatchUpdateCredentials)
return router, handler
}
@@ -64,6 +64,7 @@ type channelModelPricingRequest struct {
OutputPrice *float64 `json:"output_price" binding:"omitempty,min=0"`
CacheWritePrice *float64 `json:"cache_write_price" binding:"omitempty,min=0"`
CacheReadPrice *float64 `json:"cache_read_price" binding:"omitempty,min=0"`
ImageInputPrice *float64 `json:"image_input_price" binding:"omitempty,min=0"`
ImageOutputPrice *float64 `json:"image_output_price" binding:"omitempty,min=0"`
PerRequestPrice *float64 `json:"per_request_price" binding:"omitempty,min=0"`
Intervals []pricingIntervalRequest `json:"intervals"`
@@ -115,6 +116,7 @@ type channelModelPricingResponse struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
ImageInputPrice *float64 `json:"image_input_price"`
ImageOutputPrice *float64 `json:"image_output_price"`
PerRequestPrice *float64 `json:"per_request_price"`
Intervals []pricingIntervalResponse `json:"intervals"`
@@ -222,6 +224,7 @@ func pricingToResponse(p *service.ChannelModelPricing) channelModelPricingRespon
OutputPrice: p.OutputPrice,
CacheWritePrice: p.CacheWritePrice,
CacheReadPrice: p.CacheReadPrice,
ImageInputPrice: p.ImageInputPrice,
ImageOutputPrice: p.ImageOutputPrice,
PerRequestPrice: p.PerRequestPrice,
Intervals: intervals,
@@ -273,6 +276,7 @@ func pricingRequestToService(reqs []channelModelPricingRequest) []service.Channe
OutputPrice: r.OutputPrice,
CacheWritePrice: r.CacheWritePrice,
CacheReadPrice: r.CacheReadPrice,
ImageInputPrice: r.ImageInputPrice,
ImageOutputPrice: r.ImageOutputPrice,
PerRequestPrice: r.PerRequestPrice,
Intervals: intervals,
@@ -498,6 +502,7 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
"output_price": pricing.OutputPricePerToken,
"cache_write_price": pricing.CacheCreationPricePerToken,
"cache_read_price": pricing.CacheReadPricePerToken,
"image_input_price": pricing.ImageInputPricePerToken,
"image_output_price": pricing.ImageOutputPricePerToken,
})
}
@@ -0,0 +1,170 @@
//go:build unit
package admin
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type duplicateChannelMonitorHandlerRepoStub struct {
service.ChannelMonitorRepository
source *service.ChannelMonitor
byOperation map[string]*service.ChannelMonitor
createCalls int
}
func (r *duplicateChannelMonitorHandlerRepoStub) GetByID(_ context.Context, id int64) (*service.ChannelMonitor, error) {
if r.source == nil || r.source.ID != id {
return nil, service.ErrChannelMonitorNotFound
}
return r.source, nil
}
func (r *duplicateChannelMonitorHandlerRepoStub) Create(_ context.Context, monitor *service.ChannelMonitor) error {
r.createCalls++
monitor.ID = int64(100 + r.createCalls)
stored := *monitor
if stored.DuplicateOperationID != "" {
if r.byOperation == nil {
r.byOperation = make(map[string]*service.ChannelMonitor)
}
r.byOperation[stored.DuplicateOperationID] = &stored
}
return nil
}
func (r *duplicateChannelMonitorHandlerRepoStub) FindByDuplicateOperationID(_ context.Context, operationID string) (*service.ChannelMonitor, error) {
monitor := r.byOperation[operationID]
if monitor == nil {
return nil, nil
}
cloned := *monitor
return &cloned, nil
}
type duplicateChannelMonitorHandlerEncryptor struct{}
func (duplicateChannelMonitorHandlerEncryptor) Encrypt(plaintext string) (string, error) {
return "ENC:" + plaintext, nil
}
func (duplicateChannelMonitorHandlerEncryptor) Decrypt(ciphertext string) (string, error) {
return strings.TrimPrefix(ciphertext, "ENC:"), nil
}
func setupDuplicateChannelMonitorRouter(t *testing.T) (*gin.Engine, *duplicateChannelMonitorHandlerRepoStub) {
t.Helper()
previousCoordinator := service.DefaultIdempotencyCoordinator()
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(
newMemoryIdempotencyRepoStub(),
service.DefaultIdempotencyConfig(),
))
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previousCoordinator) })
repo := &duplicateChannelMonitorHandlerRepoStub{
source: &service.ChannelMonitor{
ID: 42,
Name: "primary",
Provider: service.MonitorProviderOpenAI,
APIMode: service.MonitorAPIModeResponses,
Endpoint: "https://api.example.com",
APIKey: "ENC:top-secret",
PrimaryModel: "gpt-5.4-mini",
ExtraModels: []string{"gpt-5.4"},
Enabled: true,
IntervalSeconds: 60,
BodyOverrideMode: service.MonitorBodyOverrideModeOff,
},
}
monitorService := service.NewChannelMonitorService(repo, duplicateChannelMonitorHandlerEncryptor{})
handler := NewChannelMonitorHandler(monitorService)
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 77})
c.Next()
})
router.POST("/api/v1/admin/channel-monitors/:id/duplicate", handler.Duplicate)
return router, repo
}
func TestDuplicateChannelMonitorHandlerRedactsKeyAndReplaysRetry(t *testing.T) {
router, repo := setupDuplicateChannelMonitorRouter(t)
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/channel-monitors/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-channel-monitor-42")
first := httptest.NewRecorder()
router.ServeHTTP(first, request)
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, 1, repo.createCalls)
require.Contains(t, first.Body.String(), `"name":"primary (Copy)"`)
require.Contains(t, first.Body.String(), `"api_key_masked":"top-***"`)
require.Contains(t, first.Body.String(), `"created_by":77`)
require.Contains(t, first.Body.String(), `"enabled":false`)
require.NotContains(t, first.Body.String(), "top-secret")
retryRequest := httptest.NewRequest(http.MethodPost, "/api/v1/admin/channel-monitors/42/duplicate", nil)
retryRequest.Header.Set("Idempotency-Key", "duplicate-channel-monitor-42")
retry := httptest.NewRecorder()
router.ServeHTTP(retry, retryRequest)
require.Equal(t, http.StatusOK, retry.Code)
require.Equal(t, "true", retry.Header().Get("X-Idempotency-Replayed"))
require.Equal(t, 1, repo.createCalls)
require.JSONEq(t, first.Body.String(), retry.Body.String())
}
func TestDuplicateChannelMonitorHandlerRejectsInvalidID(t *testing.T) {
router, repo := setupDuplicateChannelMonitorRouter(t)
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/channel-monitors/not-a-number/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-channel-monitor-invalid")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.Zero(t, repo.createCalls)
}
func TestDuplicateChannelMonitorHandlerRecoversAfterMarkSucceededFailure(t *testing.T) {
router, repo := setupDuplicateChannelMonitorRouter(t)
idempotencyRepo := &failOnceMarkSucceededRepo{
memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(),
failNext: true,
}
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(
idempotencyRepo,
service.DefaultIdempotencyConfig(),
))
call := func() *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/channel-monitors/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-channel-monitor-recovery")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, "true", first.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, "true", second.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, 1, repo.createCalls, "ambiguous retries must not repeat the create side effect")
require.Contains(t, second.Body.String(), `"id":101`)
require.Contains(t, second.Body.String(), `"api_key_masked":"top-***"`)
require.NotContains(t, second.Body.String(), "top-secret")
}
@@ -1,6 +1,8 @@
package admin
import (
"context"
"log/slog"
"strconv"
"strings"
"time"
@@ -37,11 +39,11 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch
type channelMonitorCreateRequest struct {
Name string `json:"name" binding:"required,max=100"`
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini"`
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"`
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
Endpoint string `json:"endpoint" binding:"required,max=500"`
APIKey string `json:"api_key" binding:"required,max=2000"`
PrimaryModel string `json:"primary_model" binding:"required,max=200"`
PrimaryModel string `json:"primary_model" binding:"max=200"`
ExtraModels []string `json:"extra_models"`
GroupName string `json:"group_name" binding:"max=100"`
Enabled *bool `json:"enabled"`
@@ -55,7 +57,7 @@ type channelMonitorCreateRequest struct {
type channelMonitorUpdateRequest struct {
Name *string `json:"name" binding:"omitempty,max=100"`
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini"`
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok"`
APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
Endpoint *string `json:"endpoint" binding:"omitempty,max=500"`
APIKey *string `json:"api_key" binding:"omitempty,max=2000"`
@@ -333,6 +335,63 @@ func (h *ChannelMonitorHandler) Create(c *gin.Context) {
response.Created(c, channelMonitorToResponse(m))
}
// Duplicate POST /api/v1/admin/channel-monitors/:id/duplicate
func (h *ChannelMonitorHandler) Duplicate(c *gin.Context) {
id, ok := ParseChannelMonitorID(c)
if !ok {
return
}
subject, _ := middleware2.GetAuthSubjectFromContext(c)
actorScope := adminActorScope(c)
result, err := executeAdminIdempotent(
c,
"admin.channel_monitors.duplicate",
struct {
MonitorID int64 `json:"monitor_id"`
}{MonitorID: id},
service.DefaultWriteIdempotencyTTL(),
func(ctx context.Context) (any, error) {
monitor, err := h.monitorService.Duplicate(
ctx,
id,
subject.UserID,
actorScope,
c.GetHeader("Idempotency-Key"),
)
if err != nil {
return nil, err
}
return channelMonitorToResponse(monitor), nil
},
)
if err != nil {
reason := infraerrors.Reason(err)
if reason == infraerrors.Reason(service.ErrIdempotencyInProgress) || reason == infraerrors.Reason(service.ErrIdempotencyStoreUnavail) {
recovered, recoverErr := h.monitorService.RecoverDuplicate(
c.Request.Context(),
id,
actorScope,
c.GetHeader("Idempotency-Key"),
)
if recoverErr != nil {
slog.Warn("channel_monitor_duplicate_recovery_failed", "monitor_id", id, "actor_scope", actorScope, "reason", reason, "error", recoverErr)
} else if recovered != nil {
c.Header("X-Idempotency-Recovered", "true")
response.Success(c, channelMonitorToResponse(recovered))
return
}
}
response.ErrorFrom(c, err)
return
}
if result != nil && result.Replayed {
c.Header("X-Idempotency-Replayed", "true")
}
response.Success(c, result.Data)
}
// Update PUT /api/v1/admin/channel-monitors/:id
func (h *ChannelMonitorHandler) Update(c *gin.Context) {
id, ok := ParseChannelMonitorID(c)
@@ -26,7 +26,7 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon
type channelMonitorTemplateCreateRequest struct {
Name string `json:"name" binding:"required,max=100"`
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini"`
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"`
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
Description string `json:"description" binding:"max=500"`
ExtraHeaders map[string]string `json:"extra_headers"`
@@ -0,0 +1,205 @@
package admin
import (
"context"
"log/slog"
"sync"
"time"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/service"
)
const (
grokImportProbeConcurrency = 3
grokImportProbeTimeout = 25 * time.Second
)
type grokImportProber interface {
QueryQuota(ctx context.Context, accountID int64) (*service.GrokQuotaProbeResult, error)
}
type grokImportProbeTask struct {
prober grokImportProber
accountID int64
}
type grokImportProbeScheduler struct {
mu sync.Mutex
queue []grokImportProbeTask
concurrency int
workers int
maxWorkers int
timeout time.Duration
}
var defaultGrokImportProbeScheduler = newGrokImportProbeScheduler(
grokImportProbeConcurrency,
grokImportProbeTimeout,
)
func newGrokImportProbeScheduler(concurrency int, timeout time.Duration) *grokImportProbeScheduler {
if concurrency <= 0 {
concurrency = 1
}
if timeout <= 0 {
timeout = grokImportProbeTimeout
}
return &grokImportProbeScheduler{
concurrency: concurrency,
timeout: timeout,
}
}
func (s *grokImportProbeScheduler) schedule(prober grokImportProber, account *service.Account) {
if s == nil || prober == nil || account == nil || account.ID <= 0 {
return
}
if account.Platform != service.PlatformGrok || account.Type != service.AccountTypeOAuth {
return
}
s.mu.Lock()
s.queue = append(s.queue, grokImportProbeTask{prober: prober, accountID: account.ID})
if s.workers < s.concurrency {
s.workers++
if s.workers > s.maxWorkers {
s.maxWorkers = s.workers
}
go s.worker()
}
s.mu.Unlock()
}
func (s *grokImportProbeScheduler) worker() {
for {
task, ok := s.nextTask()
if !ok {
return
}
s.run(task.prober, task.accountID)
}
}
func (s *grokImportProbeScheduler) nextTask() (grokImportProbeTask, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.queue) == 0 {
s.workers--
return grokImportProbeTask{}, false
}
task := s.queue[0]
s.queue[0] = grokImportProbeTask{}
s.queue = s.queue[1:]
if len(s.queue) == 0 {
s.queue = nil
}
return task, true
}
func (s *grokImportProbeScheduler) run(prober grokImportProber, accountID int64) {
defer func() {
if recovered := recover(); recovered != nil {
slog.Error(
"grok_import_active_probe_panic",
"account_id", accountID,
"recovery_type", panicType(recovered),
)
}
}()
// Queue time is intentionally excluded: every imported account is probed,
// while this timeout only bounds the actual upstream probe execution.
ctx, cancel := context.WithTimeout(context.Background(), s.timeout)
defer cancel()
result, err := prober.QueryQuota(ctx, accountID)
if err != nil {
slog.Warn(
"grok_import_active_probe_failed",
"account_id", accountID,
"status", infraerrors.Code(err),
"reason", infraerrors.Reason(err),
)
return
}
if result == nil {
slog.Warn(
"grok_import_active_probe_failed",
"account_id", accountID,
"reason", "empty_result",
)
return
}
slog.Info(
"grok_import_active_probe_completed",
"account_id", accountID,
"model", result.Model,
"status", result.StatusCode,
"headers_observed", result.HeadersObserved,
)
}
func panicType(value any) string {
switch value.(type) {
case string:
return "string"
case error:
return "error"
default:
return "unknown"
}
}
func (h *AccountHandler) scheduleGrokImportProbe(account *service.Account) {
if h == nil {
return
}
defaultGrokImportProbeScheduler.schedule(h.grokImportProber, account)
}
func (h *GrokOAuthHandler) scheduleGrokImportProbe(account *service.Account) {
if h == nil {
return
}
defaultGrokImportProbeScheduler.schedule(h.importProber, account)
}
// ProvideAccountHandler injects the Grok active prober for production while
// keeping NewAccountHandler convenient for focused unit tests.
func ProvideAccountHandler(
adminService service.AdminService,
oauthService *service.OAuthService,
openaiOAuthService *service.OpenAIOAuthService,
geminiOAuthService *service.GeminiOAuthService,
antigravityOAuthService *service.AntigravityOAuthService,
grokOAuthService service.GrokOAuthTokenService,
rateLimitService *service.RateLimitService,
accountUsageService *service.AccountUsageService,
accountTestService *service.AccountTestService,
concurrencyService *service.ConcurrencyService,
crsSyncService *service.CRSSyncService,
sessionLimitCache service.SessionLimitCache,
rpmCache service.RPMCache,
tokenCacheInvalidator service.TokenCacheInvalidator,
grokQuotaService *service.GrokQuotaService,
) *AccountHandler {
handler := NewAccountHandler(
adminService,
oauthService,
openaiOAuthService,
geminiOAuthService,
antigravityOAuthService,
grokOAuthService,
rateLimitService,
accountUsageService,
accountTestService,
concurrencyService,
crsSyncService,
sessionLimitCache,
rpmCache,
tokenCacheInvalidator,
)
handler.grokImportProber = grokQuotaService
return handler
}
@@ -0,0 +1,119 @@
//go:build unit
package admin
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type grokImportAdminService struct {
*stubAdminService
mu sync.Mutex
nextID int64
}
func newGrokImportAdminService() *grokImportAdminService {
return &grokImportAdminService{
stubAdminService: newStubAdminService(),
nextID: 500,
}
}
func (s *grokImportAdminService) CreateAccount(_ context.Context, input *service.CreateAccountInput) (*service.Account, error) {
s.mu.Lock()
s.nextID++
id := s.nextID
s.mu.Unlock()
return &service.Account{
ID: id,
Name: input.Name,
Platform: input.Platform,
Type: input.Type,
Credentials: input.Credentials,
Extra: input.Extra,
ProxyID: input.ProxyID,
Concurrency: input.Concurrency,
Status: service.StatusActive,
Schedulable: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}, nil
}
type grokImportOAuthClientStub struct{}
func (grokImportOAuthClientStub) ExchangeCode(context.Context, string, string, string, string, string) (*xai.TokenResponse, error) {
return &xai.TokenResponse{AccessToken: "access-token", RefreshToken: "refresh-token", ExpiresIn: 3600}, nil
}
func (grokImportOAuthClientStub) RefreshToken(context.Context, string, string, string) (*xai.TokenResponse, error) {
return &xai.TokenResponse{AccessToken: "access-token", RefreshToken: "refresh-token", ExpiresIn: 3600}, nil
}
func (grokImportOAuthClientStub) ConvertSSOToBuild(context.Context, string, string) (*xai.TokenResponse, error) {
return &xai.TokenResponse{AccessToken: "access-token", RefreshToken: "refresh-token", ExpiresIn: 3600}, nil
}
func TestGrokSSOBatchImportKeepsCreatedAccountsWhenOneAutomaticProbeFails(t *testing.T) {
gin.SetMode(gin.TestMode)
adminService := newGrokImportAdminService()
oauthService := service.NewGrokOAuthService(nil, grokImportOAuthClientStub{})
defer oauthService.Stop()
prober := newGrokImportProbeStub(3)
prober.failures[502] = infraerrors.New(502, "GROK_TEST_PROBE_FAILED", "sensitive-upstream-body")
handler := NewGrokOAuthHandler(oauthService, adminService, nil, nil)
handler.importProber = prober
router := gin.New()
router.POST("/api/v1/admin/grok/sso-to-oauth", handler.CreateAccountsFromSSO)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/admin/grok/sso-to-oauth",
strings.NewReader(`{"sso_tokens":["sso-one","sso-two","sso-three"]}`),
)
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
require.Contains(t, recorder.Body.String(), `"created"`)
require.NotContains(t, recorder.Body.String(), `GROK_TEST_PROBE_FAILED`)
for i := 0; i < 3; i++ {
awaitGrokProbeSignal(t, prober.done)
}
calls, _, _ := prober.snapshot()
require.Equal(t, map[int64]int{501: 1, 502: 1, 503: 1}, calls)
}
func TestAccountCreateWithoutAutomaticGrokProbeServiceStillSucceeds(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := NewAccountHandler(
newGrokImportAdminService(),
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
router := gin.New()
router.POST("/api/v1/admin/accounts", handler.Create)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/admin/accounts",
strings.NewReader(`{"name":"grok-rt","platform":"grok","type":"oauth","credentials":{"refresh_token":"secret"}}`),
)
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
}
@@ -0,0 +1,232 @@
//go:build unit
package admin
import (
"bytes"
"context"
"log/slog"
"sync"
"testing"
"time"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
type grokImportProbeStub struct {
mu sync.Mutex
calls map[int64]int
failures map[int64]error
active int
maxActive int
deadlineSeen bool
block <-chan struct{}
started chan int64
done chan int64
}
func newGrokImportProbeStub(buffer int) *grokImportProbeStub {
return &grokImportProbeStub{
calls: make(map[int64]int),
failures: make(map[int64]error),
started: make(chan int64, buffer),
done: make(chan int64, buffer),
}
}
func (s *grokImportProbeStub) QueryQuota(ctx context.Context, accountID int64) (*service.GrokQuotaProbeResult, error) {
_, deadlineSeen := ctx.Deadline()
s.mu.Lock()
s.calls[accountID]++
s.active++
if s.active > s.maxActive {
s.maxActive = s.active
}
s.deadlineSeen = s.deadlineSeen || deadlineSeen
s.mu.Unlock()
s.started <- accountID
var ctxErr error
if s.block != nil {
select {
case <-s.block:
case <-ctx.Done():
ctxErr = ctx.Err()
}
}
s.mu.Lock()
s.active--
failure := s.failures[accountID]
s.mu.Unlock()
s.done <- accountID
if ctxErr != nil {
return nil, ctxErr
}
if failure != nil {
return nil, failure
}
return &service.GrokQuotaProbeResult{
Source: "hybrid_probe",
Model: "grok-4.5",
StatusCode: 200,
ResetSupported: false,
}, nil
}
func (s *grokImportProbeStub) snapshot() (map[int64]int, int, bool) {
s.mu.Lock()
defer s.mu.Unlock()
calls := make(map[int64]int, len(s.calls))
for id, count := range s.calls {
calls[id] = count
}
return calls, s.maxActive, s.deadlineSeen
}
type grokImportProbeSchedulerTestSnapshot struct {
queued int
workers int
maxWorkers int
}
func snapshotGrokImportProbeScheduler(s *grokImportProbeScheduler) grokImportProbeSchedulerTestSnapshot {
if s == nil {
return grokImportProbeSchedulerTestSnapshot{}
}
s.mu.Lock()
defer s.mu.Unlock()
return grokImportProbeSchedulerTestSnapshot{
queued: len(s.queue),
workers: s.workers,
maxWorkers: s.maxWorkers,
}
}
func newGrokOAuthImportAccount(id int64) *service.Account {
return &service.Account{
ID: id,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
}
}
func awaitGrokProbeSignal(t *testing.T, signals <-chan int64) int64 {
t.Helper()
select {
case id := <-signals:
return id
case <-time.After(time.Second):
t.Fatal("timed out waiting for Grok import probe")
return 0
}
}
func TestGrokImportProbeSchedulerProbesSingleAccountOnce(t *testing.T) {
scheduler := newGrokImportProbeScheduler(1, time.Second)
prober := newGrokImportProbeStub(1)
scheduler.schedule(prober, newGrokOAuthImportAccount(101))
require.Equal(t, int64(101), awaitGrokProbeSignal(t, prober.done))
calls, maxActive, deadlineSeen := prober.snapshot()
require.Equal(t, map[int64]int{101: 1}, calls)
require.Equal(t, 1, maxActive)
require.True(t, deadlineSeen)
require.Eventually(t, func() bool {
snapshot := snapshotGrokImportProbeScheduler(scheduler)
return snapshot.queued == 0 && snapshot.workers == 0
}, time.Second, 10*time.Millisecond)
}
func TestGrokImportProbeSchedulerQueuesBatchWithoutPerTaskGoroutines(t *testing.T) {
const taskCount = 100
release := make(chan struct{})
scheduler := newGrokImportProbeScheduler(3, time.Second)
prober := newGrokImportProbeStub(taskCount)
prober.block = release
prober.failures[150] = infraerrors.New(502, "GROK_TEST_PROBE_FAILED", "sensitive-upstream-body")
for id := int64(101); id < 101+taskCount; id++ {
scheduler.schedule(prober, newGrokOAuthImportAccount(id))
}
for i := 0; i < 3; i++ {
awaitGrokProbeSignal(t, prober.started)
}
snapshot := snapshotGrokImportProbeScheduler(scheduler)
require.Equal(t, 97, snapshot.queued)
require.Equal(t, 3, snapshot.workers)
require.Equal(t, 3, snapshot.maxWorkers)
select {
case id := <-prober.started:
t.Fatalf("probe %d started before a concurrency slot was released", id)
case <-time.After(75 * time.Millisecond):
}
close(release)
for i := 0; i < taskCount; i++ {
awaitGrokProbeSignal(t, prober.done)
}
calls, maxActive, _ := prober.snapshot()
require.Len(t, calls, taskCount)
for id := int64(101); id < 101+taskCount; id++ {
require.Equal(t, 1, calls[id])
}
require.Equal(t, 3, maxActive)
require.Eventually(t, func() bool {
snapshot = snapshotGrokImportProbeScheduler(scheduler)
return snapshot.queued == 0 && snapshot.workers == 0
}, time.Second, 10*time.Millisecond)
require.Equal(t, 3, snapshot.maxWorkers)
}
func TestGrokImportProbeSchedulerTimeoutCancelsProbe(t *testing.T) {
neverRelease := make(chan struct{})
scheduler := newGrokImportProbeScheduler(1, 20*time.Millisecond)
prober := newGrokImportProbeStub(1)
prober.block = neverRelease
scheduler.schedule(prober, newGrokOAuthImportAccount(201))
require.Equal(t, int64(201), awaitGrokProbeSignal(t, prober.done))
calls, _, _ := prober.snapshot()
require.Equal(t, 1, calls[201])
}
func TestGrokImportProbeSchedulerSkipsMissingServiceAndNonGrokAccounts(t *testing.T) {
scheduler := newGrokImportProbeScheduler(1, time.Second)
prober := newGrokImportProbeStub(1)
scheduler.schedule(nil, newGrokOAuthImportAccount(301))
scheduler.schedule(prober, &service.Account{ID: 302, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth})
scheduler.schedule(prober, &service.Account{ID: 303, Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey})
select {
case id := <-prober.started:
t.Fatalf("unexpected probe for account %d", id)
case <-time.After(50 * time.Millisecond):
}
calls, _, _ := prober.snapshot()
require.Empty(t, calls)
}
func TestGrokImportProbeFailureLogDoesNotIncludeErrorMessage(t *testing.T) {
var logs bytes.Buffer
previousLogger := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil)))
defer slog.SetDefault(previousLogger)
scheduler := newGrokImportProbeScheduler(1, time.Second)
prober := newGrokImportProbeStub(1)
prober.failures[401] = infraerrors.New(502, "GROK_TEST_PROBE_FAILED", "refresh-token-secret")
scheduler.schedule(prober, newGrokOAuthImportAccount(401))
awaitGrokProbeSignal(t, prober.done)
require.Eventually(t, func() bool {
return bytes.Contains(logs.Bytes(), []byte("grok_import_active_probe_failed"))
}, time.Second, 10*time.Millisecond)
require.Contains(t, logs.String(), "GROK_TEST_PROBE_FAILED")
require.NotContains(t, logs.String(), "refresh-token-secret")
}
@@ -1,31 +1,44 @@
package admin
import (
"context"
"fmt"
"log/slog"
"strconv"
"strings"
"sync"
"time"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"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"
)
const grokSSOImportConcurrency = 3
type GrokOAuthHandler struct {
grokOAuthService *service.GrokOAuthService
adminService service.AdminService
quotaService *service.GrokQuotaService
importProber grokImportProber
reconciler service.GrokOAuthReconciler
}
func NewGrokOAuthHandler(
grokOAuthService *service.GrokOAuthService,
adminService service.AdminService,
quotaService *service.GrokQuotaService,
reconciler service.GrokOAuthReconciler,
) *GrokOAuthHandler {
return &GrokOAuthHandler{
grokOAuthService: grokOAuthService,
adminService: adminService,
quotaService: quotaService,
importProber: quotaService,
reconciler: reconciler,
}
}
@@ -151,6 +164,50 @@ func (h *GrokOAuthHandler) RefreshAccountToken(c *gin.Context) {
response.Success(c, dto.AccountFromService(updatedAccount))
}
type GrokOAuthReconcileRequest struct {
DryRun *bool `json:"dry_run"`
Apply bool `json:"apply"`
AfterID int64 `json:"after_id"`
Limit int `json:"limit"`
RefreshWindowSeconds int64 `json:"refresh_window_seconds"`
}
func (h *GrokOAuthHandler) ReconcileOAuthAccounts(c *gin.Context) {
var req GrokOAuthReconcileRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request")
return
}
dryRun := true
if req.DryRun != nil {
dryRun = *req.DryRun
}
if req.Apply == dryRun {
response.ErrorFrom(c, service.ErrGrokOAuthReconcileMode)
return
}
if req.RefreshWindowSeconds < 0 || req.RefreshWindowSeconds > int64((24*time.Hour)/time.Second) {
response.ErrorFrom(c, service.ErrGrokOAuthReconcileWindow)
return
}
if h.reconciler == nil {
response.InternalError(c, "Grok OAuth reconciliation service is unavailable")
return
}
result, err := h.reconciler.ReconcileGrokOAuth(c.Request.Context(), service.GrokOAuthReconcileInput{
DryRun: dryRun,
Apply: req.Apply,
AfterID: req.AfterID,
Limit: req.Limit,
RefreshWindow: time.Duration(req.RefreshWindowSeconds) * time.Second,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
func (h *GrokOAuthHandler) CreateAccountFromOAuth(c *gin.Context) {
var req struct {
SessionID string `json:"session_id" binding:"required"`
@@ -202,9 +259,254 @@ func (h *GrokOAuthHandler) CreateAccountFromOAuth(c *gin.Context) {
response.ErrorFrom(c, err)
return
}
h.scheduleGrokImportProbe(account)
response.Success(c, dto.AccountFromService(account))
}
type GrokSSOToOAuthRequest struct {
SSOTokens []string `json:"sso_tokens"`
SSOToken string `json:"sso_token"`
Name string `json:"name"`
Notes *string `json:"notes"`
ProxyID *int64 `json:"proxy_id"`
GroupIDs []int64 `json:"group_ids"`
Credentials map[string]any `json:"credentials"`
Extra map[string]any `json:"extra"`
Concurrency int `json:"concurrency"`
LoadFactor *int `json:"load_factor"`
Priority int `json:"priority"`
RateMultiplier *float64 `json:"rate_multiplier"`
ExpiresAt *int64 `json:"expires_at"`
AutoPauseOnExpired *bool `json:"auto_pause_on_expired"`
}
type GrokSSOToOAuthItemResult struct {
Index int `json:"index"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Account *dto.Account `json:"account,omitempty"`
Error string `json:"error,omitempty"`
}
type GrokSSOToOAuthResponse struct {
Created []GrokSSOToOAuthItemResult `json:"created"`
Failed []GrokSSOToOAuthItemResult `json:"failed"`
}
type grokSSOImportJob struct {
index int
token string
}
type grokSSOImportWorkerResult struct {
created bool
item GrokSSOToOAuthItemResult
}
func (h *GrokOAuthHandler) CreateAccountsFromSSO(c *gin.Context) {
var req GrokSSOToOAuthRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
tokens := normalizeSSOImportTokens(req.SSOTokens, req.SSOToken)
if len(tokens) == 0 {
response.BadRequest(c, "sso_tokens is required")
return
}
ctx := c.Request.Context()
workerCount := grokSSOImportConcurrency
if len(tokens) < workerCount {
workerCount = len(tokens)
}
jobs := make(chan grokSSOImportJob)
items := make([]grokSSOImportWorkerResult, len(tokens))
var wg sync.WaitGroup
for i := 0; i < workerCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
items[job.index] = h.safeCreateAccountFromSSOToken(ctx, req, job.token, job.index+1, len(tokens))
}
}()
}
for i, token := range tokens {
jobs <- grokSSOImportJob{index: i, token: token}
}
close(jobs)
wg.Wait()
result := GrokSSOToOAuthResponse{
Created: make([]GrokSSOToOAuthItemResult, 0, len(tokens)),
Failed: make([]GrokSSOToOAuthItemResult, 0),
}
for _, item := range items {
if item.created {
result.Created = append(result.Created, item.item)
} else {
result.Failed = append(result.Failed, item.item)
}
}
response.Success(c, result)
}
func (h *GrokOAuthHandler) safeCreateAccountFromSSOToken(ctx context.Context, req GrokSSOToOAuthRequest, token string, index, total int) (result grokSSOImportWorkerResult) {
defer func() {
if recovered := recover(); recovered != nil {
slog.Error("grok_sso_import_worker_panic", "index", index, "recover", recovered)
result = grokSSOImportWorkerResult{
item: GrokSSOToOAuthItemResult{
Index: index,
Error: fmt.Sprintf("internal worker panic: %v", recovered),
},
}
}
}()
return h.createAccountFromSSOToken(ctx, req, token, index, total)
}
func (h *GrokOAuthHandler) createAccountFromSSOToken(ctx context.Context, req GrokSSOToOAuthRequest, token string, index, total int) grokSSOImportWorkerResult {
tokenInfo, err := h.grokOAuthService.ConvertFromSSO(ctx, token, req.ProxyID)
if err != nil {
return grokSSOImportWorkerResult{item: GrokSSOToOAuthItemResult{Index: index, Error: grokSSOImportErrorMessage(err)}}
}
credentials := grokSSOImportCredentials(h.grokOAuthService.BuildAccountCredentials(tokenInfo), req.Credentials)
name := grokSSOImportAccountName(req.Name, tokenInfo, index, total)
expiresAt, autoPauseOnExpired := grokSSOImportExpiry(req.ExpiresAt, req.AutoPauseOnExpired, tokenInfo)
account, err := h.adminService.CreateAccount(ctx, &service.CreateAccountInput{
Name: name,
Notes: req.Notes,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Credentials: credentials,
Extra: cloneGrokSSOMap(req.Extra),
ProxyID: req.ProxyID,
Concurrency: req.Concurrency,
LoadFactor: req.LoadFactor,
Priority: req.Priority,
RateMultiplier: req.RateMultiplier,
GroupIDs: append([]int64(nil), req.GroupIDs...),
ExpiresAt: expiresAt,
AutoPauseOnExpired: autoPauseOnExpired,
})
if err != nil {
return grokSSOImportWorkerResult{item: GrokSSOToOAuthItemResult{Index: index, Name: name, Email: tokenInfo.Email, Error: grokSSOImportErrorMessage(err)}}
}
h.scheduleGrokImportProbe(account)
return grokSSOImportWorkerResult{
created: true,
item: GrokSSOToOAuthItemResult{
Index: index,
Name: name,
Email: tokenInfo.Email,
Account: dto.AccountFromService(account),
},
}
}
// grokSSOImportCredentials 合并 SSO 兑换出的凭据与导入请求携带的运营侧配置。
// token 字段以 BuildAccountCredentials 为准(请求不可覆盖);但 base_url 是运营侧
// 配置且 Build 恒写官方地址,会吞掉导入时指定的自定义转发地址——与
// RefreshAccountToken 的保留逻辑对齐,请求显式提供时以请求为准。
func grokSSOImportCredentials(built map[string]any, reqCredentials map[string]any) map[string]any {
credentials := service.MergeCredentials(cloneGrokSSOMap(reqCredentials), built)
if reqBaseURL, ok := reqCredentials["base_url"].(string); ok && strings.TrimSpace(reqBaseURL) != "" {
credentials["base_url"] = strings.TrimSpace(reqBaseURL)
}
return credentials
}
func grokSSOImportExpiry(requestExpiresAt *int64, requestAutoPause *bool, tokenInfo *service.GrokTokenInfo) (*int64, *bool) {
if tokenInfo == nil || strings.TrimSpace(tokenInfo.RefreshToken) != "" || tokenInfo.ExpiresAt <= 0 {
return requestExpiresAt, requestAutoPause
}
expiresAt := tokenInfo.ExpiresAt
if requestExpiresAt != nil && *requestExpiresAt > 0 && *requestExpiresAt < expiresAt {
expiresAt = *requestExpiresAt
}
autoPause := true
return &expiresAt, &autoPause
}
func cloneGrokSSOMap(source map[string]any) map[string]any {
if source == nil {
return nil
}
clone := make(map[string]any, len(source))
for key, value := range source {
clone[key] = cloneGrokSSOValue(value)
}
return clone
}
func cloneGrokSSOValue(value any) any {
switch v := value.(type) {
case map[string]any:
return cloneGrokSSOMap(v)
case []any:
clone := make([]any, len(v))
for i, item := range v {
clone[i] = cloneGrokSSOValue(item)
}
return clone
default:
return value
}
}
func normalizeSSOImportTokens(tokens []string, single string) []string {
items := make([]string, 0, len(tokens)+1)
if strings.TrimSpace(single) != "" {
items = append(items, single)
}
items = append(items, tokens...)
seen := make(map[string]struct{}, len(items))
result := make([]string, 0, len(items))
for _, item := range items {
parts := strings.Split(strings.NewReplacer(",", "\n", "\r", "\n").Replace(item), "\n")
for _, token := range parts {
if token = xai.NormalizeSSOToken(token); token == "" {
continue
}
if _, ok := seen[token]; ok {
continue
}
seen[token] = struct{}{}
result = append(result, token)
}
}
return result
}
func grokSSOImportAccountName(base string, tokenInfo *service.GrokTokenInfo, index, total int) string {
base = strings.TrimSpace(base)
if base == "" && tokenInfo != nil {
base = strings.TrimSpace(tokenInfo.Email)
}
if base == "" {
base = "Grok OAuth Account"
}
if total > 1 {
return base + " #" + strconv.Itoa(index)
}
return base
}
func grokSSOImportErrorMessage(err error) string {
status := infraerrors.FromError(err)
if status == nil {
return ""
}
if status.Reason != "" {
return status.Reason + ": " + status.Message
}
return status.Message
}
func (h *GrokOAuthHandler) QueryQuota(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
@@ -215,7 +517,7 @@ func (h *GrokOAuthHandler) QueryQuota(c *gin.Context) {
response.BadRequest(c, "grok quota service is not enabled")
return
}
result, err := h.quotaService.ProbeUsage(c.Request.Context(), accountID)
result, err := h.quotaService.QueryQuota(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
@@ -41,17 +42,48 @@ func (r *grokQuotaHandlerAccountRepo) UpdateExtra(_ context.Context, id int64, u
}
type grokQuotaHandlerUpstream struct {
resp *http.Response
lastReq *http.Request
lastBody []byte
mu sync.Mutex
requests []*http.Request
bodies [][]byte
}
type grokOAuthReconcilerStub struct {
input service.GrokOAuthReconcileInput
calls int
result *service.GrokOAuthReconcileResult
err error
}
func (s *grokOAuthReconcilerStub) ReconcileGrokOAuth(_ context.Context, input service.GrokOAuthReconcileInput) (*service.GrokOAuthReconcileResult, error) {
s.calls++
s.input = input
return s.result, s.err
}
func (u *grokQuotaHandlerUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.lastReq = req
var body []byte
if req.Body != nil {
u.lastBody, _ = io.ReadAll(req.Body)
body, _ = io.ReadAll(req.Body)
}
return u.resp, nil
u.mu.Lock()
u.requests = append(u.requests, req)
u.bodies = append(u.bodies, body)
u.mu.Unlock()
if req.URL.Path == "/v1/responses" {
return &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"}`)),
}, nil
}
payload := `{"config":{"billingPeriodStart":"2026-07-01T00:00:00Z","billingPeriodEnd":"2026-08-01T00:00:00Z"}}`
if req.URL.RawQuery == "format=credits" {
payload = `{"config":{"currentPeriod":{"type":"WEEKLY","start":"2026-07-09T03:25:00Z","end":"2026-07-16T03:25:00Z"}}}`
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(payload))}, nil
}
func (u *grokQuotaHandlerUpstream) DoWithTLS(
@@ -71,22 +103,18 @@ func TestGrokOAuthHandlerQueryQuotaProbesUpstream(t *testing.T) {
ID: 42,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{
"access_token": "access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
"access_token": "access-token",
"refresh_token": "refresh-token",
"expires_at": time.Now().Add(2 * 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)
upstream := &grokQuotaHandlerUpstream{}
quotaService := service.NewGrokQuotaService(repo, nil, service.NewGrokTokenProvider(repo, nil), upstream, nil)
handler := NewGrokOAuthHandler(nil, nil, quotaService, nil)
router := gin.New()
router.GET("/api/v1/admin/grok/accounts/:id/quota", handler.QueryQuota)
@@ -95,12 +123,27 @@ func TestGrokOAuthHandlerQueryQuotaProbesUpstream(t *testing.T) {
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(), `"source":"hybrid_probe"`)
require.Contains(t, rec.Body.String(), `"billing":`)
require.Contains(t, rec.Body.String(), `"snapshot":`)
require.Contains(t, rec.Body.String(), `"headers_observed":true`)
require.NotContains(t, rec.Body.String(), "access-token")
require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String())
require.Equal(t, "Bearer access-token", upstream.lastReq.Header.Get("Authorization"))
require.Contains(t, string(upstream.lastBody), `"store":false`)
upstream.mu.Lock()
requests := append([]*http.Request(nil), upstream.requests...)
bodies := append([][]byte(nil), upstream.bodies...)
upstream.mu.Unlock()
require.Len(t, requests, 3)
for i, upstreamReq := range requests {
require.Equal(t, "Bearer access-token", upstreamReq.Header.Get("Authorization"))
if upstreamReq.URL.String() == xai.DefaultCLIBaseURL+"/responses" {
require.Equal(t, "application/json, text/event-stream", upstreamReq.Header.Get("Accept"))
require.Contains(t, string(bodies[i]), `"model":"grok-4.5"`)
require.Contains(t, string(bodies[i]), `"input":"hi"`)
require.Contains(t, string(bodies[i]), `"stream":true`)
require.NotContains(t, string(bodies[i]), `"max_output_tokens"`)
require.NotContains(t, string(bodies[i]), `"store"`)
}
}
require.NotNil(t, repo.updates[42])
}
@@ -112,8 +155,8 @@ func TestGrokOAuthHandlerResetQuotaReturnsUnsupported(t *testing.T) {
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
}}
quotaService := service.NewGrokQuotaService(repo, nil, nil, nil)
handler := NewGrokOAuthHandler(nil, nil, quotaService)
quotaService := service.NewGrokQuotaService(repo, nil, nil, nil, nil)
handler := NewGrokOAuthHandler(nil, nil, quotaService, nil)
router := gin.New()
router.POST("/api/v1/admin/grok/accounts/:id/reset-quota", handler.ResetQuota)
@@ -131,7 +174,7 @@ func TestGrokOAuthHandlerRuntimeSanityDoesNotExposeSecrets(t *testing.T) {
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)
handler := NewGrokOAuthHandler(nil, nil, nil, nil)
router := gin.New()
router.GET("/api/v1/admin/grok/runtime-sanity", handler.RuntimeSanity)
rec := httptest.NewRecorder()
@@ -145,3 +188,156 @@ func TestGrokOAuthHandlerRuntimeSanityDoesNotExposeSecrets(t *testing.T) {
require.NotContains(t, rec.Body.String(), "secret")
require.NotContains(t, rec.Body.String(), "client-secret-like-value")
}
func TestGrokSSOImportExpiryUsesTokenExpiryWithoutRefreshToken(t *testing.T) {
tokenExpiry := time.Now().Add(6 * time.Hour).Unix()
expiresAt, autoPause := grokSSOImportExpiry(nil, nil, &service.GrokTokenInfo{
ExpiresAt: tokenExpiry,
})
require.NotNil(t, expiresAt)
require.Equal(t, tokenExpiry, *expiresAt)
require.NotNil(t, autoPause)
require.True(t, *autoPause)
}
func TestGrokSSOImportExpiryUsesEarlierRequestedExpiryWithoutRefreshToken(t *testing.T) {
requestedExpiry := time.Now().Add(2 * time.Hour).Unix()
tokenExpiry := time.Now().Add(6 * time.Hour).Unix()
requestedAutoPause := false
expiresAt, autoPause := grokSSOImportExpiry(&requestedExpiry, &requestedAutoPause, &service.GrokTokenInfo{
ExpiresAt: tokenExpiry,
})
require.NotNil(t, expiresAt)
require.Equal(t, requestedExpiry, *expiresAt)
require.NotNil(t, autoPause)
require.True(t, *autoPause)
}
func TestGrokSSOImportExpiryPreservesRequestSettingsWithRefreshToken(t *testing.T) {
requestedExpiry := time.Now().Add(2 * time.Hour).Unix()
requestedAutoPause := false
expiresAt, autoPause := grokSSOImportExpiry(&requestedExpiry, &requestedAutoPause, &service.GrokTokenInfo{
RefreshToken: "refresh-token",
ExpiresAt: time.Now().Add(6 * time.Hour).Unix(),
})
require.Same(t, &requestedExpiry, expiresAt)
require.Same(t, &requestedAutoPause, autoPause)
}
func TestGrokSSOImportCredentialsPreservesRequestedBaseURL(t *testing.T) {
built := map[string]any{
"access_token": "at-1",
"base_url": xai.DefaultCLIBaseURL,
}
reqCredentials := map[string]any{
"base_url": "https://relay.example.com/v1",
"header_override_enabled": true,
"header_overrides": map[string]any{"x-relay-key": "k"},
}
credentials := grokSSOImportCredentials(built, reqCredentials)
// token 字段以兑换结果为准;base_url 是运营侧配置,必须保留请求里的自定义地址
require.Equal(t, "at-1", credentials["access_token"])
require.Equal(t, "https://relay.example.com/v1", credentials["base_url"])
require.Equal(t, true, credentials["header_override_enabled"])
require.Equal(t, map[string]any{"x-relay-key": "k"}, credentials["header_overrides"])
// 入参不被污染(req.Credentials 会被多个 worker 并发读取)
require.Equal(t, "https://relay.example.com/v1", reqCredentials["base_url"])
}
func TestGrokSSOImportCredentialsDefaultsToOfficialBaseURL(t *testing.T) {
built := map[string]any{
"access_token": "at-1",
"base_url": xai.DefaultCLIBaseURL,
}
credentials := grokSSOImportCredentials(built, nil)
require.Equal(t, xai.DefaultCLIBaseURL, credentials["base_url"])
credentials = grokSSOImportCredentials(map[string]any{
"access_token": "at-2",
"base_url": xai.DefaultCLIBaseURL,
}, map[string]any{"base_url": " "})
require.Equal(t, xai.DefaultCLIBaseURL, credentials["base_url"])
require.Equal(t, "at-2", credentials["access_token"])
}
func TestGrokSSOImportWorkerRecoversPanic(t *testing.T) {
h := &GrokOAuthHandler{}
result := h.safeCreateAccountFromSSOToken(context.Background(), GrokSSOToOAuthRequest{}, "token", 2, 3)
// Without a service, createAccountFromSSOToken would panic on nil service access.
// Recovery must convert that into a failed item and keep the worker alive.
require.False(t, result.created)
require.Equal(t, 2, result.item.Index)
require.Contains(t, result.item.Error, "internal worker panic")
}
func TestGrokOAuthHandlerReconcileDefaultsToDryRun(t *testing.T) {
gin.SetMode(gin.TestMode)
reconciler := &grokOAuthReconcilerStub{result: &service.GrokOAuthReconcileResult{
DryRun: true,
Scanned: 2,
Actionable: 1,
WouldBlock: 1,
Items: []service.GrokOAuthReconcileItem{{AccountID: 42, Reason: service.GrokOAuthReconcileReasonMissingRefreshToken, Action: service.GrokOAuthReconcileActionBlock, Outcome: service.GrokOAuthReconcileOutcomePlanned}},
NextAfterID: 0,
}}
handler := NewGrokOAuthHandler(nil, nil, nil, reconciler)
router := gin.New()
router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, 1, reconciler.calls)
require.True(t, reconciler.input.DryRun)
require.False(t, reconciler.input.Apply)
require.Contains(t, rec.Body.String(), `"reason":"missing_refresh_token"`)
require.NotContains(t, rec.Body.String(), `"refresh_token":`)
require.NotContains(t, rec.Body.String(), `"access_token":`)
}
func TestGrokOAuthHandlerReconcileRequiresExplicitApply(t *testing.T) {
gin.SetMode(gin.TestMode)
reconciler := &grokOAuthReconcilerStub{}
handler := NewGrokOAuthHandler(nil, nil, nil, reconciler)
router := gin.New()
router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{"dry_run":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Zero(t, reconciler.calls)
require.NotContains(t, rec.Body.String(), "credentials")
}
func TestGrokOAuthHandlerReconcileExplicitApply(t *testing.T) {
gin.SetMode(gin.TestMode)
reconciler := &grokOAuthReconcilerStub{result: &service.GrokOAuthReconcileResult{DryRun: false, Refreshed: 1}}
handler := NewGrokOAuthHandler(nil, nil, nil, reconciler)
router := gin.New()
router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{"apply":true,"dry_run":false,"after_id":10,"limit":25,"refresh_window_seconds":3600}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, 1, reconciler.calls)
require.True(t, reconciler.input.Apply)
require.False(t, reconciler.input.DryRun)
require.Equal(t, int64(10), reconciler.input.AfterID)
require.Equal(t, 25, reconciler.input.Limit)
require.Equal(t, time.Hour, reconciler.input.RefreshWindow)
}
+207 -2
View File
@@ -2,12 +2,15 @@ package admin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -84,7 +87,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 grok"`
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok composite"`
RateMultiplier float64 `json:"rate_multiplier"`
IsExclusive bool `json:"is_exclusive"`
SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"`
@@ -129,6 +132,10 @@ type CreateGroupRequest struct {
ModelsListConfig service.GroupModelsListConfig `json:"models_list_config"`
// 分组 RPM 上限(0 = 不限制)
RPMLimit int `json:"rpm_limit"`
// OpenAI/Codex 请求推理强度上限,空字符串表示不限制。
MaxReasoningEffort string `json:"max_reasoning_effort"`
// OpenAI/Codex 推理强度精确映射。
ReasoningEffortMappings []service.ReasoningEffortMapping `json:"reasoning_effort_mappings"`
// 从指定分组复制账号(创建后自动绑定)
CopyAccountsFromGroupIDs []int64 `json:"copy_accounts_from_group_ids"`
}
@@ -137,7 +144,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 grok"`
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok composite"`
RateMultiplier *float64 `json:"rate_multiplier"`
IsExclusive *bool `json:"is_exclusive"`
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
@@ -183,10 +190,30 @@ type UpdateGroupRequest struct {
ModelsListConfig *service.GroupModelsListConfig `json:"models_list_config"`
// 分组 RPM 上限(0 = 不限制);nil 表示未提供不改动
RPMLimit *int `json:"rpm_limit"`
// OpenAI/Codex 请求推理强度上限;空字符串清除,nil 不修改。
MaxReasoningEffort *string `json:"max_reasoning_effort"`
// nil 不修改,空数组清空,非空数组替换。
ReasoningEffortMappings *[]service.ReasoningEffortMapping `json:"reasoning_effort_mappings"`
// 从指定分组复制账号(同步操作:先清空当前分组的账号绑定,再绑定源分组的账号)
CopyAccountsFromGroupIDs []int64 `json:"copy_accounts_from_group_ids"`
}
type CompositeRouteRequest struct {
PublicModel string `json:"public_model" binding:"required"`
MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"`
TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok"`
UpstreamModel string `json:"upstream_model"`
Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"`
Priority int `json:"priority"`
Enabled *bool `json:"enabled"`
Notes string `json:"notes"`
}
type CompositeRoutePreviewRequest struct {
Model string `json:"model" binding:"required"`
Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"`
}
// List handles listing all groups with pagination
// GET /api/v1/admin/groups
func (h *GroupHandler) List(c *gin.Context) {
@@ -222,6 +249,133 @@ func (h *GroupHandler) List(c *gin.Context) {
response.Paginated(c, outGroups, total, page, pageSize)
}
// ListCompositeRoutes handles listing composite model routes for one group.
// GET /api/v1/admin/groups/:id/composite-routes
func (h *GroupHandler) ListCompositeRoutes(c *gin.Context) {
groupID, ok := parsePositiveIDParam(c, "id")
if !ok {
return
}
routes, err := h.adminService.ListCompositeRoutes(c.Request.Context(), groupID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, routes)
}
// CreateCompositeRoute handles creating one composite model route.
// POST /api/v1/admin/groups/:id/composite-routes
func (h *GroupHandler) CreateCompositeRoute(c *gin.Context) {
groupID, ok := parsePositiveIDParam(c, "id")
if !ok {
return
}
var req CompositeRouteRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request body: "+err.Error())
return
}
route, err := h.adminService.CreateCompositeRoute(c.Request.Context(), groupID, compositeRouteRequestToInput(req, true))
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Created(c, route)
}
// UpdateCompositeRoute handles replacing one composite model route.
// PUT /api/v1/admin/groups/:id/composite-routes/:route_id
func (h *GroupHandler) UpdateCompositeRoute(c *gin.Context) {
groupID, ok := parsePositiveIDParam(c, "id")
if !ok {
return
}
routeID, ok := parsePositiveIDParam(c, "route_id")
if !ok {
return
}
var req CompositeRouteRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request body: "+err.Error())
return
}
route, err := h.adminService.UpdateCompositeRoute(c.Request.Context(), groupID, routeID, compositeRouteRequestToInput(req, true))
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, route)
}
// DeleteCompositeRoute handles deleting one composite model route.
// DELETE /api/v1/admin/groups/:id/composite-routes/:route_id
func (h *GroupHandler) DeleteCompositeRoute(c *gin.Context) {
groupID, ok := parsePositiveIDParam(c, "id")
if !ok {
return
}
routeID, ok := parsePositiveIDParam(c, "route_id")
if !ok {
return
}
if err := h.adminService.DeleteCompositeRoute(c.Request.Context(), groupID, routeID); err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, gin.H{"message": "Composite route deleted"})
}
// PreviewCompositeRoute resolves a model without mutating routes.
// POST /api/v1/admin/groups/:id/composite-routes/preview
func (h *GroupHandler) PreviewCompositeRoute(c *gin.Context) {
groupID, ok := parsePositiveIDParam(c, "id")
if !ok {
return
}
var req CompositeRoutePreviewRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request body: "+err.Error())
return
}
decision, err := h.adminService.PreviewCompositeRoute(c.Request.Context(), groupID, service.CompositeRoutePreviewRequest{
Model: req.Model,
Endpoint: req.Endpoint,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, decision)
}
func compositeRouteRequestToInput(req CompositeRouteRequest, defaultEnabled bool) service.CompositeRouteInput {
enabled := defaultEnabled
if req.Enabled != nil {
enabled = *req.Enabled
}
return service.CompositeRouteInput{
PublicModel: req.PublicModel,
MatchType: req.MatchType,
TargetPlatform: req.TargetPlatform,
UpstreamModel: req.UpstreamModel,
Endpoint: req.Endpoint,
Priority: req.Priority,
Enabled: enabled,
Notes: req.Notes,
}
}
func parsePositiveIDParam(c *gin.Context, name string) (int64, bool) {
raw := c.Param(name)
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
response.BadRequest(c, "Invalid "+name)
return 0, false
}
return id, true
}
// GetAll handles getting all active groups without pagination.
// Pass ?include_inactive=true to also include disabled groups (used by the
// API Key group filter, which needs to surface groups that still have API keys
@@ -351,6 +505,8 @@ func (h *GroupHandler) Create(c *gin.Context) {
MessagesDispatchModelConfig: req.MessagesDispatchModelConfig,
ModelsListConfig: req.ModelsListConfig,
RPMLimit: req.RPMLimit,
MaxReasoningEffort: req.MaxReasoningEffort,
ReasoningEffortMappings: req.ReasoningEffortMappings,
CopyAccountsFromGroupIDs: req.CopyAccountsFromGroupIDs,
})
if err != nil {
@@ -361,6 +517,53 @@ func (h *GroupHandler) Create(c *gin.Context) {
response.Success(c, dto.GroupFromServiceAdmin(group))
}
// Duplicate handles creating an inactive group copy with the source account bindings.
// POST /api/v1/admin/groups/:id/duplicate
func (h *GroupHandler) Duplicate(c *gin.Context) {
groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || groupID <= 0 {
response.BadRequest(c, "Invalid group ID")
return
}
actorScope := adminActorScope(c)
result, err := executeAdminIdempotent(
c,
"admin.groups.duplicate",
struct {
GroupID int64 `json:"group_id"`
}{GroupID: groupID},
service.DefaultWriteIdempotencyTTL(),
func(ctx context.Context) (any, error) {
group, execErr := h.adminService.DuplicateGroup(ctx, groupID, actorScope, c.GetHeader("Idempotency-Key"))
if execErr != nil {
return nil, execErr
}
return dto.GroupFromServiceAdmin(group), nil
},
)
if err != nil {
reason := infraerrors.Reason(err)
if reason == infraerrors.Reason(service.ErrIdempotencyInProgress) || reason == infraerrors.Reason(service.ErrIdempotencyStoreUnavail) {
recovered, recoverErr := h.adminService.RecoverDuplicateGroup(c.Request.Context(), groupID, actorScope, c.GetHeader("Idempotency-Key"))
if recoverErr != nil {
slog.Warn("group_duplicate_recovery_failed", "group_id", groupID, "actor_scope", actorScope, "reason", reason, "error", recoverErr)
} else if recovered != nil {
c.Header("X-Idempotency-Recovered", "true")
response.Success(c, dto.GroupFromServiceAdmin(recovered))
return
}
}
response.ErrorFrom(c, err)
return
}
if result != nil && result.Replayed {
c.Header("X-Idempotency-Replayed", "true")
}
response.Success(c, result.Data)
}
// Update handles updating a group
// PUT /api/v1/admin/groups/:id
func (h *GroupHandler) Update(c *gin.Context) {
@@ -420,6 +623,8 @@ func (h *GroupHandler) Update(c *gin.Context) {
MessagesDispatchModelConfig: req.MessagesDispatchModelConfig,
ModelsListConfig: req.ModelsListConfig,
RPMLimit: req.RPMLimit,
MaxReasoningEffort: req.MaxReasoningEffort,
ReasoningEffortMappings: req.ReasoningEffortMappings,
CopyAccountsFromGroupIDs: req.CopyAccountsFromGroupIDs,
})
if err != nil {
@@ -0,0 +1,163 @@
//go:build unit
package admin
import (
"context"
"net/http"
"net/http/httptest"
"testing"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type duplicateGroupAdminServiceStub struct {
service.AdminService
group *service.Group
calls int
recoverCalls int
groupID int64
actorScope string
operationKey string
recoverScope string
recoverKey string
created bool
}
func (s *duplicateGroupAdminServiceStub) DuplicateGroup(_ context.Context, groupID int64, actorScope, operationKey string) (*service.Group, error) {
s.calls++
s.groupID = groupID
s.actorScope = actorScope
s.operationKey = operationKey
s.created = true
return s.group, nil
}
func (s *duplicateGroupAdminServiceStub) RecoverDuplicateGroup(_ context.Context, _ int64, actorScope, operationKey string) (*service.Group, error) {
s.recoverCalls++
s.recoverScope = actorScope
s.recoverKey = operationKey
if !s.created {
return nil, nil
}
return s.group, nil
}
func setupDuplicateGroupRouter(t *testing.T, svc service.AdminService) *gin.Engine {
t.Helper()
previousCoordinator := service.DefaultIdempotencyCoordinator()
service.SetDefaultIdempotencyCoordinator(nil)
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previousCoordinator) })
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 77})
c.Next()
})
handler := NewGroupHandler(svc, nil, nil)
router.POST("/api/v1/admin/groups/:id/duplicate", handler.Duplicate)
return router
}
func duplicateGroupHandlerFixture() *service.Group {
return &service.Group{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Status: "inactive",
RateMultiplier: 1,
AccountCount: 3,
ActiveAccountCount: 2,
DuplicateOperationID: "internal-operation-must-not-leak",
ModelRouting: map[string][]int64{"claude-*": {7}},
}
}
func TestDuplicateGroupHandlerReturnsAdminDTOWithoutOperationMetadata(t *testing.T) {
svc := &duplicateGroupAdminServiceStub{group: duplicateGroupHandlerFixture()}
router := setupDuplicateGroupRouter(t, svc)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups/42/duplicate", nil)
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, 1, svc.calls)
require.Contains(t, recorder.Body.String(), `"name":"primary (Copy)"`)
require.Contains(t, recorder.Body.String(), `"status":"inactive"`)
require.Contains(t, recorder.Body.String(), `"account_count":3`)
require.NotContains(t, recorder.Body.String(), "duplicate_operation_id")
require.NotContains(t, recorder.Body.String(), "internal-operation-must-not-leak")
}
func TestDuplicateGroupHandlerRejectsInvalidID(t *testing.T) {
for _, id := range []string{"not-a-number", "0", "-1"} {
t.Run(id, func(t *testing.T) {
svc := &duplicateGroupAdminServiceStub{}
router := setupDuplicateGroupRouter(t, svc)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups/"+id+"/duplicate", nil)
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.Zero(t, svc.calls)
})
}
}
func TestDuplicateGroupHandlerReplaysSameIdempotencyKey(t *testing.T) {
svc := &duplicateGroupAdminServiceStub{group: duplicateGroupHandlerFixture()}
router := setupDuplicateGroupRouter(t, svc)
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-group-42")
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, 1, svc.calls)
require.Equal(t, int64(42), svc.groupID)
require.Equal(t, "admin:77", svc.actorScope)
require.Equal(t, "duplicate-group-42", svc.operationKey)
require.Equal(t, "true", second.Header().Get("X-Idempotency-Replayed"))
}
func TestDuplicateGroupHandlerRecoversAfterMarkSucceededFailure(t *testing.T) {
svc := &duplicateGroupAdminServiceStub{group: duplicateGroupHandlerFixture()}
router := setupDuplicateGroupRouter(t, svc)
repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true}
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/groups/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-group-42-recovery")
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, "true", first.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, "true", second.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, 1, svc.calls, "ambiguous retries must not repeat the create side effect")
require.Equal(t, 2, svc.recoverCalls)
require.Equal(t, "admin:77", svc.recoverScope)
require.Equal(t, "duplicate-group-42-recovery", svc.recoverKey)
}

Some files were not shown because too many files have changed in this diff Show More