Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4ef98a25e | ||
|
|
0a86b5a291 | ||
|
|
9309ad1ffc | ||
|
|
81d4650f3d | ||
|
|
c7cc5616ed |
+1
-1
@@ -1 +1 @@
|
||||
0.6.5
|
||||
0.6.6
|
||||
@@ -1,6 +1,6 @@
|
||||
# Backend Development Guidelines(oci-portal 后端规范)
|
||||
|
||||
> Go 后端(`oci-portal/`)编码规范入口。规范提炼自 Google / Uber Go Style Guide、Effective Go 与 Go 官方模块布局指南,按本项目裁剪;条目与项目约定冲突时,以本 spec 为准。迁自 docs/开发指南.md 与根目录 AGENTS.md(2026-07)。
|
||||
> Go 后端(`oci-portal/`)编码规范入口。规范提炼自 Google / Uber Go Style Guide、Effective Go 与 Go 官方模块布局指南,按本项目裁剪;条目与项目约定冲突时,以本 spec 为准。
|
||||
|
||||
---
|
||||
|
||||
@@ -51,7 +51,7 @@ go mod tidy # 依赖有变更时
|
||||
全部 HTTP 接口带 swaggo 注释(@Summary 中文/@Tags 按域/@Param/@Success/@Router;JWT 组接口标 @Security BearerAuth)。**新增或修改接口必须同步注释**,并重新生成 spec:
|
||||
|
||||
```bash
|
||||
go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency
|
||||
go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency --overridesFile docs/.swaggo
|
||||
```
|
||||
|
||||
生成的 `docs/` 一并提交;UI 由 `SWAGGER=1` 开启(/swagger/index.html)。同名 handler 方法(list/create/get/update/remove)分布在多个 struct 上,写注释时确认 @Router 路径与该 receiver 的真实注册一致(routes_*.go)。
|
||||
|
||||
+13
-13
@@ -183,7 +183,7 @@ Complex task: ask the user if you can create a Trellis task and enter the planni
|
||||
- 1.0 Create task `[required · once]` (only after task-creation consent)
|
||||
- 1.1 Requirement exploration `[required · repeatable]` (`prd.md`; complex tasks also need `design.md` + `implement.md`)
|
||||
- 1.2 Research `[optional · repeatable]`
|
||||
- 1.3 Configure context `[required · once]` — Claude Code, Cursor, OpenCode, Codex, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix (sub-agent-dispatch platforms only; inline platforms skip)
|
||||
- 1.3 Configure context `[required · once]` — Claude Code, Cursor, OpenCode, Codex, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix (sub-agent-dispatch platforms only; inline platforms skip)
|
||||
- 1.4 Activate task `[required · once]` (review gate, then `task.py start`; status → in_progress)
|
||||
- 1.5 Completion criteria
|
||||
|
||||
@@ -272,13 +272,13 @@ Code committed. Run `/trellis:finish-work`; if dirty, return to Phase 3.4 first.
|
||||
|
||||
When a user request matches one of these intents inside an active task, route first, then load the detailed phase step if needed.
|
||||
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
- Planning or unclear requirements -> `trellis-brainstorm`.
|
||||
- `in_progress` implementation/check -> dispatch `trellis-implement` / `trellis-check`.
|
||||
- Repeated debugging -> `trellis-break-loop`; spec updates -> `trellis-update-spec`.
|
||||
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
[codex-inline, Kilo, Antigravity, Devin]
|
||||
|
||||
@@ -353,7 +353,7 @@ Return to this step whenever requirements change and revise the relevant artifac
|
||||
|
||||
Research can happen at any time during requirement exploration. It isn't limited to local code — you can use any available tool (MCP servers, skills, web search, etc.) to look up external information, including third-party library docs, industry practices, API references, etc.
|
||||
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
Spawn the research sub-agent:
|
||||
|
||||
@@ -361,7 +361,7 @@ Spawn the research sub-agent:
|
||||
- **Task description**: Research <specific question>
|
||||
- **Key requirement**: Research output MUST be persisted to `{TASK_DIR}/research/`
|
||||
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
[codex-inline, Kilo, Antigravity, Devin]
|
||||
|
||||
@@ -380,7 +380,7 @@ Brainstorm and research can interleave freely — pause to research a technical
|
||||
|
||||
#### 1.3 Configure context `[required · once]`
|
||||
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
Curate `implement.jsonl` and `check.jsonl` so the Phase 2 sub-agents get the right spec/research context. These files were seeded on `task create` with a single self-describing `_example` line; your job here is to fill in real entries.
|
||||
|
||||
@@ -425,7 +425,7 @@ Ready gate: both `implement.jsonl` and `check.jsonl` must contain at least one r
|
||||
|
||||
Skip this step only when both files already have real curated entries.
|
||||
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
[codex-inline, Kilo, Antigravity, Devin]
|
||||
|
||||
@@ -458,11 +458,11 @@ If `task.py start` errors with a session-identity message (no context key from h
|
||||
| `design.md` exists (complex tasks) | ✅ |
|
||||
| `implement.md` exists (complex tasks) | ✅ |
|
||||
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
| `implement.jsonl` and `check.jsonl` each contain at least one real curated entry (seed row does not count) | ✅ |
|
||||
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
---
|
||||
|
||||
@@ -472,7 +472,7 @@ Goal: turn reviewed planning artifacts into code that passes quality checks.
|
||||
|
||||
#### 2.1 Implement `[required · repeatable]`
|
||||
|
||||
[Claude Code, Cursor, OpenCode, CodeBuddy, Droid, Pi]
|
||||
[Claude Code, Cursor, OpenCode, CodeBuddy, Droid, Pi, Oh My Pi]
|
||||
|
||||
Spawn the implement sub-agent:
|
||||
|
||||
@@ -484,7 +484,7 @@ The platform hook/plugin auto-handles:
|
||||
- Reads `implement.jsonl` and injects referenced spec/research files into the agent prompt
|
||||
- Injects `prd.md`, `design.md` if present, and `implement.md` if present
|
||||
|
||||
[/Claude Code, Cursor, OpenCode, CodeBuddy, Droid, Pi]
|
||||
[/Claude Code, Cursor, OpenCode, CodeBuddy, Droid, Pi, Oh My Pi]
|
||||
|
||||
[codex-sub-agent, Gemini, Qoder, Copilot, ZCode, Reasonix, Trae]
|
||||
|
||||
@@ -526,7 +526,7 @@ The platform prelude auto-handles the context load requirement:
|
||||
|
||||
#### 2.2 Quality check `[required · repeatable]`
|
||||
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
Spawn the check sub-agent:
|
||||
|
||||
@@ -540,7 +540,7 @@ The check agent's job:
|
||||
- Auto-fix issues it finds
|
||||
- Run lint and typecheck to verify
|
||||
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, ZCode, Reasonix, Trae]
|
||||
[/Claude Code, Cursor, OpenCode, codex-sub-agent, Kiro, Gemini, Qoder, CodeBuddy, Copilot, Droid, Pi, Oh My Pi, ZCode, Reasonix, Trae]
|
||||
|
||||
[codex-inline, Kilo, Antigravity, Devin]
|
||||
|
||||
|
||||
+61
-4
@@ -1,8 +1,65 @@
|
||||
# Changelog
|
||||
|
||||
格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循语义化版本。
|
||||
格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)(版本段不记日期),版本号遵循语义化版本。
|
||||
|
||||
## [0.2.0] - 2026-07-12
|
||||
## [0.5.0]
|
||||
|
||||
### Added
|
||||
|
||||
- xAI 官方格式文本转语音端点 `POST /ai/v1/tts`:接受 xAI 官方 TTS 请求(`text` / `language` 必填,`voice_id`、`output_format`{codec, sample_rate, bit_rate}、`speed` 等),网关转换为 OpenAI 兼容形态后与 `/ai/v1/audio/speech` 走同一上游与渠道调度;`model` 为网关扩展字段(缺省 `xai.grok-tts`);实测 `output_format` 对象与 `speed` 透传生效,xAI SDK / 客户端可直接指向网关
|
||||
- 「过滤弃用模型」开关(`GET` / `PUT /api/v1/ai-settings`,持久化):开启后 OCI 已宣布弃用(即使未到退役日)的模型从模型列表与路由中同时排除,关闭恢复;渠道同步入库与 30 天退役提醒不受影响
|
||||
|
||||
### Changed
|
||||
|
||||
- AI 网关文档更名为 `docs/AI网关.md`(原 `docs/ai-gateway.md`),README 引用同步
|
||||
|
||||
## [0.4.0]
|
||||
|
||||
### Added
|
||||
|
||||
- 文本转语音端点 `POST /ai/v1/audio/speech`:OpenAI Audio Speech 兼容,直通 OCI 兼容面(模型 `xai.grok-tts`,voice 取 xAI Grok Voice 列表 `ara`/`eve`/`leo`/`rex`/`sal`);上游必填的 `language` 缺省时自动注入 `"auto"`,xAI 专属参数平铺透传;响应为一次性完整音频(Content-Type 透传上游,缺省 audio/mpeg),不提供流式
|
||||
- 文档重排端点 `POST /ai/v1/rerank`:Jina / Cohere 通行协议,走 OCI typed 面(`cohere.rerank-v4.0-pro` / `-fast`),支持 `top_n` 与 `return_documents`,`results[].index` 指向入参 `documents` 下标
|
||||
- 内容审核端点 `POST /ai/v1/moderations`:OpenAI moderations 外壳映射 OCI Guardrails(内容审核 / PII / 提示注入),`input` 为字符串或字符串数组(单次至多 8 条),categories 用 OCI 原生维度 `overall` / `blocklist` / `prompt_injection`(任一得分 ≥0.5 判 `flagged`),PII 命中放扩展字段 `results[].pii`(不参与 flagged;实测中文人名 / 手机号识别较弱,英文正常)
|
||||
- Responses 服务端工具扩展:放行 Oracle 文档化的 xAI `code_interpreter` 与远程 `mcp` 工具,并解除 `web_search` / `x_search` 仅非流式的限制——四类服务端工具非流式与流式均实测可用;`code_interpreter` 的命名容器管理与 File Search 不提供
|
||||
- 模型能力映射扩展:`TEXT_RERANK` → RERANK、`TEXT_TO_AUDIO` → TTS,渠道探测 / 同步自动发现重排与语音模型入池
|
||||
|
||||
### Changed
|
||||
|
||||
- AI 网关文档独立成篇 `docs/ai-gateway.md`(端点定位、兼容边界、已知上游限制、字段兼容矩阵——矩阵只列支持项,不支持 / 忽略项以文字简述),README 精简为概览并引用;实测披露:Responses `input_file` 内容块被上游以 ZDR 形态拒绝,能力不可用
|
||||
- swagger 全面修缺:135 处响应注解从泛型 map 改为具体类型(补文档用途响应结构与泛型列表外壳),AI 网关端点请求 / 响应 schema 完整可见;`json.RawMessage` 与联合类型统一渲染为任意 JSON 值(AnyJSON),不再误显示为 byte 数组;swag overrides 配置移至 `docs/.swaggo`,生成命令加 `--overridesFile docs/.swaggo`;顺带修正网页控制台会话创建响应码(200→201)与 SAML 元数据下载(改文件响应)两处注解失真
|
||||
|
||||
## [0.3.1]
|
||||
|
||||
### Added
|
||||
|
||||
- AI 网关流式断流自动降级:Messages 与 Chat Completions 流式请求在客户端尚未收到任何输出时遭遇上游断流,自动降级为非流式重做,结果按标准事件 / chunk 序列一次推送,调用日志记 `retries=1` 与降级标记。实测 OCI 兼容面对 `instructions` 与 `tools` 合计超约 64.5KB 的流式请求会静默断连(无错误事件,非流式正常,消息正文不计入),Claude Code 等大体量系统提示客户端极易触发;Responses 直通因初始事件已转发无法透明降级,日志记「上游流提前终止」;README 增补「已知上游限制:大 system 区流式断流」小节
|
||||
|
||||
### Changed
|
||||
|
||||
- Messages 的 `max_tokens` 改为可缺省:缺省或 ≤0 时按默认值 8192 放行(此前返回 400;部分客户端将该字段视为选填)
|
||||
|
||||
### Fixed
|
||||
|
||||
- AI 网关流式假成功:上游 error / `response.failed` 事件此前被吞掉,流提前 EOF 也被伪装成正常结束,调用日志呈现 200 · 0/0 且无错误信息;现 Messages 将上游失败转为 Anthropic `error` 事件,三个流式端点日志均记录上游错误消息或「上游流提前终止,未返回终态事件」
|
||||
|
||||
## [0.3.0]
|
||||
|
||||
### Added
|
||||
|
||||
- 恢复 OpenAI Chat Completions 兼容端点 `/ai/v1/chat/completions`:请求经 OCI Responses 接口转换转发,支持非流式与 SSE、文本与图片、function 工具调用、结构化输出、推理力度、模型白名单、缓存 token 用量和调用日志
|
||||
- 代理侧批量关联租户接口 `PUT /api/v1/proxies/{id}/tenants`:一次调用设置关联该代理的租户全集——列表内租户改挂到本代理(含从其他代理改挂),列表外已关联的解除,事务生效并返回最新关联计数;含无效租户 ID 返回 400,代理不存在返回 404
|
||||
- `/api/v1/about` 扩展运行时信息:进程启动时刻 `startedAt`、运行秒数 `uptimeSeconds` 与资源占用 `resources`——CPU 自启动均值(占单核百分比)、CPU 核数、goroutine 数、Go 堆内存与向系统申请内存、数据库引擎与磁盘占用(SQLite 统计主文件与 -wal / -shm;MySQL / PostgreSQL 外部库返回 -1 表示不可度量)
|
||||
- README 重构部署、配置、鉴权、反向代理、AI 网关与升级发布说明,并新增 Responses、Chat Completions、Embeddings、Anthropic Messages 与标准接口的字段兼容矩阵,明确直通、转换、降级、忽略和拒绝边界
|
||||
|
||||
### Changed
|
||||
|
||||
- 云端关键事件通知补充操作者、来源 IP、执行结果和说明信息;支持从 OCI Audit 与 IDCS 登录事件提取成功 / 失败状态、策略描述和登录失败原因,缺失字段统一显示占位符
|
||||
|
||||
### Removed
|
||||
|
||||
- **移除自定义审计告警规则**及其阈值、窗口和冷却匹配能力;`/api/v1/log-events/alert-rules` 与 `/api/v1/log-events/alert-rules/{ruleId}` 管理接口、`audit_alert` 通知模板不再提供,已有规则升级后不再执行
|
||||
|
||||
## [0.2.0]
|
||||
|
||||
### Added
|
||||
|
||||
@@ -29,7 +86,7 @@
|
||||
- 渠道「同步模型成功但探测报错不可用」:法兰克福等区域的微调基座模型占满探测候选导致的误报(探测状态与真实可用性不符的根因)
|
||||
- 租户删除:告警命中清理改子查询,日志事件数万条时不再超出 SQL 绑定变量上限导致删除失败;无法解析的任务 payload 记警告跳过并保留原任务,不再永久阻断租户删除
|
||||
|
||||
## [0.1.0] - 2026-07-10
|
||||
## [0.1.0]
|
||||
|
||||
### Added
|
||||
|
||||
@@ -57,7 +114,7 @@
|
||||
- HTTP 入口加固:显式读写超时与优雅关闭、请求体上限(面板 1MB / AI 网关 10MB)、登录字段长度上限、登录守卫条目数有界
|
||||
- 出错响应脱敏:内部错误只返回固定文案 + requestId,完整原因写服务端日志;GORM SQL 日志参数化输出,不再记录实参
|
||||
|
||||
## [0.0.1] - 2026-07-09
|
||||
## [0.0.1]
|
||||
|
||||
首个版本:自托管 OCI 多租户管理面板后端。
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
v0.2.0
|
||||
v0.5.0
|
||||
|
||||
@@ -4,16 +4,21 @@
|
||||
|
||||
# OCI Portal
|
||||
|
||||
**Oracle Cloud Infrastructure 多租户管理面板**
|
||||
**自托管的 OCI 多租户管理面板与 GenAI 兼容网关**
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
本仓库为后端;前端工程见 [oci-portal-dash](https://github.com/wangdefaa/oci-portal-dash)(构建产物嵌入本服务成单文件)
|
||||
[快速开始](#快速开始) · [核心能力](#核心能力) · [生产部署](#生产部署) · [AI 网关](#ai-网关) · [开发](#开发)
|
||||
|
||||
</div>
|
||||
|
||||
OCI Portal 将多份 OCI API Key、云资源、自动化任务、审计事件和 OCI GenAI 渠道集中到一个管理界面。Vue 前端通过 `go:embed` 嵌入 Go 服务,Release 以单个二进制和多架构容器镜像交付。
|
||||
|
||||
本仓库为后端与发行仓库;前端源码位于 [oci-portal-dash](https://github.com/wangdefaa/oci-portal-dash)。
|
||||
|
||||
## 界面预览
|
||||
|
||||
| 总览 | 登录 |
|
||||
@@ -28,59 +33,118 @@
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
|
||||
## 特性
|
||||
## 核心能力
|
||||
|
||||
- **多租户管理**:多份 OCI API Key 配置集中管理,私钥/口令 AES-256-GCM 加密落库;分组、批量测活、账户类型与订阅信息识别
|
||||
- **资源管理**:实例(含创建/电源操作/更换公网 IP/IPv6/VNIC/引导卷)、VCN/子网/安全列表、块存储、限额与成本查询,多区域/多区间支持
|
||||
- **抢机任务**:cron 周期尝试创建实例直到成功,支持熔断与通知
|
||||
- **网页控制台**:实例串行控制台(xterm)与 VNC(noVNC),两跳 SSH 隧道
|
||||
- **AI 网关**:OpenAI Responses / Anthropic Messages / Embeddings 兼容端点转发 OCI GenAI,号池渠道加权负载均衡、熔断探测、密钥管理与用量日志;对话统一走 OCI OpenAI 兼容面(xai / meta / openai 厂商模型,流式事件与推理增量原样保真),支持 xAI Grok 服务端工具 `web_search` / `x_search`(格式同 xAI 官方 Agent Tools,仅非流式)——兼容面属实测可用但未见 Oracle 文档承诺的能力,行为可能随上游调整
|
||||
- **日志回传**:OCI Audit 事件经 Connector Hub → Notifications HTTPS 订阅回传入库,一键创建链路;自定义告警规则(事件类型/来源 IP 白名单/资源/频率阈值)命中即推送
|
||||
- **租户治理**:IAM 用户/MFA/API Key 管理、密码策略、身份提供商(SAML)、通知收件人;多 Identity Domain 租户可按域切换管理
|
||||
- **安全**:JWT + bcrypt(凭据变更旧令牌立即失效,可一键撤销全部会话)、TOTP 两步验证、OIDC/GitHub 外部登录、登录锁定、IP 限速、真实 IP 头可配、请求体/超时防护、系统操作审计
|
||||
- **通知**:模板化推送,五渠道并存(Telegram / Webhook / ntfy / Bark / SMTP),Webhook 可对接飞书、钉钉、Slack、企业微信机器人
|
||||
- **租户与区域**:集中管理多份 OCI API Key,支持分组、批量测活、账户画像、订阅区域缓存与区域切换;私钥和口令使用 AES-256-GCM 加密落库
|
||||
- **计算、网络与存储**:实例创建与电源操作、公网 IP、IPv6、VNIC、串行控制台连接,VCN / 子网 / 安全列表,引导卷与块存储挂载,限额和成本查询
|
||||
- **自动化任务**:抢机、租户测活、成本同步、AI 渠道探测四类 cron 任务,提供执行日志、重叠执行防护、熔断与结果通知
|
||||
- **网页控制台**:浏览器内使用 xterm 串行终端和 noVNC,通过 OCI 控制台连接建立两跳 SSH 隧道
|
||||
- **身份与审计**:IAM 用户、MFA、API Key、密码策略、SAML 身份提供商、通知收件人和多 Identity Domain 管理;OCI Audit 事件可经 Service Connector Hub 与 Notifications 回传,关键事件按类别通过「云端事件」通知推送
|
||||
- **通知与安全**:Telegram、Webhook、ntfy、Bark、SMTP 五类渠道;JWT、bcrypt、TOTP、OIDC / GitHub 登录、登录锁定、IP 限速、会话撤销和系统操作审计
|
||||
- **AI 网关**:提供 OpenAI Responses、Chat Completions、Embeddings 与 Anthropic Messages 兼容接口,支持渠道分组、加权路由、熔断探测、模型黑白名单、密钥管理和调用日志
|
||||
|
||||
## 运行形态
|
||||
|
||||
```text
|
||||
浏览器 / API 客户端
|
||||
│
|
||||
▼
|
||||
┌──────────────────── OCI Portal 单个 Go 进程 ────────────────────┐
|
||||
│ Vue 3 静态资源(go:embed) │
|
||||
│ /api/v1 → Gin → Service → OCI SDK │
|
||||
│ /ai/v1 → 兼容转换与路由 → OCI Generative AI │
|
||||
│ GORM → SQLite(默认)/ MySQL / PostgreSQL(experimental) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
默认推荐 SQLite 单实例部署。MySQL 和 PostgreSQL 适配仍属 experimental,不应据此推断服务支持多副本并发运行。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
前置条件:Docker、Docker Compose v2、OpenSSL。
|
||||
|
||||
1. 克隆仓库并生成一份需要长期保存的 `.env`:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/wangdefaa/oci-portal.git
|
||||
cd oci-portal
|
||||
|
||||
umask 077
|
||||
printf 'DATA_KEY=%s\nJWT_SECRET=%s\nADMIN_PASSWORD=%s\n' \
|
||||
"$(openssl rand -hex 32)" \
|
||||
"$(openssl rand -hex 32)" \
|
||||
"$(openssl rand -base64 24)" > .env
|
||||
chmod 600 .env
|
||||
```
|
||||
|
||||
2. 准备数据目录并启动:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
|
||||
# Linux bind mount 需要让镜像内的 nonroot 用户(uid 65532)可写。
|
||||
sudo chown 65532:65532 data
|
||||
|
||||
docker compose up -d
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
3. 查看初始管理员密码并登录:
|
||||
|
||||
```bash
|
||||
grep '^ADMIN_PASSWORD=' .env
|
||||
```
|
||||
|
||||
访问 `http://127.0.0.1:18888`,默认用户名为 `admin`。
|
||||
|
||||
> `DATA_KEY` 用于解密数据库中的 OCI 私钥、口令和渠道凭据。它只能生成一次并持续复用;丢失或更换后,已有密文无法恢复。请将 `.env` 与 `data/oci-portal.db` 一起备份。
|
||||
|
||||
### 二进制运行
|
||||
|
||||
从 Release 下载对应架构的二进制后:
|
||||
Release 提供 Linux amd64 / arm64 二进制。以下以 amd64 为例;arm64 主机将文件名中的 `amd64` 替换为 `arm64`:
|
||||
|
||||
```bash
|
||||
DATA_KEY=$(openssl rand -hex 32) JWT_SECRET=$(openssl rand -hex 32) ADMIN_PASSWORD=<初始密码> ./oci-portal-server
|
||||
curl -fLO https://github.com/wangdefaa/oci-portal/releases/latest/download/oci-portal-server-linux-amd64
|
||||
chmod +x oci-portal-server-linux-amd64
|
||||
|
||||
# 复用上文生成并妥善保存的 .env。
|
||||
set -a
|
||||
. ./.env
|
||||
set +a
|
||||
|
||||
./oci-portal-server-linux-amd64
|
||||
```
|
||||
|
||||
访问 `http://localhost:8080`,用 `admin` 与初始密码登录。
|
||||
默认访问地址为 `http://localhost:8080`。`ADMIN_PASSWORD` 只在数据库中没有用户时创建初始管理员,后续启动不会用它重置密码。
|
||||
|
||||
### Docker Compose
|
||||
### 源码构建
|
||||
|
||||
源码构建要求 Go 1.26.5、`curl`、`unzip` 和 `sha256sum`。仓库只保留前端占位页,编译完整单文件前应下载 `DASH_VERSION` 指定的前端产物并校验:
|
||||
|
||||
```bash
|
||||
# 镜像以 distroless nonroot(uid 65532)运行,数据卷需可写,否则 SQLite 报 unable to open database file
|
||||
mkdir -p ./data && sudo chown 65532:65532 ./data
|
||||
DATA_KEY=$(openssl rand -hex 32) JWT_SECRET=$(openssl rand -hex 32) ADMIN_PASSWORD=<初始密码> docker compose up -d
|
||||
DASH_TAG="$(tr -d '\r\n' < DASH_VERSION)"
|
||||
DASH_BASE="https://github.com/wangdefaa/oci-portal-dash/releases/download/${DASH_TAG}"
|
||||
|
||||
curl -fL -o dist.zip "${DASH_BASE}/dist.zip"
|
||||
curl -fL -o dist.zip.sha256 "${DASH_BASE}/dist.zip.sha256"
|
||||
sha256sum -c dist.zip.sha256
|
||||
|
||||
rm -rf internal/webui/dist
|
||||
mkdir -p internal/webui/dist
|
||||
unzip -q dist.zip -d internal/webui/dist
|
||||
|
||||
CGO_ENABLED=0 go build -trimpath -o bin/oci-portal-server ./cmd/server
|
||||
```
|
||||
|
||||
默认只监听 `127.0.0.1:18888`;公网访问须置于 TLS 反向代理之后,见下文「反向代理」。
|
||||
本地构建显示 `dev` 版本;Release 工作流会注入正式版本和构建时间。`internal/webui/dist` 中的真实前端产物不应提交到仓库。
|
||||
|
||||
### 源码构建(单文件,含前端)
|
||||
## 生产部署
|
||||
|
||||
```bash
|
||||
# 1. 获取前端产物:从前端仓库 Release 下载 dist.zip(或本地 npm run build 后拷入)
|
||||
curl -fL -o dist.zip https://github.com/wangdefaa/oci-portal-dash/releases/latest/download/dist.zip
|
||||
rm -rf internal/webui/dist && mkdir -p internal/webui/dist && unzip -q dist.zip -d internal/webui/dist
|
||||
# 2. 编译(免 CGO,可交叉编译;-X 两项注入「设置·关于」页的版本与构建时间,可省略,省略则显示 dev)
|
||||
CGO_ENABLED=0 go build -trimpath \
|
||||
-ldflags "-s -w -X oci-portal/internal/api.buildVersion=v0.0.1 -X oci-portal/internal/api.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
|
||||
-o bin/oci-portal-server ./cmd/server
|
||||
```
|
||||
服务本身只提供 HTTP。除本机试用外,应保持服务仅监听回环地址或容器内部网络,并由 TLS 反向代理提供 HTTPS;否则管理员密码、JWT、AI 密钥和租户凭据会经明文连接传输。
|
||||
|
||||
> 注意:上述解压会覆盖仓库占位文件 `internal/webui/dist/index.html`,提交代码前勿把真实产物带入版本库。
|
||||
|
||||
### 反向代理(公网部署必读)
|
||||
|
||||
面板自身只提供 HTTP,管理员口令、JWT 与租户 API 私钥都会经明文承载。除本机试用外,应让面板仅监听回环地址(compose 示例已默认 `127.0.0.1:18888`),由支持 TLS 的反向代理对外提供 HTTPS。
|
||||
|
||||
Caddy 最小示例(整站反代,自动申请并续期 Let's Encrypt 证书,WebSocket 自动透传):
|
||||
### Caddy
|
||||
|
||||
```caddyfile
|
||||
portal.example.com {
|
||||
@@ -88,10 +152,18 @@ portal.example.com {
|
||||
}
|
||||
```
|
||||
|
||||
nginx 示例(证书自备;Web Console 的 WebSocket 升级与长超时必须显式配置,否则串行终端连不上或空闲即断):
|
||||
Caddy 会自动处理 WebSocket。使用 nginx、Traefik 或其他反向代理时,还需要满足:
|
||||
|
||||
- 为串行终端和 VNC 转发 WebSocket Upgrade 头
|
||||
- 为 AI 流式响应和控制台连接设置较长的读写超时,建议 `1h`
|
||||
- 整站请求体上限至少为 `10MB`;后端会继续限制面板 API 为 `1MB`、AI 网关为 `10MB`
|
||||
- 将面板内「设置 → 安全 → 真实 IP 请求头」配置为反向代理实际写入的头;系统审计、登录锁定和 IP 限速依赖它
|
||||
- 配置 `PUBLIC_URL` 或面板地址,供 OAuth 回调和 OCI 日志回传链路使用
|
||||
|
||||
<details>
|
||||
<summary>nginx 最小示例</summary>
|
||||
|
||||
```nginx
|
||||
# http 块内:按请求是否升级为 WebSocket 决定 Connection 头
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
"" close;
|
||||
@@ -104,7 +176,6 @@ server {
|
||||
ssl_certificate /etc/nginx/certs/portal.example.com.crt;
|
||||
ssl_certificate_key /etc/nginx/certs/portal.example.com.key;
|
||||
|
||||
# 放行到最大入口(AI 网关 10MB);各入口更细的上限由后端自身执行
|
||||
client_max_body_size 10m;
|
||||
|
||||
location / {
|
||||
@@ -114,150 +185,88 @@ server {
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
# WebSocket 空闲与 AI 流式响应都需要长读超时(默认 60s 会断)
|
||||
proxy_read_timeout 1h;
|
||||
proxy_send_timeout 1h;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Traefik 示例(已运行 Traefik 的 Docker 环境,面板容器加 label 接入即可,WebSocket 透明支持):
|
||||
</details>
|
||||
|
||||
```yaml
|
||||
services:
|
||||
oci-portal:
|
||||
image: ghcr.io/wangdefaa/oci-portal:latest
|
||||
# ……环境变量与数据卷同上文 compose 示例;与 Traefik 同一 docker 网络,
|
||||
# Traefik 经容器网络直达 8080,无需(也不应)对外映射 ports
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.oci-portal.rule=Host(`portal.example.com`)
|
||||
- traefik.http.routers.oci-portal.entrypoints=websecure
|
||||
- traefik.http.routers.oci-portal.tls.certresolver=le # 换成你的 certResolver 名
|
||||
- traefik.http.services.oci-portal.loadbalancer.server.port=8080
|
||||
```
|
||||
若前端静态文件与后端分离部署,`/api/*` 和 `/ai/*` 必须代理到后端,其余路径由 SPA 静态服务处理并回退到 `index.html`。Traefik 通过容器网络连接时应直达容器端口 `8080`,无需暴露宿主机端口。
|
||||
|
||||
若前端静态文件由反代直接伺服(不走内嵌页面),则按前缀代理,缺一不可:
|
||||
## AI 网关
|
||||
|
||||
| 前缀 | 内容 | 何时需要 |
|
||||
面板内置 OpenAI / Anthropic 兼容的 GenAI 网关:独立密钥鉴权(`Authorization: Bearer sk-...` 或 `x-api-key`),支持渠道分组、加权路由、熔断探测、模型黑白名单、内容日志与调用日志。
|
||||
|
||||
| 端点 | 定位 | 流式 |
|
||||
| --- | --- | --- |
|
||||
| `/api/*` | 面板 REST、Web Console WebSocket、日志回传 webhook | 始终 |
|
||||
| `/ai/*` | AI 网关(OpenAI / Claude 兼容端点,独立密钥鉴权) | 启用 AI 网关时 |
|
||||
| 其余路径 | 前端 SPA 静态文件(404 回退 `index.html`) | 静态分离形态 |
|
||||
| `POST /ai/v1/responses` | OpenAI Responses,无状态主接口(xAI 服务端工具 / MCP) | SSE |
|
||||
| `POST /ai/v1/chat/completions` | OpenAI Chat Completions 兼容层 | SSE |
|
||||
| `POST /ai/v1/messages` | Anthropic Messages 转换层 | SSE |
|
||||
| `POST /ai/v1/embeddings` | OpenAI Embeddings | 否 |
|
||||
| `POST /ai/v1/audio/speech` | 文本转语音(xAI Voice) | 否 |
|
||||
| `POST /ai/v1/tts` | 文本转语音(xAI 官方格式) | 否 |
|
||||
| `POST /ai/v1/rerank` | 文档重排(Cohere Rerank) | 否 |
|
||||
| `POST /ai/v1/moderations` | 内容审核(OCI Guardrails) | 否 |
|
||||
| `GET /ai/v1/models` | 当前密钥可见的模型列表 | 否 |
|
||||
|
||||
- 反代默认追加的 `X-Forwarded-For` 用于还原真实客户端 IP,系统日志留痕、登录锁定与 IP 限速都依赖它
|
||||
- 请求体上限建议与后端一致:`/api/*` 1MB、`/ai/*` 10MB(Caddy 用 `request_body` 按前缀分层)
|
||||
协议兼容边界、已知上游限制与逐字段兼容矩阵见 **[AI 网关文档](./docs/AI网关.md)**。
|
||||
|
||||
## AI 网关接口
|
||||
## API 与配置
|
||||
|
||||
对外提供 OpenAI / Anthropic 兼容端点,转发 OCI GenAI On-Demand 推理。鉴权用面板创建的 AI 密钥,`Authorization: Bearer sk-...` 与 `x-api-key: sk-...` 双头均可;密钥可绑定渠道分组实现路由隔离,也可配置模型白名单(白名单外调用 404,模型列表只返回交集)。请求体上限 10MB。
|
||||
### API 文档
|
||||
|
||||
| 端点 | 协议 | 流式 |
|
||||
| 路径 | 鉴权 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `POST /ai/v1/responses` | OpenAI Responses(无状态子集) | SSE 支持(服务端工具除外) |
|
||||
| `POST /ai/v1/messages` | Anthropic Messages | SSE 支持 |
|
||||
| `POST /ai/v1/embeddings` | OpenAI Embeddings | — |
|
||||
| `GET /ai/v1/models` | OpenAI 模型列表(来自渠道模型目录) | — |
|
||||
| `/api/v1/*` | 登录返回的 JWT Bearer Token | 面板管理 API |
|
||||
| `/ai/v1/*` | AI 网关密钥 | OpenAI / Anthropic 兼容接口 |
|
||||
| `/api/v1/webhooks/oci-logs/:secret` | URL 中的独立回传密钥 | OCI Notifications 日志回传 |
|
||||
|
||||
对话端点统一转发 OCI OpenAI 兼容面(`/actions/v1/responses`),因此仅提供该面支持的 `xai.` / `meta.` / `openai.` 前缀模型;google / cohere 对话模型不在兼容面供给(上游 400),不再提供(cohere embed 模型不受影响)。兼容面属实测可用但无 Oracle 文档承诺的能力,行为可能随上游调整。**Chat Completions(`/ai/v1/chat/completions`)端点已移除**,请迁移到 Responses 或 Messages。
|
||||
OpenAPI 文件随仓库维护:[`docs/swagger.yaml`](docs/swagger.yaml) · [`docs/swagger.json`](docs/swagger.json)。
|
||||
|
||||
以下各表对照网关行为:✅ 转发上游;⚠️ 接受但忽略(静默丢弃,不影响请求);❌ 拒绝(400,不发上游)。
|
||||
运行进程时设置 `SWAGGER=1` 可开放 `/swagger/index.html`。Swagger 默认关闭,生产环境建议仅在受控网络内按需开启。接口注释变更后必须重新生成 OpenAPI。
|
||||
|
||||
### Responses 字段
|
||||
|
||||
请求体除下列例外**原样直通上游**(未列字段一并转发,效果由上游决定):
|
||||
|
||||
| 字段 | 支持 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `model`、`input` | ✅ | `input` 接受 string 或 item 数组 |
|
||||
| `stream` | ✅ | SSE,上游原生事件流(含 gpt-oss 推理增量);与服务端工具互斥 |
|
||||
| `reasoning.effort` | ✅ | 直达上游不限档位,见下「推理力度」 |
|
||||
| `store` | ⚠️ | 网关无状态,强制改写为 `false` |
|
||||
| `previous_response_id`、`conversation`、`background` | ❌ | 网关不保存历史,请求需自带完整上下文 |
|
||||
| `web_search` / `x_search` / `function` 之外的工具类型 | ❌ | 如 `file_search`、`code_interpreter`、`mcp` |
|
||||
|
||||
**服务端工具**:`tools` 支持 `{"type":"web_search"}` 与 `{"type":"x_search"}`(xAI Grok 官方 Agent Tools 格式,可与 `function` 混用),响应保留 `web_search_call` 输出项与引用;**仅非流式**。响应 `usage.input_tokens_details.cached_tokens` 透传缓存命中量。
|
||||
|
||||
### Anthropic Messages 字段
|
||||
|
||||
网关把 Messages 请求转换为 Responses 请求送上游,响应(含流式事件序列)转回 Anthropic 形态:
|
||||
|
||||
| 字段 | 支持 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `model`、`max_tokens`、`messages` | ✅ | `max_tokens` 必填;content 块支持 `text` / `image` / `tool_use` / `tool_result`,其余块类型 400 |
|
||||
| `system` | ✅ | string 或块数组,映射为 `instructions` |
|
||||
| `temperature`、`top_p` | ✅ | |
|
||||
| `stream` | ✅ | SSE,标准 Anthropic 事件序列(`message_start` → `content_block_*` → `message_delta` → `message_stop`) |
|
||||
| `tools`、`tool_choice` | ✅ | 映射为 Responses `function` 工具;`tool_choice` 支持 `auto` / `any` / `none` / `tool` |
|
||||
| `output_config.effort` | ✅ | 直达上游不限档位,见下「推理力度」 |
|
||||
| `stop_sequences`、`top_k`、`metadata`、`thinking`、`service_tier` | ⚠️ | Responses 面无对应物,静默忽略 |
|
||||
|
||||
模型的思考输出(reasoning)不转为 `thinking` 块,静默丢弃;`usage.cache_read_input_tokens` 透传缓存命中量。
|
||||
|
||||
### Embeddings 字段
|
||||
|
||||
| 字段 | 支持 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `model`、`input` | ✅ | `input` 接受 string 或数组 |
|
||||
| `dimensions` | ✅ | |
|
||||
| `encoding_format`、`user` | ⚠️ | 输出恒为 float 数组 |
|
||||
|
||||
### 推理力度(effort)
|
||||
|
||||
两个对话协议各以原生字段控制推理深度,取值直达上游不做档位校验:
|
||||
|
||||
| 协议 | 字段 |
|
||||
| --- | --- |
|
||||
| Responses | `reasoning.effort` |
|
||||
| Anthropic Messages | `output_config.effort`(转小写后透传) |
|
||||
|
||||
是否支持、可用档位与实际效果由模型决定(2026-07 兼容面实测):
|
||||
|
||||
| 模型 | 支持档位 | 实测行为 |
|
||||
| --- | --- | --- |
|
||||
| `xai.grok-4.3` | `none` / `minimal` / `low` / `medium` / `high` | 全部生效:`none` 完全关闭推理,默认 `low`,`high` 推理量最大 |
|
||||
| `openai.gpt-oss-*` | `minimal` / `low` / `medium` / `high` | `none` 被上游 400(Harmony 格式不支持);思考计入 completion tokens |
|
||||
| `xai.grok-3-mini(-fast)` | 名义 `low` / `high` | 各档均被接受,但 `none` 并不关闭推理(仍产生思考) |
|
||||
| `meta.llama-*` | 接受任意档 | 非推理模型,参数无实际效果 |
|
||||
| `xai.grok-4.20-multi-agent*` | `low` / `medium` / `high` / `xhigh` | effort 控制并行 agent 数(4 / 16)而非推理深度 |
|
||||
| 其余 grok(`grok-3`、`grok-4`、`grok-4-fast-*`、`grok-4-1-fast-*`、`grok-code-fast-1`、`grok-4.20-*` 单/双型号全系) | 不支持 | 携带即被上游 400(`does not support parameter reasoningEffort`) |
|
||||
|
||||
不携带该字段时网关不下发,行为由模型默认档位决定。
|
||||
|
||||
### 通用行为
|
||||
|
||||
- 未知模型 404;无可用渠道 503;单次请求最多尝试 3 个渠道(429/5xx/网络错误自动换渠道并计入熔断,模型级 400/404 换渠道不计熔断,其余 4xx 原样透传);流式建立后绑定渠道,中断不重试
|
||||
- 调用计量(渠道、token 用量、缓存命中、时延、重试数)写入面板「调用日志」;密钥可按需开启限时内容抓取
|
||||
|
||||
## 环境变量
|
||||
### 环境变量
|
||||
|
||||
| 变量 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `DATA_KEY` | 是 | 无 | 敏感字段加密主密钥(更换后已入库密文无法解密) |
|
||||
| `JWT_SECRET` | 是 | 无 | 登录令牌签名密钥 |
|
||||
| --- | :---: | --- | --- |
|
||||
| `DATA_KEY` | 是 | — | 敏感字段加密主密钥;必须持久保存,不能随意轮换 |
|
||||
| `JWT_SECRET` | 是 | — | JWT 签名密钥;更换会使已有登录令牌失效 |
|
||||
| `ADMIN_USERNAME` | 否 | `admin` | 初始管理员用户名 |
|
||||
| `ADMIN_PASSWORD` | 首次启动是 | 无 | 仅在用户不存在时创建;已存在不重置 |
|
||||
| `ADMIN_PASSWORD` | 首次启动 | — | 仅在数据库无用户时创建管理员,不会重置已有密码 |
|
||||
| `ADDR` | 否 | `:8080` | HTTP 监听地址 |
|
||||
| `DB_DRIVER` | 否 | `sqlite` | `sqlite` / `mysql` / `postgres`(后两者 experimental) |
|
||||
| `DB_DSN` | 外部库时是 | 无 | MySQL 需 `parseTime=True`;PostgreSQL 标准 DSN |
|
||||
| `DB_PATH` | 否 | `oci-portal.db` | SQLite 文件路径 |
|
||||
| `PUBLIC_URL` | 否 | 无 | 面板公网基址,日志回传一键创建链路用 |
|
||||
| `HTTPS_PROXY` | 否 | 无 | 出站代理(如 Telegram 通知走代理) |
|
||||
| `TZ` | 否 | 系统 | cron 表达式解释时区(容器内建议显式设置,二进制已嵌 tzdata) |
|
||||
| `SWAGGER` | 否 | 关 | `1` 时开放 `/swagger/index.html` API 文档(生产建议按需临时开启) |
|
||||
| `GIN_MODE` | 否 | `release` | `debug` / `release`,影响日志与调试输出 |
|
||||
| `DB_DRIVER` | 否 | `sqlite` | `sqlite` / `mysql` / `postgres`;后两者为 experimental |
|
||||
| `DB_PATH` | SQLite | `oci-portal.db` | SQLite 文件路径 |
|
||||
| `DB_DSN` | 外部数据库 | — | MySQL 需 `parseTime=True`;不要在日志或文档中暴露凭据 |
|
||||
| `PUBLIC_URL` | 否 | — | 面板公网基址,作为 OAuth 回调和日志回传引导的回退值 |
|
||||
| `TZ` | 否 | 系统时区 | cron 表达式的解释时区;容器示例使用 `Asia/Shanghai` |
|
||||
| `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` | 否 | — | Go 标准出站代理变量;面板内显式代理配置优先用于对应业务 |
|
||||
| `SWAGGER` | 否 | 关闭 | 设为 `1` 时开放 Swagger UI |
|
||||
| `GIN_MODE` | 否 | `release` | `debug` / `release` |
|
||||
|
||||
## 升级与备份
|
||||
|
||||
- 升级前同时备份 `.env` 和数据库;SQLite Compose 部署的数据文件为 `data/oci-portal.db`
|
||||
- 保持 `DATA_KEY` 不变;只恢复数据库而没有原密钥,敏感字段无法解密
|
||||
- 服务启动时会自动执行数据库迁移;跨版本升级前先阅读 [CHANGELOG](CHANGELOG.md)
|
||||
- Compose 部署使用 `docker compose pull && docker compose up -d` 更新镜像
|
||||
- OCI API Key 应遵循最小权限原则;生产环境保持 Swagger 关闭并限制管理面访问来源
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
go test ./... # 全量测试
|
||||
go vet ./... && gofmt -l .
|
||||
go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency # 接口注释变更后重新生成 OpenAPI
|
||||
gofmt -l .
|
||||
go vet ./...
|
||||
go test ./...
|
||||
|
||||
# Handler 注释变更后重新生成唯一的对外 API 文档。
|
||||
go tool swag init -g cmd/server/main.go -o docs --parseInternal --parseDependency --overridesFile docs/.swaggo
|
||||
```
|
||||
|
||||
API 文档:全部接口带 swaggo 注释,`SWAGGER=1` 启动后访问 `/swagger/index.html`;spec 文件在 `docs/swagger.json|yaml`。
|
||||
|
||||
编码规范与项目约定见 [AGENTS.md](AGENTS.md) 与 [.trellis/spec/](.trellis/spec/)。
|
||||
- Go 后端规范与目录约定:[`AGENTS.md`](AGENTS.md) · [`.trellis/spec/backend/`](.trellis/spec/backend/)
|
||||
- 前端开发与构建:[oci-portal-dash](https://github.com/wangdefaa/oci-portal-dash)
|
||||
- 版本变更:[`CHANGELOG.md`](CHANGELOG.md)
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+3
-1
@@ -135,7 +135,7 @@ func run() error {
|
||||
defer aiGateway.Wait()
|
||||
defer stopCleanup()
|
||||
tasks := service.NewTaskService(db, ociConfigs, notifier, settings)
|
||||
ociConfigs.SetTenantCleanupDeps(tasks, logEvents)
|
||||
ociConfigs.SetTenantCleanupDeps(tasks)
|
||||
tasks.AttachAiGateway(aiGateway)
|
||||
aiGateway.SetOnChannelsChanged(tasks.SyncAiProbeTask)
|
||||
if err := tasks.Start(); err != nil {
|
||||
@@ -147,6 +147,8 @@ func run() error {
|
||||
console := service.NewConsoleService(ociConfigs)
|
||||
proxies := service.NewProxyService(db, cipher)
|
||||
defer proxies.Wait()
|
||||
// 「关于」页存储指标需知数据库形态
|
||||
api.SetAboutRuntime(cfg.DBDriver, cfg.DBPath)
|
||||
router := api.NewRouter(auth, oauth, ociConfigs, tasks, console, settings, notifier, systemLogs, logEvents, proxies, aiGateway)
|
||||
return serveHTTP(cfg.Addr, router)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// swag 全局类型替换:原始 JSON 与联合类型统一渲染为 AnyJSON(任意 JSON 值),
|
||||
// 避免 json.RawMessage 被误渲染成 byte 数组、联合类型暴露内部字段。
|
||||
replace encoding/json.RawMessage oci-portal/internal/aiwire.AnyJSON
|
||||
replace oci-portal/internal/aiwire.RespInput oci-portal/internal/aiwire.AnyJSON
|
||||
replace oci-portal/internal/aiwire.Content oci-portal/internal/aiwire.AnyJSON
|
||||
replace oci-portal/internal/aiwire.StringList oci-portal/internal/aiwire.AnyJSON
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
# AI 网关
|
||||
|
||||
> 本文是 OCI Portal AI 网关的完整使用与兼容性文档:端点定位、协议兼容边界、已知上游限制与字段兼容矩阵。
|
||||
> 路由与鉴权的机器可读定义以 [Swagger YAML](swagger.yaml) 或运行时 Swagger UI 为准;无法由 OpenAPI 表达的兼容边界以本文为准。
|
||||
|
||||
AI 网关使用面板创建的独立密钥鉴权,支持 `Authorization: Bearer sk-...` 和 `x-api-key: sk-...`。密钥可绑定渠道分组和模型白名单;全局模型黑名单会从模型列表、路由和探测候选中同时排除目标模型。
|
||||
|
||||
| 端点 | 定位 | 流式 |
|
||||
| --- | --- | --- |
|
||||
| `POST /ai/v1/responses` | OpenAI Responses,无状态主接口 | SSE |
|
||||
| `POST /ai/v1/chat/completions` | OpenAI Chat Completions,存量客户端兼容层 | SSE |
|
||||
| `POST /ai/v1/messages` | Anthropic Messages 转换层 | SSE |
|
||||
| `POST /ai/v1/embeddings` | OpenAI Embeddings | 否 |
|
||||
| `POST /ai/v1/audio/speech` | OpenAI Audio Speech,文本转语音(xAI Voice) | 否 |
|
||||
| `POST /ai/v1/tts` | xAI 官方格式文本转语音(同一上游,网关转换) | 否 |
|
||||
| `POST /ai/v1/rerank` | 文档重排(Cohere Rerank,Jina 风格协议) | 否 |
|
||||
| `POST /ai/v1/moderations` | 内容审核(OCI Guardrails:内容审核 / PII / 提示注入) | 否 |
|
||||
| `GET /ai/v1/models` | 当前密钥可见的模型列表 | 否 |
|
||||
|
||||
兼容边界:
|
||||
|
||||
- 对话请求统一转发 OCI OpenAI 兼容面,当前供给以 `xai.`、`meta.`、`openai.` 前缀模型为主;Cohere Embeddings 不受该对话模型范围影响
|
||||
- 网关不保存会话历史,客户端需要携带完整上下文;Responses 拒绝非空 `previous_response_id`、非 `null` `conversation` 和 `background:true`
|
||||
- Responses 支持 Oracle 文档化的 xAI 服务端工具 `web_search` / `x_search` / `code_interpreter` 与远程 `mcp` 工具(非流式与流式均可),工具参数与限制遵循 [xAI 规格](https://docs.oracle.com/en-us/iaas/Content/generative-ai/get-started-agents.htm#xai-compatible-tools);`code_interpreter` 的命名容器管理(containers API)与 File Search 不提供
|
||||
- Responses 的 `reasoning.effort`、Messages 的 `output_config.effort` 和 Chat Completions 的 `reasoning_effort` 会传给上游,实际档位和效果由模型决定
|
||||
- Chat Completions 只承担协议转换与兼容修复;新能力优先在 Responses 和 Messages 提供
|
||||
- 单次请求最多尝试三个渠道;可重试错误会切换渠道,流式响应建立后不会换渠道重试
|
||||
- Audio Speech 直通 OCI 兼容面(模型 `xai.grok-tts`,voice 取 xAI Grok Voice 列表:`ara`/`eve`/`leo`/`rex`/`sal`);上游把 `language` 当必填,缺省时网关自动注入 `"auto"`,xAI 专属参数(`output_format` 等)可平铺在请求体透传;仅单请求返回音频,不提供 WebSocket 流式
|
||||
- `/ai/v1/tts` 为 xAI 官方 TTS 格式(`text`/`language` 必填、`voice_id`、`output_format` 对象)的转换端点:网关转换为 OpenAI 兼容形态后走同一上游与渠道调度,`model` 为网关扩展字段(缺省 `xai.grok-tts`);实测 `output_format`(codec/sample_rate/bit_rate)与 `speed` 透传生效
|
||||
- Rerank 走 OCI typed 面(`cohere.rerank-v4.0-pro` / `-fast`),请求 `{model, query, documents[], top_n?, return_documents?}`,响应 `results[].index` 指向入参下标;无 token 用量口径,调用日志只记时延
|
||||
- Moderations 是 OpenAI moderations 外壳映射 OCI Guardrails:`input` 为字符串或字符串数组(至多 8 条),categories 用 OCI 原生维度 `overall` / `blocklist` / `prompt_injection`(阈值 0.5 判定 `flagged`),PII 命中放扩展字段 `results[].pii`(不参与 flagged);`model` 字段接受但忽略,无模型白名单维度;实测中文人名/手机号识别较弱,英文 PII 识别正常
|
||||
- Responses 的 `input_file` 内容块(file_url / file_data)实测被上游拒绝:`File content is currently unsupported for ZDR customers`——网关强制 `store:false` 属 ZDR 形态,该能力在上游侧不可用
|
||||
|
||||
### 已知上游限制:大 system 区流式断流
|
||||
|
||||
实测(2026-07-13)OCI 兼容面对 `instructions` 与 `tools` 合计超约 64.5KB 的**流式**请求会在发出少量事件后静默断开连接(无任何错误事件;同请求非流式正常),与模型、字符集、消息正文大小均无关——消息正文(`input`)不计入该限制。Chat Completions 与 Messages 的 system/developer 提示会转换为 `instructions`,因此 Claude Code 等自带大体量系统提示与工具定义的客户端极易触发。
|
||||
|
||||
网关侧应对:
|
||||
|
||||
- Messages 与 Chat Completions 的流式请求在客户端尚未收到任何输出时遭遇上游断流,会自动降级为非流式重做,并按标准事件/chunk 序列一次推送;调用日志记 `retries=1` 与降级标记
|
||||
- Responses 直通因初始事件已转发、协议上无法透明降级,调用日志记「上游流提前终止」,客户端需自行回退非流式
|
||||
- 应急规避:将超长 system 内容移入首条 user 消息正文可绕过该限制(正文不计入),但语义有别,根治有待上游修复
|
||||
|
||||
这里提供的是兼容接口而非 OpenAI / Anthropic 协议的完整实现。OCI OpenAI 兼容面的部分行为来自实测,未见 Oracle 文档承诺,可能随上游调整。路由与鉴权定义以 [Swagger YAML](swagger.yaml) 或运行时 Swagger UI 为准;无法由 OpenAPI 完整表达的兼容边界列于上方。
|
||||
|
||||
### 字段兼容矩阵
|
||||
|
||||
以下矩阵以 2026-07-13 的 [OpenAI Responses](https://developers.openai.com/api/reference/resources/responses/methods/create)、[Chat Completions](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create)、[Embeddings](https://developers.openai.com/api/reference/resources/embeddings/methods/create)、[Audio Speech](https://developers.openai.com/api/reference/resources/audio/methods/speech)、[Moderations](https://developers.openai.com/api/reference/resources/moderations/methods/create) 和 [Anthropic Messages](https://platform.claude.com/docs/en/api/messages/create) 为标准基线,并与当前实现逐项核对;Rerank 无 OpenAI 对应端点,基线取 [Cohere Rerank](https://docs.cohere.com/reference/rerank) 协议。
|
||||
|
||||
这是一份兼容性快照,不替代 Swagger。标准接口和 OCI 上游都可能变化,最终行为以当前版本代码与实测为准。
|
||||
|
||||
矩阵只列网关支持的字段;不支持(本地拒绝)与被忽略的字段不入表,在各端点段落末尾以文字简述。
|
||||
|
||||
| 标记 | 含义 |
|
||||
| :---: | --- |
|
||||
| ✅ | 网关直接支持 |
|
||||
| ➡️ | 网关原样透传;是否生效由 OCI 上游决定 |
|
||||
| 🔄 | 网关进行字段或协议转换后支持 |
|
||||
| ◐ | 部分支持、存在前置条件或语义降级 |
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/responses</code> 对比 OpenAI Responses</summary>
|
||||
|
||||
Responses 是“原始 JSON 直通 + 本地门禁”。除 `store` 外,网关不会重建请求体;未知顶层字段也会保留并送往 OCI。
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `model` | ◐ | 必须非空,还要通过密钥模型白名单并匹配可用渠道;随后原样透传 |
|
||||
| `input` | ➡️ | 支持标准的字符串或 item 数组,原始内容透传;网关不逐项保证 OCI 能处理所有 item 类型 |
|
||||
| `instructions`、`max_output_tokens` | ➡️ | 类型可解析后原样透传,不做范围或模型能力校验 |
|
||||
| `temperature`、`top_p`、`parallel_tool_calls` | ➡️ | 原样透传,不做取值范围校验 |
|
||||
| `text` / `text.format` / `text.verbosity` | ➡️ | 整个原始对象透传;结构化输出是否可用由 OCI 模型决定 |
|
||||
| `reasoning` | ➡️ | 整个原始对象透传;`effort` 不校验档位,`summary` 等字段不会被网关删除 |
|
||||
| `tool_choice` | ➡️ | 任意 JSON 原样透传,本地不校验枚举或结构 |
|
||||
| `store` | 🔄 | 无论客户端传什么,上游请求都强制改写为 `false` |
|
||||
| `stream` | ✅ | 普通请求、`function` 与服务端工具均支持 SSE |
|
||||
| `tools[].type=function` | ➡️ | 非流式和流式均可,工具对象原样透传 |
|
||||
| `tools[].type=web_search` / `x_search` / `code_interpreter` | ◐ | Oracle 文档化的 xAI 服务端工具,参数与限制遵循 xAI 规格(如 `allowed_domains` 上限 10、`container` 支持 `{"type":"auto"}`),非流式与流式均实测可用;`x_search` 不是 OpenAI 标准工具 |
|
||||
| `tools[].type=mcp` | ➡️ | 远程 MCP 服务由上游直连调用(`server_url` / `require_approval` / `authorization` 等原样透传),非流式与流式均实测可用 |
|
||||
| 其余标准与未知顶层字段 | ➡️ | `context_management`、`include`、`metadata`、`prompt`、`prompt_cache_key`、`service_tier`、`truncation`、`user` 等未建模字段一律保留在原始请求中,由 OCI 决定是否接受 |
|
||||
|
||||
不支持(请求到达上游前返回 400):非空 `previous_response_id`、非 `null` 的 `conversation`、`background:true`——网关无状态,不保存历史响应;以及 `function` / xAI 服务端工具 / `mcp` 之外的工具类型(`web_search_preview`、`file_search`、`computer`、`image_generation`、`shell`、`custom` 等)。
|
||||
|
||||
响应边界:
|
||||
|
||||
- 非流式成功响应不做转换,OCI JSON 原样返回;usage 解析只用于面板调用日志
|
||||
- SSE 事件逐行原样转发,不补 `data: [DONE]`,推理增量也不会被网关过滤
|
||||
- 流建立前最多切换三个渠道;流建立后中断不重试,客户端可能只收到部分事件
|
||||
- 未知模型返回 404、无渠道返回 503;上游错误会套入 OpenAI 风格错误体,不保证与标准 OpenAI 错误字段完全相同
|
||||
|
||||
实现依据:[`airesponses.go`](../internal/service/airesponses.go) · [`responses.go`](../internal/aiwire/responses.go) · [`aigateway.go`](../internal/api/aigateway.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/chat/completions</code> 对比 OpenAI Chat Completions</summary>
|
||||
|
||||
Chat Completions 会先转换为 Responses 请求,再把 OCI Responses 响应桥接回 Chat Completions 形态。转换器只搬运下表字段,其余字段不进入上游请求。
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `model` | ◐ | 必填,受密钥白名单和可用渠道限制;模型名保留到上游请求 |
|
||||
| `messages` | 🔄 | 必填并转换为 Responses `input` / `instructions` |
|
||||
| `system` / `developer` 消息 | ◐ | 文本按出现顺序合并为 `instructions`;块数组中的非文本内容被忽略 |
|
||||
| `user` / `assistant` 文本内容 | 🔄 | 字符串及 `text` 块分别转为 `input_text` / `output_text` |
|
||||
| `image_url` 内容块 | ◐ | URL 或 data URI 转为 `input_image`;`image_url.detail` 被忽略 |
|
||||
| assistant `tool_calls` / `role=tool` | 🔄 | 转为 `function_call` / `function_call_output`,保留调用 ID、函数名和参数 |
|
||||
| `max_completion_tokens` | 🔄 | 转为 `max_output_tokens`,优先于 `max_tokens` |
|
||||
| `max_tokens` | 🔄 | 未提供 `max_completion_tokens` 时转为 `max_output_tokens` |
|
||||
| `temperature`、`top_p`、`parallel_tool_calls` | ◐ | 原值写入 Responses 请求,但不校验范围或模型能力 |
|
||||
| `stream` | 🔄 | OCI Responses SSE 桥接为 `chat.completion.chunk`,末尾补 `data: [DONE]`;上游断流且尚无输出时自动降级非流式重做,结果按 chunk 序列一次推送 |
|
||||
| `stream_options.include_usage` | 🔄 | 控制网关在终块后追加 `choices: []` 的 usage 块 |
|
||||
| `tools[].type=function` | ◐ | `name`、`description`、`parameters` 支持;`function.strict` 被忽略 |
|
||||
| `tool_choice` | ◐ | 支持 `auto` / `none` / `required` 和具名 function;非法或未知值被静默忽略 |
|
||||
| `response_format` | ◐ | `json_object`、`json_schema` 转为 Responses `text.format`;未知类型交给 OCI 处理 |
|
||||
| `reasoning_effort` | ◐ | 转小写后映射为 `reasoning.effort`,不校验模型或档位 |
|
||||
| `store` | 🔄 | 客户端取值被忽略,转换后的上游请求始终使用 `store:false` |
|
||||
|
||||
不支持(返回 400):`input_audio`、`file`、`refusal` 等消息内容块;`function` 以外的工具类型(含 `custom`)。
|
||||
|
||||
静默忽略(转换后的上游请求不包含):消息级 `name` / `refusal` / `audio` / 旧式 `function_call`;采样与输出控制类 `stop`、`seed`、`n`(恒返回单个 choice)、`frequency_penalty`、`presence_penalty`、`logprobs`、`top_logprobs`、`logit_bias`;平台类 `user`、`audio`、`modalities`、`prediction`、`metadata`、`moderation`、`prompt_cache_key`、`safety_identifier`、`service_tier`、`verbosity`、`web_search_options`、`stream_options.include_obfuscation` 及其他未知字段。
|
||||
|
||||
响应边界:
|
||||
|
||||
- 非流式固定生成一个 `choices[0]`;文本会合并,函数调用转为 `tool_calls`
|
||||
- `finish_reason` 只生成 `stop`、`tool_calls`、`length`;其他上游终止原因不保留
|
||||
- reasoning 输出、logprobs、refusal、annotations、audio、service tier 和 system fingerprint 不返回
|
||||
- usage 保留 `prompt_tokens`、`completion_tokens`、`total_tokens` 和 `prompt_tokens_details.cached_tokens`
|
||||
- 已建立的流中断或上游 `response.failed` 不会转换成标准 SSE 错误事件
|
||||
|
||||
实现依据:[`chatresponses.go`](../internal/service/chatresponses.go) · [`openai.go`](../internal/aiwire/openai.go) · [`aigateway.go`](../internal/api/aigateway.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/embeddings</code> 对比 OpenAI Embeddings</summary>
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `model` | ◐ | 必填,受密钥白名单限制,并且必须存在具有 `EMBEDDING` 能力的渠道 |
|
||||
| `input` 为字符串 | ✅ | 包装为单个输入后调用 OCI |
|
||||
| `input` 为字符串数组 | ✅ | 按原顺序调用 OCI;空字符串不在本地拒绝,由 OCI 决定 |
|
||||
| `dimensions` | ◐ | 映射为 OCI 输出维度,不做范围或模型能力校验 |
|
||||
| `encoding_format=float` | ✅ | 返回 float 数组;省略时行为相同 |
|
||||
|
||||
不支持(返回 400):token ID 数组(一维或二维)形态的 `input`、空数组、`null`,以及 `encoding_format=base64`。静默忽略:`user` 及其他未知字段。
|
||||
|
||||
响应使用标准的 `object:"list"`、`data[].object:"embedding"`、`index`、`model` 和可选 `usage` 外壳;向量为 `float32` 数组,不支持流式。
|
||||
|
||||
实现依据:[`embeddings.go`](../internal/aiwire/embeddings.go) · [`aigateway_chat.go`](../internal/service/aigateway_chat.go) · [`aigateway.go`](../internal/api/aigateway.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/messages</code> 对比 Anthropic Messages</summary>
|
||||
|
||||
网关接受 `Authorization: Bearer` 或 `x-api-key`,但不会校验或使用标准 Anthropic `anthropic-version`、`anthropic-beta` 请求头。
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `model` | ◐ | 用于模型与渠道选择,但空字符串不会在 handler 中按参数错误拒绝,通常最终返回模型不存在 |
|
||||
| `max_tokens` | 🔄 | 可缺省(缺省或 ≤0 时按默认值 8192),转换为 `max_output_tokens` |
|
||||
| `messages` | ◐ | 必须非空;角色、交替顺序和空内容不做完整校验 |
|
||||
| `system` | ◐ | 支持字符串或 text 块数组;多个文本块直接拼接,`cache_control` 等附加字段被忽略 |
|
||||
| `temperature`、`top_p` | ◐ | 写入 Responses 请求,不做取值范围或模型能力校验 |
|
||||
| `stream` | 🔄 | Responses SSE 桥接为 Anthropic 事件序列;上游断流且尚无输出时自动降级非流式重做,结果按事件序列一次推送 |
|
||||
| `tools` | ◐ | 每个工具都转换成 Responses `function`;自定义客户端工具可用,Anthropic 服务端工具类型不保留原语义 |
|
||||
| `tool_choice` | ◐ | 支持 `auto`、`any`、`none`、具名 `tool`;`disable_parallel_tool_use` 等附加字段被忽略 |
|
||||
| `output_config.effort` | 🔄 | 转小写后映射为 Responses `reasoning.effort` |
|
||||
|
||||
顶层静默忽略(能解析但不传上游):`top_k`、`stop_sequences`(响应 `stop_sequence` 恒为 `null`)、`metadata`、`thinking`(不控制上游思考预算)、`output_config` 其余子字段、`cache_control`、`container`、`inference_geo`、`service_tier` 及其他未知顶层字段。
|
||||
|
||||
`messages[].content`:
|
||||
|
||||
| 标准内容块 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| 字符串 / `text` | 🔄 | user 转 `input_text`,assistant 历史转 `output_text` |
|
||||
| `image` | ◐ | 仅支持 `base64` 和 `url` source;缺字段或其他 source 类型返回 400 |
|
||||
| `tool_use` | 🔄 | 转为 `function_call`,保留 ID、名称和输入 |
|
||||
| `tool_result` | ◐ | 转为 `function_call_output`;块数组只拼接 text,`is_error` 和非文本结果丢失 |
|
||||
| `null` / 空块数组 | ◐ | 该消息可能从上游 input 中消失,不返回参数错误 |
|
||||
|
||||
不支持的内容块(返回 400):`document`、服务端工具结果及其他未知块。历史 `thinking` / `redacted_thinking` 块会被删除,不进入上游上下文。
|
||||
|
||||
响应边界:
|
||||
|
||||
- 非流式只把 Responses `output_text` 转成 `text`、`function_call` 转成 `tool_use`
|
||||
- `stop_reason` 只生成 `end_turn`、`tool_use`、`max_tokens`;`stop_sequence` 恒为 `null`
|
||||
- reasoning 不会生成 Anthropic `thinking` / `redacted_thinking` 块,也没有 signature
|
||||
- usage 只保留 `input_tokens`、`output_tokens` 和 `cache_read_input_tokens`,不提供 `cache_creation_input_tokens`
|
||||
- 流式输出标准事件骨架,但不生成 `thinking_delta` 和 `signature_delta`;上游错误事件与无终态断流会转成 Anthropic `error` 事件
|
||||
|
||||
实现依据:[`anthresponses.go`](../internal/service/anthresponses.go) · [`anthropic.go`](../internal/aiwire/anthropic.go) · [`aigateway.go`](../internal/api/aigateway.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/audio/speech</code> 对比 OpenAI Audio Speech</summary>
|
||||
|
||||
Audio Speech 与 Responses 同为“原始 JSON 直通 + 本地门禁”:除缺省注入 `language` 外不重建请求体,未知字段原样透传。
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `model` | ◐ | 必填,受密钥白名单限制,并且必须存在具有 `TTS` 能力的渠道(当前上游仅 `xai.grok-tts`) |
|
||||
| `input` | ◐ | 必填非空,随后原样透传 |
|
||||
| `voice` | ➡️ | 原样透传;取 xAI Grok Voice 音色(`ara` / `eve` / `leo` / `rex` / `sal`),OpenAI 标准音色名不可用 |
|
||||
| `response_format` | ➡️ | 原样透传;实测 `mp3` 可用,其余格式由上游决定 |
|
||||
| `language`(扩展字段) | 🔄 | 上游必填;客户端缺省时网关自动注入 `"auto"` |
|
||||
| `speed`、`instructions` 及其他未知字段 | ➡️ | 原样透传(含 xAI 专属参数如 `output_format`),是否生效由上游决定 |
|
||||
|
||||
不支持:流式音频(`stream_format` 等流式选项无效,响应恒为一次性完整音频)与 WebSocket 语音会话。
|
||||
|
||||
响应边界:
|
||||
|
||||
- 成功响应为音频字节,`Content-Type` 透传上游(缺省 `audio/mpeg`)
|
||||
- 无 token 用量口径,调用日志只记时延与渠道
|
||||
|
||||
实现依据:[`genai_speech.go`](../internal/oci/genai_speech.go) · [`service/aigateway_extras.go`](../internal/service/aigateway_extras.go) · [`api/aigateway_extras.go`](../internal/api/aigateway_extras.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/tts</code> 对比 xAI TTS</summary>
|
||||
|
||||
`/ai/v1/tts` 接受 [xAI 官方 TTS 格式](https://docs.x.ai/developers/model-capabilities/audio/text-to-speech)(OCI 无 HTTP 版 xAI 面,网关转换为 OpenAI 兼容形态后与 `/ai/v1/audio/speech` 走同一上游与调度)。
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `text` | 🔄 | 必填非空,转换为上游 `input` |
|
||||
| `language` | ◐ | 必填(对齐 xAI 官方;接受 BCP-47 或 `auto`),原样透传 |
|
||||
| `voice_id` | 🔄 | 转换为上游 `voice`;缺省交上游默认(`eve`) |
|
||||
| `output_format` | ➡️ | `{codec, sample_rate, bit_rate}` 对象原样透传,实测生效(44.1kHz/192kbps 验证) |
|
||||
| `speed` | ➡️ | 原样透传,实测接受 |
|
||||
| `model`(网关扩展) | ◐ | xAI 官方无此字段;缺省注入 `xai.grok-tts`,可显式覆盖,受密钥白名单限制 |
|
||||
| `optimize_streaming_latency`、`text_normalization`、`with_timestamps` 及其他未知字段 | ➡️ | 原样透传,是否生效由上游决定 |
|
||||
|
||||
不支持:流式音频输出(xAI 官方 `optimize_streaming_latency` 面向流式场景,本端点响应恒为一次性完整音频);WebSocket 流式(OCI 另有 `wss://…/xai/v1/tts` 私有协议面,网关未代理)。
|
||||
|
||||
响应边界:
|
||||
|
||||
- 成功响应为音频字节,`Content-Type` 透传上游(缺省 `audio/mpeg`)
|
||||
- 无 token 用量口径,调用日志只记时延与渠道(端点名 `tts`)
|
||||
|
||||
实现依据:[`service/aigateway_extras.go`](../internal/service/aigateway_extras.go) · [`api/aigateway_extras.go`](../internal/api/aigateway_extras.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/rerank</code> 对比 Cohere Rerank</summary>
|
||||
|
||||
Rerank 无 OpenAI 对应端点,协议取 Jina / Cohere 通行风格,上游走 OCI typed 面(`cohere.rerank-v4.0-pro` / `-fast`)。
|
||||
|
||||
| 字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `model` | ◐ | 必填,受密钥白名单限制,并且必须存在具有 `RERANK` 能力的渠道 |
|
||||
| `query` | ✅ | 必填非空 |
|
||||
| `documents` | ◐ | 必填,仅接受字符串数组;Cohere 旧版 `{"text": ...}` 对象数组形态返回 400 |
|
||||
| `top_n` | ✅ | 可选,传给上游限制返回条数;缺省返回全部文档的重排结果 |
|
||||
| `return_documents` | ✅ | 可选,`true` 时 `results[].document.text` 回带原文 |
|
||||
|
||||
静默忽略:`max_tokens_per_doc` 等 Cohere 专属参数及其他未知字段。
|
||||
|
||||
响应边界:
|
||||
|
||||
- `results[]` 按相关度降序,`index` 指向入参 `documents` 下标,`relevance_score` 为 0–1 浮点;响应 `model` 回显请求值
|
||||
- 无 token 用量口径,调用日志只记时延与渠道
|
||||
|
||||
实现依据:[`genai_guard.go`](../internal/oci/genai_guard.go) · [`rerank.go`](../internal/aiwire/rerank.go) · [`service/aigateway_extras.go`](../internal/service/aigateway_extras.go)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><code>POST /ai/v1/moderations</code> 对比 OpenAI Moderations</summary>
|
||||
|
||||
Moderations 是 OpenAI moderations 外壳映射 OCI Guardrails(内容审核 / PII / 提示注入)。上游是服务级 API,没有模型与白名单维度;渠道按分组直接挑选。
|
||||
|
||||
| 标准字段 | 状态 | 网关行为 |
|
||||
| --- | :---: | --- |
|
||||
| `input` 为字符串 | ✅ | 单条审核 |
|
||||
| `input` 为字符串数组 | ✅ | 逐条审核,单次 1~8 条 |
|
||||
|
||||
不支持(返回 400):多模态 input(图片等对象数组形态)、空字符串条目、空数组或超过 8 条的数组。静默忽略:`model`(接受任意值,不校验白名单)及其他未知字段。
|
||||
|
||||
响应边界:
|
||||
|
||||
- `categories` / `category_scores` 用 OCI 原生维度 `overall` / `blocklist` / `prompt_injection`,而非 OpenAI 标准类目(`hate` / `violence` 等);任一维度得分 ≥ 0.5 判定 `flagged`
|
||||
- PII 命中放扩展字段 `results[].pii`(`text` / `label` / `score` / `offset` / `length`),不参与 `flagged` 判定;实测中文人名 / 手机号识别较弱,英文 PII 识别正常
|
||||
- 响应 `model` 恒为 `oci-guardrails`
|
||||
|
||||
实现依据:[`genai_guard.go`](../internal/oci/genai_guard.go) · [`moderations.go`](../internal/aiwire/moderations.go) · [`service/aigateway_extras.go`](../internal/service/aigateway_extras.go)
|
||||
|
||||
</details>
|
||||
|
||||
`GET /ai/v1/models` 使用 OpenAI Models 列表外壳(`object`、`data[].id/object/created/owned_by`),但只返回当前渠道目录中通过分组、全局黑名单和密钥白名单筛选后的模型;网关不提供标准的单模型检索端点。面板「过滤弃用模型」开关开启时,OCI 已宣布弃用(即使未到退役日)的模型同时从模型列表与路由中排除,关闭后恢复。
|
||||
+3624
-470
File diff suppressed because it is too large
Load Diff
+3624
-470
File diff suppressed because it is too large
Load Diff
+2434
-404
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
package aiwire
|
||||
|
||||
// AnyJSON 仅供 swagger 文档渲染:经 .swaggo 全局替换,代表任意 JSON 值
|
||||
// (json.RawMessage 与 string/数组联合类型),运行时代码不使用。
|
||||
type AnyJSON struct{}
|
||||
@@ -0,0 +1,63 @@
|
||||
package aiwire
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// ModerationsRequest 是 /ai/v1/moderations 请求体;input 兼容 OpenAI 的
|
||||
// string 与 []string 两种形态,model 字段接受但忽略(上游为服务级 API)。
|
||||
type ModerationsRequest struct {
|
||||
Model string `json:"model,omitempty"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
}
|
||||
|
||||
// ModerationPii 是一处 PII 命中(OCI 扩展,OpenAI 协议无对应物)。
|
||||
type ModerationPii struct {
|
||||
Text string `json:"text"`
|
||||
Label string `json:"label"`
|
||||
Score float64 `json:"score"`
|
||||
Offset int `json:"offset"`
|
||||
Length int `json:"length"`
|
||||
}
|
||||
|
||||
// ModerationResult 是一条输入的审核结果:categories / category_scores 用
|
||||
// OCI 原生维度(overall / blocklist / prompt_injection),pii 为扩展字段。
|
||||
type ModerationResult struct {
|
||||
Flagged bool `json:"flagged"`
|
||||
Categories map[string]bool `json:"categories"`
|
||||
CategoryScores map[string]float64 `json:"category_scores"`
|
||||
Pii []ModerationPii `json:"pii,omitempty"`
|
||||
}
|
||||
|
||||
// ModerationsResponse 是 /ai/v1/moderations 响应体(OpenAI moderations 外壳)。
|
||||
type ModerationsResponse struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Results []ModerationResult `json:"results"`
|
||||
}
|
||||
|
||||
// SpeechRequest 描述 /ai/v1/audio/speech 请求体的已知字段(文档用途)。
|
||||
// 直通端点实际按原样透传,未列字段与 xAI 专属参数(如 output_format)同样保留。
|
||||
type SpeechRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input string `json:"input"`
|
||||
Voice string `json:"voice,omitempty"`
|
||||
ResponseFormat string `json:"response_format,omitempty"`
|
||||
Language string `json:"language,omitempty"`
|
||||
}
|
||||
|
||||
// TtsRequest 描述 /ai/v1/tts 请求体的已知字段(xAI 官方 TTS 格式,文档用途)。
|
||||
// model 为网关扩展字段(缺省 xai.grok-tts);未列字段原样透传上游。
|
||||
type TtsRequest struct {
|
||||
Model string `json:"model,omitempty"`
|
||||
Text string `json:"text"`
|
||||
Language string `json:"language"`
|
||||
VoiceID string `json:"voice_id,omitempty"`
|
||||
OutputFormat *TtsOutputFormat `json:"output_format,omitempty"`
|
||||
Speed float64 `json:"speed,omitempty"`
|
||||
}
|
||||
|
||||
// TtsOutputFormat 是 xAI TTS 输出格式配置(缺省 MP3 24kHz/128kbps)。
|
||||
type TtsOutputFormat struct {
|
||||
Codec string `json:"codec,omitempty"`
|
||||
SampleRate int `json:"sample_rate,omitempty"`
|
||||
BitRate int `json:"bit_rate,omitempty"`
|
||||
}
|
||||
+182
-2
@@ -1,9 +1,11 @@
|
||||
// Package aiwire 定义 AI 网关的线格式类型:OpenAI Responses / Anthropic Messages /
|
||||
// Embeddings 与通用记账、错误、模型列表结构。上游统一为 OCI OpenAI 兼容面。
|
||||
// Package aiwire 定义 AI 网关的线格式类型:OpenAI Responses / Chat Completions /
|
||||
// Anthropic Messages / Embeddings 与通用记账、错误、模型列表结构。上游统一为
|
||||
// OCI OpenAI 兼容面。
|
||||
package aiwire
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StringList 兼容 OpenAI stop 的 string 与 []string 两种线格式。
|
||||
@@ -73,3 +75,181 @@ type ErrorDetail struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// ---- Chat Completions 线格式(/ai/v1/chat/completions,Tier 2 兼容层)----
|
||||
|
||||
// ChatRequest 是 OpenAI /v1/chat/completions 请求体;只声明网关读取的字段,
|
||||
// 无对应物的字段(stop / seed / n / penalty 等)由 JSON 解码天然忽略。
|
||||
type ChatRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []ChatMessage `json:"messages"`
|
||||
MaxTokens *int `json:"max_tokens,omitempty"`
|
||||
MaxCompletionTokens *int `json:"max_completion_tokens,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
TopP *float64 `json:"top_p,omitempty"`
|
||||
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
StreamOptions *StreamOptions `json:"stream_options,omitempty"`
|
||||
Tools []Tool `json:"tools,omitempty"`
|
||||
ToolChoice json.RawMessage `json:"tool_choice,omitempty"`
|
||||
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
|
||||
ReasoningEffort string `json:"reasoning_effort,omitempty"`
|
||||
}
|
||||
|
||||
// StreamOptions 控制流式末尾是否附带 usage 块。
|
||||
type StreamOptions struct {
|
||||
IncludeUsage bool `json:"include_usage"`
|
||||
}
|
||||
|
||||
// ChatMessage 是请求与非流式响应共用的消息结构。
|
||||
type ChatMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content Content `json:"content"`
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
}
|
||||
|
||||
// Content 兼容 string 与多模态块数组两种线格式,序列化时保形。
|
||||
type Content struct {
|
||||
Text string
|
||||
Parts []ContentPart
|
||||
IsArray bool
|
||||
}
|
||||
|
||||
func (c *Content) UnmarshalJSON(b []byte) error {
|
||||
t := strings.TrimSpace(string(b))
|
||||
if t == "null" {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(t, "[") {
|
||||
c.IsArray = true
|
||||
return json.Unmarshal(b, &c.Parts)
|
||||
}
|
||||
return json.Unmarshal(b, &c.Text)
|
||||
}
|
||||
|
||||
func (c Content) MarshalJSON() ([]byte, error) {
|
||||
if c.IsArray {
|
||||
return json.Marshal(c.Parts)
|
||||
}
|
||||
return json.Marshal(c.Text)
|
||||
}
|
||||
|
||||
// NewTextContent 构造字符串形态的内容。
|
||||
func NewTextContent(text string) Content {
|
||||
return Content{Text: text}
|
||||
}
|
||||
|
||||
// JoinText 拍平内容为纯文本(数组形态拼接 text 块)。
|
||||
func (c Content) JoinText() string {
|
||||
if !c.IsArray {
|
||||
return c.Text
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, p := range c.Parts {
|
||||
if p.Type == "" || p.Type == "text" {
|
||||
sb.WriteString(p.Text)
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// ContentPart 是块数组中的一段;text 与 image_url 被网关承接,其余类型拒绝。
|
||||
type ContentPart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL *ImageURL `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
// ImageURL 是 image_url 块负载;url 为 data URI(base64)或公网地址。
|
||||
type ImageURL struct {
|
||||
URL string `json:"url"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// Tool 是嵌套形态的 function 工具定义。
|
||||
type Tool struct {
|
||||
Type string `json:"type"`
|
||||
Function FunctionDef `json:"function"`
|
||||
}
|
||||
|
||||
// FunctionDef 描述工具的名称与 JSON Schema 参数。
|
||||
type FunctionDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Parameters json.RawMessage `json:"parameters,omitempty"`
|
||||
}
|
||||
|
||||
// ToolCall 是助手消息中的工具调用。
|
||||
type ToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Function FunctionCall `json:"function"`
|
||||
}
|
||||
|
||||
// FunctionCall 携带调用名与 JSON 编码的实参。
|
||||
type FunctionCall struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
}
|
||||
|
||||
// ResponseFormat 对应 response_format(json_object / json_schema)。
|
||||
type ResponseFormat struct {
|
||||
Type string `json:"type"`
|
||||
JSONSchema json.RawMessage `json:"json_schema,omitempty"`
|
||||
}
|
||||
|
||||
// ChatResponse 是非流式响应体(chat.completion)。
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
Model string `json:"model"`
|
||||
Choices []Choice `json:"choices"`
|
||||
Usage *Usage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
// Choice 是一条候选回复。
|
||||
type Choice struct {
|
||||
Index int `json:"index"`
|
||||
Message ChatMessage `json:"message"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
}
|
||||
|
||||
// ChatChunk 是流式增量事件体(chat.completion.chunk)。
|
||||
type ChatChunk struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
Model string `json:"model"`
|
||||
Choices []ChunkChoice `json:"choices"`
|
||||
Usage *Usage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
// ChunkChoice 是流式事件中的增量候选。
|
||||
type ChunkChoice struct {
|
||||
Index int `json:"index"`
|
||||
Delta Delta `json:"delta"`
|
||||
FinishReason *string `json:"finish_reason"`
|
||||
}
|
||||
|
||||
// Delta 是流式增量内容;Content 为纯文本片段。
|
||||
type Delta struct {
|
||||
Role string `json:"role,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
ToolCalls []ToolCallDelta `json:"tool_calls,omitempty"`
|
||||
}
|
||||
|
||||
// ToolCallDelta 是工具调用的流式片段;Index 标识聚合目标。
|
||||
type ToolCallDelta struct {
|
||||
Index int `json:"index"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Function FunctionCallDelta `json:"function"`
|
||||
}
|
||||
|
||||
// FunctionCallDelta 是函数名 / 实参的增量片段。
|
||||
type FunctionCallDelta struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Arguments string `json:"arguments,omitempty"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package aiwire
|
||||
|
||||
// RerankRequest 是 /ai/v1/rerank 请求体(Jina / Cohere 通行风格)。
|
||||
type RerankRequest struct {
|
||||
Model string `json:"model"`
|
||||
Query string `json:"query"`
|
||||
Documents []string `json:"documents"`
|
||||
TopN *int `json:"top_n,omitempty"`
|
||||
ReturnDocuments *bool `json:"return_documents,omitempty"`
|
||||
}
|
||||
|
||||
// RerankDocument 包装原文,仅在 return_documents 时返回。
|
||||
type RerankDocument struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// RerankResult 是一条重排结果:index 指向请求 documents 下标。
|
||||
type RerankResult struct {
|
||||
Index int `json:"index"`
|
||||
RelevanceScore float64 `json:"relevance_score"`
|
||||
Document *RerankDocument `json:"document,omitempty"`
|
||||
}
|
||||
|
||||
// RerankResponse 是 /ai/v1/rerank 响应体。
|
||||
type RerankResponse struct {
|
||||
Model string `json:"model"`
|
||||
Results []RerankResult `json:"results"`
|
||||
}
|
||||
@@ -184,3 +184,16 @@ type RespError struct {
|
||||
type RespIncomplete struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// RespResponse 描述 /ai/v1/responses 非流式响应的常用顶层字段(文档用途)。
|
||||
// 直通端点原样返回上游 JSON,未列字段(reasoning、incomplete_details 等)同样保留。
|
||||
type RespResponse struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Status string `json:"status"`
|
||||
Model string `json:"model"`
|
||||
Output json.RawMessage `json:"output"`
|
||||
Usage *RespUsage `json:"usage,omitempty"`
|
||||
Error *RespError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
+52
-2
@@ -1,8 +1,11 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -12,13 +15,22 @@ import (
|
||||
var (
|
||||
buildVersion = "dev"
|
||||
buildTime = ""
|
||||
// startedAt 为进程启动时刻,运行时长与 CPU 均值的计算基准
|
||||
startedAt = time.Now()
|
||||
// aboutDB 由 main 启动时注入,存储指标据此定位数据库文件
|
||||
aboutDB struct{ driver, path string }
|
||||
)
|
||||
|
||||
// SetAboutRuntime 注入数据库形态,「关于」页存储指标展示用;启动时调用一次。
|
||||
func SetAboutRuntime(dbDriver, dbPath string) {
|
||||
aboutDB.driver, aboutDB.path = dbDriver, dbPath
|
||||
}
|
||||
|
||||
// about 返回构建与运行环境信息,「设置 · 关于」页展示。
|
||||
//
|
||||
// @Summary 返回构建与运行环境信息,「设置 · 关于」页展示
|
||||
// @Summary 返回构建、运行时长与资源占用信息,「设置 · 关于」页展示
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} aboutResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/about [get]
|
||||
func about(c *gin.Context) {
|
||||
@@ -27,5 +39,43 @@ func about(c *gin.Context) {
|
||||
"buildTime": buildTime,
|
||||
"goVersion": runtime.Version(),
|
||||
"platform": runtime.GOOS + "/" + runtime.GOARCH,
|
||||
"startedAt": startedAt.UTC().Format(time.RFC3339),
|
||||
"uptimeSeconds": int64(time.Since(startedAt).Seconds()),
|
||||
"resources": resourcesSnapshot(),
|
||||
})
|
||||
}
|
||||
|
||||
// resourcesSnapshot 采集进程资源占用:CPU 自启动均值、内存、goroutine 与存储。
|
||||
func resourcesSnapshot() gin.H {
|
||||
var ms runtime.MemStats
|
||||
runtime.ReadMemStats(&ms)
|
||||
pct := 0.0
|
||||
if up := time.Since(startedAt).Seconds(); up > 0 {
|
||||
// 多核并行时均值可超 100%,口径为「占单核百分比」
|
||||
pct = processCPUTime().Seconds() / up * 100
|
||||
}
|
||||
return gin.H{
|
||||
"cpuAvgPercent": math.Round(pct*100) / 100,
|
||||
"numCpu": runtime.NumCPU(),
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
"memHeapBytes": ms.HeapAlloc,
|
||||
"memSysBytes": ms.Sys,
|
||||
"dbEngine": aboutDB.driver,
|
||||
"dbBytes": dbFileBytes(aboutDB.driver, aboutDB.path),
|
||||
}
|
||||
}
|
||||
|
||||
// dbFileBytes 统计数据库磁盘占用:sqlite 累加主文件与 -wal / -shm,
|
||||
// 外部数据库(mysql / postgres)不可从本机度量,返回 -1 表示不可用。
|
||||
func dbFileBytes(driver, path string) int64 {
|
||||
if driver != "sqlite" || path == "" {
|
||||
return -1
|
||||
}
|
||||
var total int64
|
||||
for _, p := range []string{path, path + "-wal", path + "-shm"} {
|
||||
if fi, err := os.Stat(p); err == nil {
|
||||
total += fi.Size()
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !unix
|
||||
|
||||
package api
|
||||
|
||||
import "time"
|
||||
|
||||
// processCPUTime 非 unix 平台无 getrusage,CPU 均值退化为 0。
|
||||
func processCPUTime() time.Duration { return 0 }
|
||||
@@ -0,0 +1,57 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDBFileBytes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
dbPath := filepath.Join(dir, "app.db")
|
||||
mustWrite := func(p string, n int) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(p, make([]byte, n), 0o600); err != nil {
|
||||
t.Fatalf("write %s: %v", p, err)
|
||||
}
|
||||
}
|
||||
mustWrite(dbPath, 100)
|
||||
mustWrite(dbPath+"-wal", 30)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
driver string
|
||||
path string
|
||||
want int64
|
||||
}{
|
||||
{name: "sqlite 主文件加 wal", driver: "sqlite", path: dbPath, want: 130},
|
||||
{name: "sqlite 文件不存在计 0", driver: "sqlite", path: filepath.Join(dir, "none.db"), want: 0},
|
||||
{name: "外部数据库不可度量", driver: "postgres", path: "", want: -1},
|
||||
{name: "路径为空不可度量", driver: "sqlite", path: "", want: -1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := dbFileBytes(tc.driver, tc.path); got != tc.want {
|
||||
t.Fatalf("dbFileBytes(%q, %q) = %d, want %d", tc.driver, tc.path, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcesSnapshot(t *testing.T) {
|
||||
SetAboutRuntime("sqlite", filepath.Join(t.TempDir(), "absent.db"))
|
||||
got := resourcesSnapshot()
|
||||
|
||||
if got["numCpu"].(int) < 1 || got["goroutines"].(int) < 1 {
|
||||
t.Fatalf("numCpu / goroutines 应为正数: %+v", got)
|
||||
}
|
||||
if got["memHeapBytes"].(uint64) == 0 || got["memSysBytes"].(uint64) == 0 {
|
||||
t.Fatalf("内存指标应为正数: %+v", got)
|
||||
}
|
||||
if got["cpuAvgPercent"].(float64) < 0 {
|
||||
t.Fatalf("cpuAvgPercent 不应为负: %+v", got)
|
||||
}
|
||||
if got["dbEngine"].(string) != "sqlite" || got["dbBytes"].(int64) != 0 {
|
||||
t.Fatalf("存储指标不符: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build unix
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// processCPUTime 返回进程自启动累计的 CPU 时间(用户态 + 内核态);
|
||||
// 取不到时返回 0,「关于」页 CPU 均值显示为 0 而非报错。
|
||||
func processCPUTime() time.Duration {
|
||||
var ru syscall.Rusage
|
||||
if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(ru.Utime.Nano() + ru.Stime.Nano())
|
||||
}
|
||||
+52
-12
@@ -6,6 +6,9 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/aiwire" // swagger 注解引用
|
||||
_ "oci-portal/internal/model" // swagger 注解引用
|
||||
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
@@ -18,7 +21,7 @@ type aiAdminHandler struct {
|
||||
|
||||
// @Summary ---- 密钥 ----
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[model.AiKey]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-keys [get]
|
||||
func (h *aiAdminHandler) listKeys(c *gin.Context) {
|
||||
@@ -35,7 +38,7 @@ func (h *aiAdminHandler) listKeys(c *gin.Context) {
|
||||
// @Summary 生成密钥
|
||||
// @Tags AI 管理
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} aiKeyCreateResponse "key 为明文密钥,仅本次返回"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-keys [post]
|
||||
func (h *aiAdminHandler) createKey(c *gin.Context) {
|
||||
@@ -110,7 +113,7 @@ func (h *aiAdminHandler) deleteKey(c *gin.Context) {
|
||||
// @Tags AI 管理
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} model.AiKey
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-keys/{id}/content-log [put]
|
||||
func (h *aiAdminHandler) updateKeyContentLog(c *gin.Context) {
|
||||
@@ -137,7 +140,7 @@ func (h *aiAdminHandler) updateKeyContentLog(c *gin.Context) {
|
||||
//
|
||||
// @Summary 分页查询内容日志
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} pagedResponse[model.AiCallLog]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-content-logs [get]
|
||||
func (h *aiAdminHandler) listContentLogs(c *gin.Context) {
|
||||
@@ -157,7 +160,7 @@ func (h *aiAdminHandler) listContentLogs(c *gin.Context) {
|
||||
|
||||
// @Summary ---- 渠道 ----
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[model.AiChannel]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-channels [get]
|
||||
func (h *aiAdminHandler) listChannels(c *gin.Context) {
|
||||
@@ -172,7 +175,7 @@ func (h *aiAdminHandler) listChannels(c *gin.Context) {
|
||||
// @Summary 创建 AI 渠道
|
||||
// @Tags AI 管理
|
||||
// @Param body body service.ChannelInput true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} model.AiChannel
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-channels [post]
|
||||
func (h *aiAdminHandler) createChannel(c *gin.Context) {
|
||||
@@ -236,7 +239,7 @@ func (h *aiAdminHandler) deleteChannel(c *gin.Context) {
|
||||
// @Summary 触发探测:服务可见性 + 模型同步 + 配额试调,返回更新后的渠道
|
||||
// @Tags AI 管理
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} model.AiChannel
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-channels/{id}/probe [post]
|
||||
func (h *aiAdminHandler) probeChannel(c *gin.Context) {
|
||||
@@ -255,7 +258,7 @@ func (h *aiAdminHandler) probeChannel(c *gin.Context) {
|
||||
// @Summary 同步渠道模型缓存
|
||||
// @Tags AI 管理
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[model.AiModelCache]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-channels/{id}/sync-models [post]
|
||||
func (h *aiAdminHandler) syncChannelModels(c *gin.Context) {
|
||||
@@ -275,7 +278,7 @@ func (h *aiAdminHandler) syncChannelModels(c *gin.Context) {
|
||||
|
||||
// @Summary ---- 聚合模型与调用日志 ----
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[aiwire.Model]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-models [get]
|
||||
func (h *aiAdminHandler) gatewayModels(c *gin.Context) {
|
||||
@@ -291,7 +294,7 @@ func (h *aiAdminHandler) gatewayModels(c *gin.Context) {
|
||||
|
||||
// @Summary 模型黑名单列表
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[model.AiModelBlacklist]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-blacklist [get]
|
||||
func (h *aiAdminHandler) listBlacklist(c *gin.Context) {
|
||||
@@ -308,7 +311,7 @@ func (h *aiAdminHandler) listBlacklist(c *gin.Context) {
|
||||
// @Summary 添加模型黑名单
|
||||
// @Tags AI 管理
|
||||
// @Param body body object true "请求体:{name: 模型名}"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} itemResponse[model.AiModelBlacklist]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-blacklist [post]
|
||||
func (h *aiAdminHandler) addBlacklist(c *gin.Context) {
|
||||
@@ -347,7 +350,7 @@ func (h *aiAdminHandler) removeBlacklist(c *gin.Context) {
|
||||
|
||||
// @Summary AI 调用日志列表
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} pagedResponse[model.AiContentLog]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-logs [get]
|
||||
func (h *aiAdminHandler) listLogs(c *gin.Context) {
|
||||
@@ -369,3 +372,40 @@ func aiPathID(c *gin.Context) (uint, bool) {
|
||||
}
|
||||
return uint(id), true
|
||||
}
|
||||
|
||||
// aiSettingsResponse 是 AI 网关全局设置(文档与响应共用)。
|
||||
type aiSettingsResponse struct {
|
||||
FilterDeprecated bool `json:"filterDeprecated"`
|
||||
}
|
||||
|
||||
// aiSettings 返回 AI 网关全局设置。
|
||||
//
|
||||
// @Summary AI 网关全局设置
|
||||
// @Tags AI 管理
|
||||
// @Success 200 {object} aiSettingsResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-settings [get]
|
||||
func (h *aiAdminHandler) aiSettings(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, aiSettingsResponse{FilterDeprecated: h.gw.FilterDeprecated()})
|
||||
}
|
||||
|
||||
// updateAiSettings 更新 AI 网关全局设置(当前仅「过滤弃用模型」开关)。
|
||||
//
|
||||
// @Summary 更新 AI 网关全局设置
|
||||
// @Tags AI 管理
|
||||
// @Param body body aiSettingsResponse true "开启后已宣布弃用(即使未退役)的模型从列表与路由中排除"
|
||||
// @Success 200 {object} aiSettingsResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/ai-settings [put]
|
||||
func (h *aiAdminHandler) updateAiSettings(c *gin.Context) {
|
||||
var req aiSettingsResponse
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.gw.SetFilterDeprecated(c.Request.Context(), req.FilterDeprecated); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, aiSettingsResponse{FilterDeprecated: h.gw.FilterDeprecated()})
|
||||
}
|
||||
|
||||
+223
-18
@@ -165,8 +165,8 @@ func fillUsage(entry *model.AiCallLog, u *aiwire.Usage) {
|
||||
//
|
||||
// @Summary OpenAI 兼容向量嵌入
|
||||
// @Tags AI 网关
|
||||
// @Param body body object true "OpenAI embeddings 请求体"
|
||||
// @Success 200 {object} map[string]any "OpenAI 兼容响应"
|
||||
// @Param body body aiwire.EmbeddingsRequest true "OpenAI embeddings 请求体"
|
||||
// @Success 200 {object} aiwire.EmbeddingsResponse "OpenAI 兼容响应"
|
||||
// @Router /ai/v1/embeddings [post]
|
||||
func (h *aiGatewayHandler) embeddings(c *gin.Context) {
|
||||
var req aiwire.EmbeddingsRequest
|
||||
@@ -210,12 +210,16 @@ func sseHeaders(c *gin.Context) {
|
||||
c.Writer.Flush()
|
||||
}
|
||||
|
||||
// anthDefaultMaxTokens 是 max_tokens 缺省时的默认输出上限:Anthropic 协议
|
||||
// 该字段必填,但部分客户端当选填不传,按默认值放行而非 400 拒绝。
|
||||
const anthDefaultMaxTokens = 8192
|
||||
|
||||
// messages 是 Anthropic /ai/v1/messages 端点。
|
||||
//
|
||||
// @Summary Anthropic Messages 兼容端点
|
||||
// @Tags AI 网关
|
||||
// @Param body body object true "Anthropic messages 请求体(支持 stream;经 OCI OpenAI 兼容面直通)"
|
||||
// @Success 200 {object} map[string]any "Anthropic 兼容响应(流式为 SSE)"
|
||||
// @Param body body aiwire.MessagesRequest true "Anthropic messages 请求体(支持 stream;经 OCI OpenAI 兼容面直通;max_tokens 可缺省,默认 8192)"
|
||||
// @Success 200 {object} aiwire.MessagesResponse "Anthropic 兼容响应(非流式;流式为 SSE 事件序列)"
|
||||
// @Router /ai/v1/messages [post]
|
||||
func (h *aiGatewayHandler) messages(c *gin.Context) {
|
||||
var req aiwire.MessagesRequest
|
||||
@@ -224,8 +228,7 @@ func (h *aiGatewayHandler) messages(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if req.MaxTokens <= 0 {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", "max_tokens 必填且需大于 0")
|
||||
return
|
||||
req.MaxTokens = anthDefaultMaxTokens
|
||||
}
|
||||
if len(req.Messages) == 0 {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", "messages 不能为空")
|
||||
@@ -281,10 +284,30 @@ func (h *aiGatewayHandler) streamAnthropic(c *gin.Context, body []byte, req aiwi
|
||||
defer upstream.Close()
|
||||
sseHeaders(c)
|
||||
bridge := service.NewAnthRespBridge(aiRandID("msg_"), req.Model)
|
||||
if err := forwardAnthSSE(c, upstream, bridge); err != nil {
|
||||
emitted := 0
|
||||
if err := forwardSSEData(upstream, func(data []byte) {
|
||||
evs := bridge.Feed(data)
|
||||
emitted += len(evs)
|
||||
writeAnthEvents(c, evs)
|
||||
}); err != nil {
|
||||
entry.ErrMsg = err.Error()
|
||||
}
|
||||
// 上游断流且客户端尚未收到任何事件(OCI 兼容面对大请求 + 推理模型的
|
||||
// 流式通道会在 reasoning 阶段掐断):降级非流式重做,结果按事件序列推送
|
||||
if emitted == 0 && !bridge.SawTerminal() && c.Request.Context().Err() == nil {
|
||||
if h.anthFallback(c, &entry, req) {
|
||||
entry.Status = http.StatusOK
|
||||
entry.LatencyMs = time.Since(start).Milliseconds()
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, "anthropic", req.Model, true, req, nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeAnthEvents(c, bridge.Finish())
|
||||
// 上游错误事件 / 提前终止:SSE 头已发出维持 200,错误落日志可查
|
||||
if msg := bridge.Err(); msg != "" && entry.ErrMsg == "" {
|
||||
entry.ErrMsg = msg
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
entry.LatencyMs = time.Since(start).Milliseconds()
|
||||
usage := bridge.Usage()
|
||||
@@ -295,15 +318,40 @@ func (h *aiGatewayHandler) streamAnthropic(c *gin.Context, body []byte, req aiwi
|
||||
h.maybeLogContent(c, callID, "anthropic", req.Model, true, req, nil)
|
||||
}
|
||||
|
||||
// forwardAnthSSE 逐行读上游 SSE,把 data 行喂给桥并即时写出转换后的事件。
|
||||
func forwardAnthSSE(c *gin.Context, upstream io.Reader, bridge *service.AnthRespBridge) error {
|
||||
// anthFallback 用非流式重做同一请求并把完整结果按事件序列推送;
|
||||
// 成功返回 true 并把渠道 / 用量 / 降级标注写入日志条目。
|
||||
func (h *aiGatewayHandler) anthFallback(c *gin.Context, entry *model.AiCallLog, req aiwire.MessagesRequest) bool {
|
||||
req.Stream = false
|
||||
body, err := service.AnthropicToResponsesBody(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
payload, meta, err := h.gw.RespPassthrough(c.Request.Context(), body, req.Model, keyGroup(c))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
out, err := service.ResponsesToAnthropic(payload, aiRandID("msg_"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
writeAnthEvents(c, service.AnthMessageEvents(out))
|
||||
entry.ChannelID, entry.ChannelName = meta.ChannelID, meta.ChannelName
|
||||
entry.Retries++
|
||||
entry.ErrMsg = "流式上游断流,已降级非流式完成"
|
||||
fillUsage(entry, service.RespPassthroughUsage(payload))
|
||||
return true
|
||||
}
|
||||
|
||||
// forwardSSEData 逐行读上游 SSE,把 data 行交给 emit 即时转换写出;
|
||||
// Anthropic 与 Chat Completions 两条流式桥共用。
|
||||
func forwardSSEData(upstream io.Reader, emit func([]byte)) error {
|
||||
reader := bufio.NewReader(upstream)
|
||||
for {
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if len(line) > 0 {
|
||||
trimmed := bytes.TrimSpace(line)
|
||||
if data, ok := bytes.CutPrefix(trimmed, []byte("data: ")); ok {
|
||||
writeAnthEvents(c, bridge.Feed(data))
|
||||
emit(data)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
@@ -328,11 +376,159 @@ func writeAnthEvents(c *gin.Context, events []service.AnthEvent) {
|
||||
c.Writer.Flush()
|
||||
}
|
||||
|
||||
// chatCompletions 是 OpenAI /ai/v1/chat/completions 端点(Tier 2 兼容层,
|
||||
// 承接只会说 Chat Completions 的存量客户端)。
|
||||
//
|
||||
// @Summary OpenAI Chat Completions 兼容端点
|
||||
// @Tags AI 网关
|
||||
// @Param body body aiwire.ChatRequest true "OpenAI chat/completions 请求体(支持 stream;经 Responses 转换直通)"
|
||||
// @Success 200 {object} aiwire.ChatResponse "OpenAI 兼容响应(非流式;流式为 SSE,末尾 data: [DONE])"
|
||||
// @Router /ai/v1/chat/completions [post]
|
||||
func (h *aiGatewayHandler) chatCompletions(c *gin.Context) {
|
||||
var req aiwire.ChatRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Model) == "" || len(req.Messages) == 0 {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", "model 与 messages 不能为空")
|
||||
return
|
||||
}
|
||||
if !checkKeyModel(c, req.Model) {
|
||||
return
|
||||
}
|
||||
body, err := service.ChatToResponsesBody(req)
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
if req.Stream {
|
||||
h.streamChat(c, body, req)
|
||||
return
|
||||
}
|
||||
h.chatOnce(c, body, req)
|
||||
}
|
||||
|
||||
// chatOnce 处理非流式:直通上游 → 转回 chat.completion → 记账。
|
||||
func (h *aiGatewayHandler) chatOnce(c *gin.Context, body []byte, req aiwire.ChatRequest) {
|
||||
start := time.Now()
|
||||
payload, meta, err := h.gw.RespPassthrough(c.Request.Context(), body, req.Model, keyGroup(c))
|
||||
entry := h.logEntry(c, "openai", req.Model, false, meta, start)
|
||||
if err != nil {
|
||||
upstreamError(c, err)
|
||||
entry.ErrMsg = err.Error()
|
||||
h.logFailure(c, entry, req)
|
||||
return
|
||||
}
|
||||
out, err := service.ResponsesToChat(payload, aiRandID("chatcmpl-"), time.Now().Unix())
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadGateway, "api_error", err.Error())
|
||||
entry.ErrMsg = err.Error()
|
||||
h.logFailure(c, entry, req)
|
||||
return
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
fillUsage(&entry, out.Usage)
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, "openai", req.Model, false, req, out)
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// streamChat 流式直通并桥接:上游 Responses SSE 经 ChatRespBridge 转为
|
||||
// chat.completion.chunk 序列逐块写出,末尾发 [DONE];usage 从 completed 事件记账。
|
||||
func (h *aiGatewayHandler) streamChat(c *gin.Context, body []byte, req aiwire.ChatRequest) {
|
||||
start := time.Now()
|
||||
upstream, meta, err := h.gw.RespPassthroughStream(c.Request.Context(), body, req.Model, keyGroup(c))
|
||||
entry := h.logEntry(c, "openai", req.Model, true, meta, start)
|
||||
if err != nil {
|
||||
upstreamError(c, err)
|
||||
entry.ErrMsg = err.Error()
|
||||
h.logFailure(c, entry, req)
|
||||
return
|
||||
}
|
||||
defer upstream.Close()
|
||||
sseHeaders(c)
|
||||
includeUsage := req.StreamOptions != nil && req.StreamOptions.IncludeUsage
|
||||
bridge := service.NewChatRespBridge(aiRandID("chatcmpl-"), req.Model, time.Now().Unix(), includeUsage)
|
||||
emitted := 0
|
||||
if err := forwardSSEData(upstream, func(data []byte) {
|
||||
chunks := bridge.Feed(data)
|
||||
emitted += len(chunks)
|
||||
writeChatChunks(c, chunks)
|
||||
}); err != nil {
|
||||
entry.ErrMsg = err.Error()
|
||||
}
|
||||
// 上游断流且客户端尚未收到任何块:降级非流式重做(成因同 messages 端点)
|
||||
if emitted == 0 && bridge.Usage() == nil && c.Request.Context().Err() == nil {
|
||||
if h.chatFallback(c, &entry, req, includeUsage) {
|
||||
entry.Status = http.StatusOK
|
||||
entry.LatencyMs = time.Since(start).Milliseconds()
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, "openai", req.Model, true, req, nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeChatChunks(c, bridge.Finish())
|
||||
c.Writer.WriteString("data: [DONE]\n\n")
|
||||
c.Writer.Flush()
|
||||
// 未见 completed 即结束:usage 缺失说明上游流异常提前终止,落日志可查
|
||||
if bridge.Usage() == nil && entry.ErrMsg == "" {
|
||||
entry.ErrMsg = "上游流提前终止,未返回终态事件"
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
entry.LatencyMs = time.Since(start).Milliseconds()
|
||||
fillUsage(&entry, bridge.Usage())
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, "openai", req.Model, true, req, nil)
|
||||
}
|
||||
|
||||
// chatFallback 用非流式重做同一请求并把完整结果按 chunk 序列推送;
|
||||
// 成功返回 true 并把渠道 / 用量 / 降级标注写入日志条目。
|
||||
func (h *aiGatewayHandler) chatFallback(c *gin.Context, entry *model.AiCallLog, req aiwire.ChatRequest, includeUsage bool) bool {
|
||||
req.Stream = false
|
||||
body, err := service.ChatToResponsesBody(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
payload, meta, err := h.gw.RespPassthrough(c.Request.Context(), body, req.Model, keyGroup(c))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
out, err := service.ResponsesToChat(payload, aiRandID("chatcmpl-"), time.Now().Unix())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
writeChatChunks(c, service.ChatResponseChunks(out, includeUsage))
|
||||
c.Writer.WriteString("data: [DONE]\n\n")
|
||||
c.Writer.Flush()
|
||||
entry.ChannelID, entry.ChannelName = meta.ChannelID, meta.ChannelName
|
||||
entry.Retries++
|
||||
entry.ErrMsg = "流式上游断流,已降级非流式完成"
|
||||
fillUsage(entry, service.RespPassthroughUsage(payload))
|
||||
return true
|
||||
}
|
||||
|
||||
// writeChatChunks 逐块写出 chunk 的 SSE data 行并 flush。
|
||||
func writeChatChunks(c *gin.Context, chunks []aiwire.ChatChunk) {
|
||||
for _, ch := range chunks {
|
||||
b, err := json.Marshal(ch)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
c.Writer.WriteString("data: ")
|
||||
c.Writer.Write(b)
|
||||
c.Writer.WriteString("\n\n")
|
||||
}
|
||||
if len(chunks) > 0 {
|
||||
c.Writer.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// listModels 是 /ai/v1/models 端点(OpenAI 格式,从启用渠道的模型缓存聚合)。
|
||||
//
|
||||
// @Summary 可用模型列表
|
||||
// @Tags AI 网关
|
||||
// @Success 200 {object} map[string]any "OpenAI 兼容 models 列表"
|
||||
// @Success 200 {object} aiwire.ModelList "OpenAI 兼容 models 列表"
|
||||
// @Router /ai/v1/models [get]
|
||||
func (h *aiGatewayHandler) listModels(c *gin.Context) {
|
||||
list, err := h.gw.GatewayModels(c.Request.Context(), keyGroup(c))
|
||||
@@ -356,8 +552,8 @@ func (h *aiGatewayHandler) listModels(c *gin.Context) {
|
||||
//
|
||||
// @Summary OpenAI Responses 兼容端点
|
||||
// @Tags AI 网关
|
||||
// @Param body body object true "OpenAI responses 请求体(支持 stream;web_search/x_search 服务端工具仅非流式)"
|
||||
// @Success 200 {object} map[string]any "OpenAI 兼容响应(流式为 SSE)"
|
||||
// @Param body body aiwire.RespRequest true "OpenAI responses 请求体(支持 stream;服务端工具 web_search/x_search/code_interpreter/mcp 含流式;未列字段原样透传上游)"
|
||||
// @Success 200 {object} aiwire.RespResponse "OpenAI 兼容响应(非流式;流式为 SSE);直通仅建模常用字段,未列字段原样返回"
|
||||
// @Router /ai/v1/responses [post]
|
||||
func (h *aiGatewayHandler) responses(c *gin.Context) {
|
||||
raw, err := c.GetRawData()
|
||||
@@ -422,9 +618,14 @@ func (h *aiGatewayHandler) responsesPassthroughStream(c *gin.Context, body []byt
|
||||
}
|
||||
defer upstream.Close()
|
||||
sseHeaders(c)
|
||||
usage, err := forwardSSE(c, upstream)
|
||||
usage, upErr, err := forwardSSE(c, upstream)
|
||||
if err != nil {
|
||||
entry.ErrMsg = err.Error()
|
||||
} else if upErr != "" {
|
||||
// 上游错误事件已原样转发给客户端,这里落日志可查
|
||||
entry.ErrMsg = upErr
|
||||
} else if usage == nil {
|
||||
entry.ErrMsg = "上游流提前终止,未返回终态事件"
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
entry.LatencyMs = time.Since(start).Milliseconds()
|
||||
@@ -434,10 +635,11 @@ func (h *aiGatewayHandler) responsesPassthroughStream(c *gin.Context, body []byt
|
||||
}
|
||||
|
||||
// forwardSSE 把上游 SSE 逐行转发给客户端,空行(事件边界)即 flush;
|
||||
// 顺带从 data 行提取 response.completed 的 usage。
|
||||
func forwardSSE(c *gin.Context, upstream io.Reader) (*aiwire.Usage, error) {
|
||||
// 顺带从 data 行提取 response.completed 的 usage 与错误事件消息。
|
||||
func forwardSSE(c *gin.Context, upstream io.Reader) (*aiwire.Usage, string, error) {
|
||||
reader := bufio.NewReader(upstream)
|
||||
var usage *aiwire.Usage
|
||||
var upErr string
|
||||
for {
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if len(line) > 0 {
|
||||
@@ -449,14 +651,17 @@ func forwardSSE(c *gin.Context, upstream io.Reader) (*aiwire.Usage, error) {
|
||||
if u := service.RespStreamCompletedUsage(data); u != nil {
|
||||
usage = u
|
||||
}
|
||||
if m := service.RespStreamErrorMsg(data); m != "" && upErr == "" {
|
||||
upErr = m
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
c.Writer.Flush()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return usage, nil
|
||||
return usage, upErr, nil
|
||||
}
|
||||
return usage, err
|
||||
return usage, upErr, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"oci-portal/internal/aiwire"
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
// audioSpeech 是 OpenAI /ai/v1/audio/speech 端点(TTS,直通兼容面)。
|
||||
//
|
||||
// @Summary OpenAI Audio Speech 兼容端点(文本转语音)
|
||||
// @Tags AI 网关
|
||||
// @Param body body aiwire.SpeechRequest true "OpenAI audio speech 请求体(model/input 必填,voice 见 xAI Grok Voice 列表,language 缺省 auto;未列字段原样透传)"
|
||||
// @Success 200 {file} binary "音频字节(Content-Type 透传上游,默认 audio/mpeg)"
|
||||
// @Router /ai/v1/audio/speech [post]
|
||||
func (h *aiGatewayHandler) audioSpeech(c *gin.Context) {
|
||||
raw, err := c.GetRawData()
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
modelName, body, err := service.SpeechBodyNormalize(raw)
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
h.speechRespond(c, "speech", modelName, raw, body)
|
||||
}
|
||||
|
||||
// tts 是 xAI 官方格式 TTS 端点(/ai/v1/tts),转换为上游 OpenAI 兼容形态后复用 Speech 编排。
|
||||
//
|
||||
// @Summary xAI 官方格式文本转语音端点
|
||||
// @Tags AI 网关
|
||||
// @Param body body aiwire.TtsRequest true "xAI TTS 请求体(text/language 必填,voice_id 缺省 eve;model 为网关扩展,缺省 xai.grok-tts;未列字段原样透传)"
|
||||
// @Success 200 {file} binary "音频字节(Content-Type 透传上游,默认 audio/mpeg)"
|
||||
// @Router /ai/v1/tts [post]
|
||||
func (h *aiGatewayHandler) tts(c *gin.Context) {
|
||||
raw, err := c.GetRawData()
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
modelName, body, err := service.TtsBodyConvert(raw)
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
h.speechRespond(c, "tts", modelName, raw, body)
|
||||
}
|
||||
|
||||
// speechRespond 是 audioSpeech / tts 的公共主体:白名单校验、上游调用、日志与音频响应。
|
||||
func (h *aiGatewayHandler) speechRespond(c *gin.Context, endpoint, modelName string, raw, body []byte) {
|
||||
if !checkKeyModel(c, modelName) {
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
audio, contentType, meta, err := h.gw.Speech(c.Request.Context(), modelName, body, keyGroup(c))
|
||||
entry := h.logEntry(c, endpoint, modelName, false, meta, start)
|
||||
if err != nil {
|
||||
upstreamError(c, err)
|
||||
entry.ErrMsg = err.Error()
|
||||
h.logFailure(c, entry, string(raw))
|
||||
return
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, endpoint, modelName, false, string(raw), nil)
|
||||
if contentType == "" {
|
||||
contentType = "audio/mpeg"
|
||||
}
|
||||
c.Data(http.StatusOK, contentType, audio)
|
||||
}
|
||||
|
||||
// rerank 是 /ai/v1/rerank 端点(Jina / Cohere 风格文档重排)。
|
||||
//
|
||||
// @Summary 文档重排端点(Cohere Rerank)
|
||||
// @Tags AI 网关
|
||||
// @Param body body aiwire.RerankRequest true "重排请求体(model/query/documents 必填,可选 top_n/return_documents)"
|
||||
// @Success 200 {object} aiwire.RerankResponse "重排结果(results[].index 指向入参下标)"
|
||||
// @Router /ai/v1/rerank [post]
|
||||
func (h *aiGatewayHandler) rerank(c *gin.Context) {
|
||||
var req aiwire.RerankRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Model) == "" || strings.TrimSpace(req.Query) == "" || len(req.Documents) == 0 {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", "model、query 与 documents 不能为空")
|
||||
return
|
||||
}
|
||||
if !checkKeyModel(c, req.Model) {
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
resp, meta, err := h.gw.Rerank(c.Request.Context(), req, keyGroup(c))
|
||||
entry := h.logEntry(c, "rerank", req.Model, false, meta, start)
|
||||
if err != nil {
|
||||
upstreamError(c, err)
|
||||
entry.ErrMsg = err.Error()
|
||||
h.logFailure(c, entry, req)
|
||||
return
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, "rerank", req.Model, false, req, resp)
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// moderations 是 /ai/v1/moderations 端点(OpenAI 外壳映射 OCI Guardrails)。
|
||||
//
|
||||
// @Summary 内容审核端点(OCI Guardrails)
|
||||
// @Tags AI 网关
|
||||
// @Param body body aiwire.ModerationsRequest true "审核请求体(input 为字符串或字符串数组,单次至多 8 条;model 接受但忽略)"
|
||||
// @Success 200 {object} aiwire.ModerationsResponse "审核结果(categories/category_scores 为 overall/blocklist/prompt_injection,pii 为扩展字段)"
|
||||
// @Router /ai/v1/moderations [post]
|
||||
func (h *aiGatewayHandler) moderations(c *gin.Context) {
|
||||
var req aiwire.ModerationsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
inputs, err := service.ModerationInputs(req.Input)
|
||||
if err != nil {
|
||||
aiError(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
resp, meta, err := h.gw.Moderations(c.Request.Context(), aiRandID("modr_"), inputs, keyGroup(c))
|
||||
entry := h.logEntry(c, "moderations", "oci-guardrails", false, meta, start)
|
||||
if err != nil {
|
||||
upstreamError(c, err)
|
||||
entry.ErrMsg = err.Error()
|
||||
h.logFailure(c, entry, req)
|
||||
return
|
||||
}
|
||||
entry.Status = http.StatusOK
|
||||
callID := h.gw.LogCall(entry)
|
||||
h.maybeLogContent(c, callID, "moderations", "oci-guardrails", false, req, resp)
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
@@ -81,8 +81,32 @@ func TestAiGatewayKeyModelRestrict(t *testing.T) {
|
||||
`{"model":"meta.llama-3.3-70b-instruct","input":"hi"}`, 404, deny},
|
||||
{"不限密钥穿透闸门", "open-key-12345", "/ai/v1/responses",
|
||||
`{"model":"ghost-model","input":"hi"}`, 404, pass},
|
||||
{"chat completions 端点已删除", "open-key-12345", "/ai/v1/chat/completions",
|
||||
`{"model":"ghost-model","messages":[{"role":"user","content":"hi"}]}`, 404, []string{"not found"}},
|
||||
{"chat completions 白名单外拦截", "limited-key-1234", "/ai/v1/chat/completions",
|
||||
`{"model":"meta.llama-3.3-70b-instruct","messages":[{"role":"user","content":"hi"}]}`, 404, deny},
|
||||
{"chat completions 白名单内穿透", "limited-key-1234", "/ai/v1/chat/completions",
|
||||
`{"model":"ghost-model","messages":[{"role":"user","content":"hi"}]}`, 404, pass},
|
||||
{"messages 缺 max_tokens 按默认值放行", "open-key-12345", "/ai/v1/messages",
|
||||
`{"model":"ghost-model","messages":[{"role":"user","content":"hi"}]}`, 404, pass},
|
||||
{"chat completions 缺 messages 拒绝", "open-key-12345", "/ai/v1/chat/completions",
|
||||
`{"model":"ghost-model"}`, 400, []string{"invalid_request_error"}},
|
||||
{"chat completions 非 function 工具拒绝", "open-key-12345", "/ai/v1/chat/completions",
|
||||
`{"model":"ghost-model","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"web_search","function":{}}]}`,
|
||||
400, []string{"仅支持 function"}},
|
||||
{"chat completions 不支持内容块拒绝", "open-key-12345", "/ai/v1/chat/completions",
|
||||
`{"model":"ghost-model","messages":[{"role":"user","content":[{"type":"input_audio"}]}]}`,
|
||||
400, []string{"invalid_request_error"}},
|
||||
{"audio speech 白名单外拦截", "limited-key-1234", "/ai/v1/audio/speech",
|
||||
`{"model":"meta.llama-3.3-70b-instruct","input":"你好"}`, 404, deny},
|
||||
{"rerank 白名单外拦截", "limited-key-1234", "/ai/v1/rerank",
|
||||
`{"model":"meta.llama-3.3-70b-instruct","query":"q","documents":["d"]}`, 404, deny},
|
||||
{"rerank 缺 documents 拒绝", "open-key-12345", "/ai/v1/rerank",
|
||||
`{"model":"ghost-model","query":"q"}`, 400, []string{"invalid_request_error"}},
|
||||
{"moderations 空 input 拒绝", "open-key-12345", "/ai/v1/moderations",
|
||||
`{"input":[]}`, 400, []string{"invalid_request_error"}},
|
||||
{"tts 缺 language 拒绝", "open-key-12345", "/ai/v1/tts",
|
||||
`{"text":"你好"}`, 400, []string{"invalid_request_error"}},
|
||||
{"tts 白名单外拦截", "limited-key-1234", "/ai/v1/tts",
|
||||
`{"model":"meta.llama-3.3-70b-instruct","text":"你好","language":"zh"}`, 404, deny},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
+11
-11
@@ -15,7 +15,7 @@ import (
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} publicIpResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/change-public-ip [post]
|
||||
func (h *ociConfigHandler) changePublicIP(c *gin.Context) {
|
||||
@@ -40,7 +40,7 @@ func (h *ociConfigHandler) changePublicIP(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} ipv6AddressResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/ipv6-addresses [post]
|
||||
func (h *ociConfigHandler) addInstanceIpv6(c *gin.Context) {
|
||||
@@ -92,7 +92,7 @@ type attachVnicRequest struct {
|
||||
// @Tags 计算
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.Vnic
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/vnics [get]
|
||||
func (h *ociConfigHandler) listInstanceVnics(c *gin.Context) {
|
||||
@@ -113,7 +113,7 @@ func (h *ociConfigHandler) listInstanceVnics(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body attachVnicRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.Vnic
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/vnics [post]
|
||||
func (h *ociConfigHandler) attachVnic(c *gin.Context) {
|
||||
@@ -160,7 +160,7 @@ func (h *ociConfigHandler) detachVnic(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param vnicId path string true "vnicId"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} addressResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/vnics/{vnicId}/ipv6-addresses [post]
|
||||
func (h *ociConfigHandler) addVnicIpv6(c *gin.Context) {
|
||||
@@ -195,7 +195,7 @@ type attachBootVolumeRequest struct {
|
||||
// @Tags 存储
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.BootVolumeAttachment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/boot-volume-attachments [get]
|
||||
func (h *ociConfigHandler) listBootVolumeAttachments(c *gin.Context) {
|
||||
@@ -216,7 +216,7 @@ func (h *ociConfigHandler) listBootVolumeAttachments(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body attachBootVolumeRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.BootVolumeAttachment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/boot-volume-attachments [post]
|
||||
func (h *ociConfigHandler) attachBootVolume(c *gin.Context) {
|
||||
@@ -242,7 +242,7 @@ func (h *ociConfigHandler) attachBootVolume(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body attachBootVolumeRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.BootVolumeAttachment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/replace-boot-volume [post]
|
||||
func (h *ociConfigHandler) replaceBootVolume(c *gin.Context) {
|
||||
@@ -293,7 +293,7 @@ type attachVolumeRequest struct {
|
||||
// @Summary 块存储卷列表
|
||||
// @Tags 存储
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.BlockVolume
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/volumes [get]
|
||||
func (h *ociConfigHandler) listBlockVolumes(c *gin.Context) {
|
||||
@@ -313,7 +313,7 @@ func (h *ociConfigHandler) listBlockVolumes(c *gin.Context) {
|
||||
// @Tags 存储
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.VolumeAttachment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/volume-attachments [get]
|
||||
func (h *ociConfigHandler) listVolumeAttachments(c *gin.Context) {
|
||||
@@ -334,7 +334,7 @@ func (h *ociConfigHandler) listVolumeAttachments(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body attachVolumeRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.VolumeAttachment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/volume-attachments [post]
|
||||
func (h *ociConfigHandler) attachVolume(c *gin.Context) {
|
||||
|
||||
@@ -32,9 +32,9 @@ type loginRequest struct {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body loginRequest true "登录凭据"
|
||||
// @Success 200 {object} map[string]any "token 与 expiresAt"
|
||||
// @Failure 401 {object} map[string]string "凭据错误"
|
||||
// @Failure 428 {object} map[string]any "需要两步验证码(totpRequired=true)"
|
||||
// @Success 200 {object} tokenResponse "token 与 expiresAt"
|
||||
// @Failure 401 {object} errorResponse "凭据错误"
|
||||
// @Failure 428 {object} totpRequiredResponse "需要两步验证码(totpRequired=true)"
|
||||
// @Router /api/v1/auth/login [post]
|
||||
func (h *authHandler) login(c *gin.Context) {
|
||||
var req loginRequest
|
||||
|
||||
+13
-11
@@ -8,6 +8,8 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/model" // swagger 注解引用
|
||||
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
@@ -23,7 +25,7 @@ type authxHandler struct {
|
||||
//
|
||||
// @Summary 两步验证状态
|
||||
// @Tags 认证
|
||||
// @Success 200 {object} map[string]bool "enabled"
|
||||
// @Success 200 {object} enabledResponse "enabled"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/totp [get]
|
||||
func (h *authxHandler) totpStatus(c *gin.Context) {
|
||||
@@ -39,8 +41,8 @@ func (h *authxHandler) totpStatus(c *gin.Context) {
|
||||
//
|
||||
// @Summary 发起两步验证设置
|
||||
// @Tags 认证
|
||||
// @Success 200 {object} map[string]string "secret 与 otpauthUri"
|
||||
// @Failure 409 {object} map[string]string "已启用"
|
||||
// @Success 200 {object} totpSetupResponse "secret 与 otpauthUri"
|
||||
// @Failure 409 {object} errorResponse "已启用"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/totp/setup [post]
|
||||
func (h *authxHandler) totpSetup(c *gin.Context) {
|
||||
@@ -128,7 +130,7 @@ func (h *authxHandler) respondFreshToken(c *gin.Context) {
|
||||
//
|
||||
// @Summary 撤销全部会话
|
||||
// @Tags 认证
|
||||
// @Success 200 {object} map[string]string "新 token 与 expiresAt"
|
||||
// @Success 200 {object} tokenResponse "新 token 与 expiresAt"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/revoke-sessions [post]
|
||||
func (h *authxHandler) revokeSessions(c *gin.Context) {
|
||||
@@ -146,7 +148,7 @@ func (h *authxHandler) revokeSessions(c *gin.Context) {
|
||||
//
|
||||
// @Summary 登录凭据摘要
|
||||
// @Tags 认证
|
||||
// @Success 200 {object} map[string]any "username 与 passwordLoginDisabled"
|
||||
// @Success 200 {object} credentialsResponse "username 与 passwordLoginDisabled"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/credentials [get]
|
||||
func (h *authxHandler) getCredentials(c *gin.Context) {
|
||||
@@ -167,7 +169,7 @@ func (h *authxHandler) getCredentials(c *gin.Context) {
|
||||
// @Tags 认证
|
||||
// @Param body body service.UpdateCredentialsInput true "新凭据(当前密码必验)"
|
||||
// @Success 204 "已更新,请重新登录"
|
||||
// @Failure 401 {object} map[string]string "当前密码错误"
|
||||
// @Failure 401 {object} errorResponse "当前密码错误"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/credentials [put]
|
||||
func (h *authxHandler) updateCredentials(c *gin.Context) {
|
||||
@@ -199,7 +201,7 @@ func (h *authxHandler) updateCredentials(c *gin.Context) {
|
||||
// @Tags 认证
|
||||
// @Param body body object true "{disabled: bool}"
|
||||
// @Success 204 "已保存"
|
||||
// @Failure 409 {object} map[string]string "未绑定外部身份"
|
||||
// @Failure 409 {object} errorResponse "未绑定外部身份"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/password-login [put]
|
||||
func (h *authxHandler) updatePasswordLogin(c *gin.Context) {
|
||||
@@ -230,7 +232,7 @@ func (h *authxHandler) updatePasswordLogin(c *gin.Context) {
|
||||
//
|
||||
// @Summary 外部登录 provider 列表
|
||||
// @Tags 认证
|
||||
// @Success 200 {object} map[string]any "providers 与 passwordLoginDisabled"
|
||||
// @Success 200 {object} oauthProvidersResponse "providers 与 passwordLoginDisabled"
|
||||
// @Router /api/v1/auth/oauth/providers [get]
|
||||
func (h *authxHandler) oauthProviders(c *gin.Context) {
|
||||
providers := h.oauth.Providers(c.Request.Context())
|
||||
@@ -247,7 +249,7 @@ func (h *authxHandler) oauthProviders(c *gin.Context) {
|
||||
// @Tags 认证
|
||||
// @Param provider path string true "oidc / github"
|
||||
// @Param mode query string false "bind=绑定当前账号(需 Bearer),缺省登录"
|
||||
// @Success 200 {object} map[string]string "url"
|
||||
// @Success 200 {object} urlResponse "url"
|
||||
// @Router /api/v1/auth/oauth/{provider}/authorize [get]
|
||||
func (h *authxHandler) oauthAuthorize(c *gin.Context) {
|
||||
provider := c.Param("provider")
|
||||
@@ -333,7 +335,7 @@ func oauthErrText(err error) string {
|
||||
//
|
||||
// @Summary 已绑定外部身份
|
||||
// @Tags 认证
|
||||
// @Success 200 {object} map[string]any "items"
|
||||
// @Success 200 {object} itemsResponse[model.UserIdentity] "items"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/identities [get]
|
||||
func (h *authxHandler) identities(c *gin.Context) {
|
||||
@@ -351,7 +353,7 @@ func (h *authxHandler) identities(c *gin.Context) {
|
||||
// @Tags 认证
|
||||
// @Param id path int true "身份 ID"
|
||||
// @Success 204 "已解绑"
|
||||
// @Failure 409 {object} map[string]string "最后一个身份不可解绑"
|
||||
// @Failure 409 {object} errorResponse "最后一个身份不可解绑"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/auth/identities/{id} [delete]
|
||||
func (h *authxHandler) unbindIdentity(c *gin.Context) {
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/oci" // swagger 注解引用
|
||||
)
|
||||
|
||||
// ---- 控制台连接(VNC / 串口) ----
|
||||
@@ -18,7 +20,7 @@ type createConsoleConnectionRequest struct {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body createConsoleConnectionRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.ConsoleConnection
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [post]
|
||||
func (h *ociConfigHandler) createConsoleConnection(c *gin.Context) {
|
||||
@@ -43,7 +45,7 @@ func (h *ociConfigHandler) createConsoleConnection(c *gin.Context) {
|
||||
// @Tags 计算
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.ConsoleConnection
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-connections [get]
|
||||
func (h *ociConfigHandler) listConsoleConnections(c *gin.Context) {
|
||||
|
||||
@@ -41,7 +41,7 @@ func boolOr(v *bool, def bool) bool {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.IdentityProviderInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/identity-providers [get]
|
||||
func (h *ociConfigHandler) listIdentityProviders(c *gin.Context) {
|
||||
@@ -62,7 +62,7 @@ func (h *ociConfigHandler) listIdentityProviders(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param body body createIdpRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.IdentityProviderInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/identity-providers [post]
|
||||
func (h *ociConfigHandler) createIdentityProvider(c *gin.Context) {
|
||||
@@ -102,7 +102,7 @@ func (h *ociConfigHandler) createIdentityProvider(c *gin.Context) {
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param idpId path string true "idpId"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.IdentityProviderInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/identity-providers/{idpId}/activate [post]
|
||||
func (h *ociConfigHandler) activateIdentityProvider(c *gin.Context) {
|
||||
@@ -149,7 +149,7 @@ func (h *ociConfigHandler) deleteIdentityProvider(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {file} file "SAML 元数据 XML(附件下载)"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/saml-metadata [get]
|
||||
func (h *ociConfigHandler) downloadSamlMetadata(c *gin.Context) {
|
||||
@@ -170,7 +170,7 @@ func (h *ociConfigHandler) downloadSamlMetadata(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.SignOnRuleInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/sign-on-rules [get]
|
||||
func (h *ociConfigHandler) listSignOnRules(c *gin.Context) {
|
||||
@@ -191,7 +191,7 @@ func (h *ociConfigHandler) listSignOnRules(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.SignOnRuleInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/sign-on-exemptions [post]
|
||||
func (h *ociConfigHandler) createMfaExemption(c *gin.Context) {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
// @Summary 可用域列表
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} string
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/availability-domains [get]
|
||||
func (h *ociConfigHandler) availabilityDomains(c *gin.Context) {
|
||||
@@ -67,7 +67,7 @@ type instanceActionRequest struct {
|
||||
// @Summary 实例列表
|
||||
// @Tags 计算
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.Instance
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances [get]
|
||||
func (h *ociConfigHandler) listInstances(c *gin.Context) {
|
||||
@@ -87,7 +87,7 @@ func (h *ociConfigHandler) listInstances(c *gin.Context) {
|
||||
// @Tags 计算
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body createInstanceRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} createInstancesResponse "部分成功仍 201,errors 为逐台失败信息"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances [post]
|
||||
func (h *ociConfigHandler) createInstance(c *gin.Context) {
|
||||
@@ -147,7 +147,7 @@ func (h *ociConfigHandler) createInstance(c *gin.Context) {
|
||||
// @Tags 计算
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.Instance
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId} [get]
|
||||
func (h *ociConfigHandler) getInstance(c *gin.Context) {
|
||||
@@ -168,7 +168,7 @@ func (h *ociConfigHandler) getInstance(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body updateInstanceRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.Instance
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId} [put]
|
||||
func (h *ociConfigHandler) updateInstance(c *gin.Context) {
|
||||
@@ -220,7 +220,7 @@ func (h *ociConfigHandler) terminateInstance(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Param body body instanceActionRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.Instance
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/action [post]
|
||||
func (h *ociConfigHandler) instanceAction(c *gin.Context) {
|
||||
@@ -253,7 +253,7 @@ type updateBootVolumeRequest struct {
|
||||
// @Summary 引导卷列表
|
||||
// @Tags 存储
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.BootVolume
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/boot-volumes [get]
|
||||
func (h *ociConfigHandler) listBootVolumes(c *gin.Context) {
|
||||
@@ -273,7 +273,7 @@ func (h *ociConfigHandler) listBootVolumes(c *gin.Context) {
|
||||
// @Tags 存储
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param bootVolumeId path string true "bootVolumeId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.BootVolume
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/boot-volumes/{bootVolumeId} [get]
|
||||
func (h *ociConfigHandler) getBootVolume(c *gin.Context) {
|
||||
@@ -294,7 +294,7 @@ func (h *ociConfigHandler) getBootVolume(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param bootVolumeId path string true "bootVolumeId"
|
||||
// @Param body body updateBootVolumeRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.BootVolume
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/boot-volumes/{bootVolumeId} [put]
|
||||
func (h *ociConfigHandler) updateBootVolume(c *gin.Context) {
|
||||
|
||||
+7
-127
@@ -7,7 +7,8 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"oci-portal/internal/model"
|
||||
_ "oci-portal/internal/model" // swagger 注解引用
|
||||
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
@@ -21,7 +22,7 @@ type logEventHandler struct {
|
||||
// @Summary 查询配置的回调地址
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} logWebhookStatusResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/log-webhook [get]
|
||||
func (h *logEventHandler) getWebhook(c *gin.Context) {
|
||||
@@ -46,7 +47,7 @@ func (h *logEventHandler) getWebhook(c *gin.Context) {
|
||||
// @Summary 生成
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.LogWebhookInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/log-webhook [post]
|
||||
func (h *logEventHandler) ensureWebhook(c *gin.Context) {
|
||||
@@ -88,7 +89,7 @@ func (h *logEventHandler) revokeWebhook(c *gin.Context) {
|
||||
// @Tags 任务与日志回传
|
||||
// @Param configId query int false "按配置过滤"
|
||||
// @Param q query string false "关键字"
|
||||
// @Success 200 {object} map[string]any "items 与 total"
|
||||
// @Success 200 {object} pagedResponse[model.LogEvent] "items 与 total"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/log-events [get]
|
||||
func (h *logEventHandler) list(c *gin.Context) {
|
||||
@@ -107,133 +108,12 @@ func (h *logEventHandler) list(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"items": items, "total": total})
|
||||
}
|
||||
|
||||
// alertRuleRequest 是创建/更新告警规则的请求体。
|
||||
type alertRuleRequest struct {
|
||||
Name string `json:"name"`
|
||||
Enabled bool `json:"enabled"`
|
||||
OciConfigID uint `json:"ociConfigId"`
|
||||
EventTypes string `json:"eventTypes"`
|
||||
SourceIPs string `json:"sourceIps"`
|
||||
SourceIPMode string `json:"sourceIpMode"`
|
||||
ResourceMatch string `json:"resourceMatch"`
|
||||
Threshold int `json:"threshold"`
|
||||
WindowMinutes int `json:"windowMinutes"`
|
||||
}
|
||||
|
||||
// toModel 转为规则模型(默认阈值 1)。
|
||||
func (r alertRuleRequest) toModel() model.AlertRule {
|
||||
if r.Threshold == 0 {
|
||||
r.Threshold = 1
|
||||
}
|
||||
return model.AlertRule{
|
||||
Name: r.Name, Enabled: r.Enabled, OciConfigID: r.OciConfigID,
|
||||
EventTypes: r.EventTypes, SourceIPs: r.SourceIPs, SourceIPMode: r.SourceIPMode,
|
||||
ResourceMatch: r.ResourceMatch, Threshold: r.Threshold, WindowMinutes: r.WindowMinutes,
|
||||
}
|
||||
}
|
||||
|
||||
// listAlertRules 返回全部告警规则。
|
||||
//
|
||||
// @Summary 告警规则列表
|
||||
// @Tags 任务与日志回传
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/log-events/alert-rules [get]
|
||||
func (h *logEventHandler) listAlertRules(c *gin.Context) {
|
||||
rules, err := h.svc.ListAlertRules(c.Request.Context())
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": rules})
|
||||
}
|
||||
|
||||
// createAlertRule 创建告警规则;字段非法返回 400。
|
||||
//
|
||||
// @Summary 创建告警规则
|
||||
// @Tags 任务与日志回传
|
||||
// @Param body body alertRuleRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/log-events/alert-rules [post]
|
||||
func (h *logEventHandler) createAlertRule(c *gin.Context) {
|
||||
var req alertRuleRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
rule, err := h.svc.CreateAlertRule(c.Request.Context(), req.toModel())
|
||||
if err != nil {
|
||||
respondAlertRuleError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, rule)
|
||||
}
|
||||
|
||||
// updateAlertRule 整体覆盖告警规则(含启停)。
|
||||
//
|
||||
// @Summary 更新告警规则
|
||||
// @Tags 任务与日志回传
|
||||
// @Param ruleId path int true "规则 ID"
|
||||
// @Param body body alertRuleRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/log-events/alert-rules/{ruleId} [put]
|
||||
func (h *logEventHandler) updateAlertRule(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("ruleId"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "规则 ID 非法"})
|
||||
return
|
||||
}
|
||||
var req alertRuleRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
rule, err := h.svc.UpdateAlertRule(c.Request.Context(), uint(id), req.toModel())
|
||||
if err != nil {
|
||||
respondAlertRuleError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, rule)
|
||||
}
|
||||
|
||||
// deleteAlertRule 删除告警规则及其命中记录。
|
||||
//
|
||||
// @Summary 删除告警规则
|
||||
// @Tags 任务与日志回传
|
||||
// @Param ruleId path int true "规则 ID"
|
||||
// @Success 204 "无内容"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/log-events/alert-rules/{ruleId} [delete]
|
||||
func (h *logEventHandler) deleteAlertRule(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("ruleId"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "规则 ID 非法"})
|
||||
return
|
||||
}
|
||||
if err := h.svc.DeleteAlertRule(c.Request.Context(), uint(id)); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// respondAlertRuleError 把字段校验错误映射为 400。
|
||||
func respondAlertRuleError(c *gin.Context, err error) {
|
||||
if errors.Is(err, service.ErrInvalidAlertRule) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
respondError(c, err)
|
||||
}
|
||||
|
||||
// getRelay 查询 OCI 侧链路状态与关键事件清单。
|
||||
//
|
||||
// @Summary 查询 OCI 侧链路状态与关键事件清单
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.RelayView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/log-relay [get]
|
||||
func (h *logEventHandler) getRelay(c *gin.Context) {
|
||||
@@ -254,7 +134,7 @@ func (h *logEventHandler) getRelay(c *gin.Context) {
|
||||
// @Summary 一键建立回传链路
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.RelayView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/log-relay [post]
|
||||
func (h *logEventHandler) setupRelay(c *gin.Context) {
|
||||
|
||||
+16
-16
@@ -11,7 +11,7 @@ import (
|
||||
// @Summary 实例形状列表
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.ComputeShape
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/shapes [get]
|
||||
func (h *ociConfigHandler) shapes(c *gin.Context) {
|
||||
@@ -30,7 +30,7 @@ func (h *ociConfigHandler) shapes(c *gin.Context) {
|
||||
// @Summary 镜像列表
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.Image
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/images [get]
|
||||
func (h *ociConfigHandler) images(c *gin.Context) {
|
||||
@@ -54,7 +54,7 @@ func (h *ociConfigHandler) images(c *gin.Context) {
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param imageId path string true "imageId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.Image
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/images/{imageId} [get]
|
||||
func (h *ociConfigHandler) getImage(c *gin.Context) {
|
||||
@@ -89,7 +89,7 @@ type renameRequest struct {
|
||||
// @Summary VCN 列表
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.VCN
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/vcns [get]
|
||||
func (h *ociConfigHandler) listVCNs(c *gin.Context) {
|
||||
@@ -109,7 +109,7 @@ func (h *ociConfigHandler) listVCNs(c *gin.Context) {
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body createVCNRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.VCN
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/vcns [post]
|
||||
func (h *ociConfigHandler) createVCN(c *gin.Context) {
|
||||
@@ -141,7 +141,7 @@ func (h *ociConfigHandler) createVCN(c *gin.Context) {
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param vcnId path string true "vcnId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.VCN
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/vcns/{vcnId} [get]
|
||||
func (h *ociConfigHandler) getVCN(c *gin.Context) {
|
||||
@@ -162,7 +162,7 @@ func (h *ociConfigHandler) getVCN(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param vcnId path string true "vcnId"
|
||||
// @Param body body renameRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.VCN
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/vcns/{vcnId} [put]
|
||||
func (h *ociConfigHandler) updateVCN(c *gin.Context) {
|
||||
@@ -211,7 +211,7 @@ type enableIPv6Request struct {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param vcnId path string true "vcnId"
|
||||
// @Param body body enableIPv6Request true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} ipv6StepsResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/vcns/{vcnId}/enable-ipv6 [post]
|
||||
func (h *ociConfigHandler) enableVCNIPv6(c *gin.Context) {
|
||||
@@ -247,7 +247,7 @@ type createSubnetRequest struct {
|
||||
// @Summary 子网列表
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.Subnet
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/subnets [get]
|
||||
func (h *ociConfigHandler) listSubnets(c *gin.Context) {
|
||||
@@ -267,7 +267,7 @@ func (h *ociConfigHandler) listSubnets(c *gin.Context) {
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body createSubnetRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.Subnet
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/subnets [post]
|
||||
func (h *ociConfigHandler) createSubnet(c *gin.Context) {
|
||||
@@ -300,7 +300,7 @@ func (h *ociConfigHandler) createSubnet(c *gin.Context) {
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param subnetId path string true "subnetId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.Subnet
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/subnets/{subnetId} [get]
|
||||
func (h *ociConfigHandler) getSubnet(c *gin.Context) {
|
||||
@@ -321,7 +321,7 @@ func (h *ociConfigHandler) getSubnet(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param subnetId path string true "subnetId"
|
||||
// @Param body body renameRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.Subnet
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/subnets/{subnetId} [put]
|
||||
func (h *ociConfigHandler) updateSubnet(c *gin.Context) {
|
||||
@@ -381,7 +381,7 @@ type updateSecurityListRequest struct {
|
||||
// @Summary 安全列表清单
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.SecurityList
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/security-lists [get]
|
||||
func (h *ociConfigHandler) listSecurityLists(c *gin.Context) {
|
||||
@@ -401,7 +401,7 @@ func (h *ociConfigHandler) listSecurityLists(c *gin.Context) {
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body createSecurityListRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.SecurityList
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/security-lists [post]
|
||||
func (h *ociConfigHandler) createSecurityList(c *gin.Context) {
|
||||
@@ -432,7 +432,7 @@ func (h *ociConfigHandler) createSecurityList(c *gin.Context) {
|
||||
// @Tags 网络
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param securityListId path string true "securityListId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.SecurityList
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/security-lists/{securityListId} [get]
|
||||
func (h *ociConfigHandler) getSecurityList(c *gin.Context) {
|
||||
@@ -453,7 +453,7 @@ func (h *ociConfigHandler) getSecurityList(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param securityListId path string true "securityListId"
|
||||
// @Param body body updateSecurityListRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.SecurityList
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/security-lists/{securityListId} [put]
|
||||
func (h *ociConfigHandler) updateSecurityList(c *gin.Context) {
|
||||
|
||||
@@ -9,8 +9,10 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/oracle/oci-go-sdk/v65/common"
|
||||
"gorm.io/gorm"
|
||||
_ "oci-portal/internal/model" // swagger 注解引用
|
||||
|
||||
"oci-portal/internal/oci"
|
||||
"oci-portal/internal/service"
|
||||
@@ -39,7 +41,7 @@ type importRequest struct {
|
||||
// @Summary 导入租户配置
|
||||
// @Tags 租户配置
|
||||
// @Param body body importRequest true "API Key 配置(私钥密文落库)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} model.OciConfig
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs [post]
|
||||
func (h *ociConfigHandler) create(c *gin.Context) {
|
||||
@@ -71,7 +73,7 @@ func (h *ociConfigHandler) create(c *gin.Context) {
|
||||
|
||||
// @Summary 租户配置列表
|
||||
// @Tags 租户配置
|
||||
// @Success 200 {object} map[string]any "items"
|
||||
// @Success 200 {array} service.ConfigSummary
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs [get]
|
||||
func (h *ociConfigHandler) list(c *gin.Context) {
|
||||
@@ -86,7 +88,7 @@ func (h *ociConfigHandler) list(c *gin.Context) {
|
||||
// @Summary 租户配置详情
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} model.OciConfig
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id} [get]
|
||||
func (h *ociConfigHandler) get(c *gin.Context) {
|
||||
@@ -105,7 +107,7 @@ func (h *ociConfigHandler) get(c *gin.Context) {
|
||||
// @Summary 验证配置连通性并刷新画像
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} configChangesResponse "config 与 changes 字段变更对照"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/verify [post]
|
||||
func (h *ociConfigHandler) verify(c *gin.Context) {
|
||||
@@ -139,7 +141,7 @@ type updateConfigRequest struct {
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body object true "可更新字段(别名/分组/代理/多区域开关等)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} configChangesResponse "config 与 changes 字段变更对照"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id} [put]
|
||||
func (h *ociConfigHandler) update(c *gin.Context) {
|
||||
@@ -194,7 +196,7 @@ func (h *ociConfigHandler) remove(c *gin.Context) {
|
||||
// @Summary 列出租户下全部 ACTIVE compartment
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.Compartment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/compartments [get]
|
||||
func (h *ociConfigHandler) compartments(c *gin.Context) {
|
||||
@@ -216,7 +218,7 @@ func (h *ociConfigHandler) compartments(c *gin.Context) {
|
||||
// @Summary 返回筛选器用区域列表:未开多区域支持只含默认区域
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} service.RegionSubscriptionView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/cached-regions [get]
|
||||
func (h *ociConfigHandler) cachedRegions(c *gin.Context) {
|
||||
@@ -237,7 +239,7 @@ func (h *ociConfigHandler) cachedRegions(c *gin.Context) {
|
||||
// @Summary 返回筛选器用区间列表:未开多区间支持返回空数组
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.Compartment
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/cached-compartments [get]
|
||||
func (h *ociConfigHandler) cachedCompartments(c *gin.Context) {
|
||||
|
||||
@@ -4,13 +4,15 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/service" // swagger 注解引用
|
||||
)
|
||||
|
||||
// overview 返回总览页聚合数据(本地快照,不发云端请求)。
|
||||
//
|
||||
// @Summary 返回总览页聚合数据
|
||||
// @Tags 租户配置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.Overview
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/overview [get]
|
||||
func (h *ociConfigHandler) overview(c *gin.Context) {
|
||||
|
||||
+34
-5
@@ -18,7 +18,7 @@ type proxyHandler struct {
|
||||
//
|
||||
// @Summary 代理列表
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any "items"
|
||||
// @Success 200 {object} itemsResponse[service.ProxyView] "items"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/proxies [get]
|
||||
func (h *proxyHandler) list(c *gin.Context) {
|
||||
@@ -35,7 +35,7 @@ func (h *proxyHandler) list(c *gin.Context) {
|
||||
// @Summary 创建代理
|
||||
// @Tags 设置
|
||||
// @Param body body service.ProxyInput true "代理配置(密码只写不回)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} service.ProxyView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/proxies [post]
|
||||
func (h *proxyHandler) create(c *gin.Context) {
|
||||
@@ -58,7 +58,7 @@ func (h *proxyHandler) create(c *gin.Context) {
|
||||
// @Tags 设置
|
||||
// @Param id path int true "代理 ID"
|
||||
// @Param body body service.ProxyInput true "代理配置(密码缺省沿用)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.ProxyView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/proxies/{id} [put]
|
||||
func (h *proxyHandler) update(c *gin.Context) {
|
||||
@@ -104,7 +104,7 @@ func (h *proxyHandler) remove(c *gin.Context) {
|
||||
// @Summary 批量导入代理
|
||||
// @Tags 设置
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.ImportResult
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/proxies/import [post]
|
||||
func (h *proxyHandler) importBatch(c *gin.Context) {
|
||||
@@ -128,7 +128,7 @@ func (h *proxyHandler) importBatch(c *gin.Context) {
|
||||
// @Summary 手动重测代理出口地区,同步返回最新视图
|
||||
// @Tags 设置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.ProxyView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/proxies/{id}/probe [post]
|
||||
func (h *proxyHandler) probe(c *gin.Context) {
|
||||
@@ -144,6 +144,35 @@ func (h *proxyHandler) probe(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, view)
|
||||
}
|
||||
|
||||
// setTenants 设置代理关联的租户全集(代理侧批量关联 / 解除)。
|
||||
//
|
||||
// @Summary 设置代理关联的租户全集
|
||||
// @Tags 设置
|
||||
// @Param id path int true "代理 ID"
|
||||
// @Param body body object true "请求体 {\"ociConfigIds\": [1,2]}"
|
||||
// @Success 200 {object} usedByResponse "usedBy"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/proxies/{id}/tenants [put]
|
||||
func (h *proxyHandler) setTenants(c *gin.Context) {
|
||||
id, ok := pathID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
OciConfigIDs []uint `json:"ociConfigIds"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
used, err := h.svc.SetTenants(c.Request.Context(), id, req.OciConfigIDs)
|
||||
if err != nil {
|
||||
h.respond(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"usedBy": used})
|
||||
}
|
||||
|
||||
// respond 把代理业务错误映射到语义状态码。
|
||||
func (h *proxyHandler) respond(c *gin.Context, err error) {
|
||||
switch {
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/service" // swagger 注解引用
|
||||
|
||||
"oci-portal/internal/oci"
|
||||
)
|
||||
|
||||
@@ -13,7 +15,7 @@ import (
|
||||
//
|
||||
// @Summary 返回本地维护的完整区域表
|
||||
// @Tags 租户配置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.RegionInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/regions [get]
|
||||
func listRegions(c *gin.Context) {
|
||||
@@ -28,7 +30,7 @@ func listRegions(c *gin.Context) {
|
||||
// @Summary 区域订阅列表
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} service.RegionSubscriptionView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/region-subscriptions [get]
|
||||
func (h *ociConfigHandler) regionSubscriptions(c *gin.Context) {
|
||||
@@ -52,7 +54,7 @@ type subscribeRegionRequest struct {
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param body body subscribeRegionRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} service.RegionSubscriptionView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/region-subscriptions [post]
|
||||
func (h *ociConfigHandler) subscribeRegion(c *gin.Context) {
|
||||
@@ -76,7 +78,7 @@ func (h *ociConfigHandler) subscribeRegion(c *gin.Context) {
|
||||
// @Summary 服务限额查询
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.LimitValue
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/limits [get]
|
||||
func (h *ociConfigHandler) limits(c *gin.Context) {
|
||||
|
||||
@@ -11,9 +11,14 @@ import (
|
||||
func registerAiGateway(r *gin.Engine, aiGateway *service.AiGatewayService) {
|
||||
aih := &aiGatewayHandler{gw: aiGateway}
|
||||
ai := r.Group("/ai/v1", bodyLimit(10<<20), aih.auth)
|
||||
ai.POST("/chat/completions", aih.chatCompletions)
|
||||
ai.POST("/responses", aih.responses)
|
||||
ai.POST("/messages", aih.messages)
|
||||
ai.POST("/embeddings", aih.embeddings)
|
||||
ai.POST("/audio/speech", aih.audioSpeech)
|
||||
ai.POST("/tts", aih.tts)
|
||||
ai.POST("/rerank", aih.rerank)
|
||||
ai.POST("/moderations", aih.moderations)
|
||||
ai.GET("/models", aih.listModels)
|
||||
}
|
||||
|
||||
@@ -32,6 +37,8 @@ func registerAiAdmin(secured *gin.RouterGroup, aiGateway *service.AiGatewayServi
|
||||
secured.POST("/ai-channels/:id/probe", aiadmin.probeChannel)
|
||||
secured.POST("/ai-channels/:id/sync-models", aiadmin.syncChannelModels)
|
||||
secured.GET("/ai-models", aiadmin.gatewayModels)
|
||||
secured.GET("/ai-settings", aiadmin.aiSettings)
|
||||
secured.PUT("/ai-settings", aiadmin.updateAiSettings)
|
||||
secured.GET("/ai-blacklist", aiadmin.listBlacklist)
|
||||
secured.POST("/ai-blacklist", aiadmin.addBlacklist)
|
||||
secured.DELETE("/ai-blacklist/:id", aiadmin.removeBlacklist)
|
||||
|
||||
@@ -35,4 +35,5 @@ func registerSettings(secured *gin.RouterGroup, settings *service.SettingService
|
||||
secured.PUT("/proxies/:id", px.update)
|
||||
secured.DELETE("/proxies/:id", px.remove)
|
||||
secured.POST("/proxies/:id/probe", px.probe)
|
||||
secured.PUT("/proxies/:id/tenants", px.setTenants)
|
||||
}
|
||||
|
||||
@@ -19,10 +19,6 @@ func registerTasksAndLogs(secured *gin.RouterGroup, tasks *service.TaskService,
|
||||
|
||||
le := &logEventHandler{svc: logEvents}
|
||||
secured.GET("/log-events", le.list)
|
||||
secured.GET("/log-events/alert-rules", le.listAlertRules)
|
||||
secured.POST("/log-events/alert-rules", le.createAlertRule)
|
||||
secured.PUT("/log-events/alert-rules/:ruleId", le.updateAlertRule)
|
||||
secured.DELETE("/log-events/alert-rules/:ruleId", le.deleteAlertRule)
|
||||
secured.GET("/oci-configs/:id/log-webhook", le.getWebhook)
|
||||
secured.POST("/oci-configs/:id/log-webhook", le.ensureWebhook)
|
||||
secured.DELETE("/oci-configs/:id/log-webhook", le.revokeWebhook)
|
||||
|
||||
+11
-11
@@ -19,7 +19,7 @@ type settingsHandler struct {
|
||||
//
|
||||
// @Summary 返回脱敏后的 Telegram 配置,绝不回 token 明文
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.TelegramView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/telegram [get]
|
||||
func (h *settingsHandler) getTelegram(c *gin.Context) {
|
||||
@@ -44,7 +44,7 @@ type updateTelegramRequest struct {
|
||||
// @Summary 保存配置并返回最新脱敏视图
|
||||
// @Tags 设置
|
||||
// @Param body body updateTelegramRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.TelegramView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/telegram [put]
|
||||
func (h *settingsHandler) updateTelegram(c *gin.Context) {
|
||||
@@ -84,7 +84,7 @@ func (h *settingsHandler) testTelegram(c *gin.Context) {
|
||||
//
|
||||
// @Summary 返回全部通知渠道的脱敏视图
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[service.NotifyChannelView]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/notify-channels [get]
|
||||
func (h *settingsHandler) listNotifyChannels(c *gin.Context) {
|
||||
@@ -119,7 +119,7 @@ type updateNotifyChannelRequest struct {
|
||||
// @Tags 设置
|
||||
// @Param type path string true "渠道类型(webhook/ntfy/bark/smtp)"
|
||||
// @Param body body updateNotifyChannelRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[service.NotifyChannelView]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/notify-channels/{type} [put]
|
||||
func (h *settingsHandler) updateNotifyChannel(c *gin.Context) {
|
||||
@@ -160,7 +160,7 @@ func (h *settingsHandler) testNotifyChannel(c *gin.Context) {
|
||||
//
|
||||
// @Summary 返回全部通知事件开关
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.NotifyEventsView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/notify-events [get]
|
||||
func (h *settingsHandler) getNotifyEvents(c *gin.Context) {
|
||||
@@ -178,7 +178,7 @@ func (h *settingsHandler) getNotifyEvents(c *gin.Context) {
|
||||
// @Summary 全量保存五个事件开关并返回最新值
|
||||
// @Tags 设置
|
||||
// @Param body body service.NotifyEventsView true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.NotifyEventsView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/notify-events [put]
|
||||
func (h *settingsHandler) updateNotifyEvents(c *gin.Context) {
|
||||
@@ -198,7 +198,7 @@ func (h *settingsHandler) updateNotifyEvents(c *gin.Context) {
|
||||
//
|
||||
// @Summary 返回全部通知模板
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} itemsResponse[service.NotifyTemplateView]
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/notify-templates [get]
|
||||
func (h *settingsHandler) listNotifyTemplates(c *gin.Context) {
|
||||
@@ -263,7 +263,7 @@ func (h *settingsHandler) testNotifyTemplate(c *gin.Context) {
|
||||
//
|
||||
// @Summary 返回任务行为设置
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.TaskSettingsView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/task [get]
|
||||
func (h *settingsHandler) getTaskSettings(c *gin.Context) {
|
||||
@@ -280,7 +280,7 @@ func (h *settingsHandler) getTaskSettings(c *gin.Context) {
|
||||
// @Summary 保存任务行为设置并返回最新值
|
||||
// @Tags 设置
|
||||
// @Param body body service.TaskSettingsView true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.TaskSettingsView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/task [put]
|
||||
func (h *settingsHandler) updateTaskSettings(c *gin.Context) {
|
||||
@@ -304,7 +304,7 @@ func (h *settingsHandler) updateTaskSettings(c *gin.Context) {
|
||||
//
|
||||
// @Summary 返回安全设置
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.SecuritySettings
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/security [get]
|
||||
func (h *settingsHandler) getSecurity(c *gin.Context) {
|
||||
@@ -321,7 +321,7 @@ func (h *settingsHandler) getSecurity(c *gin.Context) {
|
||||
// @Summary 保存安全设置并返回最新值
|
||||
// @Tags 设置
|
||||
// @Param body body service.SecuritySettings true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.SecuritySettings
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/settings/security [put]
|
||||
func (h *settingsHandler) updateSecurity(c *gin.Context) {
|
||||
|
||||
@@ -4,12 +4,14 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/oci" // swagger 注解引用
|
||||
)
|
||||
|
||||
// @Summary 订阅列表
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.SubscriptionInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/subscriptions [get]
|
||||
func (h *ociConfigHandler) subscriptions(c *gin.Context) {
|
||||
@@ -29,7 +31,7 @@ func (h *ociConfigHandler) subscriptions(c *gin.Context) {
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param subscriptionId path string true "subscriptionId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.SubscriptionDetail
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/subscriptions/{subscriptionId} [get]
|
||||
func (h *ociConfigHandler) subscriptionDetail(c *gin.Context) {
|
||||
@@ -48,7 +50,7 @@ func (h *ociConfigHandler) subscriptionDetail(c *gin.Context) {
|
||||
// @Summary 限额服务列表
|
||||
// @Tags 租户配置
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.LimitService
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/limits/services [get]
|
||||
func (h *ociConfigHandler) limitServices(c *gin.Context) {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"oci-portal/internal/model"
|
||||
"oci-portal/internal/oci"
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
// 本文件的类型仅供 swagger 文档渲染(@Success/@Failure 注解引用),
|
||||
// 运行时代码不使用;字段与各 handler 返回的 gin.H 外壳保持一致。
|
||||
|
||||
// errorResponse 是统一错误响应外壳。
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// itemsResponse 是 {"items": [...]} 列表外壳。
|
||||
type itemsResponse[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
}
|
||||
|
||||
// pagedResponse 是 {"items": [...], "total": n} 分页外壳。
|
||||
type pagedResponse[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// itemResponse 是 {"item": {...}} 单项外壳。
|
||||
type itemResponse[T any] struct {
|
||||
Item T `json:"item"`
|
||||
}
|
||||
|
||||
// triggerResponse 是任务触发受理响应。
|
||||
type triggerResponse struct {
|
||||
Triggered bool `json:"triggered"`
|
||||
}
|
||||
|
||||
// tokenResponse 是登录 / 换发令牌响应。
|
||||
type tokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
// totpRequiredResponse 是密码通过但需两步验证码的 428 响应。
|
||||
type totpRequiredResponse struct {
|
||||
Error string `json:"error"`
|
||||
TotpRequired bool `json:"totpRequired"`
|
||||
}
|
||||
|
||||
// enabledResponse 是布尔开关查询响应。
|
||||
type enabledResponse struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// totpSetupResponse 是 TOTP 初始化响应。
|
||||
type totpSetupResponse struct {
|
||||
Secret string `json:"secret"`
|
||||
OtpauthUri string `json:"otpauthUri"`
|
||||
}
|
||||
|
||||
// credentialsResponse 是当前登录账号信息。
|
||||
type credentialsResponse struct {
|
||||
Username string `json:"username"`
|
||||
PasswordLoginDisabled bool `json:"passwordLoginDisabled"`
|
||||
}
|
||||
|
||||
// oauthProvidersResponse 是外部登录 provider 列表。
|
||||
type oauthProvidersResponse struct {
|
||||
Providers []service.ProviderInfo `json:"providers"`
|
||||
PasswordLoginDisabled bool `json:"passwordLoginDisabled"`
|
||||
}
|
||||
|
||||
// urlResponse 是跳转地址响应。
|
||||
type urlResponse struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// aboutResponse 是「设置 · 关于」页构建与运行信息。
|
||||
type aboutResponse struct {
|
||||
Version string `json:"version"`
|
||||
BuildTime string `json:"buildTime"`
|
||||
GoVersion string `json:"goVersion"`
|
||||
Platform string `json:"platform"`
|
||||
StartedAt string `json:"startedAt"`
|
||||
UptimeSeconds int64 `json:"uptimeSeconds"`
|
||||
Resources aboutResources `json:"resources"`
|
||||
}
|
||||
|
||||
// aboutResources 是进程资源占用快照。
|
||||
type aboutResources struct {
|
||||
CpuAvgPercent float64 `json:"cpuAvgPercent"`
|
||||
NumCpu int `json:"numCpu"`
|
||||
Goroutines int `json:"goroutines"`
|
||||
MemHeapBytes uint64 `json:"memHeapBytes"`
|
||||
MemSysBytes uint64 `json:"memSysBytes"`
|
||||
DbEngine string `json:"dbEngine"`
|
||||
DbBytes int64 `json:"dbBytes"`
|
||||
}
|
||||
|
||||
// publicIpResponse 是换绑公网 IP 结果。
|
||||
type publicIpResponse struct {
|
||||
PublicIp string `json:"publicIp"`
|
||||
}
|
||||
|
||||
// ipv6AddressResponse 是实例新增 IPv6 结果。
|
||||
type ipv6AddressResponse struct {
|
||||
Ipv6Address string `json:"ipv6Address"`
|
||||
}
|
||||
|
||||
// addressResponse 是 VNIC 新增 IPv6 结果。
|
||||
type addressResponse struct {
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
// ipv6StepsResponse 是 VCN 开启 IPv6 的分步结果。
|
||||
type ipv6StepsResponse struct {
|
||||
Steps []oci.IPv6Step `json:"steps"`
|
||||
}
|
||||
|
||||
// configChangesResponse 是租户配置校验 / 更新结果(config 与字段变更对照)。
|
||||
type configChangesResponse struct {
|
||||
Config *model.OciConfig `json:"config"`
|
||||
Changes service.Changes `json:"changes"`
|
||||
}
|
||||
|
||||
// aiKeyCreateResponse 是 AI 密钥创建结果;key 为明文,仅本次返回。
|
||||
type aiKeyCreateResponse struct {
|
||||
Key string `json:"key"`
|
||||
Item model.AiKey `json:"item"`
|
||||
}
|
||||
|
||||
// usedByResponse 是代理关联租户结果(关联数)。
|
||||
type usedByResponse struct {
|
||||
UsedBy int64 `json:"usedBy"`
|
||||
}
|
||||
|
||||
// rawDetailResponse 是审计事件原文响应。
|
||||
type rawDetailResponse struct {
|
||||
Raw json.RawMessage `json:"raw"`
|
||||
}
|
||||
|
||||
// passwordResponse 是租户用户重置密码结果(一次性明文)。
|
||||
type passwordResponse struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// deletedTotpResponse 是清除 MFA 设备结果。
|
||||
type deletedTotpResponse struct {
|
||||
DeletedTotpDevices int `json:"deletedTotpDevices"`
|
||||
}
|
||||
|
||||
// deletedApiKeysResponse 是清理用户 API Key 结果。
|
||||
type deletedApiKeysResponse struct {
|
||||
DeletedApiKeys int `json:"deletedApiKeys"`
|
||||
}
|
||||
|
||||
// createInstancesResponse 是批量创建实例结果;部分成功仍 201,errors 为逐台失败信息。
|
||||
type createInstancesResponse struct {
|
||||
Instances []oci.Instance `json:"instances"`
|
||||
Errors []string `json:"errors"`
|
||||
}
|
||||
|
||||
// logWebhookStatusResponse 是日志回传 webhook 状态。
|
||||
type logWebhookStatusResponse struct {
|
||||
Exists bool `json:"exists"`
|
||||
Webhook *service.LogWebhookInfo `json:"webhook,omitempty"`
|
||||
}
|
||||
|
||||
// webConsoleSessionResponse 是网页控制台会话创建结果。
|
||||
type webConsoleSessionResponse struct {
|
||||
SessionId string `json:"sessionId"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/model" // swagger 注解引用
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
@@ -18,7 +19,7 @@ type systemLogHandler struct {
|
||||
//
|
||||
// @Summary 系统操作日志列表
|
||||
// @Tags 设置
|
||||
// @Success 200 {object} map[string]any "items 与 total"
|
||||
// @Success 200 {object} pagedResponse[model.SystemLog] "items 与 total"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/system-logs [get]
|
||||
func (h *systemLogHandler) list(c *gin.Context) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
_ "oci-portal/internal/model" // swagger 注解引用
|
||||
"oci-portal/internal/service"
|
||||
)
|
||||
|
||||
@@ -33,7 +34,7 @@ type updateTaskRequest struct {
|
||||
// @Summary 创建任务
|
||||
// @Tags 任务与日志回传
|
||||
// @Param body body createTaskRequest true "任务定义(类型/cron/payload)"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} model.Task
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/tasks [post]
|
||||
func (h *taskHandler) create(c *gin.Context) {
|
||||
@@ -57,7 +58,7 @@ func (h *taskHandler) create(c *gin.Context) {
|
||||
|
||||
// @Summary 任务列表
|
||||
// @Tags 任务与日志回传
|
||||
// @Success 200 {array} map[string]any
|
||||
// @Success 200 {array} model.Task
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/tasks [get]
|
||||
func (h *taskHandler) list(c *gin.Context) {
|
||||
@@ -72,7 +73,7 @@ func (h *taskHandler) list(c *gin.Context) {
|
||||
// @Summary 任务详情
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "任务 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} model.Task
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/tasks/{id} [get]
|
||||
func (h *taskHandler) get(c *gin.Context) {
|
||||
@@ -92,7 +93,7 @@ func (h *taskHandler) get(c *gin.Context) {
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "任务 ID"
|
||||
// @Param body body updateTaskRequest true "可更新字段"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} model.Task
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/tasks/{id} [put]
|
||||
func (h *taskHandler) update(c *gin.Context) {
|
||||
@@ -139,7 +140,7 @@ func (h *taskHandler) remove(c *gin.Context) {
|
||||
// @Summary 任务执行日志
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} model.TaskLog
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/tasks/{id}/logs [get]
|
||||
func (h *taskHandler) logs(c *gin.Context) {
|
||||
@@ -159,8 +160,8 @@ func (h *taskHandler) logs(c *gin.Context) {
|
||||
// @Summary 立即执行任务(异步触发,结果经任务日志轮询获取)
|
||||
// @Tags 任务与日志回传
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 202 {object} map[string]any
|
||||
// @Failure 409 {object} map[string]any "任务正在执行中"
|
||||
// @Success 202 {object} triggerResponse
|
||||
// @Failure 409 {object} errorResponse "任务正在执行中"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/tasks/{id}/run [post]
|
||||
func (h *taskHandler) run(c *gin.Context) {
|
||||
|
||||
+18
-18
@@ -18,7 +18,7 @@ import (
|
||||
// @Tags 计算
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "instanceId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.InstanceTraffic
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/traffic [get]
|
||||
func (h *ociConfigHandler) instanceTraffic(c *gin.Context) {
|
||||
@@ -38,7 +38,7 @@ func (h *ociConfigHandler) instanceTraffic(c *gin.Context) {
|
||||
// @Summary 配置成本快照
|
||||
// @Tags 成本
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.CostItem
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/costs [get]
|
||||
func (h *ociConfigHandler) costs(c *gin.Context) {
|
||||
@@ -75,7 +75,7 @@ func (h *ociConfigHandler) costs(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param cursor query string false "续查游标(上次响应原样带回)"
|
||||
// @Param limit query int false "单批目标条数,缺省 100,上限 200"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} service.AuditEventsView
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/audit-events [get]
|
||||
func (h *ociConfigHandler) getAuditEvents(c *gin.Context) {
|
||||
@@ -103,7 +103,7 @@ func (h *ociConfigHandler) getAuditEvents(c *gin.Context) {
|
||||
// @Summary 按 eventId 取回原始事件 JSON:缓存命中秒开,
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} rawDetailResponse "raw 为事件原文 JSON"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/audit-events/detail [get]
|
||||
func (h *ociConfigHandler) getAuditEventDetail(c *gin.Context) {
|
||||
@@ -145,7 +145,7 @@ type createTenantUserRequest struct {
|
||||
// @Summary 租户身份域列表
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.IdentityDomain
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/domains [get]
|
||||
func (h *ociConfigHandler) listIdentityDomains(c *gin.Context) {
|
||||
@@ -165,7 +165,7 @@ func (h *ociConfigHandler) listIdentityDomains(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.TenantUser
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users [get]
|
||||
func (h *ociConfigHandler) listTenantUsers(c *gin.Context) {
|
||||
@@ -186,7 +186,7 @@ func (h *ociConfigHandler) listTenantUsers(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param userId path string true "userId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.TenantUserDetail
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users/{userId} [get]
|
||||
func (h *ociConfigHandler) getTenantUserDetail(c *gin.Context) {
|
||||
@@ -207,7 +207,7 @@ func (h *ociConfigHandler) getTenantUserDetail(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param body body createTenantUserRequest true "请求体"
|
||||
// @Success 201 {object} map[string]any
|
||||
// @Success 201 {object} oci.TenantUser
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users [post]
|
||||
func (h *ociConfigHandler) createTenantUser(c *gin.Context) {
|
||||
@@ -253,7 +253,7 @@ type updateTenantUserRequest struct {
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param userId path string true "userId"
|
||||
// @Param body body updateTenantUserRequest true "请求体"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.TenantUser
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users/{userId} [put]
|
||||
func (h *ociConfigHandler) updateTenantUser(c *gin.Context) {
|
||||
@@ -306,7 +306,7 @@ func (h *ociConfigHandler) deleteTenantUser(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param userId path string true "userId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} passwordResponse "一次性明文密码"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users/{userId}/reset-password [post]
|
||||
func (h *ociConfigHandler) resetTenantUserPassword(c *gin.Context) {
|
||||
@@ -327,7 +327,7 @@ func (h *ociConfigHandler) resetTenantUserPassword(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param userId path string true "userId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} deletedTotpResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users/{userId}/mfa-devices [delete]
|
||||
func (h *ociConfigHandler) deleteTenantUserMfa(c *gin.Context) {
|
||||
@@ -347,7 +347,7 @@ func (h *ociConfigHandler) deleteTenantUserMfa(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param userId path string true "userId"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} deletedApiKeysResponse
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/users/{userId}/api-keys [delete]
|
||||
func (h *ociConfigHandler) deleteTenantUserApiKeys(c *gin.Context) {
|
||||
@@ -370,7 +370,7 @@ func (h *ociConfigHandler) deleteTenantUserApiKeys(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.NotificationRecipients
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/notification-recipients [get]
|
||||
func (h *ociConfigHandler) getNotificationRecipients(c *gin.Context) {
|
||||
@@ -391,7 +391,7 @@ func (h *ociConfigHandler) getNotificationRecipients(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.NotificationRecipients
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/notification-recipients [put]
|
||||
func (h *ociConfigHandler) updateNotificationRecipients(c *gin.Context) {
|
||||
@@ -418,7 +418,7 @@ func (h *ociConfigHandler) updateNotificationRecipients(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {array} oci.PasswordPolicyInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/password-policies [get]
|
||||
func (h *ociConfigHandler) listPasswordPolicies(c *gin.Context) {
|
||||
@@ -440,7 +440,7 @@ func (h *ociConfigHandler) listPasswordPolicies(c *gin.Context) {
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param policyId path string true "policyId"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.PasswordPolicyInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/password-policies/{policyId} [put]
|
||||
func (h *ociConfigHandler) updatePasswordPolicy(c *gin.Context) {
|
||||
@@ -473,7 +473,7 @@ func (h *ociConfigHandler) updatePasswordPolicy(c *gin.Context) {
|
||||
// @Tags 租户 IAM
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.IdentitySettingInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/identity-settings [get]
|
||||
func (h *ociConfigHandler) getIdentitySetting(c *gin.Context) {
|
||||
@@ -494,7 +494,7 @@ func (h *ociConfigHandler) getIdentitySetting(c *gin.Context) {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param domainId query string false "身份域 OCID(缺省 Default 域)"
|
||||
// @Param body body object true "请求体(见接口说明)"
|
||||
// @Success 200 {object} map[string]any
|
||||
// @Success 200 {object} oci.IdentitySettingInfo
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/identity-settings [put]
|
||||
func (h *ociConfigHandler) updateIdentitySetting(c *gin.Context) {
|
||||
|
||||
@@ -29,7 +29,7 @@ type createConsoleSessionRequest struct {
|
||||
// @Param id path int true "配置 ID"
|
||||
// @Param instanceId path string true "实例 OCID"
|
||||
// @Param body body object true "{type: serial|vnc}"
|
||||
// @Success 200 {object} map[string]any "sessionId 与 wsPath"
|
||||
// @Success 201 {object} webConsoleSessionResponse "sessionId 与 type"
|
||||
// @Security BearerAuth
|
||||
// @Router /api/v1/oci-configs/{id}/instances/{instanceId}/console-sessions [post]
|
||||
func (h *consoleHandler) create(c *gin.Context) {
|
||||
|
||||
@@ -53,7 +53,7 @@ type webhookHandler struct {
|
||||
// @Param secret path string true "面板生成的回传密钥(鉴权凭据)"
|
||||
// @Param body body object true "ONS 消息原文(SubscriptionConfirmation / Notification)"
|
||||
// @Success 200 "已受理"
|
||||
// @Failure 403 {object} map[string]string "时间戳超窗或证书源非 Oracle 域"
|
||||
// @Failure 403 {object} errorResponse "时间戳超窗或证书源非 Oracle 域"
|
||||
// @Failure 404 "secret 无效(不暴露端点存在性)"
|
||||
// @Router /api/v1/webhooks/oci-logs/{secret} [post]
|
||||
func (h *webhookHandler) handle(c *gin.Context) {
|
||||
|
||||
@@ -67,7 +67,7 @@ func autoMigrate(db *gorm.DB) error {
|
||||
&model.User{}, &model.UserIdentity{}, &model.OciConfig{}, &model.Task{}, &model.TaskLog{},
|
||||
&model.CheckSnapshot{}, &model.CostSnapshot{},
|
||||
&model.RegionCache{}, &model.CompartmentCache{}, &model.Setting{},
|
||||
&model.SystemLog{}, &model.LogEvent{}, &model.AlertRule{}, &model.AlertRuleHit{}, &model.Proxy{},
|
||||
&model.SystemLog{}, &model.LogEvent{}, &model.Proxy{},
|
||||
&model.AiKey{}, &model.AiChannel{}, &model.AiModelCache{}, &model.AiModelBlacklist{}, &model.AiCallLog{},
|
||||
&model.AiContentLog{},
|
||||
)
|
||||
|
||||
@@ -211,31 +211,6 @@ type LogEvent struct {
|
||||
ReceivedAt time.Time `json:"receivedAt"`
|
||||
}
|
||||
|
||||
// AlertRule 是回传事件的自定义告警规则;条件间 AND 关系,空条件视为任意。
|
||||
type AlertRule struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:64" json:"name"`
|
||||
Enabled bool `json:"enabled"`
|
||||
OciConfigID uint `json:"ociConfigId"` // 0=全部租户
|
||||
EventTypes string `gorm:"size:512" json:"eventTypes"` // 逗号分隔事件短名,空=全部
|
||||
SourceIPs string `gorm:"size:512" json:"sourceIps"` // 逗号分隔 IP/CIDR,空=任意
|
||||
// in:来源命中列表才告警(默认);notin:不在列表才告警(白名单场景)
|
||||
SourceIPMode string `gorm:"size:8" json:"sourceIpMode"`
|
||||
ResourceMatch string `gorm:"size:128" json:"resourceMatch"` // 资源名子串,空=任意
|
||||
Threshold int `json:"threshold"` // 触发阈值,默认 1(即时)
|
||||
WindowMinutes int `json:"windowMinutes"` // 聚合窗口,Threshold>1 时必填
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// AlertRuleHit 记录规则命中,供阈值窗口计数;随周期清理删除过期行。
|
||||
type AlertRuleHit struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
RuleID uint `gorm:"index" json:"ruleId"`
|
||||
LogEventID uint `json:"logEventId"`
|
||||
HitAt time.Time `gorm:"index" json:"hitAt"`
|
||||
}
|
||||
|
||||
// RegionCache 是开启多区域支持的配置缓存的订阅区域(每配置多行,整组覆盖)。
|
||||
// Status 非 READY(新订阅进行中)时读取接口会实时刷新,直到全部 READY。
|
||||
type RegionCache struct {
|
||||
@@ -298,7 +273,7 @@ type AiChannel struct {
|
||||
}
|
||||
|
||||
// AiModelCache 是渠道区域的可用模型缓存(整渠道覆盖式同步)。
|
||||
// Capability 为 CHAT / EMBEDDING;存量空串视为 CHAT(加列前只同步对话模型)。
|
||||
// Capability 为 CHAT / EMBEDDING / RERANK / TTS;存量空串视为 CHAT(加列前只同步对话模型)。
|
||||
type AiModelCache struct {
|
||||
ID uint `gorm:"primaryKey" json:"-"`
|
||||
ChannelID uint `gorm:"index" json:"channelId"`
|
||||
|
||||
@@ -106,6 +106,12 @@ type Client interface {
|
||||
GenAiCompatResponses(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, error)
|
||||
// GenAiCompatResponsesStream 流式直通 /actions/v1/responses,建立成功返回 SSE body。
|
||||
GenAiCompatResponsesStream(ctx context.Context, cred Credentials, region string, body []byte) (io.ReadCloser, error)
|
||||
// GenAiCompatSpeech 直通 OpenAI Audio Speech 请求体到 /openai/v1/audio/speech,返回音频与 Content-Type。
|
||||
GenAiCompatSpeech(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, string, error)
|
||||
// GenAiRerank 文档重排,返回按相关度排序的下标与得分。
|
||||
GenAiRerank(ctx context.Context, cred Credentials, region, modelOcid, query string, documents []string, topN *int) ([]RerankRank, error)
|
||||
// GenAiApplyGuardrails 对单条文本执行内容审核 / PII / 提示注入检测。
|
||||
GenAiApplyGuardrails(ctx context.Context, cred Credentials, region, text string) (*GuardrailsOutcome, error)
|
||||
// 控制台连接:创建(VNC/串口连接串)、列出、删除。
|
||||
CreateConsoleConnection(ctx context.Context, cred Credentials, region, instanceID, sshPublicKey string) (ConsoleConnection, error)
|
||||
ListConsoleConnections(ctx context.Context, cred Credentials, region, instanceID string) ([]ConsoleConnection, error)
|
||||
|
||||
@@ -131,6 +131,11 @@ func modelCapability(m generativeai.ModelSummary) string {
|
||||
return "CHAT"
|
||||
case generativeai.ModelCapabilityTextEmbeddings:
|
||||
capability = "EMBEDDING"
|
||||
case generativeai.ModelCapabilityTextRerank:
|
||||
capability = "RERANK"
|
||||
case generativeai.ModelCapabilityEnum("TEXT_TO_AUDIO"):
|
||||
// SDK v65.120 尚无该枚举常量,按原始字符串匹配(xai.grok-tts)
|
||||
capability = "TTS"
|
||||
}
|
||||
}
|
||||
return capability
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package oci
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/oracle/oci-go-sdk/v65/common"
|
||||
"github.com/oracle/oci-go-sdk/v65/generativeaiinference"
|
||||
)
|
||||
|
||||
// RerankRank 是重排结果的一项:index 指向入参 documents 下标。
|
||||
type RerankRank struct {
|
||||
Index int
|
||||
Score float64
|
||||
}
|
||||
|
||||
// GuardrailCategory 是内容审核分类得分(OVERALL / BLOCKLIST)。
|
||||
type GuardrailCategory struct {
|
||||
Name string
|
||||
Score float64
|
||||
}
|
||||
|
||||
// GuardrailPiiHit 是一处 PII 命中(片段原文与位置)。
|
||||
type GuardrailPiiHit struct {
|
||||
Text string
|
||||
Label string
|
||||
Score float64
|
||||
Offset int
|
||||
Length int
|
||||
}
|
||||
|
||||
// GuardrailsOutcome 汇总 ApplyGuardrails 三能力结果。
|
||||
type GuardrailsOutcome struct {
|
||||
Categories []GuardrailCategory
|
||||
Pii []GuardrailPiiHit
|
||||
PromptInjectionScore *float64
|
||||
}
|
||||
|
||||
// GenAiRerank 实现 Client:文档重排(on-demand serving),返回按相关度排序的下标与得分。
|
||||
func (c *RealClient) GenAiRerank(ctx context.Context, cred Credentials, region, modelOcid, query string, documents []string, topN *int) ([]RerankRank, error) {
|
||||
ic, err := c.genAiInferenceClient(cred, region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := ic.RerankText(ctx, generativeaiinference.RerankTextRequest{
|
||||
RerankTextDetails: generativeaiinference.RerankTextDetails{
|
||||
CompartmentId: &cred.TenancyOCID,
|
||||
ServingMode: generativeaiinference.OnDemandServingMode{ModelId: &modelOcid},
|
||||
Input: &query,
|
||||
Documents: documents,
|
||||
TopN: topN,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("genai rerank: %w", err)
|
||||
}
|
||||
ranks := make([]RerankRank, 0, len(resp.DocumentRanks))
|
||||
for _, r := range resp.DocumentRanks {
|
||||
if r.Index == nil || r.RelevanceScore == nil {
|
||||
continue
|
||||
}
|
||||
ranks = append(ranks, RerankRank{Index: *r.Index, Score: *r.RelevanceScore})
|
||||
}
|
||||
return ranks, nil
|
||||
}
|
||||
|
||||
// GenAiApplyGuardrails 实现 Client:对单条文本执行内容审核 / PII / 提示注入三检测。
|
||||
func (c *RealClient) GenAiApplyGuardrails(ctx context.Context, cred Credentials, region, text string) (*GuardrailsOutcome, error) {
|
||||
ic, err := c.genAiInferenceClient(cred, region)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := ic.ApplyGuardrails(ctx, generativeaiinference.ApplyGuardrailsRequest{
|
||||
ApplyGuardrailsDetails: generativeaiinference.ApplyGuardrailsDetails{
|
||||
CompartmentId: &cred.TenancyOCID,
|
||||
Input: generativeaiinference.GuardrailsTextInput{Content: common.String(text)},
|
||||
GuardrailConfigs: &generativeaiinference.GuardrailConfigs{
|
||||
ContentModerationConfig: &generativeaiinference.ContentModerationConfiguration{Categories: []string{"OVERALL"}},
|
||||
PersonallyIdentifiableInformationConfig: &generativeaiinference.PersonallyIdentifiableInformationConfiguration{Types: []string{}},
|
||||
PromptInjectionConfig: &generativeaiinference.PromptInjectionConfiguration{},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("genai guardrails: %w", err)
|
||||
}
|
||||
return guardrailsOutcome(resp.Results), nil
|
||||
}
|
||||
|
||||
// guardrailsOutcome 把 SDK 结果换算为 IR;空段置空切片,得分缺失跳过。
|
||||
func guardrailsOutcome(r *generativeaiinference.GuardrailsResults) *GuardrailsOutcome {
|
||||
out := &GuardrailsOutcome{}
|
||||
if r == nil {
|
||||
return out
|
||||
}
|
||||
if r.ContentModeration != nil {
|
||||
for _, cat := range r.ContentModeration.Categories {
|
||||
if cat.Name == nil || cat.Score == nil {
|
||||
continue
|
||||
}
|
||||
out.Categories = append(out.Categories, GuardrailCategory{Name: *cat.Name, Score: *cat.Score})
|
||||
}
|
||||
}
|
||||
for _, hit := range r.PersonallyIdentifiableInformation {
|
||||
h := GuardrailPiiHit{}
|
||||
if hit.Text != nil {
|
||||
h.Text = *hit.Text
|
||||
}
|
||||
if hit.Label != nil {
|
||||
h.Label = *hit.Label
|
||||
}
|
||||
if hit.Score != nil {
|
||||
h.Score = *hit.Score
|
||||
}
|
||||
if hit.Offset != nil {
|
||||
h.Offset = *hit.Offset
|
||||
}
|
||||
if hit.Length != nil {
|
||||
h.Length = *hit.Length
|
||||
}
|
||||
out.Pii = append(out.Pii, h)
|
||||
}
|
||||
if r.PromptInjection != nil && r.PromptInjection.Score != nil {
|
||||
out.PromptInjectionScore = r.PromptInjection.Score
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -14,9 +14,9 @@ import (
|
||||
const compatResponsesLimit = int64(8 << 20)
|
||||
|
||||
// GenAiCompatResponses 实现 Client:把 OpenAI Responses 请求体直通到 OCI
|
||||
// `/20231130/actions/v1/responses`(IAM 签名)。该端点实测可执行 xAI 服务端工具
|
||||
// (web_search / x_search),但不在 Oracle 文档化工具白名单内,行为可能随服务
|
||||
// 版本、模型或区域变化;调用方须自行校验并改写请求体(store/stream)。
|
||||
// `/20231130/actions/v1/responses`(IAM 签名)。xAI 服务端工具(web_search /
|
||||
// x_search / code_interpreter)与 mcp 已被 Oracle 文档正式支持,工具参数与限制
|
||||
// 遵循 xAI 规格;调用方须自行校验并改写请求体(store/stream)。
|
||||
func (c *RealClient) GenAiCompatResponses(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, error) {
|
||||
ic, err := c.genAiInferenceClient(cred, region)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package oci
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/oracle/oci-go-sdk/v65/common"
|
||||
)
|
||||
|
||||
// compatSpeechLimit 限制 TTS 音频响应体大小(长文本 mp3 给足余量)。
|
||||
const compatSpeechLimit = int64(64 << 20)
|
||||
|
||||
// GenAiCompatSpeech 实现 Client:把 OpenAI Audio Speech 请求体直通到 OCI
|
||||
// 兼容面 `/openai/v1/audio/speech`(IAM 签名,BasePath 置空——该面与
|
||||
// /20231130/actions 面并存,实测仅前者承载 TTS)。返回音频字节与 Content-Type。
|
||||
func (c *RealClient) GenAiCompatSpeech(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, string, error) {
|
||||
ic, err := c.genAiInferenceClient(cred, region)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
client := ic.BaseClient
|
||||
common.UpdateEndpointTemplateForOptions(&client)
|
||||
common.SetMissingTemplateParams(&client)
|
||||
client.BasePath = ""
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "/openai/v1/audio/speech", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("build compat speech request: %w", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("opc-compartment-id", cred.TenancyOCID)
|
||||
response, err := client.Call(ctx, request)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(response.Body, compatSpeechLimit))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("read compat speech body: %w", err)
|
||||
}
|
||||
return payload, response.Header.Get("Content-Type"), nil
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -58,11 +59,39 @@ type AiGatewayService struct {
|
||||
lastTouch map[uint]time.Time
|
||||
// onChannelsChanged 在渠道增删后触发,由 main 装配为探测任务同步钩子
|
||||
onChannelsChanged func(context.Context)
|
||||
// filterDeprecated 是「过滤弃用模型」开关(内存镜像,持久化在 settings 表)
|
||||
filterDeprecated atomic.Bool
|
||||
}
|
||||
|
||||
// NewAiGatewayService 组装依赖;调用 StartCleanup 后开始调用日志周期清理。
|
||||
func NewAiGatewayService(db *gorm.DB, configs *OciConfigService, client oci.Client) *AiGatewayService {
|
||||
return &AiGatewayService{db: db, configs: configs, client: client, lastTouch: map[uint]time.Time{}}
|
||||
s := &AiGatewayService{db: db, configs: configs, client: client, lastTouch: map[uint]time.Time{}}
|
||||
var row model.Setting
|
||||
if err := db.Where("key = ?", settingAiFilterDeprecated).First(&row).Error; err == nil {
|
||||
s.filterDeprecated.Store(row.Value == "1")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// settingAiFilterDeprecated 是「过滤弃用模型」开关的配置键,值 "1"/"0",缺省关闭。
|
||||
const settingAiFilterDeprecated = "ai_filter_deprecated"
|
||||
|
||||
// FilterDeprecated 返回「过滤弃用模型」开关状态。
|
||||
func (s *AiGatewayService) FilterDeprecated() bool { return s.filterDeprecated.Load() }
|
||||
|
||||
// SetFilterDeprecated 持久化并即时生效开关:开启后已宣布弃用
|
||||
// (deprecated_at 非空,即使未退役)的模型从列表与路由中排除。
|
||||
func (s *AiGatewayService) SetFilterDeprecated(ctx context.Context, on bool) error {
|
||||
value := "0"
|
||||
if on {
|
||||
value = "1"
|
||||
}
|
||||
err := s.db.WithContext(ctx).Save(&model.Setting{Key: settingAiFilterDeprecated, Value: value}).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存过滤弃用模型开关: %w", err)
|
||||
}
|
||||
s.filterDeprecated.Store(on)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetOnChannelsChanged 注册渠道数量变化钩子(渠道创建/删除成功后调用)。
|
||||
@@ -511,6 +540,9 @@ func (s *AiGatewayService) GatewayModels(ctx context.Context, group string) (aiw
|
||||
if group != "" {
|
||||
q = q.Where("ai_channels.channel_group = ?", group)
|
||||
}
|
||||
if s.FilterDeprecated() {
|
||||
q = q.Where("ai_model_caches.deprecated_at IS NULL")
|
||||
}
|
||||
var rows []model.AiModelCache
|
||||
err := q.Order("ai_model_caches.name ASC").Find(&rows).Error
|
||||
list := aiwire.ModelList{Object: "list", Data: []aiwire.Model{}}
|
||||
|
||||
@@ -164,6 +164,9 @@ func (s *AiGatewayService) modelChannels(ctx context.Context, modelName, capabil
|
||||
} else {
|
||||
q = q.Where("capability = ?", capability)
|
||||
}
|
||||
if s.FilterDeprecated() {
|
||||
q = q.Where("deprecated_at IS NULL")
|
||||
}
|
||||
var rows []model.AiModelCache
|
||||
if err := q.Find(&rows).Error; err != nil {
|
||||
return nil, nil, err
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"oci-portal/internal/aiwire"
|
||||
"oci-portal/internal/model"
|
||||
"oci-portal/internal/oci"
|
||||
)
|
||||
|
||||
// moderationsMaxInputs 限制单次审核条数,防止批量滥用拖垮渠道配额。
|
||||
const moderationsMaxInputs = 8
|
||||
|
||||
// SpeechBodyNormalize 校验并规范化 TTS 请求体:model / input 必填;
|
||||
// xAI 上游把 language 当必填(实测缺失返回 422),缺省注入 "auto"。
|
||||
// 其余字段(voice / response_format / extra_body 平铺项)原样保留。
|
||||
func SpeechBodyNormalize(raw []byte) (string, []byte, error) {
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.UseNumber()
|
||||
var body map[string]any
|
||||
if err := dec.Decode(&body); err != nil {
|
||||
return "", nil, fmt.Errorf("解析请求体: %w", err)
|
||||
}
|
||||
modelName, _ := body["model"].(string)
|
||||
input, _ := body["input"].(string)
|
||||
if strings.TrimSpace(modelName) == "" || strings.TrimSpace(input) == "" {
|
||||
return "", nil, fmt.Errorf("model 与 input 不能为空")
|
||||
}
|
||||
if lang, ok := body["language"].(string); !ok || strings.TrimSpace(lang) == "" {
|
||||
body["language"] = "auto"
|
||||
}
|
||||
out, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("重组请求体: %w", err)
|
||||
}
|
||||
return modelName, out, nil
|
||||
}
|
||||
|
||||
// ttsDefaultModel 是 /ai/v1/tts 缺省注入的模型(xAI 官方格式无 model 字段)。
|
||||
const ttsDefaultModel = "xai.grok-tts"
|
||||
|
||||
// TtsBodyConvert 把 xAI 官方 TTS 格式转换为上游 OpenAI 兼容 audio/speech 形态:
|
||||
// text→input、voice_id→voice,text 与 language 必填(对齐 xAI 官方);
|
||||
// model 为网关扩展字段,缺省注入 ttsDefaultModel;其余字段原样保留。
|
||||
func TtsBodyConvert(raw []byte) (string, []byte, error) {
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.UseNumber()
|
||||
var body map[string]any
|
||||
if err := dec.Decode(&body); err != nil {
|
||||
return "", nil, fmt.Errorf("解析请求体: %w", err)
|
||||
}
|
||||
text, _ := body["text"].(string)
|
||||
language, _ := body["language"].(string)
|
||||
if strings.TrimSpace(text) == "" || strings.TrimSpace(language) == "" {
|
||||
return "", nil, fmt.Errorf("text 与 language 不能为空")
|
||||
}
|
||||
modelName, _ := body["model"].(string)
|
||||
if strings.TrimSpace(modelName) == "" {
|
||||
modelName = ttsDefaultModel
|
||||
body["model"] = modelName
|
||||
}
|
||||
delete(body, "text")
|
||||
body["input"] = text
|
||||
if voice, ok := body["voice_id"].(string); ok && strings.TrimSpace(voice) != "" {
|
||||
body["voice"] = voice
|
||||
}
|
||||
delete(body, "voice_id")
|
||||
out, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("重组请求体: %w", err)
|
||||
}
|
||||
return modelName, out, nil
|
||||
}
|
||||
|
||||
// Speech 编排 TTS 调用:按 TTS 能力选渠道,可重试错误换渠道(上限 3 次)。
|
||||
func (s *AiGatewayService) Speech(ctx context.Context, modelName string, body []byte, group string) ([]byte, string, ChatMeta, error) {
|
||||
meta := ChatMeta{}
|
||||
excluded := map[uint]bool{}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
cand, err := s.pick(ctx, modelName, group, "TTS", excluded)
|
||||
if err != nil {
|
||||
return nil, "", meta, firstErr(lastErr, err)
|
||||
}
|
||||
meta.ChannelID, meta.ChannelName = cand.ch.ID, cand.ch.Name
|
||||
cred, err := s.configs.credentialsByID(ctx, cand.ch.OciConfigID)
|
||||
if err != nil {
|
||||
return nil, "", meta, err
|
||||
}
|
||||
audio, contentType, err := s.client.GenAiCompatSpeech(ctx, cred, cand.ch.Region, body)
|
||||
if err == nil {
|
||||
s.markSuccess(ctx, cand.ch.ID)
|
||||
return audio, contentType, meta, nil
|
||||
}
|
||||
if done := s.retryStep(ctx, cand.ch.ID, err, excluded, &meta, &lastErr); done {
|
||||
return nil, "", meta, err
|
||||
}
|
||||
}
|
||||
return nil, "", meta, lastErr
|
||||
}
|
||||
|
||||
// Rerank 编排文档重排:按 RERANK 能力选渠道,装配 Jina 风格响应。
|
||||
func (s *AiGatewayService) Rerank(ctx context.Context, req aiwire.RerankRequest, group string) (*aiwire.RerankResponse, ChatMeta, error) {
|
||||
meta := ChatMeta{}
|
||||
excluded := map[uint]bool{}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
cand, err := s.pick(ctx, req.Model, group, "RERANK", excluded)
|
||||
if err != nil {
|
||||
return nil, meta, firstErr(lastErr, err)
|
||||
}
|
||||
meta.ChannelID, meta.ChannelName = cand.ch.ID, cand.ch.Name
|
||||
cred, err := s.configs.credentialsByID(ctx, cand.ch.OciConfigID)
|
||||
if err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
ranks, err := s.client.GenAiRerank(ctx, cred, cand.ch.Region, cand.modelOcid, req.Query, req.Documents, req.TopN)
|
||||
if err == nil {
|
||||
s.markSuccess(ctx, cand.ch.ID)
|
||||
return rerankResponse(req, ranks), meta, nil
|
||||
}
|
||||
if done := s.retryStep(ctx, cand.ch.ID, err, excluded, &meta, &lastErr); done {
|
||||
return nil, meta, err
|
||||
}
|
||||
}
|
||||
return nil, meta, lastErr
|
||||
}
|
||||
|
||||
// retryStep 统一处理换渠道重试:不可重试返回 true 终止,可重试记罚并排除渠道。
|
||||
func (s *AiGatewayService) retryStep(ctx context.Context, chID uint, err error, excluded map[uint]bool, meta *ChatMeta, lastErr *error) bool {
|
||||
retry, penalize := switchable(err)
|
||||
if !retry {
|
||||
return true
|
||||
}
|
||||
if penalize {
|
||||
s.markFailure(ctx, chID)
|
||||
}
|
||||
excluded[chID] = true
|
||||
meta.Retries++
|
||||
*lastErr = err
|
||||
return false
|
||||
}
|
||||
|
||||
// rerankResponse 把上游排序结果装配为对外响应;return_documents 时回填原文。
|
||||
func rerankResponse(req aiwire.RerankRequest, ranks []oci.RerankRank) *aiwire.RerankResponse {
|
||||
out := &aiwire.RerankResponse{Model: req.Model, Results: make([]aiwire.RerankResult, 0, len(ranks))}
|
||||
withDoc := req.ReturnDocuments != nil && *req.ReturnDocuments
|
||||
for _, r := range ranks {
|
||||
if r.Index < 0 || r.Index >= len(req.Documents) {
|
||||
continue
|
||||
}
|
||||
item := aiwire.RerankResult{Index: r.Index, RelevanceScore: r.Score}
|
||||
if withDoc {
|
||||
item.Document = &aiwire.RerankDocument{Text: req.Documents[r.Index]}
|
||||
}
|
||||
out.Results = append(out.Results, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ModerationInputs 解析 moderations 的 input 字段:string 或 []string,
|
||||
// 条数与空值校验(上限 moderationsMaxInputs)。
|
||||
func ModerationInputs(raw json.RawMessage) ([]string, error) {
|
||||
var single string
|
||||
if err := json.Unmarshal(raw, &single); err == nil {
|
||||
if strings.TrimSpace(single) == "" {
|
||||
return nil, fmt.Errorf("input 不能为空")
|
||||
}
|
||||
return []string{single}, nil
|
||||
}
|
||||
var many []string
|
||||
if err := json.Unmarshal(raw, &many); err != nil {
|
||||
return nil, fmt.Errorf("input 需为字符串或字符串数组")
|
||||
}
|
||||
if len(many) == 0 || len(many) > moderationsMaxInputs {
|
||||
return nil, fmt.Errorf("input 条数需在 1~%d 之间", moderationsMaxInputs)
|
||||
}
|
||||
for _, item := range many {
|
||||
if strings.TrimSpace(item) == "" {
|
||||
return nil, fmt.Errorf("input 含空条目")
|
||||
}
|
||||
}
|
||||
return many, nil
|
||||
}
|
||||
|
||||
// Moderations 编排内容审核:guardrails 为服务级 API 无模型维度,
|
||||
// 按分组选启用渠道(整批同渠道),可重试错误换渠道(上限 3 次)。
|
||||
func (s *AiGatewayService) Moderations(ctx context.Context, id string, inputs []string, group string) (*aiwire.ModerationsResponse, ChatMeta, error) {
|
||||
meta := ChatMeta{}
|
||||
excluded := map[uint]bool{}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
ch, err := s.pickGuardChannel(ctx, group, excluded)
|
||||
if err != nil {
|
||||
return nil, meta, firstErr(lastErr, err)
|
||||
}
|
||||
meta.ChannelID, meta.ChannelName = ch.ID, ch.Name
|
||||
resp, err := s.moderateOnce(ctx, ch, id, inputs)
|
||||
if err == nil {
|
||||
s.markSuccess(ctx, ch.ID)
|
||||
return resp, meta, nil
|
||||
}
|
||||
if done := s.retryStep(ctx, ch.ID, err, excluded, &meta, &lastErr); done {
|
||||
return nil, meta, err
|
||||
}
|
||||
}
|
||||
return nil, meta, lastErr
|
||||
}
|
||||
|
||||
// pickGuardChannel 按分组挑一个启用且未熔断的渠道(权重加成,不查模型缓存)。
|
||||
func (s *AiGatewayService) pickGuardChannel(ctx context.Context, group string, excluded map[uint]bool) (model.AiChannel, error) {
|
||||
q := s.db.WithContext(ctx).Where("enabled = ?", true)
|
||||
if group != "" {
|
||||
q = q.Where("channel_group = ?", group)
|
||||
}
|
||||
var channels []model.AiChannel
|
||||
if err := q.Find(&channels).Error; err != nil {
|
||||
return model.AiChannel{}, err
|
||||
}
|
||||
now := time.Now()
|
||||
avail := channels[:0]
|
||||
for _, ch := range channels {
|
||||
if excluded[ch.ID] || (ch.DisabledUntil != nil && ch.DisabledUntil.After(now)) {
|
||||
continue
|
||||
}
|
||||
avail = append(avail, ch)
|
||||
}
|
||||
if len(avail) == 0 {
|
||||
return model.AiChannel{}, ErrAiNoChannel
|
||||
}
|
||||
return weightedPick(topPriority(avail)), nil
|
||||
}
|
||||
|
||||
// moderateOnce 在单渠道上逐条审核并装配 OpenAI moderations 外壳。
|
||||
func (s *AiGatewayService) moderateOnce(ctx context.Context, ch model.AiChannel, id string, inputs []string) (*aiwire.ModerationsResponse, error) {
|
||||
cred, err := s.configs.credentialsByID(ctx, ch.OciConfigID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := &aiwire.ModerationsResponse{ID: id, Model: "oci-guardrails",
|
||||
Results: make([]aiwire.ModerationResult, 0, len(inputs))}
|
||||
for _, text := range inputs {
|
||||
outcome, err := s.client.GenAiApplyGuardrails(ctx, cred, ch.Region, text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.Results = append(out.Results, moderationResult(outcome))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// moderationFlagThreshold 是判定违规的得分阈值(上游 CM / PI 为二值得分)。
|
||||
const moderationFlagThreshold = 0.5
|
||||
|
||||
// moderationResult 把 guardrails 结果映射为 OpenAI moderations 条目:
|
||||
// flagged 由内容审核与提示注入判定,PII 命中只作扩展信息不参与 flagged。
|
||||
func moderationResult(outcome *oci.GuardrailsOutcome) aiwire.ModerationResult {
|
||||
res := aiwire.ModerationResult{Categories: map[string]bool{}, CategoryScores: map[string]float64{}}
|
||||
for _, cat := range outcome.Categories {
|
||||
key := strings.ToLower(cat.Name)
|
||||
res.Categories[key] = cat.Score >= moderationFlagThreshold
|
||||
res.CategoryScores[key] = cat.Score
|
||||
if res.Categories[key] {
|
||||
res.Flagged = true
|
||||
}
|
||||
}
|
||||
if outcome.PromptInjectionScore != nil {
|
||||
hit := *outcome.PromptInjectionScore >= moderationFlagThreshold
|
||||
res.Categories["prompt_injection"] = hit
|
||||
res.CategoryScores["prompt_injection"] = *outcome.PromptInjectionScore
|
||||
if hit {
|
||||
res.Flagged = true
|
||||
}
|
||||
}
|
||||
for _, p := range outcome.Pii {
|
||||
res.Pii = append(res.Pii, aiwire.ModerationPii{Text: p.Text, Label: p.Label,
|
||||
Score: p.Score, Offset: p.Offset, Length: p.Length})
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"oci-portal/internal/aiwire"
|
||||
"oci-portal/internal/model"
|
||||
"oci-portal/internal/oci"
|
||||
)
|
||||
|
||||
// TestSpeechBodyNormalize 断言 TTS 请求体校验与 language 缺省注入。
|
||||
func TestSpeechBodyNormalize(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
wantErr bool
|
||||
wantLang string
|
||||
}{
|
||||
{"缺 model 拒绝", `{"input":"你好"}`, true, ""},
|
||||
{"缺 input 拒绝", `{"model":"xai.grok-tts"}`, true, ""},
|
||||
{"language 缺省注入 auto", `{"model":"xai.grok-tts","input":"你好","voice":"ara"}`, false, "auto"},
|
||||
{"language 已有保留", `{"model":"xai.grok-tts","input":"你好","language":"zh"}`, false, "zh"},
|
||||
{"非 JSON 拒绝", `<html>`, true, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
modelName, body, err := SpeechBodyNormalize([]byte(tt.raw))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(body, &out)
|
||||
if modelName != "xai.grok-tts" || out["language"] != tt.wantLang {
|
||||
t.Fatalf("model=%s language=%v, want %s", modelName, out["language"], tt.wantLang)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTtsBodyConvert 断言 xAI 官方 TTS 格式到 OpenAI 兼容形态的转换。
|
||||
func TestTtsBodyConvert(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
wantErr bool
|
||||
wantModel string
|
||||
}{
|
||||
{"缺 text 拒绝", `{"language":"zh"}`, true, ""},
|
||||
{"缺 language 拒绝", `{"text":"你好"}`, true, ""},
|
||||
{"缺省注入默认模型", `{"text":"你好","language":"zh"}`, false, "xai.grok-tts"},
|
||||
{"model 扩展字段可覆盖", `{"model":"xai.other-tts","text":"你好","language":"auto"}`, false, "xai.other-tts"},
|
||||
{"非 JSON 拒绝", `<html>`, true, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
modelName, _, err := TtsBodyConvert([]byte(tt.raw))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if modelName != tt.wantModel {
|
||||
t.Fatalf("model = %s, want %s", modelName, tt.wantModel)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTtsBodyConvertMapping 断言字段映射与未知字段保留。
|
||||
func TestTtsBodyConvertMapping(t *testing.T) {
|
||||
raw := `{"text":"你好","language":"zh","voice_id":"ara","speed":1.2,` +
|
||||
`"output_format":{"codec":"mp3","sample_rate":44100}}`
|
||||
_, body, err := TtsBodyConvert([]byte(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(body, &out)
|
||||
if out["input"] != "你好" || out["voice"] != "ara" {
|
||||
t.Fatalf("input/voice 映射错误: %v", out)
|
||||
}
|
||||
if _, ok := out["text"]; ok {
|
||||
t.Fatal("text 字段应被移除")
|
||||
}
|
||||
if _, ok := out["voice_id"]; ok {
|
||||
t.Fatal("voice_id 字段应被移除")
|
||||
}
|
||||
of, _ := out["output_format"].(map[string]any)
|
||||
if of == nil || of["codec"] != "mp3" {
|
||||
t.Fatalf("output_format 应原样保留: %v", out["output_format"])
|
||||
}
|
||||
if out["language"] != "zh" || out["speed"] == nil {
|
||||
t.Fatalf("language/speed 应保留: %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestModerationInputs 断言 input 的 string / []string 解析与边界校验。
|
||||
func TestModerationInputs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
wantN int
|
||||
wantErr bool
|
||||
}{
|
||||
{"单字符串", `"hello"`, 1, false},
|
||||
{"数组", `["a","b"]`, 2, false},
|
||||
{"空字符串拒绝", `""`, 0, true},
|
||||
{"空数组拒绝", `[]`, 0, true},
|
||||
{"含空条目拒绝", `["a",""]`, 0, true},
|
||||
{"超上限拒绝", `["1","2","3","4","5","6","7","8","9"]`, 0, true},
|
||||
{"非法类型拒绝", `{"x":1}`, 0, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ModerationInputs(json.RawMessage(tt.raw))
|
||||
if (err != nil) != tt.wantErr || len(got) != tt.wantN {
|
||||
t.Fatalf("got %v (err=%v), want n=%d wantErr=%v", got, err, tt.wantN, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestModerationResultMapping 断言 guardrails 结果到 OpenAI 外壳的映射与 flagged 判定。
|
||||
func TestModerationResultMapping(t *testing.T) {
|
||||
one := 1.0
|
||||
zero := 0.0
|
||||
tests := []struct {
|
||||
name string
|
||||
outcome oci.GuardrailsOutcome
|
||||
wantFlagged bool
|
||||
wantPii int
|
||||
}{
|
||||
{"内容审核命中", oci.GuardrailsOutcome{Categories: []oci.GuardrailCategory{{Name: "OVERALL", Score: 1}}}, true, 0},
|
||||
{"提示注入命中", oci.GuardrailsOutcome{PromptInjectionScore: &one}, true, 0},
|
||||
{"仅 PII 不 flag", oci.GuardrailsOutcome{Categories: []oci.GuardrailCategory{{Name: "OVERALL", Score: 0}},
|
||||
PromptInjectionScore: &zero, Pii: []oci.GuardrailPiiHit{{Text: "Jane", Label: "PERSON", Score: 0.99}}}, false, 1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
res := moderationResult(&tt.outcome)
|
||||
if res.Flagged != tt.wantFlagged || len(res.Pii) != tt.wantPii {
|
||||
t.Fatalf("res = %+v, want flagged=%v pii=%d", res, tt.wantFlagged, tt.wantPii)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAiRerank 断言重排编排:能力路由、top_n 透传、return_documents 回填与越界防御。
|
||||
func TestAiRerank(t *testing.T) {
|
||||
client := &gatewayStubClient{
|
||||
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
|
||||
rerankRanks: []oci.RerankRank{{Index: 1, Score: 0.9}, {Index: 0, Score: 0.4}, {Index: 9, Score: 0.1}},
|
||||
}
|
||||
gw, svc := newTestGateway(t, client)
|
||||
cfg := importAliveConfig(t, svc)
|
||||
ch := seedChannel(t, gw, cfg.ID, "us-chicago-1", 1, 1)
|
||||
gw.db.Create(&model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..rr", Name: "cohere.rerank-v4.0-fast",
|
||||
Vendor: "cohere", Capability: "RERANK", SyncedAt: time.Now()})
|
||||
ctx := context.Background()
|
||||
yes := true
|
||||
req := aiwire.RerankRequest{Model: "cohere.rerank-v4.0-fast", Query: "q", Documents: []string{"d0", "d1"}, ReturnDocuments: &yes}
|
||||
resp, _, err := gw.Rerank(ctx, req, "")
|
||||
if err != nil || len(resp.Results) != 2 {
|
||||
t.Fatalf("Rerank = %+v, %v(越界 index 应被丢弃)", resp, err)
|
||||
}
|
||||
if resp.Results[0].Index != 1 || resp.Results[0].Document == nil || resp.Results[0].Document.Text != "d1" {
|
||||
t.Fatalf("results[0] = %+v", resp.Results[0])
|
||||
}
|
||||
// 对话模型名打 rerank:能力不匹配 → 未知模型
|
||||
if _, _, err := gw.Rerank(ctx, aiwire.RerankRequest{Model: "meta.llama-3.3-70b-instruct", Query: "q", Documents: []string{"d"}}, ""); !errors.Is(err, ErrAiUnknownModel) {
|
||||
t.Errorf("chat 模型走 rerank err = %v, want ErrAiUnknownModel", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAiSpeech 断言 TTS 编排走 TTS 能力路由并透传音频与 Content-Type。
|
||||
func TestAiSpeech(t *testing.T) {
|
||||
client := &gatewayStubClient{
|
||||
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
|
||||
speechAudio: []byte{0xFF, 0xF3}, speechCT: "audio/mpeg",
|
||||
}
|
||||
gw, svc := newTestGateway(t, client)
|
||||
cfg := importAliveConfig(t, svc)
|
||||
ch := seedChannel(t, gw, cfg.ID, "us-chicago-1", 1, 1)
|
||||
gw.db.Create(&model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..tts", Name: "xai.grok-tts",
|
||||
Vendor: "xai", Capability: "TTS", SyncedAt: time.Now()})
|
||||
audio, ct, _, err := gw.Speech(context.Background(), "xai.grok-tts", []byte(`{"model":"xai.grok-tts","input":"你好","language":"auto"}`), "")
|
||||
if err != nil || ct != "audio/mpeg" || len(audio) != 2 {
|
||||
t.Fatalf("Speech = %d bytes, ct=%s, %v", len(audio), ct, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAiModerations 断言审核编排:无模型维度按分组选渠道,多条输入逐条聚合。
|
||||
func TestAiModerations(t *testing.T) {
|
||||
one := 1.0
|
||||
client := &gatewayStubClient{
|
||||
fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}},
|
||||
guardOutcome: &oci.GuardrailsOutcome{Categories: []oci.GuardrailCategory{{Name: "OVERALL", Score: 1}}, PromptInjectionScore: &one},
|
||||
}
|
||||
gw, svc := newTestGateway(t, client)
|
||||
cfg := importAliveConfig(t, svc)
|
||||
seedChannel(t, gw, cfg.ID, "us-chicago-1", 1, 1)
|
||||
resp, meta, err := gw.Moderations(context.Background(), "modr_test", []string{"a", "b"}, "")
|
||||
if err != nil || len(resp.Results) != 2 || !resp.Results[0].Flagged || resp.ID != "modr_test" {
|
||||
t.Fatalf("Moderations = %+v, meta=%+v, %v", resp, meta, err)
|
||||
}
|
||||
if !strings.Contains(resp.Model, "guardrails") {
|
||||
t.Errorf("model = %s", resp.Model)
|
||||
}
|
||||
// 分组不匹配 → 无可用渠道
|
||||
if _, _, err := gw.Moderations(context.Background(), "modr_x", []string{"a"}, "ghost-group"); !errors.Is(err, ErrAiNoChannel) {
|
||||
t.Errorf("ghost 分组 err = %v, want ErrAiNoChannel", err)
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,26 @@ type gatewayStubClient struct {
|
||||
passErrs []error
|
||||
passCalls int
|
||||
passRegions []string
|
||||
|
||||
speechAudio []byte
|
||||
speechCT string
|
||||
speechErr error
|
||||
rerankRanks []oci.RerankRank
|
||||
rerankErr error
|
||||
guardOutcome *oci.GuardrailsOutcome
|
||||
guardErr error
|
||||
}
|
||||
|
||||
func (f *gatewayStubClient) GenAiCompatSpeech(ctx context.Context, cred oci.Credentials, region string, body []byte) ([]byte, string, error) {
|
||||
return f.speechAudio, f.speechCT, f.speechErr
|
||||
}
|
||||
|
||||
func (f *gatewayStubClient) GenAiRerank(ctx context.Context, cred oci.Credentials, region, modelOcid, query string, documents []string, topN *int) ([]oci.RerankRank, error) {
|
||||
return f.rerankRanks, f.rerankErr
|
||||
}
|
||||
|
||||
func (f *gatewayStubClient) GenAiApplyGuardrails(ctx context.Context, cred oci.Credentials, region, text string) (*oci.GuardrailsOutcome, error) {
|
||||
return f.guardOutcome, f.guardErr
|
||||
}
|
||||
|
||||
func (f *gatewayStubClient) GenAiCompatResponses(ctx context.Context, cred oci.Credentials, region string, body []byte) ([]byte, error) {
|
||||
@@ -116,7 +136,7 @@ func (f *gatewayStubClient) GenAiProbeChat(ctx context.Context, cred oci.Credent
|
||||
func newTestGateway(t *testing.T, client oci.Client) (*AiGatewayService, *OciConfigService) {
|
||||
t.Helper()
|
||||
svc := newTestService(t, client)
|
||||
if err := svc.db.AutoMigrate(&model.AiKey{}, &model.AiChannel{}, &model.AiModelCache{}, &model.AiModelBlacklist{}, &model.AiCallLog{}); err != nil {
|
||||
if err := svc.db.AutoMigrate(&model.Setting{}, &model.AiKey{}, &model.AiChannel{}, &model.AiModelCache{}, &model.AiModelBlacklist{}, &model.AiCallLog{}); err != nil {
|
||||
t.Fatalf("auto migrate ai tables: %v", err)
|
||||
}
|
||||
return NewAiGatewayService(svc.db, svc, client), svc
|
||||
@@ -208,6 +228,46 @@ func seedChannel(t *testing.T, gw *AiGatewayService, cfgID uint, region string,
|
||||
return ch
|
||||
}
|
||||
|
||||
// TestFilterDeprecatedModels 断言「过滤弃用模型」开关对列表 / 路由的过滤与持久化。
|
||||
func TestFilterDeprecatedModels(t *testing.T) {
|
||||
gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}})
|
||||
cfg := importAliveConfig(t, svc)
|
||||
ch := seedChannel(t, gw, cfg.ID, "eu-frankfurt-1", 1, 1)
|
||||
dep := time.Now().Add(-24 * time.Hour)
|
||||
old := &model.AiModelCache{ChannelID: ch.ID, ModelOcid: "ocid1..dep", Name: "meta.llama-old",
|
||||
Vendor: "meta", SyncedAt: time.Now(), DeprecatedAt: &dep}
|
||||
if err := gw.db.Create(old).Error; err != nil {
|
||||
t.Fatalf("seed deprecated cache: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
list, _ := gw.GatewayModels(ctx, "")
|
||||
if len(list.Data) != 2 {
|
||||
t.Fatalf("开关关:应含弃用模型,got %d", len(list.Data))
|
||||
}
|
||||
if err := gw.SetFilterDeprecated(ctx, true); err != nil {
|
||||
t.Fatalf("SetFilterDeprecated: %v", err)
|
||||
}
|
||||
list, _ = gw.GatewayModels(ctx, "")
|
||||
if len(list.Data) != 1 || list.Data[0].ID != "meta.llama-3.3-70b-instruct" {
|
||||
t.Fatalf("开关开:弃用模型应被过滤,got %+v", list.Data)
|
||||
}
|
||||
if _, err := gw.pick(ctx, "meta.llama-old", "", "CHAT", map[uint]bool{}); !errors.Is(err, ErrAiUnknownModel) {
|
||||
t.Errorf("开关开:弃用模型路由应不可达,err = %v", err)
|
||||
}
|
||||
// 持久化:重建 service 后开关仍生效
|
||||
gw2 := NewAiGatewayService(gw.db, svc, &gatewayStubClient{})
|
||||
if !gw2.FilterDeprecated() {
|
||||
t.Error("重建后开关状态应保持开启")
|
||||
}
|
||||
if err := gw.SetFilterDeprecated(ctx, false); err != nil {
|
||||
t.Fatalf("关闭开关: %v", err)
|
||||
}
|
||||
if list, _ = gw.GatewayModels(ctx, ""); len(list.Data) != 2 {
|
||||
t.Errorf("开关关:弃用模型应恢复,got %d", len(list.Data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPickPriorityAndBreaker(t *testing.T) {
|
||||
gw, svc := newTestGateway(t, &gatewayStubClient{fakeClient: &fakeClient{tenancy: oci.TenancyInfo{Name: "t"}}})
|
||||
cfg := importAliveConfig(t, svc)
|
||||
|
||||
@@ -22,34 +22,21 @@ func respRejectStateful(req aiwire.RespRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RespServerTools 报告工具列表是否含 xAI 服务端工具(web_search / x_search)。
|
||||
func RespServerTools(tools []aiwire.RespTool) bool {
|
||||
for _, t := range tools {
|
||||
if t.Type == "web_search" || t.Type == "x_search" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RespPassthroughValidate 校验直通请求:模型必填,有状态特性不支持,工具类型
|
||||
// 只放行 function 与已实测的 web_search / x_search;流式仅在含服务端工具时拒绝
|
||||
// (工具流式事件形态未实测,不放开)。
|
||||
// 只放行 function 与 Oracle 文档化的服务端工具(web_search / x_search /
|
||||
// code_interpreter / mcp)。
|
||||
func RespPassthroughValidate(req aiwire.RespRequest) error {
|
||||
if strings.TrimSpace(req.Model) == "" {
|
||||
return fmt.Errorf("model 不能为空")
|
||||
}
|
||||
if req.Stream && RespServerTools(req.Tools) {
|
||||
return fmt.Errorf("服务端工具暂不支持流式:请去掉 stream 或改用 function 工具")
|
||||
}
|
||||
if err := respRejectStateful(req); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, t := range req.Tools {
|
||||
switch t.Type {
|
||||
case "function", "web_search", "x_search":
|
||||
case "function", "web_search", "x_search", "code_interpreter", "mcp":
|
||||
default:
|
||||
return fmt.Errorf("不支持的工具类型 %q:服务端工具仅支持 web_search / x_search", t.Type)
|
||||
return fmt.Errorf("不支持的工具类型 %q:服务端工具仅支持 web_search / x_search / code_interpreter / mcp", t.Type)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -73,12 +60,20 @@ func RespPassthroughUsage(payload []byte) *aiwire.Usage {
|
||||
var root struct {
|
||||
Usage *aiwire.RespUsage `json:"usage"`
|
||||
}
|
||||
if json.Unmarshal(payload, &root) != nil || root.Usage == nil {
|
||||
if json.Unmarshal(payload, &root) != nil {
|
||||
return nil
|
||||
}
|
||||
usage := &aiwire.Usage{PromptTokens: root.Usage.InputTokens,
|
||||
CompletionTokens: root.Usage.OutputTokens, TotalTokens: root.Usage.TotalTokens}
|
||||
if cached := root.Usage.InputTokensDetails.CachedTokens; cached > 0 {
|
||||
return usageFromResp(root.Usage)
|
||||
}
|
||||
|
||||
// usageFromResp 换算 Responses usage 为 OpenAI 口径(缓存命中透传);nil 原样返回。
|
||||
func usageFromResp(u *aiwire.RespUsage) *aiwire.Usage {
|
||||
if u == nil {
|
||||
return nil
|
||||
}
|
||||
usage := &aiwire.Usage{PromptTokens: u.InputTokens,
|
||||
CompletionTokens: u.OutputTokens, TotalTokens: u.TotalTokens}
|
||||
if cached := u.InputTokensDetails.CachedTokens; cached > 0 {
|
||||
usage.PromptTokensDetails = &aiwire.PromptTokensDetails{CachedTokens: cached}
|
||||
}
|
||||
return usage
|
||||
@@ -96,3 +91,25 @@ func RespStreamCompletedUsage(data []byte) *aiwire.Usage {
|
||||
}
|
||||
return RespPassthroughUsage(ev.Response)
|
||||
}
|
||||
|
||||
// RespStreamErrorMsg 从一行 SSE data JSON 中提取 error / response.failed 事件的
|
||||
// 错误消息;非错误事件返回空串。流式直通据此把上游错误写入调用日志。
|
||||
func RespStreamErrorMsg(data []byte) string {
|
||||
var ev respStreamEvent
|
||||
if json.Unmarshal(data, &ev) != nil {
|
||||
return ""
|
||||
}
|
||||
switch ev.Type {
|
||||
case "error":
|
||||
if ev.Message != "" {
|
||||
return ev.Message
|
||||
}
|
||||
return "上游返回错误事件 error"
|
||||
case "response.failed":
|
||||
if m := respErrorMsg(ev.Response); m != "" {
|
||||
return m
|
||||
}
|
||||
return "上游返回错误事件 response.failed"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -24,27 +24,6 @@ func deref(p *int) int {
|
||||
return *p
|
||||
}
|
||||
|
||||
func TestRespServerTools(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
tools []aiwire.RespTool
|
||||
want bool
|
||||
}{
|
||||
{"web_search", []aiwire.RespTool{{Type: "web_search"}}, true},
|
||||
{"x_search混用", []aiwire.RespTool{{Type: "function", Name: "f"}, {Type: "x_search"}}, true},
|
||||
{"仅function", []aiwire.RespTool{{Type: "function", Name: "f"}}, false},
|
||||
{"空", nil, false},
|
||||
{"其他类型", []aiwire.RespTool{{Type: "code_interpreter"}}, false},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := RespServerTools(test.tools); got != test.want {
|
||||
t.Fatalf("got %v, want %v", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRespPassthroughValidate(t *testing.T) {
|
||||
prev := "resp_1"
|
||||
bg := true
|
||||
@@ -56,12 +35,14 @@ func TestRespPassthroughValidate(t *testing.T) {
|
||||
{"合法", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}}}, false},
|
||||
{"混用function", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "function", Name: "f"}}}, false},
|
||||
{"缺model", aiwire.RespRequest{Tools: []aiwire.RespTool{{Type: "web_search"}}}, true},
|
||||
{"工具加流式拒绝", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "web_search"}}}, true},
|
||||
{"服务端工具流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "web_search"}}}, false},
|
||||
{"无工具流式放行", aiwire.RespRequest{Model: "m", Stream: true}, false},
|
||||
{"function工具流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "function", Name: "f"}}}, false},
|
||||
{"code_interpreter放行", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "code_interpreter"}}}, false},
|
||||
{"mcp流式放行", aiwire.RespRequest{Model: "m", Stream: true, Tools: []aiwire.RespTool{{Type: "mcp"}}}, false},
|
||||
{"有状态拒绝", aiwire.RespRequest{Model: "m", PreviousResponseID: prev}, true},
|
||||
{"background拒绝", aiwire.RespRequest{Model: "m", Background: &bg}, true},
|
||||
{"未知工具拒绝", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "mcp"}}}, true},
|
||||
{"未知工具拒绝", aiwire.RespRequest{Model: "m", Tools: []aiwire.RespTool{{Type: "web_search"}, {Type: "file_search"}}}, true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
@@ -1,305 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"oci-portal/internal/model"
|
||||
)
|
||||
|
||||
// 告警规则约束与命中记录保留期(窗口计数之外多留几天便于排查)。
|
||||
const (
|
||||
alertMaxThreshold = 100
|
||||
alertMaxWindowMin = 1440
|
||||
alertHitRetention = 7 * 24 * time.Hour
|
||||
alertSourceIPIn = "in"
|
||||
alertSourceIPNotIn = "notin"
|
||||
)
|
||||
|
||||
// ErrInvalidAlertRule 标记规则字段非法,api 层映射 400。
|
||||
var ErrInvalidAlertRule = fmt.Errorf("告警规则字段非法")
|
||||
|
||||
// ListAlertRules 返回全部告警规则(创建顺序)。
|
||||
func (s *LogEventService) ListAlertRules(ctx context.Context) ([]model.AlertRule, error) {
|
||||
var rules []model.AlertRule
|
||||
if err := s.db.WithContext(ctx).Order("id").Find(&rules).Error; err != nil {
|
||||
return nil, fmt.Errorf("list alert rules: %w", err)
|
||||
}
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
// CreateAlertRule 校验并创建规则。
|
||||
func (s *LogEventService) CreateAlertRule(ctx context.Context, rule model.AlertRule) (model.AlertRule, error) {
|
||||
if err := validateAlertRule(&rule); err != nil {
|
||||
return model.AlertRule{}, err
|
||||
}
|
||||
rule.ID = 0
|
||||
if err := s.db.WithContext(ctx).Create(&rule).Error; err != nil {
|
||||
return model.AlertRule{}, fmt.Errorf("create alert rule: %w", err)
|
||||
}
|
||||
return rule, nil
|
||||
}
|
||||
|
||||
// UpdateAlertRule 校验并整体覆盖规则(含启停)。
|
||||
func (s *LogEventService) UpdateAlertRule(ctx context.Context, id uint, rule model.AlertRule) (model.AlertRule, error) {
|
||||
if err := validateAlertRule(&rule); err != nil {
|
||||
return model.AlertRule{}, err
|
||||
}
|
||||
var cur model.AlertRule
|
||||
if err := s.db.WithContext(ctx).First(&cur, id).Error; err != nil {
|
||||
return model.AlertRule{}, fmt.Errorf("find alert rule %d: %w", id, err)
|
||||
}
|
||||
rule.ID, rule.CreatedAt = cur.ID, cur.CreatedAt
|
||||
if err := s.db.WithContext(ctx).Save(&rule).Error; err != nil {
|
||||
return model.AlertRule{}, fmt.Errorf("update alert rule: %w", err)
|
||||
}
|
||||
return rule, nil
|
||||
}
|
||||
|
||||
// DeleteAlertRule 删除规则及其命中记录。
|
||||
func (s *LogEventService) DeleteAlertRule(ctx context.Context, id uint) error {
|
||||
if err := s.db.WithContext(ctx).Delete(&model.AlertRule{}, id).Error; err != nil {
|
||||
return fmt.Errorf("delete alert rule: %w", err)
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Where("rule_id = ?", id).Delete(&model.AlertRuleHit{}).Error; err != nil {
|
||||
return fmt.Errorf("delete alert rule hits: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateAlertRule 校验字段并归一化;非法时返回含具体原因的 ErrInvalidAlertRule 包装。
|
||||
func validateAlertRule(rule *model.AlertRule) error {
|
||||
rule.Name = strings.TrimSpace(rule.Name)
|
||||
if rule.Name == "" {
|
||||
return fmt.Errorf("%w: 名称必填", ErrInvalidAlertRule)
|
||||
}
|
||||
if rule.SourceIPMode == "" {
|
||||
rule.SourceIPMode = alertSourceIPIn
|
||||
}
|
||||
if rule.SourceIPMode != alertSourceIPIn && rule.SourceIPMode != alertSourceIPNotIn {
|
||||
return fmt.Errorf("%w: 来源 IP 模式须为 in/notin", ErrInvalidAlertRule)
|
||||
}
|
||||
if rule.Threshold < 1 || rule.Threshold > alertMaxThreshold {
|
||||
return fmt.Errorf("%w: 阈值须在 1-%d 之间", ErrInvalidAlertRule, alertMaxThreshold)
|
||||
}
|
||||
if rule.Threshold > 1 && (rule.WindowMinutes < 1 || rule.WindowMinutes > alertMaxWindowMin) {
|
||||
return fmt.Errorf("%w: 阈值>1 时窗口须在 1-%d 分钟之间", ErrInvalidAlertRule, alertMaxWindowMin)
|
||||
}
|
||||
if rule.EventTypes != "" {
|
||||
rule.EventTypes = normalizeCSV(rule.EventTypes)
|
||||
}
|
||||
return validateAlertRuleIPs(rule)
|
||||
}
|
||||
|
||||
// validateAlertRuleIPs 归一化并校验来源 IP 列表(裸 IP 或 CIDR)。
|
||||
func validateAlertRuleIPs(rule *model.AlertRule) error {
|
||||
if rule.SourceIPs == "" {
|
||||
return nil
|
||||
}
|
||||
rule.SourceIPs = normalizeCSV(rule.SourceIPs)
|
||||
for _, item := range strings.Split(rule.SourceIPs, ",") {
|
||||
if _, err := parseIPMatcher(item); err != nil {
|
||||
return fmt.Errorf("%w: 来源 IP %q 不是合法的 IP 或 CIDR", ErrInvalidAlertRule, item)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeCSV 去除各项空白与空项后重组逗号分隔串。
|
||||
func normalizeCSV(s string) string {
|
||||
parts := strings.Split(s, ",")
|
||||
out := parts[:0]
|
||||
for _, p := range parts {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
|
||||
// parseIPMatcher 把裸 IP 或 CIDR 解析为前缀(裸 IP 视为单地址前缀)。
|
||||
func parseIPMatcher(item string) (netip.Prefix, error) {
|
||||
if strings.Contains(item, "/") {
|
||||
return netip.ParsePrefix(item)
|
||||
}
|
||||
addr, err := netip.ParseAddr(item)
|
||||
if err != nil {
|
||||
return netip.Prefix{}, err
|
||||
}
|
||||
return netip.PrefixFrom(addr, addr.BitLen()), nil
|
||||
}
|
||||
|
||||
// ipListMatch 报告 ip 是否命中列表中的任一前缀;ip 解析失败视为未命中。
|
||||
func ipListMatch(list, ip string) bool {
|
||||
addr, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, item := range strings.Split(list, ",") {
|
||||
if p, err := parseIPMatcher(item); err == nil && p.Contains(addr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ruleHits 报告事件是否命中规则的全部条件(AND 语义,空条件视为任意)。
|
||||
func ruleHits(rule model.AlertRule, e *model.LogEvent, p parsedEvent) bool {
|
||||
if rule.OciConfigID != 0 && rule.OciConfigID != e.OciConfigID {
|
||||
return false
|
||||
}
|
||||
name := relayEventShortName(p.EventType)
|
||||
if rule.EventTypes != "" && !slices.Contains(strings.Split(rule.EventTypes, ","), name) {
|
||||
return false
|
||||
}
|
||||
if rule.ResourceMatch != "" && !strings.Contains(p.ResourceName, rule.ResourceMatch) {
|
||||
return false
|
||||
}
|
||||
return ruleIPHits(rule, p.SourceIP)
|
||||
}
|
||||
|
||||
// ruleIPHits 按模式判定来源 IP 条件:in 命中列表告警;notin 不在列表才告警,
|
||||
// 事件缺 IP 字段时 notin 不告警(避免解析缺字段导致白名单误报)。
|
||||
func ruleIPHits(rule model.AlertRule, ip string) bool {
|
||||
if rule.SourceIPs == "" {
|
||||
return true
|
||||
}
|
||||
if rule.SourceIPMode == alertSourceIPNotIn {
|
||||
return ip != "" && !ipListMatch(rule.SourceIPs, ip)
|
||||
}
|
||||
return ipListMatch(rule.SourceIPs, ip)
|
||||
}
|
||||
|
||||
// matchAlertRules 对一条已解析事件执行全部启用规则;任何内部错误只记日志,不影响解析主流程。
|
||||
func (s *LogEventService) matchAlertRules(ctx context.Context, rules []model.AlertRule, e *model.LogEvent, p parsedEvent) {
|
||||
if s.notifier == nil {
|
||||
return
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if !rule.Enabled || !ruleHits(rule, e, p) {
|
||||
continue
|
||||
}
|
||||
count, ok := s.recordAlertHit(ctx, rule, e)
|
||||
if !ok || count < rule.Threshold || !s.alertCooldownPass(rule) {
|
||||
continue
|
||||
}
|
||||
s.notifier.SendTemplateAsync("audit_alert", map[string]string{
|
||||
"rule": rule.Name, "tenant": s.configAlias(ctx, e.OciConfigID),
|
||||
"event": relayEventShortName(p.EventType), "resource": p.ResourceName,
|
||||
"ip": p.SourceIP, "count": fmt.Sprint(count),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// recordAlertHit 落一条命中并返回窗口内累计次数;阈值 1 的规则免计数直接触发。
|
||||
func (s *LogEventService) recordAlertHit(ctx context.Context, rule model.AlertRule, e *model.LogEvent) (int, bool) {
|
||||
count, err := s.recordAlertHitTx(ctx, rule, e)
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
log.Printf("alert rule hit record: %v", err)
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
return count, true
|
||||
}
|
||||
|
||||
func (s *LogEventService) recordAlertHitTx(ctx context.Context, rule model.AlertRule, event *model.LogEvent) (int, error) {
|
||||
count := 0
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
count, err = insertAlertHit(tx, rule, event)
|
||||
return err
|
||||
})
|
||||
return count, err
|
||||
}
|
||||
|
||||
// insertAlertHit 按 rule→event 锁顺序确认引用存在后插入并统计窗口命中。
|
||||
func insertAlertHit(tx *gorm.DB, rule model.AlertRule, event *model.LogEvent) (int, error) {
|
||||
if err := lockAlertRefs(tx, rule.ID, event.ID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if rule.Threshold <= 1 {
|
||||
return 1, nil
|
||||
}
|
||||
now := time.Now()
|
||||
hit := model.AlertRuleHit{RuleID: rule.ID, LogEventID: event.ID, HitAt: now}
|
||||
if err := tx.Create(&hit).Error; err != nil {
|
||||
return 0, fmt.Errorf("create alert rule hit: %w", err)
|
||||
}
|
||||
var count int64
|
||||
cutoff := now.Add(-time.Duration(rule.WindowMinutes) * time.Minute)
|
||||
err := tx.Model(&model.AlertRuleHit{}).
|
||||
Where("rule_id = ? AND hit_at >= ?", rule.ID, cutoff).Count(&count).Error
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("count alert rule hits: %w", err)
|
||||
}
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
func lockAlertRefs(tx *gorm.DB, ruleID, eventID uint) error {
|
||||
var rule model.AlertRule
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").First(&rule, ruleID).Error; err != nil {
|
||||
return fmt.Errorf("lock alert rule %d: %w", ruleID, err)
|
||||
}
|
||||
var event model.LogEvent
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").First(&event, eventID).Error; err != nil {
|
||||
return fmt.Errorf("lock log event %d: %w", eventID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// alertCooldownPass 报告规则是否已过冷却窗口;通过即记录本次发送时刻。
|
||||
// 阈值 1 的规则无冷却(每次命中即时告警,与既有云端事件通知一致)。
|
||||
func (s *LogEventService) alertCooldownPass(rule model.AlertRule) bool {
|
||||
if rule.Threshold <= 1 {
|
||||
return true
|
||||
}
|
||||
s.alertMu.Lock()
|
||||
defer s.alertMu.Unlock()
|
||||
window := time.Duration(rule.WindowMinutes) * time.Minute
|
||||
if last, ok := s.alertSentAt[rule.ID]; ok && time.Since(last) < window {
|
||||
return false
|
||||
}
|
||||
if s.alertSentAt == nil {
|
||||
s.alertSentAt = map[uint]time.Time{}
|
||||
}
|
||||
s.alertSentAt[rule.ID] = time.Now()
|
||||
return true
|
||||
}
|
||||
|
||||
// ClearAlertCooldown 清除已删除租户规则的进程内冷却状态。
|
||||
func (s *LogEventService) ClearAlertCooldown(ruleIDs []uint) {
|
||||
s.alertMu.Lock()
|
||||
defer s.alertMu.Unlock()
|
||||
for _, id := range ruleIDs {
|
||||
delete(s.alertSentAt, id)
|
||||
}
|
||||
}
|
||||
|
||||
// loadEnabledAlertRules 载入启用中的规则;失败时返回空集并记日志(解析主流程照常)。
|
||||
func (s *LogEventService) loadEnabledAlertRules(ctx context.Context) []model.AlertRule {
|
||||
var rules []model.AlertRule
|
||||
err := s.db.WithContext(ctx).Where("enabled = ?", true).Order("id").Find(&rules).Error
|
||||
if err != nil {
|
||||
log.Printf("load alert rules: %v", err)
|
||||
return nil
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
// cleanupAlertHits 删除保留期外的命中记录(随 cleanupOnce 周期执行)。
|
||||
func (s *LogEventService) cleanupAlertHits(ctx context.Context) {
|
||||
cutoff := time.Now().Add(-alertHitRetention)
|
||||
if err := s.db.WithContext(ctx).Where("hit_at < ?", cutoff).Delete(&model.AlertRuleHit{}).Error; err != nil {
|
||||
log.Printf("cleanup alert hits: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"oci-portal/internal/crypto"
|
||||
"oci-portal/internal/model"
|
||||
)
|
||||
|
||||
func TestValidateAlertRule(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
rule model.AlertRule
|
||||
wantErr string
|
||||
check func(t *testing.T, r model.AlertRule)
|
||||
}{
|
||||
{name: "名称必填", rule: model.AlertRule{Threshold: 1}, wantErr: "名称"},
|
||||
{name: "模式非法", rule: model.AlertRule{Name: "r", Threshold: 1, SourceIPMode: "any"}, wantErr: "in/notin"},
|
||||
{name: "阈值越界", rule: model.AlertRule{Name: "r", Threshold: 101}, wantErr: "阈值"},
|
||||
{name: "阈值>1须带窗口", rule: model.AlertRule{Name: "r", Threshold: 3}, wantErr: "窗口"},
|
||||
{name: "IP 非法", rule: model.AlertRule{Name: "r", Threshold: 1, SourceIPs: "300.1.1.1"}, wantErr: "IP"},
|
||||
{name: "CIDR 合法", rule: model.AlertRule{Name: "r", Threshold: 1, SourceIPs: "10.0.0.0/8, 1.2.3.4"},
|
||||
check: func(t *testing.T, r model.AlertRule) {
|
||||
if r.SourceIPs != "10.0.0.0/8,1.2.3.4" {
|
||||
t.Errorf("SourceIPs = %q, 应去空白归一化", r.SourceIPs)
|
||||
}
|
||||
if r.SourceIPMode != alertSourceIPIn {
|
||||
t.Errorf("SourceIPMode = %q, 应默认 in", r.SourceIPMode)
|
||||
}
|
||||
}},
|
||||
{name: "事件清单归一化", rule: model.AlertRule{Name: "r", Threshold: 1, EventTypes: " TerminateInstance , CreateApiKey ,"},
|
||||
check: func(t *testing.T, r model.AlertRule) {
|
||||
if r.EventTypes != "TerminateInstance,CreateApiKey" {
|
||||
t.Errorf("EventTypes = %q", r.EventTypes)
|
||||
}
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rule := tt.rule
|
||||
err := validateAlertRule(&rule)
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validateAlertRule: %v", err)
|
||||
}
|
||||
if tt.check != nil {
|
||||
tt.check(t, rule)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("err = %v, want contains %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleHits(t *testing.T) {
|
||||
base := model.AlertRule{Name: "r", Threshold: 1, SourceIPMode: alertSourceIPIn}
|
||||
ev := &model.LogEvent{OciConfigID: 7}
|
||||
parsed := parsedEvent{
|
||||
EventType: "com.oraclecloud.ComputeApi.TerminateInstance",
|
||||
SourceIP: "203.0.113.8",
|
||||
ResourceName: "web-server-1",
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
mod func(r *model.AlertRule)
|
||||
p *parsedEvent
|
||||
want bool
|
||||
}{
|
||||
{name: "空条件全命中", mod: func(r *model.AlertRule) {}, want: true},
|
||||
{name: "租户匹配", mod: func(r *model.AlertRule) { r.OciConfigID = 7 }, want: true},
|
||||
{name: "租户不匹配", mod: func(r *model.AlertRule) { r.OciConfigID = 8 }, want: false},
|
||||
{name: "事件短名命中", mod: func(r *model.AlertRule) { r.EventTypes = "LaunchInstance,TerminateInstance" }, want: true},
|
||||
{name: "事件不在清单", mod: func(r *model.AlertRule) { r.EventTypes = "CreateUser" }, want: false},
|
||||
{name: "资源子串命中", mod: func(r *model.AlertRule) { r.ResourceMatch = "web-" }, want: true},
|
||||
{name: "资源不含", mod: func(r *model.AlertRule) { r.ResourceMatch = "db-" }, want: false},
|
||||
{name: "IP in 命中 CIDR", mod: func(r *model.AlertRule) { r.SourceIPs = "203.0.113.0/24" }, want: true},
|
||||
{name: "IP in 未命中", mod: func(r *model.AlertRule) { r.SourceIPs = "10.0.0.0/8" }, want: false},
|
||||
{name: "IP notin 白名单外告警", mod: func(r *model.AlertRule) {
|
||||
r.SourceIPs, r.SourceIPMode = "10.0.0.0/8", alertSourceIPNotIn
|
||||
}, want: true},
|
||||
{name: "IP notin 白名单内不告警", mod: func(r *model.AlertRule) {
|
||||
r.SourceIPs, r.SourceIPMode = "203.0.113.8", alertSourceIPNotIn
|
||||
}, want: false},
|
||||
{name: "notin 事件缺 IP 不告警", mod: func(r *model.AlertRule) {
|
||||
r.SourceIPs, r.SourceIPMode = "10.0.0.0/8", alertSourceIPNotIn
|
||||
}, p: &parsedEvent{EventType: parsed.EventType}, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rule := base
|
||||
tt.mod(&rule)
|
||||
p := parsed
|
||||
if tt.p != nil {
|
||||
p = *tt.p
|
||||
}
|
||||
if got := ruleHits(rule, ev, p); got != tt.want {
|
||||
t.Errorf("ruleHits = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertRuleCRUD(t *testing.T) {
|
||||
svc, _, _ := newLogEventEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created, err := svc.CreateAlertRule(ctx, model.AlertRule{Name: "非白名单终止", Enabled: true, Threshold: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if created.ID == 0 {
|
||||
t.Fatal("create 未回填 ID")
|
||||
}
|
||||
if _, err := svc.CreateAlertRule(ctx, model.AlertRule{Threshold: 1}); err == nil {
|
||||
t.Fatal("空名称应校验失败")
|
||||
}
|
||||
|
||||
created.Enabled = false
|
||||
created.EventTypes = "TerminateInstance"
|
||||
updated, err := svc.UpdateAlertRule(ctx, created.ID, created)
|
||||
if err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
if updated.Enabled || updated.EventTypes != "TerminateInstance" {
|
||||
t.Fatalf("update 未生效: %+v", updated)
|
||||
}
|
||||
|
||||
rules, err := svc.ListAlertRules(ctx)
|
||||
if err != nil || len(rules) != 1 {
|
||||
t.Fatalf("list = %v, %v", rules, err)
|
||||
}
|
||||
if err := svc.DeleteAlertRule(ctx, created.ID); err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if rules, _ := svc.ListAlertRules(ctx); len(rules) != 0 {
|
||||
t.Fatalf("delete 后仍有 %d 条", len(rules))
|
||||
}
|
||||
}
|
||||
|
||||
// auditEventPayload 构造一条含资源与来源 IP 的 CloudEvents 审计消息。
|
||||
func auditEventPayload(event, resource, ip string) string {
|
||||
return fmt.Sprintf(`{"eventType":"com.oraclecloud.ComputeApi.%s","source":"ComputeApi",`+
|
||||
`"eventTime":"2026-07-10T08:00:00Z","data":{"resourceName":%q,"identity":{"ipAddress":%q}}}`,
|
||||
event, resource, ip)
|
||||
}
|
||||
|
||||
// newAlertNotifyEnv 组装带假 Telegram 通道的告警测试环境。
|
||||
func newAlertNotifyEnv(t *testing.T) (*LogEventService, *telegramCapture, func()) {
|
||||
t.Helper()
|
||||
svc, db, _ := newLogEventEnv(t)
|
||||
srv, rec := newFakeTelegram(t, `{"ok":true}`)
|
||||
cipher, err := crypto.NewCipher("test-data-key")
|
||||
if err != nil {
|
||||
t.Fatalf("new cipher: %v", err)
|
||||
}
|
||||
settings := NewSettingService(db, cipher)
|
||||
token := "123456:AAfake"
|
||||
if err := settings.UpdateTelegram(context.Background(),
|
||||
UpdateTelegramInput{Enabled: true, BotToken: &token, ChatID: "42"}); err != nil {
|
||||
t.Fatalf("update telegram: %v", err)
|
||||
}
|
||||
n := NewNotifier(settings)
|
||||
n.base = srv.URL
|
||||
svc.SetNotifier(n, settings)
|
||||
return svc, rec, n.Wait
|
||||
}
|
||||
|
||||
func TestMatchAlertRulesNotify(t *testing.T) {
|
||||
svc, rec, wait := newAlertNotifyEnv(t)
|
||||
ctx := context.Background()
|
||||
_, err := svc.CreateAlertRule(ctx, model.AlertRule{
|
||||
Name: "白名单外终止", Enabled: true, Threshold: 1,
|
||||
EventTypes: "TerminateInstance", SourceIPs: "10.0.0.0/8", SourceIPMode: alertSourceIPNotIn,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create rule: %v", err)
|
||||
}
|
||||
// 命中:白名单外 IP;不命中:白名单内 IP
|
||||
mustIngest(t, svc, "m1", auditEventPayload("TerminateInstance", "web-1", "203.0.113.8"))
|
||||
mustIngest(t, svc, "m2", auditEventPayload("TerminateInstance", "web-2", "10.1.2.3"))
|
||||
svc.parseOnce(ctx)
|
||||
wait()
|
||||
|
||||
alerts := auditAlerts(rec.snapshot())
|
||||
joined := strings.Join(alerts, "\n---\n")
|
||||
if !strings.Contains(joined, "白名单外终止") || !strings.Contains(joined, "web-1") {
|
||||
t.Fatalf("应收到含规则名与资源的告警,got %q", joined)
|
||||
}
|
||||
if strings.Contains(joined, "web-2") {
|
||||
t.Fatalf("白名单内事件不应告警,got %q", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// auditAlerts 过滤出审计告警推送(排除既有 notifyCritical 的云端事件通知)。
|
||||
func auditAlerts(texts []string) []string {
|
||||
var out []string
|
||||
for _, s := range texts {
|
||||
if strings.Contains(s, "审计告警") {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestAlertThresholdWindow(t *testing.T) {
|
||||
svc, rec, wait := newAlertNotifyEnv(t)
|
||||
ctx := context.Background()
|
||||
_, err := svc.CreateAlertRule(ctx, model.AlertRule{
|
||||
Name: "登录风暴", Enabled: true, Threshold: 3, WindowMinutes: 5, EventTypes: "InteractiveLogin",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create rule: %v", err)
|
||||
}
|
||||
for i := 1; i <= 4; i++ {
|
||||
mustIngest(t, svc, fmt.Sprint("login-", i),
|
||||
auditEventPayload("InteractiveLogin", "user@x.com", "203.0.113.8"))
|
||||
}
|
||||
svc.parseOnce(ctx)
|
||||
wait()
|
||||
|
||||
alerts := auditAlerts(rec.snapshot())
|
||||
if len(alerts) != 1 {
|
||||
t.Fatalf("窗口内 4 次命中应只告警 1 次(第 3 次触发后冷却),got %d 条: %v", len(alerts), alerts)
|
||||
}
|
||||
if !strings.Contains(alerts[0], "3 次") {
|
||||
t.Errorf("告警文案应含累计次数,got %q", alerts[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAlertRuleBadDataDoesNotBlockParse 验证规则表异常不影响解析主流程。
|
||||
func TestAlertRuleBadDataDoesNotBlockParse(t *testing.T) {
|
||||
svc, db, _ := newLogEventEnv(t)
|
||||
ctx := context.Background()
|
||||
// 直插一条绕过校验的坏规则(IP 列表非法)
|
||||
bad := model.AlertRule{Name: "bad", Enabled: true, Threshold: 1, SourceIPs: "not-an-ip"}
|
||||
if err := db.Create(&bad).Error; err != nil {
|
||||
t.Fatalf("insert bad rule: %v", err)
|
||||
}
|
||||
mustIngest(t, svc, "m1", auditEventPayload("TerminateInstance", "web-1", "1.2.3.4"))
|
||||
svc.parseOnce(ctx)
|
||||
|
||||
var e model.LogEvent
|
||||
if err := db.First(&e, "message_id = ?", "m1").Error; err != nil {
|
||||
t.Fatalf("find event: %v", err)
|
||||
}
|
||||
if !e.Processed {
|
||||
t.Fatal("坏规则不应阻塞事件解析")
|
||||
}
|
||||
}
|
||||
|
||||
// mustIngest 落一条回传事件,失败即终止测试。
|
||||
func mustIngest(t *testing.T, svc *LogEventService, msgID, payload string) {
|
||||
t.Helper()
|
||||
if err := svc.Ingest(context.Background(), 1, msgID, []byte(payload), false); err != nil {
|
||||
t.Fatalf("ingest %s: %v", msgID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCleanupAlertHits 验证过期命中记录随清理删除。
|
||||
func TestCleanupAlertHits(t *testing.T) {
|
||||
svc, db, _ := newLogEventEnv(t)
|
||||
old := model.AlertRuleHit{RuleID: 1, HitAt: time.Now().Add(-8 * 24 * time.Hour)}
|
||||
fresh := model.AlertRuleHit{RuleID: 1, HitAt: time.Now()}
|
||||
if err := db.Create(&old).Error; err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
if err := db.Create(&fresh).Error; err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
svc.cleanupAlertHits(context.Background())
|
||||
var count int64
|
||||
db.Model(&model.AlertRuleHit{}).Count(&count)
|
||||
if count != 1 {
|
||||
t.Fatalf("清理后应剩 1 条,got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearAlertCooldown(t *testing.T) {
|
||||
svc := NewLogEventService(nil)
|
||||
rule1 := model.AlertRule{ID: 1, Threshold: 2, WindowMinutes: 10}
|
||||
rule2 := model.AlertRule{ID: 2, Threshold: 2, WindowMinutes: 10}
|
||||
if !svc.alertCooldownPass(rule1) || !svc.alertCooldownPass(rule2) {
|
||||
t.Fatal("首次命中应通过冷却检查")
|
||||
}
|
||||
|
||||
svc.ClearAlertCooldown([]uint{rule1.ID})
|
||||
if !svc.alertCooldownPass(rule1) {
|
||||
t.Fatal("已清理规则应重新通过冷却检查")
|
||||
}
|
||||
if svc.alertCooldownPass(rule2) {
|
||||
t.Fatal("未清理规则不应通过冷却检查")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordAlertHitRejectsMissingRefs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
deleteRule bool
|
||||
}{
|
||||
{name: "规则已删除", deleteRule: true},
|
||||
{name: "事件已删除"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
testRecordAlertHitMissingRef(t, tt.deleteRule)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testRecordAlertHitMissingRef(t *testing.T, deleteRule bool) {
|
||||
t.Helper()
|
||||
svc, db, cfgID := newLogEventEnv(t)
|
||||
rule := model.AlertRule{Name: "r", OciConfigID: cfgID, Threshold: 2, WindowMinutes: 5}
|
||||
event := model.LogEvent{OciConfigID: cfgID, MessageID: "m"}
|
||||
if err := db.Create(&rule).Error; err != nil {
|
||||
t.Fatalf("create rule: %v", err)
|
||||
}
|
||||
if err := db.Create(&event).Error; err != nil {
|
||||
t.Fatalf("create event: %v", err)
|
||||
}
|
||||
var err error
|
||||
if deleteRule {
|
||||
err = db.Delete(&rule).Error
|
||||
} else {
|
||||
err = db.Delete(&event).Error
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("delete reference: %v", err)
|
||||
}
|
||||
if count, ok := svc.recordAlertHit(context.Background(), rule, &event); ok || count != 0 {
|
||||
t.Fatalf("record missing refs = (%d,%v), want (0,false)", count, ok)
|
||||
}
|
||||
var hits int64
|
||||
db.Model(&model.AlertRuleHit{}).Count(&hits)
|
||||
if hits != 0 {
|
||||
t.Fatalf("orphan alert hits = %d, want 0", hits)
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,7 @@ func anthInputItems(messages []aiwire.AnthMessage) ([]any, error) {
|
||||
func anthBlockItem(role string, b aiwire.AnthBlock) (item, part map[string]any, err error) {
|
||||
switch b.Type {
|
||||
case "text":
|
||||
return nil, anthTextPart(role, b.Text), nil
|
||||
return nil, respTextPart(role, b.Text), nil
|
||||
case "image":
|
||||
part, err = anthImageInput(b.Source)
|
||||
return nil, part, err
|
||||
@@ -100,8 +100,9 @@ func anthBlockItem(role string, b aiwire.AnthBlock) (item, part map[string]any,
|
||||
}
|
||||
}
|
||||
|
||||
// anthTextPart 按角色选择 Responses 文本部件类型(assistant 历史为 output_text)。
|
||||
func anthTextPart(role, text string) map[string]any {
|
||||
// respTextPart 按角色选择 Responses 文本部件类型(assistant 历史为 output_text);
|
||||
// Anthropic 与 Chat Completions 两条转换链共用。
|
||||
func respTextPart(role, text string) map[string]any {
|
||||
if role == "assistant" {
|
||||
return map[string]any{"type": "output_text", "text": text}
|
||||
}
|
||||
@@ -219,8 +220,7 @@ func ResponsesToAnthropic(payload []byte, msgID string) (*aiwire.MessagesRespons
|
||||
out.StopReason = "tool_use"
|
||||
}
|
||||
}
|
||||
if resp.Status == "incomplete" && resp.IncompleteDetails != nil &&
|
||||
resp.IncompleteDetails.Reason == "max_output_tokens" {
|
||||
if respTruncated(&resp) {
|
||||
out.StopReason = "max_tokens"
|
||||
}
|
||||
out.Usage = anthUsageFromResp(resp.Usage)
|
||||
@@ -258,7 +258,7 @@ type AnthEvent struct {
|
||||
|
||||
// AnthRespBridge 把直通 SSE 事件流桥接为 Anthropic 事件序列:
|
||||
// message_start → content_block_start/delta/stop(text 与 tool_use 分块)→ message_delta → message_stop。
|
||||
// reasoning 系列事件丢弃。
|
||||
// reasoning 系列事件丢弃;上游 error / response.failed 转 Anthropic error 事件透传。
|
||||
type AnthRespBridge struct {
|
||||
id, model string
|
||||
started bool
|
||||
@@ -267,6 +267,11 @@ type AnthRespBridge struct {
|
||||
blockIndex int
|
||||
stopReason string
|
||||
usage aiwire.AnthUsage
|
||||
// sawTerminal 标记收到过终态事件(completed/incomplete/failed);
|
||||
// 上游流提前 EOF 时据此发 error 事件而非伪装正常结束
|
||||
sawTerminal bool
|
||||
// errMsg 记录上游错误消息,非空即本流已失败(供调用日志)
|
||||
errMsg string
|
||||
}
|
||||
|
||||
// NewAnthRespBridge 构造桥;id 为响应消息 ID。
|
||||
@@ -278,6 +283,7 @@ func NewAnthRespBridge(id, model string) *AnthRespBridge {
|
||||
type respStreamEvent struct {
|
||||
Type string `json:"type"`
|
||||
Delta string `json:"delta"`
|
||||
Message string `json:"message"`
|
||||
Item *respOutputItem `json:"item"`
|
||||
Response *respPayload `json:"response"`
|
||||
}
|
||||
@@ -288,27 +294,130 @@ func (st *AnthRespBridge) Feed(data []byte) []AnthEvent {
|
||||
if json.Unmarshal(data, &ev) != nil {
|
||||
return nil
|
||||
}
|
||||
var events []AnthEvent
|
||||
if !st.started {
|
||||
st.started = true
|
||||
events = append(events, st.startEvent())
|
||||
if ev.Type == "error" || ev.Type == "response.failed" {
|
||||
return st.failWith(ev)
|
||||
}
|
||||
// message_start 延迟到首个可见输出事件:created / reasoning 阶段不向客户端
|
||||
// 写任何字节,上游此段断流时 handler 才有降级非流式重做的无感窗口
|
||||
var events []AnthEvent
|
||||
switch ev.Type {
|
||||
case "response.output_item.added":
|
||||
if ev.Item != nil && ev.Item.Type == "function_call" {
|
||||
events = append(events, st.ensureStarted()...)
|
||||
events = append(events, st.openBlock(true, ev.Item.CallID, ev.Item.Name)...)
|
||||
st.stopReason = "tool_use"
|
||||
}
|
||||
case "response.output_text.delta":
|
||||
events = append(events, st.ensureStarted()...)
|
||||
events = append(events, st.textDelta(ev.Delta)...)
|
||||
case "response.function_call_arguments.delta":
|
||||
events = append(events, st.argsDelta(ev.Delta)...)
|
||||
case "response.completed", "response.incomplete", "response.failed":
|
||||
case "response.completed", "response.incomplete":
|
||||
st.sawTerminal = true
|
||||
st.finishFrom(ev.Response)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
// ensureStarted 在首个可见输出事件前补发 message_start(仅一次)。
|
||||
func (st *AnthRespBridge) ensureStarted() []AnthEvent {
|
||||
if st.started {
|
||||
return nil
|
||||
}
|
||||
st.started = true
|
||||
return []AnthEvent{st.startEvent()}
|
||||
}
|
||||
|
||||
// failWith 记录上游错误并产出 Anthropic error 事件(每流至多一次)。
|
||||
func (st *AnthRespBridge) failWith(ev respStreamEvent) []AnthEvent {
|
||||
if st.errMsg != "" {
|
||||
return nil
|
||||
}
|
||||
st.sawTerminal = true
|
||||
msg := ev.Message
|
||||
if ev.Type == "response.failed" {
|
||||
st.finishFrom(ev.Response)
|
||||
if m := respErrorMsg(ev.Response); m != "" {
|
||||
msg = m
|
||||
}
|
||||
}
|
||||
if msg == "" {
|
||||
msg = "上游返回错误事件 " + ev.Type
|
||||
}
|
||||
st.errMsg = msg
|
||||
return []AnthEvent{st.errorEvent()}
|
||||
}
|
||||
|
||||
// respErrorMsg 提取 response.failed 载荷中的错误消息。
|
||||
func respErrorMsg(resp *respPayload) string {
|
||||
if resp == nil || resp.Error == nil {
|
||||
return ""
|
||||
}
|
||||
return (*resp.Error)["message"]
|
||||
}
|
||||
|
||||
// errorEvent 按 Anthropic 流式协议产出 error 事件。
|
||||
func (st *AnthRespBridge) errorEvent() AnthEvent {
|
||||
return AnthEvent{Event: "error", Data: map[string]any{
|
||||
"type": "error",
|
||||
"error": map[string]string{"type": "api_error", "message": st.errMsg},
|
||||
}}
|
||||
}
|
||||
|
||||
// Err 返回上游错误消息;空串表示流正常(供调用日志)。
|
||||
func (st *AnthRespBridge) Err() string { return st.errMsg }
|
||||
|
||||
// SawTerminal 报告是否收到过终态事件;false 即上游流提前终止。
|
||||
func (st *AnthRespBridge) SawTerminal() bool { return st.sawTerminal }
|
||||
|
||||
// AnthMessageEvents 把完整 Messages 响应展开为标准事件序列,
|
||||
// 供流式上游断流后的非流式降级结果推送(客户端协议不变)。
|
||||
func AnthMessageEvents(m *aiwire.MessagesResponse) []AnthEvent {
|
||||
events := []AnthEvent{{Event: "message_start", Data: map[string]any{
|
||||
"type": "message_start",
|
||||
"message": map[string]any{
|
||||
"id": m.ID, "type": "message", "role": m.Role, "model": m.Model,
|
||||
"content": []any{}, "stop_reason": nil,
|
||||
"usage": map[string]int{"input_tokens": 0, "output_tokens": 0},
|
||||
},
|
||||
}}}
|
||||
for i, b := range m.Content {
|
||||
events = append(events, anthBlockEvents(i, b)...)
|
||||
}
|
||||
usage := map[string]int{"input_tokens": m.Usage.InputTokens, "output_tokens": m.Usage.OutputTokens}
|
||||
if m.Usage.CacheReadInputTokens > 0 {
|
||||
usage["cache_read_input_tokens"] = m.Usage.CacheReadInputTokens
|
||||
}
|
||||
events = append(events,
|
||||
AnthEvent{Event: "message_delta", Data: map[string]any{
|
||||
"type": "message_delta",
|
||||
"delta": map[string]any{"stop_reason": m.StopReason, "stop_sequence": nil},
|
||||
"usage": usage,
|
||||
}},
|
||||
AnthEvent{Event: "message_stop", Data: map[string]any{"type": "message_stop"}})
|
||||
return events
|
||||
}
|
||||
|
||||
// anthBlockEvents 把一个内容块展开为 start / delta / stop 三事件。
|
||||
func anthBlockEvents(index int, b aiwire.AnthBlock) []AnthEvent {
|
||||
var start, delta map[string]any
|
||||
if b.Type == "tool_use" {
|
||||
start = map[string]any{"type": "tool_use", "id": b.ID, "name": b.Name, "input": map[string]any{}}
|
||||
delta = map[string]any{"type": "input_json_delta", "partial_json": string(b.Input)}
|
||||
} else {
|
||||
start = map[string]any{"type": "text", "text": ""}
|
||||
delta = map[string]any{"type": "text_delta", "text": b.Text}
|
||||
}
|
||||
return []AnthEvent{
|
||||
{Event: "content_block_start", Data: map[string]any{
|
||||
"type": "content_block_start", "index": index, "content_block": start}},
|
||||
{Event: "content_block_delta", Data: map[string]any{
|
||||
"type": "content_block_delta", "index": index, "delta": delta}},
|
||||
{Event: "content_block_stop", Data: map[string]any{
|
||||
"type": "content_block_stop", "index": index}},
|
||||
}
|
||||
}
|
||||
|
||||
func (st *AnthRespBridge) textDelta(delta string) []AnthEvent {
|
||||
var events []AnthEvent
|
||||
if !st.blockOpen || st.blockIsTool {
|
||||
@@ -337,8 +446,7 @@ func (st *AnthRespBridge) finishFrom(resp *respPayload) {
|
||||
return
|
||||
}
|
||||
st.usage = anthUsageFromResp(resp.Usage)
|
||||
if resp.Status == "incomplete" && resp.IncompleteDetails != nil &&
|
||||
resp.IncompleteDetails.Reason == "max_output_tokens" {
|
||||
if respTruncated(resp) {
|
||||
st.stopReason = "max_tokens"
|
||||
}
|
||||
}
|
||||
@@ -379,7 +487,16 @@ func (st *AnthRespBridge) closeBlockEvent() AnthEvent {
|
||||
}
|
||||
|
||||
// Finish 在上游流结束后收尾:关块 → message_delta(stop_reason+usage)→ message_stop。
|
||||
// 已发过 error 事件的流不再补终态;未见终态事件即 EOF 视为上游提前终止,
|
||||
// 发 error 事件而非伪装正常结束(否则客户端拿到"成功的空消息")。
|
||||
func (st *AnthRespBridge) Finish() []AnthEvent {
|
||||
if st.errMsg != "" {
|
||||
return nil
|
||||
}
|
||||
if !st.sawTerminal {
|
||||
st.errMsg = "上游流提前终止,未返回终态事件"
|
||||
return []AnthEvent{st.errorEvent()}
|
||||
}
|
||||
var events []AnthEvent
|
||||
if !st.started {
|
||||
st.started = true
|
||||
|
||||
@@ -164,10 +164,105 @@ func TestAnthRespBridge(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthRespBridgeEmpty 断言空流也产出完整事件骨架。
|
||||
func TestAnthRespBridgeEmpty(t *testing.T) {
|
||||
// TestAnthRespBridgeFailure 断言异常流的错误透传:上游 error / response.failed
|
||||
// 事件转 Anthropic error 事件,提前 EOF(未见终态)不再伪装正常结束。
|
||||
func TestAnthRespBridgeFailure(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
lines []string
|
||||
wantKinds string
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "上游 error 事件透传",
|
||||
lines: []string{`{"type":"error","message":"model overloaded"}`},
|
||||
wantKinds: "error",
|
||||
wantErr: "model overloaded",
|
||||
},
|
||||
{
|
||||
name: "response.failed 提取错误消息",
|
||||
lines: []string{
|
||||
`{"type":"response.output_text.delta","delta":"你"}`,
|
||||
`{"type":"response.failed","response":{"status":"failed","error":{"message":"content filtered"}}}`,
|
||||
},
|
||||
wantKinds: "message_start,content_block_start,content_block_delta,error",
|
||||
wantErr: "content filtered",
|
||||
},
|
||||
{
|
||||
name: "空流提前终止",
|
||||
lines: nil,
|
||||
wantKinds: "error",
|
||||
wantErr: "上游流提前终止,未返回终态事件",
|
||||
},
|
||||
{
|
||||
name: "输出中途 EOF 无终态",
|
||||
lines: []string{
|
||||
`{"type":"response.output_text.delta","delta":"你"}`,
|
||||
},
|
||||
wantKinds: "message_start,content_block_start,content_block_delta,error",
|
||||
wantErr: "上游流提前终止,未返回终态事件",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
st := NewAnthRespBridge("msg_1", "m1")
|
||||
if got := bridgeEventTypes(st.Finish()); got != "message_start,message_delta,message_stop" {
|
||||
t.Errorf("空流事件序列 = %s", got)
|
||||
var events []AnthEvent
|
||||
for _, l := range tc.lines {
|
||||
events = append(events, st.Feed([]byte(l))...)
|
||||
}
|
||||
events = append(events, st.Finish()...)
|
||||
if got := bridgeEventTypes(events); got != tc.wantKinds {
|
||||
t.Fatalf("事件序列 = %s, want %s", got, tc.wantKinds)
|
||||
}
|
||||
if st.Err() != tc.wantErr {
|
||||
t.Fatalf("Err() = %q, want %q", st.Err(), tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRespStreamErrorMsg 断言直通流错误事件消息提取。
|
||||
func TestRespStreamErrorMsg(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
data string
|
||||
want string
|
||||
}{
|
||||
{name: "error 事件", data: `{"type":"error","message":"boom"}`, want: "boom"},
|
||||
{name: "error 无消息用占位", data: `{"type":"error"}`, want: "上游返回错误事件 error"},
|
||||
{name: "failed 事件", data: `{"type":"response.failed","response":{"error":{"message":"bad"}}}`, want: "bad"},
|
||||
{name: "正常事件返回空", data: `{"type":"response.completed","response":{}}`, want: ""},
|
||||
{name: "非 JSON 返回空", data: `<html>`, want: ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := RespStreamErrorMsg([]byte(tc.data)); got != tc.want {
|
||||
t.Fatalf("RespStreamErrorMsg = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthMessageEvents 断言非流式降级结果展开的事件序列与 usage。
|
||||
func TestAnthMessageEvents(t *testing.T) {
|
||||
msg := &aiwire.MessagesResponse{
|
||||
ID: "msg_1", Type: "message", Role: "assistant", Model: "m1",
|
||||
Content: []aiwire.AnthBlock{
|
||||
{Type: "text", Text: "好"},
|
||||
{Type: "tool_use", ID: "c1", Name: "f", Input: json.RawMessage(`{"a":1}`)},
|
||||
},
|
||||
StopReason: "tool_use",
|
||||
Usage: aiwire.AnthUsage{InputTokens: 9, OutputTokens: 3, CacheReadInputTokens: 5},
|
||||
}
|
||||
events := AnthMessageEvents(msg)
|
||||
want := "message_start,content_block_start,content_block_delta,content_block_stop," +
|
||||
"content_block_start,content_block_delta,content_block_stop,message_delta,message_stop"
|
||||
if got := bridgeEventTypes(events); got != want {
|
||||
t.Fatalf("事件序列:\n got %s\nwant %s", got, want)
|
||||
}
|
||||
delta := events[len(events)-2].Data.(map[string]any)
|
||||
usage := delta["usage"].(map[string]int)
|
||||
if usage["input_tokens"] != 9 || usage["output_tokens"] != 3 || usage["cache_read_input_tokens"] != 5 {
|
||||
t.Fatalf("usage = %+v", usage)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"oci-portal/internal/aiwire"
|
||||
)
|
||||
|
||||
// OpenAI Chat Completions ↔ OCI OpenAI 兼容面(/actions/v1/responses)直通转换。
|
||||
// 端点定位 Tier 2 兼容层(承接只会说 CC 的存量客户端),机制与 anthresponses.go
|
||||
// 同构。语义损失(README 披露):stop / seed / n / penalty 等无对应字段,忽略;
|
||||
// 上游 reasoning 输出项与增量事件丢弃;非 function 工具类型拒绝。
|
||||
|
||||
// ChatToResponsesBody 把 Chat Completions 请求转为直通 body(强制 store:false)。
|
||||
func ChatToResponsesBody(req aiwire.ChatRequest) ([]byte, error) {
|
||||
input, instructions, err := chatInputItems(req.Messages)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body := map[string]any{"model": req.Model, "input": input, "store": false}
|
||||
if instructions != "" {
|
||||
body["instructions"] = instructions
|
||||
}
|
||||
chatSampling(body, req)
|
||||
if err := chatBodyTools(body, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tf := chatTextFormat(req.ResponseFormat); tf != nil {
|
||||
body["text"] = map[string]any{"format": tf}
|
||||
}
|
||||
if req.ReasoningEffort != "" {
|
||||
body["reasoning"] = map[string]string{"effort": strings.ToLower(req.ReasoningEffort)}
|
||||
}
|
||||
if req.Stream {
|
||||
body["stream"] = true
|
||||
}
|
||||
return json.Marshal(body)
|
||||
}
|
||||
|
||||
// chatSampling 装配采样与输出预算;max_completion_tokens 优先于已弃用的 max_tokens。
|
||||
func chatSampling(body map[string]any, req aiwire.ChatRequest) {
|
||||
if req.MaxCompletionTokens != nil {
|
||||
body["max_output_tokens"] = *req.MaxCompletionTokens
|
||||
} else if req.MaxTokens != nil {
|
||||
body["max_output_tokens"] = *req.MaxTokens
|
||||
}
|
||||
if req.Temperature != nil {
|
||||
body["temperature"] = *req.Temperature
|
||||
}
|
||||
if req.TopP != nil {
|
||||
body["top_p"] = *req.TopP
|
||||
}
|
||||
if req.ParallelToolCalls != nil {
|
||||
body["parallel_tool_calls"] = *req.ParallelToolCalls
|
||||
}
|
||||
}
|
||||
|
||||
// chatBodyTools 装配工具与 tool_choice;非 function 工具类型拒绝
|
||||
// (web_search 等新能力仅在 Responses / Messages 端点供给)。
|
||||
func chatBodyTools(body map[string]any, req aiwire.ChatRequest) error {
|
||||
if len(req.Tools) == 0 {
|
||||
return nil
|
||||
}
|
||||
tools := make([]map[string]any, 0, len(req.Tools))
|
||||
for _, t := range req.Tools {
|
||||
if t.Type != "function" {
|
||||
return fmt.Errorf("不支持的工具类型 %q:该端点仅支持 function 工具", t.Type)
|
||||
}
|
||||
tools = append(tools, map[string]any{"type": "function", "name": t.Function.Name,
|
||||
"description": t.Function.Description, "parameters": t.Function.Parameters})
|
||||
}
|
||||
body["tools"] = tools
|
||||
if tc := chatRespToolChoice(req.ToolChoice); tc != nil {
|
||||
body["tool_choice"] = tc
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// chatInputItems 把消息序列展开为 Responses input 项与 instructions:
|
||||
// system/developer 文本聚为 instructions;tool 消息为 function_call_output 项;
|
||||
// 其余消息经 chatMessageItems 展开,保持相对顺序。
|
||||
func chatInputItems(messages []aiwire.ChatMessage) ([]any, string, error) {
|
||||
items := make([]any, 0, len(messages))
|
||||
var sys []string
|
||||
for _, m := range messages {
|
||||
switch m.Role {
|
||||
case "system", "developer":
|
||||
if txt := m.Content.JoinText(); txt != "" {
|
||||
sys = append(sys, txt)
|
||||
}
|
||||
case "tool":
|
||||
items = append(items, map[string]any{"type": "function_call_output",
|
||||
"call_id": m.ToolCallID, "output": m.Content.JoinText()})
|
||||
default:
|
||||
msgItems, err := chatMessageItems(m)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
items = append(items, msgItems...)
|
||||
}
|
||||
}
|
||||
return items, strings.Join(sys, "\n\n"), nil
|
||||
}
|
||||
|
||||
// chatMessageItems 把 user/assistant 消息转为 message 项;assistant 的
|
||||
// tool_calls 追加为独立 function_call 项(内容在前,与原语序一致)。
|
||||
func chatMessageItems(m aiwire.ChatMessage) ([]any, error) {
|
||||
parts, err := chatContentParts(m.Role, m.Content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]any, 0, 1+len(m.ToolCalls))
|
||||
if len(parts) > 0 {
|
||||
items = append(items, map[string]any{"role": m.Role, "content": parts})
|
||||
}
|
||||
for _, tc := range m.ToolCalls {
|
||||
items = append(items, map[string]any{"type": "function_call", "call_id": tc.ID,
|
||||
"name": tc.Function.Name, "arguments": tc.Function.Arguments})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// chatContentParts 把消息内容转为 Responses 部件(文本按角色定型,图片转 input_image)。
|
||||
func chatContentParts(role string, c aiwire.Content) ([]map[string]any, error) {
|
||||
if !c.IsArray {
|
||||
if c.Text == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return []map[string]any{respTextPart(role, c.Text)}, nil
|
||||
}
|
||||
parts := make([]map[string]any, 0, len(c.Parts))
|
||||
for _, p := range c.Parts {
|
||||
switch p.Type {
|
||||
case "", "text":
|
||||
parts = append(parts, respTextPart(role, p.Text))
|
||||
case "image_url":
|
||||
if p.ImageURL == nil || p.ImageURL.URL == "" {
|
||||
return nil, fmt.Errorf("image_url 块缺少 url")
|
||||
}
|
||||
// detail 不透传:兼容面对该字段的支持无法证实(实测期间上游视觉请求不稳,
|
||||
// 无从归因),它仅是质量提示,忽略合法且消除一个风险轴(README 披露)
|
||||
parts = append(parts, map[string]any{"type": "input_image", "image_url": p.ImageURL.URL})
|
||||
default:
|
||||
return nil, ErrAiUnsupportedBlock
|
||||
}
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
// chatRespToolChoice 映射 tool_choice:string 形态(auto/none/required)原样;
|
||||
// {"type":"function","function":{"name":N}} 拍平为 Responses 具名形态;其余忽略。
|
||||
func chatRespToolChoice(raw json.RawMessage) any {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
switch s {
|
||||
case "auto", "none", "required":
|
||||
return s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var tc struct {
|
||||
Type string `json:"type"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"function"`
|
||||
}
|
||||
if json.Unmarshal(raw, &tc) != nil || tc.Type != "function" || tc.Function.Name == "" {
|
||||
return nil
|
||||
}
|
||||
return map[string]string{"type": "function", "name": tc.Function.Name}
|
||||
}
|
||||
|
||||
// chatTextFormat 把 response_format 拍平为 text.format(json_schema 提升嵌套字段)。
|
||||
func chatTextFormat(rf *aiwire.ResponseFormat) map[string]any {
|
||||
if rf == nil || rf.Type == "" || rf.Type == "text" {
|
||||
return nil
|
||||
}
|
||||
format := map[string]any{"type": rf.Type}
|
||||
if rf.Type != "json_schema" || len(rf.JSONSchema) == 0 {
|
||||
return format
|
||||
}
|
||||
var js struct {
|
||||
Name string `json:"name"`
|
||||
Schema json.RawMessage `json:"schema"`
|
||||
Strict *bool `json:"strict"`
|
||||
}
|
||||
if json.Unmarshal(rf.JSONSchema, &js) != nil {
|
||||
return format
|
||||
}
|
||||
if js.Name != "" {
|
||||
format["name"] = js.Name
|
||||
}
|
||||
if len(js.Schema) > 0 {
|
||||
format["schema"] = js.Schema
|
||||
}
|
||||
if js.Strict != nil {
|
||||
format["strict"] = *js.Strict
|
||||
}
|
||||
return format
|
||||
}
|
||||
|
||||
// ResponsesToChat 把直通非流式响应转为 Chat Completions 响应(reasoning 项丢弃)。
|
||||
func ResponsesToChat(payload []byte, id string, created int64) (*aiwire.ChatResponse, error) {
|
||||
var resp respPayload
|
||||
if err := json.Unmarshal(payload, &resp); err != nil {
|
||||
return nil, fmt.Errorf("解析上游响应: %w", err)
|
||||
}
|
||||
msg := aiwire.ChatMessage{Role: "assistant"}
|
||||
var text strings.Builder
|
||||
for _, item := range resp.Output {
|
||||
switch item.Type {
|
||||
case "message":
|
||||
for _, part := range item.Content {
|
||||
if part.Type == "output_text" {
|
||||
text.WriteString(part.Text)
|
||||
}
|
||||
}
|
||||
case "function_call":
|
||||
msg.ToolCalls = append(msg.ToolCalls, aiwire.ToolCall{ID: item.CallID, Type: "function",
|
||||
Function: aiwire.FunctionCall{Name: item.Name, Arguments: item.Arguments}})
|
||||
}
|
||||
}
|
||||
msg.Content = aiwire.NewTextContent(text.String())
|
||||
choice := aiwire.Choice{Index: 0, Message: msg,
|
||||
FinishReason: chatFinishReason(&resp, len(msg.ToolCalls) > 0)}
|
||||
return &aiwire.ChatResponse{ID: id, Object: "chat.completion", Created: created,
|
||||
Model: resp.Model, Choices: []aiwire.Choice{choice}, Usage: usageFromResp(resp.Usage)}, nil
|
||||
}
|
||||
|
||||
// chatFinishReason 映射终态:截断优先 → length;含工具调用 → tool_calls;默认 stop。
|
||||
func chatFinishReason(resp *respPayload, hasTools bool) string {
|
||||
if respTruncated(resp) {
|
||||
return "length"
|
||||
}
|
||||
if hasTools {
|
||||
return "tool_calls"
|
||||
}
|
||||
return "stop"
|
||||
}
|
||||
|
||||
// respTruncated 报告直通响应是否因 max_output_tokens 截断。
|
||||
func respTruncated(resp *respPayload) bool {
|
||||
return resp != nil && resp.Status == "incomplete" && resp.IncompleteDetails != nil &&
|
||||
resp.IncompleteDetails.Reason == "max_output_tokens"
|
||||
}
|
||||
|
||||
// ---- Chat Completions 流式桥:直通 SSE 事件 → chat.completion.chunk 序列 ----
|
||||
|
||||
// ChatRespBridge 把直通 SSE 事件流桥接为 chunk 序列:首个增量补 role,文本与
|
||||
// 工具增量按 OpenAI 形态输出;reasoning 系列事件丢弃;[DONE] 由传输层写出。
|
||||
type ChatRespBridge struct {
|
||||
id, model string
|
||||
created int64
|
||||
includeUsage bool
|
||||
started bool
|
||||
toolIndex int
|
||||
inTool bool
|
||||
finish string
|
||||
usage *aiwire.Usage
|
||||
}
|
||||
|
||||
// NewChatRespBridge 构造桥;includeUsage 即 stream_options.include_usage。
|
||||
func NewChatRespBridge(id, model string, created int64, includeUsage bool) *ChatRespBridge {
|
||||
return &ChatRespBridge{id: id, model: model, created: created,
|
||||
includeUsage: includeUsage, toolIndex: -1, finish: "stop"}
|
||||
}
|
||||
|
||||
// Feed 消费一行 SSE data JSON,返回应立即写出的 chunk。
|
||||
func (b *ChatRespBridge) Feed(data []byte) []aiwire.ChatChunk {
|
||||
var ev respStreamEvent
|
||||
if json.Unmarshal(data, &ev) != nil {
|
||||
return nil
|
||||
}
|
||||
switch ev.Type {
|
||||
case "response.output_text.delta":
|
||||
b.inTool = false
|
||||
return []aiwire.ChatChunk{b.chunk(b.deltaWithRole(aiwire.Delta{Content: ev.Delta}), nil)}
|
||||
case "response.output_item.added":
|
||||
return b.toolOpen(ev.Item)
|
||||
case "response.function_call_arguments.delta":
|
||||
return b.argsChunk(ev.Delta)
|
||||
case "response.completed", "response.incomplete", "response.failed":
|
||||
b.finishFrom(ev.Response)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// chunk 装配一条单 choice 增量事件。
|
||||
func (b *ChatRespBridge) chunk(delta aiwire.Delta, finish *string) aiwire.ChatChunk {
|
||||
return aiwire.ChatChunk{ID: b.id, Object: "chat.completion.chunk", Created: b.created,
|
||||
Model: b.model, Choices: []aiwire.ChunkChoice{{Index: 0, Delta: delta, FinishReason: finish}}}
|
||||
}
|
||||
|
||||
// deltaWithRole 给首个增量补 role(OpenAI 首块携带 role 语义)。
|
||||
func (b *ChatRespBridge) deltaWithRole(d aiwire.Delta) aiwire.Delta {
|
||||
if !b.started {
|
||||
b.started = true
|
||||
d.Role = "assistant"
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// toolOpen 在新 function_call 输出项开始时发 id/name 增量并推进聚合 index;
|
||||
// 非工具输出项只复位增量目标。
|
||||
func (b *ChatRespBridge) toolOpen(item *respOutputItem) []aiwire.ChatChunk {
|
||||
if item == nil || item.Type != "function_call" {
|
||||
b.inTool = false
|
||||
return nil
|
||||
}
|
||||
b.toolIndex++
|
||||
b.inTool = true
|
||||
b.finish = "tool_calls"
|
||||
d := aiwire.Delta{ToolCalls: []aiwire.ToolCallDelta{{Index: b.toolIndex, ID: item.CallID,
|
||||
Type: "function", Function: aiwire.FunctionCallDelta{Name: item.Name}}}}
|
||||
return []aiwire.ChatChunk{b.chunk(b.deltaWithRole(d), nil)}
|
||||
}
|
||||
|
||||
// argsChunk 输出当前工具的实参增量(仅在工具输出项进行中)。
|
||||
func (b *ChatRespBridge) argsChunk(delta string) []aiwire.ChatChunk {
|
||||
if !b.inTool {
|
||||
return nil
|
||||
}
|
||||
d := aiwire.Delta{ToolCalls: []aiwire.ToolCallDelta{{Index: b.toolIndex,
|
||||
Function: aiwire.FunctionCallDelta{Arguments: delta}}}}
|
||||
return []aiwire.ChatChunk{b.chunk(d, nil)}
|
||||
}
|
||||
|
||||
// finishFrom 记录终态 usage 与截断语义(max_output_tokens → length)。
|
||||
func (b *ChatRespBridge) finishFrom(resp *respPayload) {
|
||||
if resp == nil {
|
||||
return
|
||||
}
|
||||
b.usage = usageFromResp(resp.Usage)
|
||||
if respTruncated(resp) {
|
||||
b.finish = "length"
|
||||
}
|
||||
}
|
||||
|
||||
// Finish 在上游流结束后收尾:终块带 finish_reason;include_usage 时追加 usage 块
|
||||
// (choices 为空数组,OpenAI 规范形态;上游未给 usage 时输出零值)。
|
||||
func (b *ChatRespBridge) Finish() []aiwire.ChatChunk {
|
||||
chunks := []aiwire.ChatChunk{b.chunk(b.deltaWithRole(aiwire.Delta{}), &b.finish)}
|
||||
if !b.includeUsage {
|
||||
return chunks
|
||||
}
|
||||
usage := b.usage
|
||||
if usage == nil {
|
||||
usage = &aiwire.Usage{}
|
||||
}
|
||||
return append(chunks, aiwire.ChatChunk{ID: b.id, Object: "chat.completion.chunk",
|
||||
Created: b.created, Model: b.model, Choices: []aiwire.ChunkChoice{}, Usage: usage})
|
||||
}
|
||||
|
||||
// Usage 返回聚合到的用量(供调用日志),上游未报告时为 nil。
|
||||
func (b *ChatRespBridge) Usage() *aiwire.Usage { return b.usage }
|
||||
|
||||
// ChatResponseChunks 把完整 Chat 响应展开为 chunk 序列(内容与工具调用 →
|
||||
// 终块 → 可选 usage 块),供流式上游断流后的非流式降级结果推送。
|
||||
func ChatResponseChunks(resp *aiwire.ChatResponse, includeUsage bool) []aiwire.ChatChunk {
|
||||
if len(resp.Choices) == 0 {
|
||||
return nil
|
||||
}
|
||||
choice := resp.Choices[0]
|
||||
mk := func(delta aiwire.Delta, finish *string) aiwire.ChatChunk {
|
||||
return aiwire.ChatChunk{ID: resp.ID, Object: "chat.completion.chunk", Created: resp.Created,
|
||||
Model: resp.Model, Choices: []aiwire.ChunkChoice{{Index: 0, Delta: delta, FinishReason: finish}}}
|
||||
}
|
||||
delta := aiwire.Delta{Role: "assistant", Content: choice.Message.Content.Text}
|
||||
for i, tc := range choice.Message.ToolCalls {
|
||||
delta.ToolCalls = append(delta.ToolCalls, aiwire.ToolCallDelta{Index: i, ID: tc.ID,
|
||||
Type: "function", Function: aiwire.FunctionCallDelta{Name: tc.Function.Name, Arguments: tc.Function.Arguments}})
|
||||
}
|
||||
finish := choice.FinishReason
|
||||
chunks := []aiwire.ChatChunk{mk(delta, nil), mk(aiwire.Delta{}, &finish)}
|
||||
if includeUsage {
|
||||
usage := resp.Usage
|
||||
if usage == nil {
|
||||
usage = &aiwire.Usage{}
|
||||
}
|
||||
chunks = append(chunks, aiwire.ChatChunk{ID: resp.ID, Object: "chat.completion.chunk",
|
||||
Created: resp.Created, Model: resp.Model, Choices: []aiwire.ChunkChoice{}, Usage: usage})
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"oci-portal/internal/aiwire"
|
||||
)
|
||||
|
||||
func mustChatReq(t *testing.T, raw string) aiwire.ChatRequest {
|
||||
t.Helper()
|
||||
var req aiwire.ChatRequest
|
||||
if err := json.Unmarshal([]byte(raw), &req); err != nil {
|
||||
t.Fatalf("解析请求: %v", err)
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
func mustChatBody(t *testing.T, raw string) map[string]any {
|
||||
t.Helper()
|
||||
payload, err := ChatToResponsesBody(mustChatReq(t, raw))
|
||||
if err != nil {
|
||||
t.Fatalf("ChatToResponsesBody: %v", err)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(payload, &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// TestChatToResponsesBody 断言消息展开、instructions 聚合、工具与顶层字段装配。
|
||||
func TestChatToResponsesBody(t *testing.T) {
|
||||
body := mustChatBody(t, `{
|
||||
"model": "xai.grok-4.3", "max_tokens": 64, "max_completion_tokens": 128,
|
||||
"temperature": 0.5, "top_p": 0.9, "parallel_tool_calls": false, "stream": true,
|
||||
"reasoning_effort": "HIGH",
|
||||
"messages": [
|
||||
{"role": "system", "content": "你是助手"},
|
||||
{"role": "developer", "content": [{"type": "text", "text": "简洁作答"}]},
|
||||
{"role": "user", "content": "东京天气?"},
|
||||
{"role": "assistant", "content": "查询中", "tool_calls": [
|
||||
{"id": "t1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"东京\"}"}}
|
||||
]},
|
||||
{"role": "tool", "tool_call_id": "t1", "content": "晴 25 度"},
|
||||
{"role": "user", "content": "继续"}
|
||||
],
|
||||
"tools": [{"type": "function", "function": {"name": "get_weather", "description": "查天气", "parameters": {"type": "object"}}}],
|
||||
"tool_choice": "required"
|
||||
}`)
|
||||
if body["model"] != "xai.grok-4.3" || body["store"] != false || body["stream"] != true {
|
||||
t.Fatalf("顶层字段装配错误: %v", body)
|
||||
}
|
||||
if body["max_output_tokens"] != float64(128) {
|
||||
t.Fatalf("max_output_tokens = %v, want 128(max_completion_tokens 优先)", body["max_output_tokens"])
|
||||
}
|
||||
if body["instructions"] != "你是助手\n\n简洁作答" {
|
||||
t.Fatalf("instructions = %v", body["instructions"])
|
||||
}
|
||||
if body["temperature"] != 0.5 || body["top_p"] != 0.9 || body["parallel_tool_calls"] != false {
|
||||
t.Fatalf("采样字段装配错误: %v", body)
|
||||
}
|
||||
if body["tool_choice"] != "required" {
|
||||
t.Fatalf("tool_choice = %v", body["tool_choice"])
|
||||
}
|
||||
if reasoning, _ := body["reasoning"].(map[string]any); reasoning["effort"] != "high" {
|
||||
t.Fatalf("effort = %v, want high(小写透传)", body["reasoning"])
|
||||
}
|
||||
kinds := chatInputKinds(t, body)
|
||||
want := "message/user,message/assistant,function_call,function_call_output,message/user"
|
||||
if kinds != want {
|
||||
t.Fatalf("input 顺序 = %s, want %s", kinds, want)
|
||||
}
|
||||
tools, _ := body["tools"].([]any)
|
||||
tool, _ := tools[0].(map[string]any)
|
||||
if tool["type"] != "function" || tool["name"] != "get_weather" {
|
||||
t.Fatalf("工具应拍平为 Responses 形态: %v", tool)
|
||||
}
|
||||
}
|
||||
|
||||
func chatInputKinds(t *testing.T, body map[string]any) string {
|
||||
t.Helper()
|
||||
input, _ := body["input"].([]any)
|
||||
kinds := make([]string, 0, len(input))
|
||||
for _, it := range input {
|
||||
m := it.(map[string]any)
|
||||
if ty, ok := m["type"].(string); ok {
|
||||
kinds = append(kinds, ty)
|
||||
} else {
|
||||
kinds = append(kinds, "message/"+m["role"].(string))
|
||||
}
|
||||
}
|
||||
return strings.Join(kinds, ",")
|
||||
}
|
||||
|
||||
// TestChatToResponsesBodyContent 断言文本部件按角色定型与图片装配/拒绝。
|
||||
func TestChatToResponsesBodyContent(t *testing.T) {
|
||||
body := mustChatBody(t, `{"model":"m","messages":[
|
||||
{"role":"user","content":[
|
||||
{"type":"text","text":"看图"},
|
||||
{"type":"image_url","image_url":{"url":"data:image/png;base64,QUJD"}}]},
|
||||
{"role":"assistant","content":"这是猫"}]}`)
|
||||
raw, _ := json.Marshal(body["input"])
|
||||
if !strings.Contains(string(raw), `"input_image"`) ||
|
||||
!strings.Contains(string(raw), "data:image/png;base64,QUJD") {
|
||||
t.Fatalf("图片应转 input_image: %s", raw)
|
||||
}
|
||||
if !strings.Contains(string(raw), `"output_text"`) {
|
||||
t.Fatalf("assistant 历史文本应为 output_text 部件: %s", raw)
|
||||
}
|
||||
|
||||
for name, msg := range map[string]string{
|
||||
"audio 块": `{"role":"user","content":[{"type":"input_audio","input_audio":{}}]}`,
|
||||
"图片缺 url": `{"role":"user","content":[{"type":"image_url","image_url":{}}]}`,
|
||||
} {
|
||||
raw := `{"model":"m","messages":[` + msg + `]}`
|
||||
if _, err := ChatToResponsesBody(mustChatReq(t, raw)); err == nil {
|
||||
t.Errorf("%s 应拒绝", name)
|
||||
}
|
||||
}
|
||||
badTool := mustChatReq(t, `{"model":"m","messages":[{"role":"user","content":"hi"}],
|
||||
"tools":[{"type":"web_search","function":{}}]}`)
|
||||
if _, err := ChatToResponsesBody(badTool); err == nil {
|
||||
t.Error("非 function 工具类型应拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatRespToolChoice 断言 tool_choice 各形态映射。
|
||||
func TestChatRespToolChoice(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, raw string
|
||||
want any
|
||||
}{
|
||||
{"auto", `"auto"`, "auto"},
|
||||
{"none", `"none"`, "none"},
|
||||
{"required", `"required"`, "required"},
|
||||
{"具名 function", `{"type":"function","function":{"name":"f1"}}`,
|
||||
map[string]string{"type": "function", "name": "f1"}},
|
||||
{"未知 string", `"whatever"`, nil},
|
||||
{"缺 name", `{"type":"function","function":{}}`, nil},
|
||||
{"空", ``, nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := chatRespToolChoice(json.RawMessage(tc.raw))
|
||||
if gotMap, ok := got.(map[string]string); ok {
|
||||
wantMap, _ := tc.want.(map[string]string)
|
||||
if wantMap == nil || gotMap["name"] != wantMap["name"] {
|
||||
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatTextFormat 断言 response_format 拍平映射。
|
||||
func TestChatTextFormat(t *testing.T) {
|
||||
if got := chatTextFormat(nil); got != nil {
|
||||
t.Errorf("nil 应不下发: %v", got)
|
||||
}
|
||||
if got := chatTextFormat(&aiwire.ResponseFormat{Type: "text"}); got != nil {
|
||||
t.Errorf("text 应不下发: %v", got)
|
||||
}
|
||||
if got := chatTextFormat(&aiwire.ResponseFormat{Type: "json_object"}); got["type"] != "json_object" {
|
||||
t.Errorf("json_object: %v", got)
|
||||
}
|
||||
got := chatTextFormat(&aiwire.ResponseFormat{Type: "json_schema",
|
||||
JSONSchema: json.RawMessage(`{"name":"out","schema":{"type":"object"},"strict":true}`)})
|
||||
if got["type"] != "json_schema" || got["name"] != "out" || got["strict"] != true {
|
||||
t.Errorf("json_schema 应提升嵌套字段: %v", got)
|
||||
}
|
||||
if _, ok := got["schema"]; !ok {
|
||||
t.Errorf("schema 缺失: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResponsesToChat 断言文本聚合、tool_calls、finish_reason 与 usage 回转。
|
||||
func TestResponsesToChat(t *testing.T) {
|
||||
payload := []byte(`{"model":"xai.grok-4.3","status":"completed","output":[
|
||||
{"type":"reasoning","summary":[]},
|
||||
{"type":"message","content":[{"type":"output_text","text":"你"},{"type":"output_text","text":"好"}]},
|
||||
{"type":"function_call","call_id":"c1","name":"get_weather","arguments":"{\"city\":\"东京\"}"}],
|
||||
"usage":{"input_tokens":10,"output_tokens":5,"total_tokens":15,"input_tokens_details":{"cached_tokens":4}}}`)
|
||||
out, err := ResponsesToChat(payload, "chatcmpl-1", 1700000000)
|
||||
if err != nil {
|
||||
t.Fatalf("ResponsesToChat: %v", err)
|
||||
}
|
||||
if out.Object != "chat.completion" || out.ID != "chatcmpl-1" || out.Created != 1700000000 {
|
||||
t.Fatalf("响应骨架错误: %+v", out)
|
||||
}
|
||||
msg := out.Choices[0].Message
|
||||
if msg.Role != "assistant" || msg.Content.JoinText() != "你好" {
|
||||
t.Fatalf("content 装配错误: %+v", msg)
|
||||
}
|
||||
if len(msg.ToolCalls) != 1 || msg.ToolCalls[0].ID != "c1" ||
|
||||
msg.ToolCalls[0].Function.Arguments != `{"city":"东京"}` {
|
||||
t.Fatalf("tool_calls 装配错误: %+v", msg.ToolCalls)
|
||||
}
|
||||
if out.Choices[0].FinishReason != "tool_calls" {
|
||||
t.Fatalf("finish_reason = %s, want tool_calls", out.Choices[0].FinishReason)
|
||||
}
|
||||
if out.Usage.PromptTokens != 10 || out.Usage.CompletionTokens != 5 || out.Usage.CachedTokens() != 4 {
|
||||
t.Fatalf("usage = %+v", out.Usage)
|
||||
}
|
||||
|
||||
trunc := []byte(`{"model":"m","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},
|
||||
"output":[{"type":"message","content":[{"type":"output_text","text":"半"}]}]}`)
|
||||
out2, err := ResponsesToChat(trunc, "chatcmpl-2", 1)
|
||||
if err != nil || out2.Choices[0].FinishReason != "length" {
|
||||
t.Fatalf("截断 finish_reason = %+v, %v", out2.Choices, err)
|
||||
}
|
||||
if out2.Usage != nil {
|
||||
t.Fatalf("无 usage 时应为 nil: %+v", out2.Usage)
|
||||
}
|
||||
}
|
||||
|
||||
func chatChunkShapes(chunks []aiwire.ChatChunk) string {
|
||||
kinds := make([]string, 0, len(chunks))
|
||||
for _, ch := range chunks {
|
||||
switch {
|
||||
case len(ch.Choices) == 0:
|
||||
kinds = append(kinds, "usage")
|
||||
case ch.Choices[0].FinishReason != nil:
|
||||
kinds = append(kinds, "finish:"+*ch.Choices[0].FinishReason)
|
||||
case len(ch.Choices[0].Delta.ToolCalls) > 0:
|
||||
kinds = append(kinds, "tool")
|
||||
case ch.Choices[0].Delta.Role != "":
|
||||
kinds = append(kinds, "role+text")
|
||||
default:
|
||||
kinds = append(kinds, "text")
|
||||
}
|
||||
}
|
||||
return strings.Join(kinds, ",")
|
||||
}
|
||||
|
||||
// TestChatRespBridge 断言流桥:首块 role、文本与工具增量、reasoning 丢弃、usage 块。
|
||||
func TestChatRespBridge(t *testing.T) {
|
||||
b := NewChatRespBridge("chatcmpl-1", "m1", 1700000000, true)
|
||||
var chunks []aiwire.ChatChunk
|
||||
feed := func(lines ...string) {
|
||||
for _, l := range lines {
|
||||
chunks = append(chunks, b.Feed([]byte(l))...)
|
||||
}
|
||||
}
|
||||
feed(`{"type":"response.created","response":{"model":"m1"}}`,
|
||||
`{"type":"response.reasoning_text.delta","delta":"思考中"}`,
|
||||
`{"type":"response.output_text.delta","delta":"你"}`,
|
||||
`{"type":"response.output_text.delta","delta":"好"}`,
|
||||
`{"type":"response.output_item.added","item":{"type":"function_call","call_id":"c1","name":"f"}}`,
|
||||
`{"type":"response.function_call_arguments.delta","delta":"{\"a\":"}`,
|
||||
`{"type":"response.function_call_arguments.delta","delta":"1}"}`,
|
||||
`{"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":8,"output_tokens":4,"total_tokens":12}}}`)
|
||||
chunks = append(chunks, b.Finish()...)
|
||||
|
||||
got := chatChunkShapes(chunks)
|
||||
want := "role+text,text,tool,tool,tool,finish:tool_calls,usage"
|
||||
if got != want {
|
||||
t.Fatalf("chunk 序列:\n got %s\nwant %s", got, want)
|
||||
}
|
||||
if chunks[0].Choices[0].Delta.Role != "assistant" || chunks[0].Choices[0].Delta.Content != "你" {
|
||||
t.Fatalf("首块应含 role 与文本: %+v", chunks[0].Choices[0].Delta)
|
||||
}
|
||||
tool := chunks[2].Choices[0].Delta.ToolCalls[0]
|
||||
if tool.Index != 0 || tool.ID != "c1" || tool.Function.Name != "f" {
|
||||
t.Fatalf("工具首块 = %+v", tool)
|
||||
}
|
||||
args := chunks[3].Choices[0].Delta.ToolCalls[0].Function.Arguments +
|
||||
chunks[4].Choices[0].Delta.ToolCalls[0].Function.Arguments
|
||||
if args != `{"a":1}` {
|
||||
t.Fatalf("实参增量聚合 = %s", args)
|
||||
}
|
||||
last := chunks[len(chunks)-1]
|
||||
if last.Usage == nil || last.Usage.PromptTokens != 8 || len(last.Choices) != 0 {
|
||||
t.Fatalf("usage 块 = %+v", last)
|
||||
}
|
||||
if b.Usage().TotalTokens != 12 {
|
||||
t.Fatalf("Usage() = %+v", b.Usage())
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatRespBridgeVariants 断言 include_usage 关闭、截断与空流的收尾形态。
|
||||
func TestChatRespBridgeVariants(t *testing.T) {
|
||||
noUsage := NewChatRespBridge("c", "m", 1, false)
|
||||
noUsage.Feed([]byte(`{"type":"response.output_text.delta","delta":"x"}`))
|
||||
noUsage.Feed([]byte(`{"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}}`))
|
||||
if got := chatChunkShapes(noUsage.Finish()); got != "finish:length" {
|
||||
t.Errorf("截断且不带 usage 块: %s", got)
|
||||
}
|
||||
|
||||
empty := NewChatRespBridge("c", "m", 1, false)
|
||||
fin := empty.Finish()
|
||||
if got := chatChunkShapes(fin); got != "finish:stop" {
|
||||
t.Errorf("空流收尾 = %s", got)
|
||||
}
|
||||
if fin[0].Choices[0].Delta.Role != "assistant" {
|
||||
t.Errorf("空流终块应补 role: %+v", fin[0].Choices[0].Delta)
|
||||
}
|
||||
}
|
||||
+113
-16
@@ -57,9 +57,6 @@ type LogEventService struct {
|
||||
|
||||
relayPollTick time.Duration // 订阅确认轮询间隔,零值用默认
|
||||
relayPollTimeout time.Duration // 订阅确认轮询上限,零值用默认
|
||||
|
||||
alertMu sync.Mutex // 保护告警规则冷却表
|
||||
alertSentAt map[uint]time.Time // 规则 ID → 上次告警时刻(阈值型规则冷却)
|
||||
}
|
||||
|
||||
// NewLogEventService 组装依赖;调用 StartParser / StartCleanup 后台协程后生效。
|
||||
@@ -373,20 +370,18 @@ func (s *LogEventService) parseOnce(ctx context.Context) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
rules := s.loadEnabledAlertRules(ctx)
|
||||
for i := range events {
|
||||
s.processLogEvent(ctx, &events[i], rules)
|
||||
s.processLogEvent(ctx, &events[i])
|
||||
}
|
||||
}
|
||||
|
||||
// processLogEvent 仅在条件更新命中原行后触发通知,删除并发胜出时静默跳过。
|
||||
func (s *LogEventService) processLogEvent(ctx context.Context, event *model.LogEvent, rules []model.AlertRule) {
|
||||
func (s *LogEventService) processLogEvent(ctx context.Context, event *model.LogEvent) {
|
||||
parsed := parseLogEvent([]byte(event.Payload))
|
||||
if !s.updateParsedEvent(ctx, event, parsed) {
|
||||
return
|
||||
}
|
||||
s.notifyCritical(ctx, event, parsed)
|
||||
s.matchAlertRules(ctx, rules, event, parsed)
|
||||
}
|
||||
|
||||
// updateParsedEvent 用条件 UPDATE 禁止 Save 在删除后隐式重建事件。
|
||||
@@ -418,21 +413,44 @@ type onsEnvelope struct {
|
||||
Source string `json:"source"`
|
||||
EventTime string `json:"eventTime"`
|
||||
ResourceName string `json:"resourceName"`
|
||||
Message string `json:"message"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
Identity *onsIdentity `json:"identity"`
|
||||
AdditionalDetails *onsAddDetails `json:"additionalDetails"`
|
||||
StateChange *onsStateChange `json:"stateChange"`
|
||||
}
|
||||
|
||||
// onsIdentity 是 Audit 事件 data.identity 中与展示相关的字段。
|
||||
type onsIdentity struct {
|
||||
IPAddress string `json:"ipAddress"`
|
||||
PrincipalName string `json:"principalName"`
|
||||
}
|
||||
|
||||
// parsedEvent 是从消息原文提取的展示字段集;ResourceName 仅供 P2 推送文案,不落库。
|
||||
// onsAddDetails 是 IDCS 登录类事件 data.additionalDetails 的补充字段;
|
||||
// AuditEventMapValue 为嵌套的 JSON 字符串(含 eventId 成败与失败原因)。
|
||||
type onsAddDetails struct {
|
||||
ActorName string `json:"actorName"`
|
||||
ClientIP string `json:"clientIp"`
|
||||
AuditEventMapValue string `json:"auditEventMapValue"`
|
||||
}
|
||||
|
||||
// onsStateChange 承载 Audit v2 的资源变更快照;description 供策略类事件推送文案。
|
||||
type onsStateChange struct {
|
||||
Current struct {
|
||||
Description string `json:"description"`
|
||||
} `json:"current"`
|
||||
}
|
||||
|
||||
// parsedEvent 是从消息原文提取的展示字段集;ResourceName/Actor/Outcome/Detail
|
||||
// 仅供 P2 推送文案,不落库。
|
||||
type parsedEvent struct {
|
||||
EventType string
|
||||
Source string
|
||||
SourceIP string
|
||||
ResourceName string
|
||||
Actor string // 操作者(identity.principalName,登录事件回退 actorName)
|
||||
Outcome string // 成功 / 失败 / 空(判读不出)
|
||||
Detail string // 补充说明(策略描述、登录失败原因等)
|
||||
EventTime *time.Time
|
||||
}
|
||||
|
||||
@@ -455,7 +473,7 @@ func parseLogEvent(payload []byte) parsedEvent {
|
||||
return envelopeFields(env)
|
||||
}
|
||||
|
||||
// mergeEnvelope 外层缺失字段时以 data 内层补齐(Audit 的 identity 在内层)。
|
||||
// mergeEnvelope 外层缺失字段时以 data 内层补齐(Audit 的 identity 等在内层)。
|
||||
func mergeEnvelope(outer, inner onsEnvelope) onsEnvelope {
|
||||
if outer.EventType == "" {
|
||||
outer.EventType = inner.EventType
|
||||
@@ -472,13 +490,22 @@ func mergeEnvelope(outer, inner onsEnvelope) onsEnvelope {
|
||||
if outer.ResourceName == "" {
|
||||
outer.ResourceName = inner.ResourceName
|
||||
}
|
||||
if outer.Message == "" {
|
||||
outer.Message = inner.Message
|
||||
}
|
||||
if outer.Identity == nil {
|
||||
outer.Identity = inner.Identity
|
||||
}
|
||||
if outer.AdditionalDetails == nil {
|
||||
outer.AdditionalDetails = inner.AdditionalDetails
|
||||
}
|
||||
if outer.StateChange == nil {
|
||||
outer.StateChange = inner.StateChange
|
||||
}
|
||||
return outer
|
||||
}
|
||||
|
||||
// envelopeFields 收敛字段别名并解析事件时间。
|
||||
// envelopeFields 收敛字段别名并解析事件时间与推送用补充字段。
|
||||
func envelopeFields(env onsEnvelope) parsedEvent {
|
||||
eventType := env.EventType
|
||||
if eventType == "" {
|
||||
@@ -490,19 +517,81 @@ func envelopeFields(env onsEnvelope) parsedEvent {
|
||||
eventTime = &ts
|
||||
}
|
||||
}
|
||||
ip := ""
|
||||
if env.Identity != nil {
|
||||
ip = env.Identity.IPAddress
|
||||
}
|
||||
outcome, detail := envOutcome(env)
|
||||
return parsedEvent{
|
||||
EventType: clip(eventType, 128),
|
||||
Source: clip(env.Source, 64),
|
||||
SourceIP: clip(ip, 64),
|
||||
SourceIP: clip(envIP(env), 64),
|
||||
ResourceName: clip(env.ResourceName, 128),
|
||||
Actor: clipRunes(envActor(env), 64),
|
||||
Outcome: outcome,
|
||||
Detail: clipRunes(detail, 200),
|
||||
EventTime: eventTime,
|
||||
}
|
||||
}
|
||||
|
||||
// envIP 取发起方 IP:Audit 的 identity.ipAddress,登录事件回退 additionalDetails.clientIp。
|
||||
func envIP(env onsEnvelope) string {
|
||||
if env.Identity != nil && env.Identity.IPAddress != "" {
|
||||
return env.Identity.IPAddress
|
||||
}
|
||||
if env.AdditionalDetails != nil {
|
||||
return env.AdditionalDetails.ClientIP
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// envActor 取操作者:Audit 的 identity.principalName,登录事件回退 additionalDetails.actorName。
|
||||
func envActor(env onsEnvelope) string {
|
||||
if env.Identity != nil && env.Identity.PrincipalName != "" {
|
||||
return env.Identity.PrincipalName
|
||||
}
|
||||
if env.AdditionalDetails != nil {
|
||||
return env.AdditionalDetails.ActorName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// envOutcome 判读事件成败与补充说明:登录事件解析 auditEventMapValue;其余
|
||||
// Audit 事件看 message 后缀,补充说明取 stateChange.current.description(策略描述)。
|
||||
func envOutcome(env onsEnvelope) (outcome, detail string) {
|
||||
if env.StateChange != nil {
|
||||
detail = env.StateChange.Current.Description
|
||||
}
|
||||
if env.AdditionalDetails != nil && env.AdditionalDetails.AuditEventMapValue != "" {
|
||||
return ssoOutcome(env.AdditionalDetails.AuditEventMapValue, detail)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(env.Message, " succeeded"):
|
||||
outcome = "成功"
|
||||
case strings.HasSuffix(env.Message, " failed"):
|
||||
outcome = "失败"
|
||||
}
|
||||
return outcome, detail
|
||||
}
|
||||
|
||||
// ssoOutcome 解析 IDCS 审计负载(JSON 字符串):eventId 含 success/failure 定成败,
|
||||
// 失败时以其 message 作为原因说明。
|
||||
func ssoOutcome(raw, detail string) (string, string) {
|
||||
var ev struct {
|
||||
EventID string `json:"eventId"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if json.Unmarshal([]byte(raw), &ev) != nil {
|
||||
return "", detail
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(ev.EventID, "success"):
|
||||
return "成功", detail
|
||||
case strings.Contains(ev.EventID, "failure"):
|
||||
if ev.Message != "" {
|
||||
detail = ev.Message
|
||||
}
|
||||
return "失败", detail
|
||||
}
|
||||
return "", detail
|
||||
}
|
||||
|
||||
// clip 按模型列宽截断解析出的字段。
|
||||
func clip(s string, max int) string {
|
||||
if len(s) > max {
|
||||
@@ -511,6 +600,15 @@ func clip(s string, max int) string {
|
||||
return s
|
||||
}
|
||||
|
||||
// clipRunes 按字符数截断(通知文案用,中文安全)。
|
||||
func clipRunes(s string, max int) string {
|
||||
r := []rune(s)
|
||||
if len(r) > max {
|
||||
return string(r[:max])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// StartCleanup 启动周期清理:启动即清一次,之后每 24h 一次,随 ctx 取消退出。
|
||||
func (s *LogEventService) StartCleanup(ctx context.Context) {
|
||||
s.wg.Add(1)
|
||||
@@ -535,7 +633,6 @@ func (s *LogEventService) cleanupOnce(ctx context.Context) {
|
||||
if err := s.cleanup(ctx, logEventRetention, logEventMaxRows); err != nil {
|
||||
log.Printf("log event cleanup: %v", err)
|
||||
}
|
||||
s.cleanupAlertHits(ctx)
|
||||
}
|
||||
|
||||
// cleanup 先删过期记录,再对超量部分删最旧;阈值参数化便于测试。
|
||||
|
||||
@@ -30,8 +30,7 @@ func newLogEventEnv(t *testing.T) (*LogEventService, *gorm.DB, uint) {
|
||||
t.Fatalf("db handle: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
if err := db.AutoMigrate(&model.Setting{}, &model.OciConfig{}, &model.LogEvent{},
|
||||
&model.AlertRule{}, &model.AlertRuleHit{}); err != nil {
|
||||
if err := db.AutoMigrate(&model.Setting{}, &model.OciConfig{}, &model.LogEvent{}); err != nil {
|
||||
t.Fatalf("auto migrate: %v", err)
|
||||
}
|
||||
cfg := model.OciConfig{Alias: "测试租户"}
|
||||
@@ -246,6 +245,9 @@ func TestParseLogEvent(t *testing.T) {
|
||||
wantSource string
|
||||
wantIP string
|
||||
wantTime bool
|
||||
wantActor string
|
||||
wantOutcome string
|
||||
wantDetail string
|
||||
}{
|
||||
{
|
||||
name: "CloudEvents 单事件",
|
||||
@@ -283,6 +285,29 @@ func TestParseLogEvent(t *testing.T) {
|
||||
payload: `{"eventType":"x","data":{"identity":{}}}`,
|
||||
wantType: "x",
|
||||
},
|
||||
{
|
||||
name: "Audit v2 提取操作者成败与策略描述",
|
||||
payload: `{"eventType":"com.oraclecloud.identityControlPlane.CreatePolicy","data":{
|
||||
"identity":{"principalName":"Alfonso Garcia","ipAddress":"129.159.43.9"},
|
||||
"message":"ociportal-logs-sch CreatePolicy succeeded",
|
||||
"stateChange":{"current":{"description":"允许 Connector 发布到 ONS"}}}}`,
|
||||
wantType: "com.oraclecloud.identityControlPlane.CreatePolicy", wantIP: "129.159.43.9",
|
||||
wantActor: "Alfonso Garcia", wantOutcome: "成功", wantDetail: "允许 Connector 发布到 ONS",
|
||||
},
|
||||
{
|
||||
name: "IDCS 登录失败提取用户 IP 与原因",
|
||||
payload: `{"eventType":"com.oraclecloud.IdentitySignOn.InteractiveLogin","data":{
|
||||
"additionalDetails":{"actorName":"oci","clientIp":"155.117.82.111",
|
||||
"auditEventMapValue":"{\"eventId\":\"sso.authentication.failure\",\"message\":\"Authentication failure : incorrect password.\"}"}}}`,
|
||||
wantType: "com.oraclecloud.IdentitySignOn.InteractiveLogin", wantIP: "155.117.82.111",
|
||||
wantActor: "oci", wantOutcome: "失败", wantDetail: "Authentication failure : incorrect password.",
|
||||
},
|
||||
{
|
||||
name: "message failed 后缀判失败",
|
||||
payload: `{"eventType":"x","data":{"message":"vm TerminateInstance failed"}}`,
|
||||
wantType: "x",
|
||||
wantOutcome: "失败",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -291,6 +316,10 @@ func TestParseLogEvent(t *testing.T) {
|
||||
t.Errorf("parse = (%q,%q,%q), want (%q,%q,%q)",
|
||||
got.EventType, got.Source, got.SourceIP, tt.wantType, tt.wantSource, tt.wantIP)
|
||||
}
|
||||
if got.Actor != tt.wantActor || got.Outcome != tt.wantOutcome || got.Detail != tt.wantDetail {
|
||||
t.Errorf("推送字段 = (%q,%q,%q), want (%q,%q,%q)",
|
||||
got.Actor, got.Outcome, got.Detail, tt.wantActor, tt.wantOutcome, tt.wantDetail)
|
||||
}
|
||||
if (got.EventTime != nil) != tt.wantTime {
|
||||
t.Errorf("eventTime present = %v, want %v", got.EventTime != nil, tt.wantTime)
|
||||
}
|
||||
|
||||
@@ -322,12 +322,34 @@ func relayEventShortName(eventType string) string {
|
||||
}
|
||||
|
||||
// criticalEventVars 判定关键事件并生成模板变量;非关键事件 ok 为 false。
|
||||
// actor/ip/outcome/resource 缺失时兜底 —,detail 包装为独立行(空则不占行)。
|
||||
func criticalEventVars(alias string, p parsedEvent) (map[string]string, bool) {
|
||||
name := relayEventShortName(p.EventType)
|
||||
if name == "" || !relayCriticalSet[name] {
|
||||
return nil, false
|
||||
}
|
||||
return map[string]string{"tenant": alias, "event": name, "resource": p.ResourceName}, true
|
||||
return map[string]string{
|
||||
"tenant": alias, "event": name,
|
||||
"resource": orDash(p.ResourceName), "actor": orDash(p.Actor),
|
||||
"ip": orDash(p.SourceIP), "outcome": orDash(p.Outcome),
|
||||
"detail": detailLine(p.Detail),
|
||||
}, true
|
||||
}
|
||||
|
||||
// orDash 空值兜底为 —,避免模板出现悬空标签。
|
||||
func orDash(v string) string {
|
||||
if v == "" {
|
||||
return "—"
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// detailLine 把补充说明包装为独立行;为空时不产生多余空行。
|
||||
func detailLine(v string) string {
|
||||
if v == "" {
|
||||
return ""
|
||||
}
|
||||
return "\n" + v
|
||||
}
|
||||
|
||||
// notifyCritical 对关键事件推送告警;依赖未注入或对应子类开关关闭时跳过。
|
||||
|
||||
@@ -316,23 +316,33 @@ func TestCriticalEventText(t *testing.T) {
|
||||
name string
|
||||
event parsedEvent
|
||||
wantOK bool
|
||||
wantText string
|
||||
want map[string]string
|
||||
}{
|
||||
{
|
||||
name: "实例终止命中",
|
||||
event: parsedEvent{EventType: "com.oraclecloud.ComputeApi.TerminateInstance", ResourceName: "vm-1"},
|
||||
name: "实例终止含操作者与成败",
|
||||
event: parsedEvent{EventType: "com.oraclecloud.ComputeApi.TerminateInstance",
|
||||
ResourceName: "vm-1", Actor: "demo@example.com", SourceIP: "203.0.113.8", Outcome: "成功"},
|
||||
wantOK: true,
|
||||
wantText: "☁️ 云端事件:免费01 TerminateInstance vm-1",
|
||||
want: map[string]string{"event": "TerminateInstance", "resource": "vm-1",
|
||||
"actor": "demo@example.com", "ip": "203.0.113.8", "outcome": "成功", "detail": ""},
|
||||
},
|
||||
{
|
||||
name: "无资源名省略尾段",
|
||||
name: "字段缺失兜底破折号",
|
||||
event: parsedEvent{EventType: "com.oraclecloud.IdentityControlPlane.CreateApiKey"},
|
||||
wantOK: true,
|
||||
wantText: "☁️ 云端事件:免费01 CreateApiKey",
|
||||
want: map[string]string{"event": "CreateApiKey", "resource": "—",
|
||||
"actor": "—", "ip": "—", "outcome": "—", "detail": ""},
|
||||
},
|
||||
{
|
||||
name: "补充说明独立成行",
|
||||
event: parsedEvent{EventType: "CreatePolicy", Detail: "允许发布到 ONS Topic"},
|
||||
wantOK: true,
|
||||
want: map[string]string{"event": "CreatePolicy", "detail": "\n允许发布到 ONS Topic"},
|
||||
},
|
||||
{name: "List 噪声不推", event: parsedEvent{EventType: "com.oraclecloud.ComputeApi.ListInstances"}, wantOK: false},
|
||||
{name: "空类型不推", event: parsedEvent{}, wantOK: false},
|
||||
{name: "短名直接命中", event: parsedEvent{EventType: "LaunchInstance"}, wantOK: true, wantText: "☁️ 云端事件:免费01 LaunchInstance"},
|
||||
{name: "短名直接命中", event: parsedEvent{EventType: "LaunchInstance"}, wantOK: true,
|
||||
want: map[string]string{"event": "LaunchInstance"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -340,13 +350,15 @@ func TestCriticalEventText(t *testing.T) {
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("ok = %v, want %v", ok, tt.wantOK)
|
||||
}
|
||||
if ok {
|
||||
got := "☁️ 云端事件:" + vars["tenant"] + " " + vars["event"]
|
||||
if vars["resource"] != "" {
|
||||
got += " " + vars["resource"]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if got != tt.wantText {
|
||||
t.Errorf("vars 渲染 = %q, want %q", got, tt.wantText)
|
||||
if vars["tenant"] != "免费01" {
|
||||
t.Errorf("tenant = %q, want 免费01", vars["tenant"])
|
||||
}
|
||||
for k, want := range tt.want {
|
||||
if vars[k] != want {
|
||||
t.Errorf("%s = %q, want %q", k, vars[k], want)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -21,7 +21,6 @@ var notifyTplOrder = []string{
|
||||
"task_fail", "task_recover", "snatch_success", "tenant_dead", "task_stop",
|
||||
"login_lock", "model_deprecated",
|
||||
"log_event_instance", "log_event_identity", "log_event_policy", "log_event_region", "log_event_login",
|
||||
"audit_alert",
|
||||
}
|
||||
|
||||
var notifyTplDefs = map[string]notifyTplDef{
|
||||
@@ -73,40 +72,40 @@ var notifyTplDefs = map[string]notifyTplDef{
|
||||
},
|
||||
"log_event_instance": {
|
||||
Label: "实例生命周期",
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}}",
|
||||
Vars: []string{"tenant", "event", "resource"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "TerminateInstance", "resource": "web-server-1"},
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}} · {{outcome}}\n操作者 {{actor}} · 来源 {{ip}}{{detail}}",
|
||||
Vars: []string{"tenant", "event", "resource", "actor", "ip", "outcome", "detail"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "TerminateInstance", "resource": "web-server-1",
|
||||
"actor": "demo@example.com", "ip": "203.0.113.8", "outcome": "成功", "detail": ""},
|
||||
},
|
||||
"log_event_identity": {
|
||||
Label: "用户与凭据",
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}}",
|
||||
Vars: []string{"tenant", "event", "resource"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "CreateApiKey", "resource": "user/demo"},
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}} · {{outcome}}\n操作者 {{actor}} · 来源 {{ip}}{{detail}}",
|
||||
Vars: []string{"tenant", "event", "resource", "actor", "ip", "outcome", "detail"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "CreateApiKey", "resource": "user/demo",
|
||||
"actor": "admin@example.com", "ip": "203.0.113.8", "outcome": "成功", "detail": ""},
|
||||
},
|
||||
"log_event_policy": {
|
||||
Label: "策略变更",
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}}",
|
||||
Vars: []string{"tenant", "event", "resource"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "UpdatePolicy", "resource": "admin-policy"},
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}} · {{outcome}}\n操作者 {{actor}} · 来源 {{ip}}{{detail}}",
|
||||
Vars: []string{"tenant", "event", "resource", "actor", "ip", "outcome", "detail"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "CreatePolicy", "resource": "admin-policy",
|
||||
"actor": "admin@example.com", "ip": "203.0.113.8", "outcome": "成功",
|
||||
"detail": "\n允许 Service Connector 发布到 ONS Topic"},
|
||||
},
|
||||
"log_event_region": {
|
||||
Label: "区域订阅",
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}}",
|
||||
Vars: []string{"tenant", "event", "resource"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "CreateRegionSubscription", "resource": "ap-osaka-1"},
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}} · {{outcome}}\n操作者 {{actor}} · 来源 {{ip}}{{detail}}",
|
||||
Vars: []string{"tenant", "event", "resource", "actor", "ip", "outcome", "detail"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "CreateRegionSubscription", "resource": "ap-osaka-1",
|
||||
"actor": "admin@example.com", "ip": "203.0.113.8", "outcome": "成功", "detail": ""},
|
||||
},
|
||||
"log_event_login": {
|
||||
Label: "控制台登录",
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} {{resource}}",
|
||||
Vars: []string{"tenant", "event", "resource"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "InteractiveLogin", "resource": "demo@example.com"},
|
||||
},
|
||||
"audit_alert": {
|
||||
Label: "审计告警",
|
||||
Default: "🔔 审计告警:{{rule}}\n租户 {{tenant}} · {{event}} {{resource}}\n来源 {{ip}} · 窗口内 {{count}} 次",
|
||||
Vars: []string{"rule", "tenant", "event", "resource", "ip", "count"},
|
||||
Sample: map[string]string{"rule": "非白名单终止实例", "tenant": "免费01",
|
||||
"event": "TerminateInstance", "resource": "web-server-1", "ip": "203.0.113.8", "count": "1"},
|
||||
Default: "☁️ 云端事件:{{tenant}} {{event}} · {{outcome}}\n用户 {{actor}} · 登录 IP {{ip}}{{detail}}",
|
||||
Vars: []string{"tenant", "event", "resource", "actor", "ip", "outcome", "detail"},
|
||||
Sample: map[string]string{"tenant": "免费01", "event": "InteractiveLogin", "resource": "—",
|
||||
"actor": "demo@example.com", "ip": "155.117.82.111", "outcome": "失败",
|
||||
"detail": "\nAuthentication failure : You entered an incorrect user name or password."},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ type OciConfigService struct {
|
||||
cipher *crypto.Cipher
|
||||
client oci.Client
|
||||
cleanupTasks *TaskService
|
||||
cleanupEvents *LogEventService
|
||||
// auditRaw 按 configId:eventId 暂存审计原始事件(TTL 10 分钟),
|
||||
// 列表响应剥离 raw 后详情接口据此秒开;miss 走小窗重查兜底。
|
||||
auditRaw *cache.Cache
|
||||
@@ -31,10 +30,9 @@ func NewOciConfigService(db *gorm.DB, cipher *crypto.Cipher, client oci.Client)
|
||||
return &OciConfigService{db: db, cipher: cipher, client: client, auditRaw: cache.New(auditRawMax)}
|
||||
}
|
||||
|
||||
// SetTenantCleanupDeps 注入租户删除提交后的任务与告警内存状态同步依赖。
|
||||
func (s *OciConfigService) SetTenantCleanupDeps(tasks *TaskService, events *LogEventService) {
|
||||
// SetTenantCleanupDeps 注入租户删除提交后的任务内存状态同步依赖。
|
||||
func (s *OciConfigService) SetTenantCleanupDeps(tasks *TaskService) {
|
||||
s.cleanupTasks = tasks
|
||||
s.cleanupEvents = events
|
||||
}
|
||||
|
||||
// ImportInput 是导入一份 API Key 的输入:
|
||||
|
||||
@@ -229,6 +229,63 @@ func (s *ProxyService) Delete(ctx context.Context, id uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetTenants 设置关联此代理的租户全集:列表内的租户改挂到本代理(含从
|
||||
// 其他代理改挂),列表外已关联的解除;整体事务生效,返回新的关联计数。
|
||||
func (s *ProxyService) SetTenants(ctx context.Context, id uint, cfgIDs []uint) (int64, error) {
|
||||
if err := s.db.WithContext(ctx).First(&model.Proxy{}, id).Error; err != nil {
|
||||
return 0, fmt.Errorf("find proxy %d: %w", id, err)
|
||||
}
|
||||
ids, err := s.validTenantIDs(ctx, cfgIDs)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
unbind := tx.Model(&model.OciConfig{}).Where("proxy_id = ?", id)
|
||||
if len(ids) > 0 {
|
||||
unbind = unbind.Where("id NOT IN ?", ids)
|
||||
}
|
||||
if err := unbind.Update("proxy_id", nil).Error; err != nil {
|
||||
return fmt.Errorf("unbind tenants: %w", err)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
err := tx.Model(&model.OciConfig{}).Where("id IN ?", ids).Update("proxy_id", id).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("bind tenants: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int64(len(ids)), nil
|
||||
}
|
||||
|
||||
// validTenantIDs 去重并校验租户 ID 均存在;含无效 ID 时报 ErrProxyInvalid。
|
||||
func (s *ProxyService) validTenantIDs(ctx context.Context, cfgIDs []uint) ([]uint, error) {
|
||||
seen := map[uint]struct{}{}
|
||||
ids := make([]uint, 0, len(cfgIDs))
|
||||
for _, v := range cfgIDs {
|
||||
if _, ok := seen[v]; !ok {
|
||||
seen[v] = struct{}{}
|
||||
ids = append(ids, v)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return ids, nil
|
||||
}
|
||||
var n int64
|
||||
err := s.db.WithContext(ctx).Model(&model.OciConfig{}).Where("id IN ?", ids).Count(&n).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("count tenants: %w", err)
|
||||
}
|
||||
if n != int64(len(ids)) {
|
||||
return nil, fmt.Errorf("存在无效的租户 ID: %w", ErrProxyInvalid)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// SpecOf 解密并组装 SDK 用的代理参数;id 为 nil 返回 nil(直连)。
|
||||
func (s *ProxyService) SpecOf(ctx context.Context, id *uint) (*oci.ProxySpec, error) {
|
||||
if id == nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -227,3 +228,99 @@ func TestProxyGeoProbe(t *testing.T) {
|
||||
t.Fatalf("probe view = %+v, want 空地区带探测时间", view)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxySetTenants(t *testing.T) {
|
||||
svc, db := newProxyEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
pa, _ := svc.Create(ctx, ProxyInput{Type: "socks5", Host: "10.0.0.1", Port: 1080})
|
||||
pb, _ := svc.Create(ctx, ProxyInput{Type: "socks5", Host: "10.0.0.2", Port: 1080})
|
||||
// t1 已挂 A,t2 挂 B,t3 直连
|
||||
t1 := model.OciConfig{Alias: "t1", ProxyID: &pa.ID}
|
||||
t2 := model.OciConfig{Alias: "t2", ProxyID: &pb.ID}
|
||||
t3 := model.OciConfig{Alias: "t3"}
|
||||
for _, cfg := range []*model.OciConfig{&t1, &t2, &t3} {
|
||||
if err := db.Create(cfg).Error; err != nil {
|
||||
t.Fatalf("seed config: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
proxyOf := func(id uint) *uint {
|
||||
var row model.OciConfig
|
||||
if err := db.First(&row, id).Error; err != nil {
|
||||
t.Fatalf("load config %d: %v", id, err)
|
||||
}
|
||||
return row.ProxyID
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
proxyID uint
|
||||
cfgIDs []uint
|
||||
wantN int64
|
||||
wantErr error
|
||||
}{
|
||||
{name: "改挂并新增", proxyID: pa.ID, cfgIDs: []uint{t2.ID, t3.ID, t3.ID}, wantN: 2},
|
||||
{name: "清空解除全部", proxyID: pa.ID, cfgIDs: nil, wantN: 0},
|
||||
{name: "无效租户拒绝", proxyID: pa.ID, cfgIDs: []uint{9999}, wantErr: ErrProxyInvalid},
|
||||
{name: "代理不存在", proxyID: 9999, cfgIDs: nil, wantErr: gorm.ErrRecordNotFound},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
n, err := svc.SetTenants(ctx, tc.proxyID, tc.cfgIDs)
|
||||
if tc.wantErr != nil {
|
||||
if !errors.Is(err, tc.wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, tc.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || n != tc.wantN {
|
||||
t.Fatalf("SetTenants = %d, %v; want %d, nil", n, err, tc.wantN)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 终态:清空后三租户全部直连(t1 在第一步已被解除,t2/t3 在第二步解除)
|
||||
for _, id := range []uint{t1.ID, t2.ID, t3.ID} {
|
||||
if got := proxyOf(id); got != nil {
|
||||
t.Fatalf("config %d proxyID = %v, want nil", id, *got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxySetTenantsRebind(t *testing.T) {
|
||||
svc, db := newProxyEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
pa, _ := svc.Create(ctx, ProxyInput{Type: "socks5", Host: "10.0.1.1", Port: 1080})
|
||||
pb, _ := svc.Create(ctx, ProxyInput{Type: "socks5", Host: "10.0.1.2", Port: 1080})
|
||||
cfg := model.OciConfig{Alias: "steal", ProxyID: &pa.ID}
|
||||
if err := db.Create(&cfg).Error; err != nil {
|
||||
t.Fatalf("seed config: %v", err)
|
||||
}
|
||||
|
||||
if _, err := svc.SetTenants(ctx, pb.ID, []uint{cfg.ID}); err != nil {
|
||||
t.Fatalf("SetTenants: %v", err)
|
||||
}
|
||||
var row model.OciConfig
|
||||
if err := db.First(&row, cfg.ID).Error; err != nil {
|
||||
t.Fatalf("load config: %v", err)
|
||||
}
|
||||
if row.ProxyID == nil || *row.ProxyID != pb.ID {
|
||||
t.Fatalf("proxyID = %v, want %d(改挂到 B)", row.ProxyID, pb.ID)
|
||||
}
|
||||
// A 侧计数应归零,B 侧为 1
|
||||
views, err := svc.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
for _, v := range views {
|
||||
want := int64(0)
|
||||
if v.ID == pb.ID {
|
||||
want = 1
|
||||
}
|
||||
if v.UsedBy != want {
|
||||
t.Fatalf("proxy %d UsedBy = %d, want %d", v.ID, v.UsedBy, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
type tenantDeleteResult struct {
|
||||
config model.OciConfig
|
||||
deletedTaskIDs []uint
|
||||
alertRuleIDs []uint
|
||||
channelsGone bool
|
||||
}
|
||||
|
||||
@@ -48,7 +47,7 @@ func (s *OciConfigService) deleteTenantInTx(tx *gorm.DB, id uint, result *tenant
|
||||
if err := s.deleteTenantTasks(tx, id, result); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := deleteTenantEvents(tx, id, result); err != nil {
|
||||
if err := deleteTenantEvents(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := deleteTenantAI(tx, id, result); err != nil {
|
||||
@@ -205,17 +204,9 @@ func resetTenantTask(tx *gorm.DB, action tenantTaskAction) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteTenantEvents(tx *gorm.DB, id uint, result *tenantDeleteResult) error {
|
||||
ruleIDs, affectedRules, err := loadTenantEventRefs(tx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := deleteAlertHits(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
result.alertRuleIDs = mergeIDs(ruleIDs, affectedRules)
|
||||
if err := deleteWhere(tx, &model.AlertRule{}, "oci_config_id = ?", id); err != nil {
|
||||
return fmt.Errorf("delete tenant alert rules: %w", err)
|
||||
func deleteTenantEvents(tx *gorm.DB, id uint) error {
|
||||
if err := lockTenantEventRows(tx, id); err != nil {
|
||||
return fmt.Errorf("load tenant log events: %w", err)
|
||||
}
|
||||
if err := deleteWhere(tx, &model.LogEvent{}, "oci_config_id = ?", id); err != nil {
|
||||
return fmt.Errorf("delete tenant log events: %w", err)
|
||||
@@ -223,84 +214,15 @@ func deleteTenantEvents(tx *gorm.DB, id uint, result *tenantDeleteResult) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadTenantEventRefs(tx *gorm.DB, id uint) ([]uint, []uint, error) {
|
||||
ruleIDs, err := lockedTenantRuleIDs(tx, id)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("load tenant alert rules: %w", err)
|
||||
}
|
||||
if err := lockTenantEventRows(tx, id); err != nil {
|
||||
return nil, nil, fmt.Errorf("load tenant log events: %w", err)
|
||||
}
|
||||
affected, err := alertHitRuleIDs(tx, id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return ruleIDs, affected, nil
|
||||
}
|
||||
|
||||
func lockedTenantRuleIDs(tx *gorm.DB, id uint) ([]uint, error) {
|
||||
var rows []model.AlertRule
|
||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").
|
||||
Where("oci_config_id = ?", id).Order("id").Find(&rows).Error
|
||||
ids := make([]uint, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.ID)
|
||||
}
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// lockTenantEventRows 对租户全部日志事件行加 FOR UPDATE 锁(SQLite 忽略,
|
||||
// MySQL/PG 阻塞并发命中写入);事件可达数万,ID 不再回传拼接 SQL,
|
||||
// 后续删除与关联查询一律用子查询,避免绑定变量上限。
|
||||
// MySQL/PG 阻塞并发写入);事件可达数万,ID 不回传拼接 SQL,删除用条件语句,
|
||||
// 避免绑定变量上限。
|
||||
func lockTenantEventRows(tx *gorm.DB, id uint) error {
|
||||
var rows []model.LogEvent
|
||||
return tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").
|
||||
Where("oci_config_id = ?", id).Order("id").Find(&rows).Error
|
||||
}
|
||||
|
||||
// tenantEventIDs 构造「本租户日志事件 ID」子查询,供 IN (?) 内联。
|
||||
func tenantEventIDs(tx *gorm.DB, id uint) *gorm.DB {
|
||||
return tx.Model(&model.LogEvent{}).Select("id").Where("oci_config_id = ?", id)
|
||||
}
|
||||
|
||||
// alertHitRuleIDs 找出命中引用了本租户事件的规则 ID(去重,可能含他租户/全局规则)。
|
||||
func alertHitRuleIDs(tx *gorm.DB, id uint) ([]uint, error) {
|
||||
ids := make([]uint, 0)
|
||||
err := tx.Model(&model.AlertRuleHit{}).Where("log_event_id IN (?)", tenantEventIDs(tx, id)).
|
||||
Distinct().Pluck("rule_id", &ids).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load affected alert rules: %w", err)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func mergeIDs(groups ...[]uint) []uint {
|
||||
seen := make(map[uint]struct{})
|
||||
out := make([]uint, 0)
|
||||
for _, ids := range groups {
|
||||
for _, id := range ids {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// deleteAlertHits 删除本租户相关的全部命中:规则属于本租户,或命中引用了
|
||||
// 本租户的日志事件(他租户/全局规则命中本租户事件的行一并清)。
|
||||
func deleteAlertHits(tx *gorm.DB, id uint) error {
|
||||
rules := tx.Model(&model.AlertRule{}).Select("id").Where("oci_config_id = ?", id)
|
||||
err := tx.Where("rule_id IN (?) OR log_event_id IN (?)", rules, tenantEventIDs(tx, id)).
|
||||
Delete(&model.AlertRuleHit{}).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete tenant alert hits: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteTenantAI(tx *gorm.DB, id uint, result *tenantDeleteResult) error {
|
||||
channelIDs, err := lockedAiChannelIDs(tx, id)
|
||||
if err != nil {
|
||||
@@ -451,9 +373,6 @@ func (s *OciConfigService) afterTenantDelete(ctx context.Context, result *tenant
|
||||
if client, ok := s.client.(tenancyCacheInvalidator); ok {
|
||||
client.InvalidateTenancy(result.config.TenancyOCID)
|
||||
}
|
||||
if s.cleanupEvents != nil {
|
||||
s.cleanupEvents.ClearAlertCooldown(result.alertRuleIDs)
|
||||
}
|
||||
if s.cleanupTasks != nil {
|
||||
s.cleanupTasks.ApplyTenantCleanup(ctx, result.deletedTaskIDs, result.channelsGone)
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ func newTenantDeleteEnv(t *testing.T, client oci.Client) (*OciConfigService, *Ta
|
||||
}
|
||||
configs := NewOciConfigService(db, cipher, client)
|
||||
tasks := NewTaskService(db, configs, nil, nil)
|
||||
configs.SetTenantCleanupDeps(tasks, nil)
|
||||
configs.SetTenantCleanupDeps(tasks)
|
||||
return configs, tasks, db
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func migrateTenantDeleteModels(t *testing.T, db *gorm.DB) {
|
||||
err := db.AutoMigrate(
|
||||
&model.OciConfig{}, &model.Task{}, &model.TaskLog{}, &model.Setting{},
|
||||
&model.CheckSnapshot{}, &model.CostSnapshot{}, &model.RegionCache{}, &model.CompartmentCache{},
|
||||
&model.LogEvent{}, &model.AlertRule{}, &model.AlertRuleHit{},
|
||||
&model.LogEvent{},
|
||||
&model.AiChannel{}, &model.AiModelCache{}, &model.AiCallLog{}, &model.AiContentLog{},
|
||||
&model.Proxy{}, &model.AiKey{}, &model.SystemLog{},
|
||||
)
|
||||
@@ -162,19 +162,9 @@ func seedTenantEvents(t *testing.T, db *gorm.DB, target, other uint) {
|
||||
t.Helper()
|
||||
targetEvent := model.LogEvent{OciConfigID: target, MessageID: "target-event"}
|
||||
otherEvent := model.LogEvent{OciConfigID: other, MessageID: "other-event"}
|
||||
targetRule := model.AlertRule{Name: "target-rule", OciConfigID: target}
|
||||
globalRule := model.AlertRule{Name: "global-rule", OciConfigID: 0}
|
||||
for _, value := range []any{&targetEvent, &otherEvent, &targetRule, &globalRule} {
|
||||
for _, value := range []any{&targetEvent, &otherEvent} {
|
||||
mustCreate(t, db, value)
|
||||
}
|
||||
hits := []model.AlertRuleHit{
|
||||
{RuleID: targetRule.ID, LogEventID: otherEvent.ID},
|
||||
{RuleID: globalRule.ID, LogEventID: targetEvent.ID},
|
||||
{RuleID: globalRule.ID, LogEventID: otherEvent.ID},
|
||||
}
|
||||
for i := range hits {
|
||||
mustCreate(t, db, &hits[i])
|
||||
}
|
||||
}
|
||||
|
||||
func seedTenantAI(t *testing.T, db *gorm.DB, target, other uint) {
|
||||
@@ -202,7 +192,7 @@ func assertTenantRowsGone(t *testing.T, db *gorm.DB, id uint) {
|
||||
rows := []any{
|
||||
&model.OciConfig{}, &model.CheckSnapshot{}, &model.CostSnapshot{},
|
||||
&model.RegionCache{}, &model.CompartmentCache{}, &model.LogEvent{},
|
||||
&model.AlertRule{}, &model.AiChannel{},
|
||||
&model.AiChannel{},
|
||||
}
|
||||
for _, value := range rows {
|
||||
column := "oci_config_id"
|
||||
@@ -212,7 +202,6 @@ func assertTenantRowsGone(t *testing.T, db *gorm.DB, id uint) {
|
||||
assertCount(t, db, value, column+" = ?", []any{id}, 0)
|
||||
}
|
||||
assertCount(t, db, &model.Setting{}, "key = ?", []any{secretKey(id)}, 0)
|
||||
assertCount(t, db, &model.AlertRuleHit{}, "", nil, 1)
|
||||
assertCount(t, db, &model.AiModelCache{}, "", nil, 1)
|
||||
assertCount(t, db, &model.AiCallLog{}, "", nil, 1)
|
||||
assertCount(t, db, &model.AiContentLog{}, "", nil, 1)
|
||||
@@ -248,31 +237,10 @@ func assertRemainingIndirectRows(t *testing.T, db *gorm.DB, otherID uint) {
|
||||
t.Fatalf("load other AI call: %v", err)
|
||||
}
|
||||
assertCount(t, db, &model.AiContentLog{}, "call_log_id = ?", []any{call.ID}, 1)
|
||||
assertRemainingAlertHit(t, db, otherID)
|
||||
}
|
||||
|
||||
func assertRemainingAlertHit(t *testing.T, db *gorm.DB, otherID uint) {
|
||||
t.Helper()
|
||||
var hit model.AlertRuleHit
|
||||
if err := db.First(&hit).Error; err != nil {
|
||||
t.Fatalf("load remaining alert hit: %v", err)
|
||||
}
|
||||
var rule model.AlertRule
|
||||
var event model.LogEvent
|
||||
if err := db.First(&rule, hit.RuleID).Error; err != nil {
|
||||
t.Fatalf("load remaining rule: %v", err)
|
||||
}
|
||||
if err := db.First(&event, hit.LogEventID).Error; err != nil {
|
||||
t.Fatalf("load remaining event: %v", err)
|
||||
}
|
||||
if rule.OciConfigID != 0 || event.OciConfigID != otherID {
|
||||
t.Errorf("remaining hit = rule cfg %d/event cfg %d, want global/other", rule.OciConfigID, event.OciConfigID)
|
||||
}
|
||||
}
|
||||
|
||||
func assertRetainedGlobals(t *testing.T, db *gorm.DB) {
|
||||
t.Helper()
|
||||
assertCount(t, db, &model.AlertRule{}, "oci_config_id = 0", nil, 1)
|
||||
assertCount(t, db, &model.Proxy{}, "", nil, 1)
|
||||
assertCount(t, db, &model.AiKey{}, "", nil, 1)
|
||||
assertCount(t, db, &model.SystemLog{}, "", nil, 1)
|
||||
@@ -629,35 +597,6 @@ func TestDeleteTenantSkipsCorruptTaskPayload(t *testing.T) {
|
||||
assertCount(t, db, &model.OciConfig{}, "id = ?", []any{target.ID}, 0)
|
||||
}
|
||||
|
||||
func TestDeleteTenantEventsAffectedRules(t *testing.T) {
|
||||
_, _, db := newTenantDeleteEnv(t, &fakeClient{})
|
||||
target, other := seedDeleteTenants(t, db)
|
||||
seedTenantEvents(t, db, target.ID, other.ID)
|
||||
|
||||
// 规则 ID 须在删除前取:target-rule 会随租户一并删除
|
||||
var targetRule, globalRule model.AlertRule
|
||||
db.Where("name = ?", "target-rule").First(&targetRule)
|
||||
db.Where("name = ?", "global-rule").First(&globalRule)
|
||||
|
||||
result := &tenantDeleteResult{}
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
return deleteTenantEvents(tx, target.ID, result)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("deleteTenantEvents: %v", err)
|
||||
}
|
||||
// target-rule 属本租户,global-rule 的命中引用了本租户事件:都应回收冷却
|
||||
got := map[uint]bool{}
|
||||
for _, id := range result.alertRuleIDs {
|
||||
got[id] = true
|
||||
}
|
||||
if len(got) != 2 || !got[targetRule.ID] || !got[globalRule.ID] {
|
||||
t.Errorf("alertRuleIDs = %v, want 含 target-rule(%d) 与 global-rule(%d)", result.alertRuleIDs, targetRule.ID, globalRule.ID)
|
||||
}
|
||||
// 仅保留 global-rule × other-event 一条命中
|
||||
assertCount(t, db, &model.AlertRuleHit{}, "", nil, 1)
|
||||
}
|
||||
|
||||
func TestDeleteTenantManyEventsNoVarLimit(t *testing.T) {
|
||||
// 回归:事件数超 SQLite 绑定变量上限(32766)时删除仍成功(旧实现 IN 展开必失败)
|
||||
configs, _, db := newTenantDeleteEnv(t, &fakeClient{})
|
||||
|
||||
Reference in New Issue
Block a user