erio
6892e84ad2
fix: skip rate limiting when custom error codes don't match upstream status
...
Add ShouldHandleErrorCode guard at the entry of handleGeminiUpstreamError
and AntigravityGatewayService.handleUpstreamError so that accounts with
custom error codes (e.g. [599]) are not rate-limited when the upstream
returns a non-matching status (e.g. 429).
2026-02-09 19:55:05 +08:00
erio
73f455745c
feat: ErrorPolicySkipped returns 500 instead of upstream status code
...
When custom error codes are enabled and the upstream error code is NOT
in the configured list, return HTTP 500 to the client instead of
transparently forwarding the original status code.
Also adds integration test TestCustomErrorCode599 verifying that 429,
500, 503, 401, 403 all return 500 without triggering SetRateLimited
or SetError.
2026-02-09 19:54:54 +08:00
erio
a67d9337b8
feat: integrate CheckErrorPolicy into Gemini error handling paths
2026-02-09 06:55:45 +08:00
erio
fb58560d15
refactor(upstream): replace upstream account type with apikey, auto-append /antigravity
...
Upstream accounts now use the standard APIKey type instead of a dedicated
upstream type. GetBaseURL() and new GetGeminiBaseURL() automatically append
/antigravity for Antigravity platform APIKey accounts, eliminating the need
for separate upstream forwarding methods.
- Remove ForwardUpstream, ForwardUpstreamGemini, testUpstreamConnection
- Remove upstream branch guards in Forward/ForwardGemini/TestConnection
- Add migration 052 to convert existing upstream accounts to apikey
- Update frontend CreateAccountModal to create apikey type
- Add unit tests for GetBaseURL and GetGeminiBaseURL
2026-02-08 13:06:25 +08:00
erio
edb0937024
fix: restore non-failover error passthrough from 7b156489
2026-02-07 14:24:55 +08:00
erio
5e98445b22
feat(antigravity): comprehensive enhancements - model mapping, rate limiting, scheduling & ops
...
Key changes:
- Upgrade model mapping: Opus 4.5 → Opus 4.6-thinking with precise matching
- Unified rate limiting: scope-level → model-level with Redis snapshot sync
- Load-balanced scheduling by call count with smart retry mechanism
- Force cache billing support
- Model identity injection in prompts with leak prevention
- Thinking mode auto-handling (max_tokens/budget_tokens fix)
- Frontend: whitelist mode toggle, model mapping validation, status indicators
- Gemini session fallback with Redis Trie O(L) matching
- Ops: enhanced concurrency monitoring, account availability, retry logic
- Migration scripts: 049-051 for model mapping unification
2026-02-07 12:31:10 +08:00
shaw
7b1564898b
fix: make error passthrough effective for non-failover upstream errors
2026-02-07 10:25:56 +08:00
shaw
39e05a2dad
feat: 新增全局错误透传规则功能
...
支持管理员配置上游错误如何返回给客户端:
- 新增 ErrorPassthroughRule 数据模型和 Ent Schema
- 实现规则的 CRUD API(/admin/error-passthrough-rules)
- 支持按错误码、关键词匹配,支持 any/all 匹配模式
- 支持按平台过滤(anthropic/openai/gemini/antigravity)
- 支持透传或自定义响应状态码和错误消息
- 实现两级缓存(Redis + 本地内存)和多实例同步
- 集成到 gateway_handler 的错误处理流程
- 新增前端管理界面组件
- 新增单元测试覆盖核心匹配逻辑
优化:
- 移除 refreshLocalCache 中的冗余排序(数据库已排序)
- 后端 Validate() 增加匹配条件非空校验
2026-02-05 21:52:54 +08:00
song
2220fd18ca
merge upstream main
2026-02-03 15:36:17 +08:00
ianshaw
03e94f9f53
fix(gemini): 为 Gemini 工具调用添加 thoughtSignature 避免 INVALID_ARGUMENT 错误
2026-02-03 06:01:29 +08:00
song
0170d19fa7
merge upstream main
2026-02-02 22:13:50 +08:00
Wesley Liddick
cc7e67b01a
Merge pull request #445 from touwaeriol/fix/gemini-cache-token-billing
...
fix(billing): 修复 Gemini 接口缓存 token 统计
2026-02-02 15:22:46 +08:00
liuxiongfeng
4bfeeecb05
fix(billing): 修复 Gemini 接口缓存 token 统计
...
extractGeminiUsage 函数未提取 cachedContentTokenCount,
导致计费时缓存读取 token 始终为 0。
修复:
- 提取 usageMetadata.cachedContentTokenCount
- 设置 CacheReadInputTokens 字段
- InputTokens 减去缓存 token(与 response_transformer 逻辑一致)
2026-02-02 14:01:17 +08:00
song
7ade9baa15
fix(gateway): 过滤 Gemini 请求中 parts 为空的消息
...
Gemini API 不接受 contents 数组中 parts 为空的消息,会返回 400 INVALID_ARGUMENT 错误。
添加 filterEmptyPartsFromGeminiRequest 函数在转发前过滤这类消息。
影响范围:ForwardGemini (antigravity) 和 ForwardNative (gemini)
2026-01-29 21:09:33 +08:00
song
7cea6b6fc9
feat(gemini): 为 Gemini 原生平台添加图片计费支持
...
对齐 Antigravity 平台的图片计费逻辑:
- 添加 extractImageSize() 方法提取图片尺寸
- Forward() 和 ForwardNative() 返回 ImageCount/ImageSize
- 支持分组自定义图片价格和倍率
2026-01-27 00:33:48 +08:00
song
0059a232a6
feat(gemini): 为 Gemini 原生平台添加图片计费支持
...
对齐 Antigravity 平台的图片计费逻辑:
- 添加 extractImageSize() 方法提取图片尺寸
- Forward() 和 ForwardNative() 返回 ImageCount/ImageSize
- 支持分组自定义图片价格和倍率
2026-01-26 20:51:40 +08:00
lynoot
909b8a8f9c
fix(gateway): aggregate all text chunks in non-streaming Gemini responses
...
Previously, collectGeminiSSE() only returned the last chunk received
from the upstream streaming response when converting to non-streaming.
This caused incomplete responses where only the final text fragment
was returned to clients.
For example, a request asking to "count from 1 to 10" would only
return "\n" (the last chunk) instead of "1\n2\n3\n...\n10\n".
This was especially problematic for JSON structured output where
the opening brace "{" from the first chunk was lost, resulting
in invalid JSON like: colors": ["red", "blue"]}
The fix:
- Collect all text parts from each SSE chunk into a slice
- Merge all collected text parts into the final response
- Reuse the same pattern as handleGeminiStreamToNonStreaming
in antigravity_gateway_service.go
Fixes: non-streaming responses returning incomplete text
Fixes: structured output (JSON schema) returning invalid JSON
2026-01-23 13:54:09 +00:00
yangjianbo
91f01309da
fix(调度): 完善粘性会话清理与账号调度刷新
...
- Update/BulkUpdate 按不可调度字段触发缓存刷新
- GatewayCache 支持多前缀会话键清理
- 模型路由与混合调度优化粘性会话处理
- 补充调度与缓存相关测试覆盖
2026-01-20 11:40:55 +08:00
IanShaw027
63711067e6
refactor(ops): 完善gateway服务ops集成
2026-01-14 14:30:00 +08:00
IanShaw027
060699c3b8
refactor(ops): 更新gateway服务集成ops功能
2026-01-14 12:40:49 +08:00
yangjianbo
3141aa5144
feat(scheduler): 引入调度快照缓存与 outbox 回放
...
- 调度热路径优先读 Redis 快照,保留分组排序语义
- outbox 回放 + 全量重建纠偏,失败重试不推进水位
- 自动 Atlas 基线对齐并同步调度配置示例
2026-01-12 14:19:06 +08:00
IanShaw027
7ebca553ef
feat(ops): 实现上游错误事件记录与查询功能
...
**新增功能**:
- 新建ops_upstream_error_events表存储上游服务错误详情
- 支持记录上游429/529/5xx错误的详细上下文信息
- 提供按时间范围查询上游错误事件的API
**后端改动**:
1. 模型层(ops_models.go, ops_port.go):
- 新增UpstreamErrorEvent结构体
- 扩展Repository接口支持上游错误事件CRUD
2. 仓储层(ops_repo.go):
- 实现InsertUpstreamErrorEvent写入上游错误
- 实现GetUpstreamErrorEvents按时间范围查询
3. 服务层(ops_service.go, ops_upstream_context.go):
- ops_service: 新增GetUpstreamErrorEvents查询方法
- ops_upstream_context: 封装上游错误上下文构建逻辑
4. Handler层(ops_error_logger.go):
- 新增GetUpstreamErrorsHandler处理上游错误查询请求
5. Gateway层集成:
- antigravity_gateway_service.go: 429/529错误时记录上游事件
- gateway_service.go: OpenAI 429/5xx错误时记录
- gemini_messages_compat_service.go: Gemini 429/5xx错误时记录
- openai_gateway_service.go: OpenAI 429/5xx错误时记录
- ratelimit_service.go: 429限流错误时记录
**数据记录字段**:
- request_id: 关联ops_logs主记录
- platform/model: 上游服务标识
- status_code/error_message: 错误详情
- request_headers/response_body: 调试信息(可选)
- created_at: 错误发生时间
2026-01-11 15:30:27 +08:00
yangjianbo
297f08c683
Merge branch 'test' into dev
2026-01-10 09:39:02 +08:00
yangjianbo
2597fe78ba
fix(分组): 防止降级环并校验上下文分组
...
- 增加降级链路环检测并拦截配置
- 仅复用合法分组上下文并必要时回退查询
- 标注 GetByIDLite 轻量语义并补充测试
2026-01-10 07:56:50 +08:00
yangjianbo
675543240e
perf(网关): 复用分组上下文减少热路径查询
...
新增 GetByIDLite 并在网关与 Gemini 选择流程复用上下文 group,避免 COUNT 触发
更新 API key 中间件注入 group 上下文,减少重复查库
补充 gateway/gemini 中间件与仓库层回归测试
测试: make test
2026-01-09 23:01:42 +08:00
Song Siyu
7d1fe818be
feat: antigravity 配额域限流 + SSE 上限 ( #222 )
...
* fix: 添加 gemini-3-flash 前缀映射支持 gemini-3-flash-preview
* feat(antigravity): 增强请求参数和注入 Antigravity 身份 system prompt
* feat: antigravity 配额域限流
* chore: 调整 SSE 单行上限到 25MB
* chore: 提升 SSE 单行上限到 40MB
2026-01-09 22:00:14 +08:00
Edric Li
a42105881f
feat(groups): add Claude Code client restriction and session isolation
...
- Add claude_code_only field to restrict groups to Claude Code clients only
- Add fallback_group_id for non-Claude Code requests to use alternate group
- Implement ClaudeCodeValidator for User-Agent detection
- Add group-level session binding isolation (groupID in Redis key)
- Prevent cross-group sticky session pollution
- Update frontend with Claude Code restriction controls
2026-01-08 23:07:00 +08:00
yangjianbo
fb313356f7
Merge branch 'main' into test-dev
2026-01-05 14:43:08 +08:00
yangjianbo
048ed061c2
fix(安全): 关闭白名单时保留最小校验与默认白名单
...
实现 allow_insecure_http 并在关闭校验时执行最小格式验证
- 关闭 allowlist 时要求 URL 可解析且 scheme 合规
- 响应头过滤关闭时使用默认白名单策略
- 更新相关文档、示例与测试覆盖
2026-01-05 14:41:08 +08:00
yangjianbo
794a9f969b
feat(安全): 添加安全开关并完善测试流程
...
实现安全开关默认关闭与响应头透传逻辑
- URL 校验与响应头过滤支持开关并覆盖流式路径
- 非流式 Content-Type 透传/默认值按配置生效
- 接入 go test、golangci-lint 与前端 lint/typecheck
- 补充相关测试与配置/文档说明
2026-01-05 13:54:43 +08:00
IanShaw027
aa6f253374
merge: 合并 upstream/main 并解决冲突
...
解决了以下文件的冲突:
- backend/internal/handler/admin/setting_handler.go
- 采用 upstream 的字段对齐风格和 *Configured 字段名
- 添加 EnableIdentityPatch 和 IdentityPatchPrompt 字段
- backend/internal/handler/gateway_handler.go
- 采用 upstream 的 billingErrorDetails 错误处理方式
- frontend/src/api/admin/settings.ts
- 采用 upstream 的 *_configured 字段名
- 添加 enable_identity_patch 和 identity_patch_prompt 字段
- frontend/src/views/admin/SettingsView.vue
- 合并 turnstile_secret_key_configured 字段
- 保留 enable_identity_patch 和 identity_patch_prompt 字段
2026-01-04 23:17:15 +08:00
IanShaw027
87426e5dda
fix(backend): 改进 thinking/tool block 签名处理和重试策略
...
主要改动:
- request_transformer: thinking block 缺少签名时降级为文本而非丢弃,保留内容并在上层禁用 thinking mode
- antigravity_gateway_service: 新增两阶段降级策略,先处理 thinking blocks,如仍失败且涉及 tool 签名错误则进一步降级 tool blocks
- gateway_request: 新增 FilterSignatureSensitiveBlocksForRetry 函数,支持将 tool_use/tool_result 降级为文本
- gateway_request: 改进 FilterThinkingBlocksForRetry,禁用顶层 thinking 配置以避免结构约束冲突
- gateway_service: 实现保守的两阶段重试逻辑,优先保留内容,仅在必要时降级工具调用
- 新增 antigravity_gateway_service_test.go 测试签名块剥离逻辑
- 更新相关测试用例以验证降级行为
此修复解决了跨平台/账户切换时历史消息签名失效导致的请求失败问题。
2026-01-04 22:32:36 +08:00
yangjianbo
7dddd06583
Merge branch 'main' of https://github.com/mt21625457/aicodex2api
2026-01-04 21:06:12 +08:00
IanShaw027
a4953785d9
fix(lint): 修复所有 Go 命名规范问题
...
- 全局替换 ApiKey → APIKey(类型、字段、方法、变量)
- 修复所有 initialism 命名(API, SMTP, HTML, URL 等)
- 添加所有缺失的包注释
- 修复导出符号的注释格式
主要修改:
- ApiKey → APIKey(所有出现的地方)
- ApiKeyID → APIKeyID
- ApiKeyIDs → APIKeyIDs
- TestSmtpConnection → TestSMTPConnection
- HtmlURL → HTMLURL
- 添加 20+ 个包注释
- 修复 10+ 个导出符号注释格式
验证结果:
- ✓ golangci-lint: 0 issues
- ✓ 单元测试: 通过
- ✓ 集成测试: 通过
2026-01-04 19:28:20 +08:00
IanShaw027
a185ad1144
feat(gemini): 完善 Gemini OAuth 配额系统和用量显示
...
主要改动:
- 后端:重构 Gemini 配额服务,支持多层级配额策略(GCP Standard/Free, Google One, AI Studio, Code Assist)
- 后端:优化 OAuth 服务,增强 tier_id 识别和存储逻辑
- 后端:改进用量统计服务,支持不同平台的配额查询
- 后端:优化限流服务,增加临时解除调度状态管理
- 前端:统一四种授权方式的用量显示格式和徽标样式
- 前端:增强账户配额信息展示,支持多种配额类型
- 前端:改进创建和重新授权模态框的用户体验
- 国际化:完善中英文配额相关文案
- 移除 CHANGELOG.md 文件
测试:所有单元测试通过
2026-01-04 15:36:00 +08:00
ianshaw
26106eb0ac
feat(gemini): 优化 OAuth 和配额展示
...
主要改进:
- 修复 google_one OAuth scopes 配置问题
- 添加 Gemini 账号配额展示组件
- 优化 Code Assist 类型检测逻辑
- 添加 OAuth 测试用例
2026-01-03 06:32:04 -08:00
yangjianbo
e51a32881b
merge: 合并 test 分支到 test-dev,解决冲突
...
解决的冲突文件:
- wire_gen.go: 合并 ConcurrencyService/CRSSyncService 参数和 userAttributeHandler
- gateway_handler.go: 合并 pkg/errors 和 antigravity 导入
- gateway_service.go: 合并 validateUpstreamBaseURL 和 GetAvailableModels
- config.example.yaml: 合并 billing/turnstile 配置和额外 gateway 选项
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2026-01-03 11:36:31 +08:00
IanShaw
45bd9ac705
运维监控系统安全加固和功能优化 ( #21 )
...
* fix(ops): 修复运维监控系统的关键安全和稳定性问题
## 修复内容
### P0 严重问题
1. **DNS Rebinding防护** (ops_alert_service.go)
- 实现IP钉住机制防止验证后的DNS rebinding攻击
- 自定义Transport.DialContext强制只允许拨号到验证过的公网IP
- 扩展IP黑名单,包括云metadata地址(169.254.169.254)
- 添加完整的单元测试覆盖
2. **OpsAlertService生命周期管理** (wire.go)
- 在ProvideOpsMetricsCollector中添加opsAlertService.Start()调用
- 确保stopCtx正确初始化,避免nil指针问题
- 实现防御式启动,保证服务启动顺序
3. **数据库查询排序** (ops_repo.go)
- 在ListRecentSystemMetrics中添加显式ORDER BY updated_at DESC, id DESC
- 在GetLatestSystemMetric中添加排序保证
- 避免数据库返回顺序不确定导致告警误判
### P1 重要问题
4. **并发安全** (ops_metrics_collector.go)
- 为lastGCPauseTotal字段添加sync.Mutex保护
- 防止数据竞争
5. **Goroutine泄漏** (ops_error_logger.go)
- 实现worker pool模式限制并发goroutine数量
- 使用256容量缓冲队列和10个固定worker
- 非阻塞投递,队列满时丢弃任务
6. **生命周期控制** (ops_alert_service.go)
- 添加Start/Stop方法实现优雅关闭
- 使用context控制goroutine生命周期
- 实现WaitGroup等待后台任务完成
7. **Webhook URL验证** (ops_alert_service.go)
- 防止SSRF攻击:验证scheme、禁止内网IP
- DNS解析验证,拒绝解析到私有IP的域名
- 添加8个单元测试覆盖各种攻击场景
8. **资源泄漏** (ops_repo.go)
- 修复多处defer rows.Close()问题
- 简化冗余的defer func()包装
9. **HTTP超时控制** (ops_alert_service.go)
- 创建带10秒超时的http.Client
- 添加buildWebhookHTTPClient辅助函数
- 防止HTTP请求无限期挂起
10. **数据库查询优化** (ops_repo.go)
- 将GetWindowStats的4次独立查询合并为1次CTE查询
- 减少网络往返和表扫描次数
- 显著提升性能
11. **重试机制** (ops_alert_service.go)
- 实现邮件发送重试:最多3次,指数退避(1s/2s/4s)
- 添加webhook备用通道
- 实现完整的错误处理和日志记录
12. **魔法数字** (ops_repo.go, ops_metrics_collector.go)
- 提取硬编码数字为有意义的常量
- 提高代码可读性和可维护性
## 测试验证
- ✅ go test ./internal/service -tags opsalert_unit 通过
- ✅ 所有webhook验证测试通过
- ✅ 重试机制测试通过
## 影响范围
- 运维监控系统安全性显著提升
- 系统稳定性和性能优化
- 无破坏性变更,向后兼容
* feat(ops): 运维监控系统V2 - 完整实现
## 核心功能
- 运维监控仪表盘V2(实时监控、历史趋势、告警管理)
- WebSocket实时QPS/TPS监控(30s心跳,自动重连)
- 系统指标采集(CPU、内存、延迟、错误率等)
- 多维度统计分析(按provider、model、user等维度)
- 告警规则管理(阈值配置、通知渠道)
- 错误日志追踪(详细错误信息、堆栈跟踪)
## 数据库Schema (Migration 025)
### 扩展现有表
- ops_system_metrics: 新增RED指标、错误分类、延迟指标、资源指标、业务指标
- ops_alert_rules: 新增JSONB字段(dimension_filters, notify_channels, notify_config)
### 新增表
- ops_dimension_stats: 多维度统计数据
- ops_data_retention_config: 数据保留策略配置
### 新增视图和函数
- ops_latest_metrics: 最新1分钟窗口指标(已修复字段名和window过滤)
- ops_active_alerts: 当前活跃告警(已修复字段名和状态值)
- calculate_health_score: 健康分数计算函数
## 一致性修复(98/100分)
### P0级别(阻塞Migration)
- ✅ 修复ops_latest_metrics视图字段名(latency_p99→p99_latency_ms, cpu_usage→cpu_usage_percent)
- ✅ 修复ops_active_alerts视图字段名(metric→metric_type, triggered_at→fired_at, trigger_value→metric_value, threshold→threshold_value)
- ✅ 统一告警历史表名(删除ops_alert_history,使用ops_alert_events)
- ✅ 统一API参数限制(ListMetricsHistory和ListErrorLogs的limit改为5000)
### P1级别(功能完整性)
- ✅ 修复ops_latest_metrics视图未过滤window_minutes(添加WHERE m.window_minutes = 1)
- ✅ 修复数据回填UPDATE逻辑(QPS计算改为request_count/(window_minutes*60.0))
- ✅ 添加ops_alert_rules JSONB字段后端支持(Go结构体+序列化)
### P2级别(优化)
- ✅ 前端WebSocket自动重连(指数退避1s→2s→4s→8s→16s,最大5次)
- ✅ 后端WebSocket心跳检测(30s ping,60s pong超时)
## 技术实现
### 后端 (Go)
- Handler层: ops_handler.go(REST API), ops_ws_handler.go(WebSocket)
- Service层: ops_service.go(核心逻辑), ops_cache.go(缓存), ops_alerts.go(告警)
- Repository层: ops_repo.go(数据访问), ops.go(模型定义)
- 路由: admin.go(新增ops相关路由)
- 依赖注入: wire_gen.go(自动生成)
### 前端 (Vue3 + TypeScript)
- 组件: OpsDashboardV2.vue(仪表盘主组件)
- API: ops.ts(REST API + WebSocket封装)
- 路由: index.ts(新增/admin/ops路由)
- 国际化: en.ts, zh.ts(中英文支持)
## 测试验证
- ✅ 所有Go测试通过
- ✅ Migration可正常执行
- ✅ WebSocket连接稳定
- ✅ 前后端数据结构对齐
* refactor: 代码清理和测试优化
## 测试文件优化
- 简化integration test fixtures和断言
- 优化test helper函数
- 统一测试数据格式
## 代码清理
- 移除未使用的代码和注释
- 简化concurrency_cache实现
- 优化middleware错误处理
## 小修复
- 修复gateway_handler和openai_gateway_handler的小问题
- 统一代码风格和格式
变更统计: 27个文件,292行新增,322行删除(净减少30行)
* fix(ops): 运维监控系统安全加固和功能优化
## 安全增强
- feat(security): WebSocket日志脱敏机制,防止token/api_key泄露
- feat(security): X-Forwarded-Host白名单验证,防止CSRF绕过
- feat(security): Origin策略配置化,支持strict/permissive模式
- feat(auth): WebSocket认证支持query参数传递token
## 配置优化
- feat(config): 支持环境变量配置代理信任和Origin策略
- OPS_WS_TRUST_PROXY
- OPS_WS_TRUSTED_PROXIES
- OPS_WS_ORIGIN_POLICY
- fix(ops): 错误日志查询限流从5000降至500,优化内存使用
## 架构改进
- refactor(ops): 告警服务解耦,独立运行评估定时器
- refactor(ops): OpsDashboard统一版本,移除V2分离
## 测试和文档
- test(ops): 添加WebSocket安全验证单元测试(8个测试用例)
- test(ops): 添加告警服务集成测试
- docs(api): 更新API文档,标注限流变更
- docs: 添加CHANGELOG记录breaking changes
## 修复文件
Backend:
- backend/internal/server/middleware/logger.go
- backend/internal/handler/admin/ops_handler.go
- backend/internal/handler/admin/ops_ws_handler.go
- backend/internal/server/middleware/admin_auth.go
- backend/internal/service/ops_alert_service.go
- backend/internal/service/ops_metrics_collector.go
- backend/internal/service/wire.go
Frontend:
- frontend/src/views/admin/ops/OpsDashboard.vue
- frontend/src/router/index.ts
- frontend/src/api/admin/ops.ts
Tests:
- backend/internal/handler/admin/ops_ws_handler_test.go (新增)
- backend/internal/service/ops_alert_service_integration_test.go (新增)
Docs:
- CHANGELOG.md (新增)
- docs/API-运维监控中心2.0.md (更新)
* fix(migrations): 修复calculate_health_score函数类型匹配问题
在ops_latest_metrics视图中添加显式类型转换,确保参数类型与函数签名匹配
* fix(lint): 修复golangci-lint检查发现的所有问题
- 将Redis依赖从service层移到repository层
- 添加错误检查(WebSocket连接和读取超时)
- 运行gofmt格式化代码
- 添加nil指针检查
- 删除未使用的alertService字段
修复问题:
- depguard: 3个(service层不应直接import redis)
- errcheck: 3个(未检查错误返回值)
- gofmt: 2个(代码格式问题)
- staticcheck: 4个(nil指针解引用)
- unused: 1个(未使用字段)
代码统计:
- 修改文件:11个
- 删除代码:490行
- 新增代码:105行
- 净减少:385行
2026-01-02 20:01:12 +08:00
yangjianbo
bd4bf00856
feat(安全): 强化安全策略与配置校验
...
- 增加 CORS/CSP/安全响应头与代理信任配置
- 引入 URL 白名单与私网开关,校验上游与价格源
- 改善 API Key 处理与网关错误返回
- 管理端设置隐藏敏感字段并优化前端提示
- 增加计费熔断与相关配置示例
测试: go test ./...
2026-01-02 17:40:57 +08:00
IanShaw027
4a7e2a44d9
fix(lint): 修复 golangci-lint 问题(gofmt + staticcheck)
2026-01-01 04:32:37 +08:00
IanShaw027
06d483fa8d
feat(backend): implement gemini quota simulation and rate limiting
...
- feat: add local quota tracking for gemini tiers (Legacy/Pro/Ultra)
- feat: implement PreCheckUsage in RateLimitService
- feat: align gemini daily reset window with PST
- fix: sticky session fallback logic
2026-01-01 04:29:22 +08:00
IanShaw027
e49281774d
fix(gemini): 修复 P0/P1 级别问题(429误判/Tier丢失/expires_at/前端一致性)
...
P0 修复(Critical - 影响生产稳定性):
- 修复 429 判断逻辑:使用 project_id 判断而非 account.Type
防止 AI Studio OAuth 被误判为 Code Assist 5分钟窗口
- 修复 Tier ID 丢失:刷新时始终保留旧值,默认 LEGACY
防止 fetchProjectID 失败导致 tier_id 被清空
- 修复 expires_at 下界:添加 minTTL=30s 保护
防止 expires_in <= 300 时生成过去时间引发刷新风暴
P1 修复(Important - 行为一致性):
- 前端 isCodeAssist 判断与后端一致(支持 legacy)
- 前端日期解析添加 NaN 保护
- 迁移脚本覆盖 legacy 账号
前端功能(新增):
- AccountQuotaInfo 组件:Tier Badge + 二元进度条 + 倒计时
- 定时器动态管理:watch 监听限流状态
- 类型定义:GeminiCredentials 接口
测试:
- ✅ TypeScript 类型检查通过
- ✅ 前端构建成功(3.33s)
- ✅ Gemini + Codex 双 AI 审查通过
Refs: #gemini-quota
2026-01-01 04:29:22 +08:00
IanShaw
34c102045a
fix: 修复 /v1/messages 间歇性 400 错误 ( #18 )
...
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* feat(gemini): 添加Gemini限额与TierID支持
实现PR1:Gemini限额与TierID功能
后端修改:
- GeminiTokenInfo结构体添加TierID字段
- fetchProjectID函数返回(projectID, tierID, error)
- 从LoadCodeAssist响应中提取tierID(优先IsDefault,回退到第一个非空tier)
- ExchangeCode、RefreshAccountToken、GetAccessToken函数更新以处理tierID
- BuildAccountCredentials函数保存tier_id到credentials
前端修改:
- AccountStatusIndicator组件添加tier显示
- 支持LEGACY/PRO/ULTRA等tier类型的友好显示
- 使用蓝色badge展示tier信息
技术细节:
- tierID提取逻辑:优先选择IsDefault的tier,否则选择第一个非空tier
- 所有fetchProjectID调用点已更新以处理新的返回签名
- 前端gracefully处理missing/unknown tier_id
* refactor(gemini): 优化TierID实现并添加安全验证
根据并发代码审查(code-reviewer, security-auditor, gemini, codex)的反馈进行改进:
安全改进:
- 添加validateTierID函数验证tier_id格式和长度(最大64字符)
- 限制tier_id字符集为字母数字、下划线、连字符和斜杠
- 在BuildAccountCredentials中验证tier_id后再存储
- 静默跳过无效tier_id,不阻塞账户创建
代码质量改进:
- 提取extractTierIDFromAllowedTiers辅助函数消除重复代码
- 重构fetchProjectID函数,tierID提取逻辑只执行一次
- 改进代码可读性和可维护性
审查工具:
- code-reviewer agent (a09848e)
- security-auditor agent (a9a149c)
- gemini CLI (bcc7c81)
- codex (b5d8919)
修复问题:
- HIGH: 未验证的tier_id输入
- MEDIUM: 代码重复(tierID提取逻辑重复2次)
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(upstream): 修复上游格式兼容性问题 (#14 )
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(format): 修复 claude_types.go 的 gofmt 格式问题
* feat(antigravity): 优化 thinking block 和 schema 处理
- 为 dummy thinking block 添加 ThoughtSignature
- 重构 thinking block 处理逻辑,在每个条件分支内创建 part
- 优化 excludedSchemaKeys,移除 Gemini 实际支持的字段
(minItems, maxItems, minimum, maximum, additionalProperties, format)
- 添加详细注释说明 Gemini API 支持的 schema 字段
* fix(antigravity): 增强 schema 清理的安全性
基于 Codex review 建议:
- 添加 format 字段白名单过滤,只保留 Gemini 支持的 date-time/date/time
- 补充更多不支持的 schema 关键字到黑名单:
* 组合 schema: oneOf, anyOf, allOf, not, if/then/else
* 对象验证: minProperties, maxProperties, patternProperties 等
* 定义引用: $defs, definitions
- 避免不支持的 schema 字段导致 Gemini API 校验失败
* fix(lint): 修复 gemini_messages_compat_service 空分支警告
- 在 cleanToolSchema 的 if 语句中添加 continue
- 移除重复的注释
* fix(antigravity): 移除 minItems/maxItems 以兼容 Claude API
- 将 minItems 和 maxItems 添加到 schema 黑名单
- Claude API (Vertex AI) 不支持这些数组验证字段
- 添加调试日志记录工具 schema 转换过程
- 修复 tools.14.custom.input_schema 验证错误
* fix(antigravity): 修复 additionalProperties schema 对象问题
- 将 additionalProperties 的 schema 对象转换为布尔值 true
- Claude API 只支持 additionalProperties: false,不支持 schema 对象
- 修复 tools.14.custom.input_schema 验证错误
- 参考 Claude 官方文档的 JSON Schema 限制
* fix(antigravity): 修复 Claude 模型 thinking 块兼容性问题
- 完全跳过 Claude 模型的 thinking 块以避免 signature 验证失败
- 只在 Gemini 模型中使用 dummy thought signature
- 修改 additionalProperties 默认值为 false(更安全)
- 添加调试日志以便排查问题
* fix(upstream): 修复跨模型切换时的 dummy signature 问题
基于 Codex review 和用户场景分析的修复:
1. 问题场景
- Gemini (thinking) → Claude (thinking) 切换时
- Gemini 返回的 thinking 块使用 dummy signature
- Claude API 会拒绝 dummy signature,导致 400 错误
2. 修复内容
- request_transformer.go:262: 跳过 dummy signature
- 只保留真实的 Claude signature
- 支持频繁的跨模型切换
3. 其他修复(基于 Codex review)
- gateway_service.go:691: 修复 io.ReadAll 错误处理
- gateway_service.go:687: 条件日志(尊重 LogUpstreamErrorBody 配置)
- gateway_service.go:915: 收紧 400 failover 启发式
- request_transformer.go:188: 移除签名成功日志
4. 新增功能(默认关闭)
- 阶段 1: 上游错误日志(GATEWAY_LOG_UPSTREAM_ERROR_BODY)
- 阶段 2: Antigravity thinking 修复
- 阶段 3: API-key beta 注入(GATEWAY_INJECT_BETA_FOR_APIKEY)
- 阶段 3: 智能 400 failover(GATEWAY_FAILOVER_ON_400)
测试:所有测试通过
* fix(lint): 修复 golangci-lint 问题
- 应用 De Morgan 定律简化条件判断
- 修复 gofmt 格式问题
- 移除未使用的 min 函数
2026-01-01 04:21:18 +08:00
IanShaw027
c1e25b7ecf
fix(upstream): 完善边界检查和 thinking block 处理
...
基于 Gemini + Codex 审查结果的修复:
1. thinking block dummy signature 填充
- Gemini 模型现在会填充 dummyThoughtSignature
- 与 tool_use 处理逻辑保持一致
2. 边界检查增强
- buildTools: 跳过空工具名称
- buildTools: 为 nil schema 提供默认值
- convertClaudeToolsToGeminiTools: 为 nil params 提供默认值
3. 防止下游 API 验证错误
- 确保所有工具都有有效的 parameters
- 默认 schema: {type: 'object', properties: {}}
审查报告:Gemini 评分 95%, Codex 评分 8.2/10
2025-12-31 21:44:56 +08:00
IanShaw027
15e676e9cd
fix(upstream): 支持 Claude custom 类型工具 (MCP) 格式
...
- ClaudeTool 结构体增加 Type 和 Custom 字段
- buildTools 函数支持从 custom 字段读取 input_schema
- convertClaudeToolsToGeminiTools 函数支持 MCP 工具格式
- 修复 Antigravity upstream error 400: JSON schema invalid
修复 Issue 0.2: tools.X.custom.input_schema 验证错误
2025-12-31 20:56:38 +08:00
yangjianbo
d1c9889609
perf(网关): 实现上游账号连接池隔离
...
新增隔离策略与连接池缓存回收
连接池大小跟随账号并发并处理代理切换
同步配置默认值与示例并补充测试
2025-12-31 11:43:58 +08:00
yangjianbo
7efa8b54c4
perf(后端): 完成性能优化与连接池配置
...
新增 DB/Redis 连接池配置与校验,并补充单测
网关请求体大小限制与 413 处理
HTTP/req 客户端池化并调整上游连接池默认值
并发槽位改为 ZSET+Lua 与指数退避
用量统计改 SQL 聚合并新增索引迁移
计费缓存写入改工作池并补测试/基准
测试: 在 backend/ 下运行 go test ./...
2025-12-31 08:50:12 +08:00
song
caa8c47b68
fix(antigravity): 修复 429 限流处理逻辑
...
- 只有 5 次重试全部失败后才标记账户限流
- 使用 Gemini 格式解析 429 响应中的重试时间
- Claude 模型无重试时间时默认 1 分钟,Gemini 默认 5 分钟
- 添加生图模型映射 gemini-3-pro-image-preview
2025-12-29 21:28:28 +08:00
song
21a04332ec
fix: 修复 golangci-lint 检查错误
...
- SA1029: 创建 ctxkey 包定义类型安全的 context key
- ST1005: 错误字符串首字母改小写
- errcheck: 显式忽略 bytes.Buffer.Write 返回值
- 修复单元测试中 GatewayService 缺少 cfg 字段的问题
2025-12-29 17:46:52 +08:00
song
b31bfd53ab
feat(antigravity): 添加专用路由,支持仅使用 antigravity 账户
...
添加 /antigravity/v1/* 和 /antigravity/v1beta/* 路由:
- 通过 ForcePlatform 中间件强制使用 antigravity 平台
- 跳过混合调度逻辑,仅调度 antigravity 账户
- 支持按分组优先查找,找不到时回退查询全部 antigravity 账户
修复 context key 类型不匹配问题:
- middleware 和 service 统一使用字符串常量 "ctx_force_platform"
- 解决 Go context.Value() 类型+值匹配导致的读取失败
其他改动:
- 嵌入式前端中间件白名单添加 /antigravity/ 路径
- e2e 测试 Gemini 端点 URL 添加 endpointPrefix 支持
2025-12-29 16:52:55 +08:00