luckfun233 commited on
Commit
7e312e3
·
1 Parent(s): 700f251

feat(logs): 请求日志页面与只读日志 API Key;修复禁言账号导致的 503

Browse files

- 新增 reqlog:内存环形窗口 + JSONL 按大小轮转(默认 8MiB×5),
仅记录请求元数据,不记录正文
- 新增 WebUI「请求日志」页:实时查询、级别/状态/关键词过滤、
详情查看、单文件/打包下载
- 新增日志读取 API Key:仅保存 SHA-256、固定 ds2log_ 前缀、
可设有效期与删除;只放行 /logs/api 只读接口,无法触达 /admin
- 上游 HTTP 200 + JSON 业务错误(禁言 / MISSING_HEADER /
INVALID_POW_RESPONSE)不再被当作空 SSE 流,返回明确错误码
- 禁言状态从登录与 completion 响应落库到 muted_until,账号池自动
跳过;全部禁言时快速返回 429 而非排队等待
- 「刷新 Token」成功时显示刷新成功,禁言账号显示解除时间
- 补充 docs/request-logs.md

Files changed (38) hide show
  1. README.md +1 -0
  2. docs/request-logs.md +110 -0
  3. internal/account/pool_acquire.go +5 -2
  4. internal/account/pool_core.go +14 -2
  5. internal/account/pool_waiters.go +26 -3
  6. internal/auth/request.go +64 -1
  7. internal/completionruntime/nonstream.go +1 -1
  8. internal/completionruntime/upstream_error.go +62 -0
  9. internal/config/config.go +9 -0
  10. internal/config/paths.go +16 -0
  11. internal/config/store.go +39 -0
  12. internal/deepseek/client/client_auth.go +21 -0
  13. internal/deepseek/client/client_completion.go +10 -0
  14. internal/deepseek/client/client_continue.go +9 -0
  15. internal/deepseek/client/client_upstream_error.go +192 -0
  16. internal/deepseek/client/client_upstream_error_test.go +67 -0
  17. internal/httpapi/admin/accounts/handler_accounts_crud.go +1 -0
  18. internal/httpapi/admin/accounts/handler_accounts_testing.go +6 -0
  19. internal/httpapi/admin/handler.go +6 -0
  20. internal/httpapi/openai/chat/handler_chat.go +4 -1
  21. internal/httpapi/openai/chat/vercel_stream.go +1 -1
  22. internal/httpapi/openai/embeddings/embeddings_handler.go +1 -1
  23. internal/httpapi/openai/files/handler_files.go +2 -2
  24. internal/httpapi/openai/responses/responses_handler.go +4 -1
  25. internal/httpapi/openai/shared/handler_errors.go +2 -0
  26. internal/proxyhealth/checker.go +7 -7
  27. internal/reqlog/context.go +104 -0
  28. internal/reqlog/keys.go +229 -0
  29. internal/reqlog/middleware.go +156 -0
  30. internal/reqlog/store.go +458 -0
  31. internal/reqlog/store_test.go +123 -0
  32. internal/server/router.go +55 -2
  33. webui/src/features/account/AccountsTable.jsx +9 -2
  34. webui/src/features/account/QueueCards.jsx +10 -0
  35. webui/src/features/account/useAccountActions.js +4 -2
  36. webui/src/layout/DashboardShell.jsx +10 -2
  37. webui/src/locales/en.json +57 -1
  38. webui/src/locales/zh.json +57 -1
README.md CHANGED
@@ -24,5 +24,6 @@ DeepSeek web chat to OpenAI-compatible API adapter with multi-protocol support (
24
  | [README.en.md](README.en.md) | Full English README (models, deployment, configuration) |
25
  | [docs/prompt-compatibility.md](docs/prompt-compatibility.md) | 源文档:API 请求 → 纯文本 web-chat 上下文的兼容流程(中文) |
26
  | [docs/prompt-design.md](docs/prompt-design.md) | 提示词方案:分层、文案全文、写作特化与调优建议(中文) |
 
27
 
28
  Models: only the `deepseek-v4-flash` family is published (`deepseek-v4-flash`, `deepseek-v4-flash-search`, plus `-nothinking` variants). The retired `deepseek-v4-pro` / `deepseek-v4-vision` names still resolve to their flash counterparts, so old clients keep working.
 
24
  | [README.en.md](README.en.md) | Full English README (models, deployment, configuration) |
25
  | [docs/prompt-compatibility.md](docs/prompt-compatibility.md) | 源文档:API 请求 → 纯文本 web-chat 上下文的兼容流程(中文) |
26
  | [docs/prompt-design.md](docs/prompt-design.md) | 提示词方案:分层、文案全文、写作特化与调优建议(中文) |
27
+ | [docs/request-logs.md](docs/request-logs.md) | 请求日志页面、轮转下载与只读日志读取 API Key(中文) |
28
 
29
  Models: only the `deepseek-v4-flash` family is published (`deepseek-v4-flash`, `deepseek-v4-flash-search`, plus `-nothinking` variants). The retired `deepseek-v4-pro` / `deepseek-v4-vision` names still resolve to their flash counterparts, so old clients keep working.
docs/request-logs.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 请求日志与日志读取 API Key
2
+
3
+ 面向排障的请求日志模块:管理员可以在 WebUI 的「请求日志」页查看最近请求、下载轮转文件,并生成只读的日志读取 Key 供给外部脚本/Agent 拉取日志,无需登录容器或 Hugging Face 控制台。
4
+
5
+ ## 记录内容
6
+
7
+ 每条记录只保存请求元数据,不保存请求/响应正文,避免泄露聊天内容:
8
+
9
+ | 字段 | 说明 |
10
+ | --- | --- |
11
+ | `time` | 请求开始时间(RFC3339,含毫秒) |
12
+ | `method` / `path` | HTTP 方法与路径 |
13
+ | `status` | 响应状态码 |
14
+ | `latency_ms` | 端到端耗时 |
15
+ | `client_ip` | 客户端 IP(优先 `X-Forwarded-For`) |
16
+ | `user_agent` | User-Agent;带 `X-Ds2-Source` 时会前置该值 |
17
+ | `api_key` / `api_key_name` | 调用方 Key 的掩码与名称 |
18
+ | `account` | 实际使用的 DeepSeek 账号 |
19
+ | `model` / `stream` | 归一化后的模型与是否流式 |
20
+ | `req_bytes` / `resp_bytes` | 请求/响应字节数 |
21
+ | `error_code` | 业务错误码(如 `account_muted`、`upstream_error`) |
22
+ | `upstream` | 上游错误详情(截断 500 字符) |
23
+
24
+ 以下路径不会记录:`/healthz`、`/readyz`、静态资源、`/admin/logs*`、`/logs/*`。
25
+
26
+ ## 存储与轮转
27
+
28
+ - 内存环形窗口:默认保留 2000 条,供 WebUI 实时查询。
29
+ - 文件日志:JSONL,按大小轮转,默认单文件 8 MiB、保留 5 个。
30
+ - 默认目录:`data/logs`;Vercel 运行时自动改用 `/tmp/ds2api-logs`。
31
+
32
+ | 环境变量 | 默认值 | 说明 |
33
+ | --- | --- | --- |
34
+ | `DS2API_REQUEST_LOG_DIR` | `data/logs` | 轮转文件目录 |
35
+ | `DS2API_REQUEST_LOG_MEMORY` | `2000` | 内存窗口条数 |
36
+ | `DS2API_REQUEST_LOG_MAX_MB` | `8` | 单文件大小上限(MiB) |
37
+ | `DS2API_REQUEST_LOG_MAX_FILES` | `5` | 保留文件数 |
38
+ | `DS2API_REQUEST_LOG_DISABLE_FILE` | - | 设为 `1` 时只保留内存窗口 |
39
+ | `DS2API_LOG_KEYS_PATH` | `data/log_api_keys.json` | 日志 Key 持久化路径 |
40
+
41
+ > 容器里若 `data/` 不可写,内存窗口仍然可用,但轮转文件与 Key 持久化会失败。请把上述目录挂载到可写卷。
42
+
43
+ ## 管理端接口(需管理员 JWT)
44
+
45
+ | 方法 | 路径 | 说明 |
46
+ | --- | --- | --- |
47
+ | GET | `/admin/logs?limit=&level=&status=&q=&since=&until=&file=` | 查询内存窗口;带 `file` 时读取指定轮转文件最后 N 行 |
48
+ | GET | `/admin/logs/stats` | 总量、5xx、4xx、最近 1 小时 |
49
+ | GET | `/admin/logs/files` | 轮转文件列表 |
50
+ | GET | `/admin/logs/files/{name}` | 下载单个 JSONL |
51
+ | GET | `/admin/logs/download` | 打包下载全部(zip) |
52
+ | GET | `/admin/logs/keys` | 日志 Key 列表(不含明文/哈希) |
53
+ | POST | `/admin/logs/keys` | 生成 Key,body:`{"name":"ops","ttl_hours":720}` |
54
+ | DELETE | `/admin/logs/keys/{id}` | 删除并立即失效 |
55
+
56
+ ## 只读日志 API
57
+
58
+ 前缀 `/logs/api`,只接受日志读取 Key:
59
+
60
+ ```
61
+ Authorization: Bearer ds2log_xxx
62
+ # 或 X-Log-Key: ds2log_xxx
63
+ ```
64
+
65
+ | 方法 | 路径 |
66
+ | --- | --- |
67
+ | GET | `/logs/api/entries` |
68
+ | GET | `/logs/api/stats` |
69
+ | GET | `/logs/api/files` |
70
+ | GET | `/logs/api/files/{name}` |
71
+ | GET | `/logs/api/download` |
72
+
73
+ 示例:
74
+
75
+ ```bash
76
+ curl -H "Authorization: Bearer ds2log_xxx" \
77
+ "https://your-host/logs/api/entries?limit=200&level=error&q=account_muted"
78
+ ```
79
+
80
+ ## 安全模型
81
+
82
+ - Key 明文只在创建时返回一次,服务端仅保存 SHA-256 哈希,落盘文件权限 `0600`。
83
+ - Key 前缀固定为 `ds2log_`,随机部分 192 bit,不可枚举。
84
+ - 日志 Key 只能访问 `/logs/api` 下的只读接口;无法访问 `/admin/*`、配置、账号、聊天记录,也不能生成/删除其他 Key。
85
+ - 支持有效期(默认 30 天,最长 365 天)与立即删除;过期或删除后请求返回 `401`。
86
+ - 下载路径经过 `filepath.Base` 校验并限定 `.jsonl`,拒绝路径穿越。
87
+ - 日志不包含请求/响应正文,因此不会通过日志接口泄露聊天内容。
88
+
89
+ ## 账号禁言(`account_muted`)
90
+
91
+ DeepSeek 在账号被禁言时会返回 HTTP 200 + `application/json`:
92
+
93
+ ```json
94
+ {"code":0,"data":{"biz_code":5,"biz_msg":"user is muted",
95
+ "biz_data":{"is_muted":1,"mute_until":1826030258}}}
96
+ ```
97
+
98
+ 旧版本把它当作空 SSE 流,最终对外表现为
99
+ `503 Upstream service is unavailable and returned no output.`。
100
+
101
+ 现在的处理:
102
+
103
+ 1. `CallCompletion` 识别非 SSE 的 JSON 响应并解析 `code` / `biz_code`。
104
+ 2. 禁言时立即返回 `429 account_muted`,消息中包含解除时间。
105
+ 3. 登录响应里的 `user.chat.is_muted` / `mute_until` 也会同步落库。
106
+ 4. `muted_until` 写入账号配置,账号池自动跳过该账号;到期或登录显示已解禁时自动清除。
107
+ 5. 所有账号都禁言时快速返回
108
+ `429 all N account(s) are muted by upstream until ...`,不再排队等待。
109
+
110
+ WebUI 的账号列表会显示「已禁言」标记与解除时间,队列卡片新增 `muted_count`。
internal/account/pool_acquire.go CHANGED
@@ -2,6 +2,7 @@ package account
2
 
3
  import (
4
  "context"
 
5
 
6
  "ds2api/internal/config"
7
  )
@@ -47,12 +48,13 @@ func (p *Pool) AcquireWait(ctx context.Context, target string, exclude map[strin
47
  }
48
 
49
  func (p *Pool) acquireLocked(target string, exclude map[string]bool) (config.Account, bool) {
 
50
  if target != "" {
51
  if exclude[target] || !p.canAcquireIDLocked(target) {
52
  return config.Account{}, false
53
  }
54
  acc, ok := p.store.FindAccount(target)
55
- if !ok {
56
  return config.Account{}, false
57
  }
58
  p.inUse[target]++
@@ -64,13 +66,14 @@ func (p *Pool) acquireLocked(target string, exclude map[string]bool) (config.Acc
64
  }
65
 
66
  func (p *Pool) tryAcquire(exclude map[string]bool) (config.Account, bool) {
 
67
  for i := 0; i < len(p.queue); i++ {
68
  id := p.queue[i]
69
  if exclude[id] || !p.canAcquireIDLocked(id) {
70
  continue
71
  }
72
  acc, ok := p.store.FindAccount(id)
73
- if !ok {
74
  continue
75
  }
76
  p.inUse[id]++
 
2
 
3
  import (
4
  "context"
5
+ "time"
6
 
7
  "ds2api/internal/config"
8
  )
 
48
  }
49
 
50
  func (p *Pool) acquireLocked(target string, exclude map[string]bool) (config.Account, bool) {
51
+ now := time.Now()
52
  if target != "" {
53
  if exclude[target] || !p.canAcquireIDLocked(target) {
54
  return config.Account{}, false
55
  }
56
  acc, ok := p.store.FindAccount(target)
57
+ if !ok || acc.IsMuted(now) {
58
  return config.Account{}, false
59
  }
60
  p.inUse[target]++
 
66
  }
67
 
68
  func (p *Pool) tryAcquire(exclude map[string]bool) (config.Account, bool) {
69
+ now := time.Now()
70
  for i := 0; i < len(p.queue); i++ {
71
  id := p.queue[i]
72
  if exclude[id] || !p.canAcquireIDLocked(id) {
73
  continue
74
  }
75
  acc, ok := p.store.FindAccount(id)
76
+ if !ok || acc.IsMuted(now) {
77
  continue
78
  }
79
  p.inUse[id]++
internal/account/pool_core.go CHANGED
@@ -3,6 +3,7 @@ package account
3
  import (
4
  "sort"
5
  "sync"
 
6
 
7
  "ds2api/internal/config"
8
  )
@@ -34,6 +35,10 @@ func NewPool(store *config.Store) *Pool {
34
  }
35
 
36
  func (p *Pool) Reset() {
 
 
 
 
37
  accounts := p.store.Accounts()
38
  sort.SliceStable(accounts, func(i, j int) bool {
39
  iHas := accounts[i].Token != ""
@@ -44,13 +49,14 @@ func (p *Pool) Reset() {
44
  return iHas
45
  })
46
  ids := make([]string, 0, len(accounts))
 
47
  for _, a := range accounts {
48
  id := a.Identifier()
49
  if id == "" {
50
  continue
51
  }
52
- // Only include normal (non-standby) and non-banned accounts in the pool.
53
- if a.Role == "standby" || a.Banned {
54
  continue
55
  }
56
  ids = append(ids, id)
@@ -126,11 +132,16 @@ func (p *Pool) Status() map[string]any {
126
  normalCount := 0
127
  standbyCount := 0
128
  bannedCount := 0
 
 
129
  for _, acc := range allAccounts {
130
  if acc.Banned {
131
  bannedCount++
132
  continue
133
  }
 
 
 
134
  if acc.Role == "standby" {
135
  standbyCount++
136
  } else {
@@ -151,5 +162,6 @@ func (p *Pool) Status() map[string]any {
151
  "normal_count": normalCount,
152
  "standby_count": standbyCount,
153
  "banned_count": bannedCount,
 
154
  }
155
  }
 
3
  import (
4
  "sort"
5
  "sync"
6
+ "time"
7
 
8
  "ds2api/internal/config"
9
  )
 
35
  }
36
 
37
  func (p *Pool) Reset() {
38
+ if p.store != nil {
39
+ // 禁言到期后自动恢复账号,避免需要人工清理配置。
40
+ p.store.ClearExpiredMutes(time.Now())
41
+ }
42
  accounts := p.store.Accounts()
43
  sort.SliceStable(accounts, func(i, j int) bool {
44
  iHas := accounts[i].Token != ""
 
49
  return iHas
50
  })
51
  ids := make([]string, 0, len(accounts))
52
+ now := time.Now()
53
  for _, a := range accounts {
54
  id := a.Identifier()
55
  if id == "" {
56
  continue
57
  }
58
+ // Only include normal (non-standby), non-banned and non-muted accounts in the pool.
59
+ if a.Role == "standby" || a.Banned || a.IsMuted(now) {
60
  continue
61
  }
62
  ids = append(ids, id)
 
132
  normalCount := 0
133
  standbyCount := 0
134
  bannedCount := 0
135
+ mutedCount := 0
136
+ now := time.Now()
137
  for _, acc := range allAccounts {
138
  if acc.Banned {
139
  bannedCount++
140
  continue
141
  }
142
+ if acc.IsMuted(now) {
143
+ mutedCount++
144
+ }
145
  if acc.Role == "standby" {
146
  standbyCount++
147
  } else {
 
162
  "normal_count": normalCount,
163
  "standby_count": standbyCount,
164
  "banned_count": bannedCount,
165
+ "muted_count": mutedCount,
166
  }
167
  }
internal/account/pool_waiters.go CHANGED
@@ -1,18 +1,41 @@
1
  package account
2
 
 
 
3
  func (p *Pool) canQueueLocked(target string, exclude map[string]bool) bool {
4
  if target != "" {
5
  if exclude[target] {
6
  return false
7
  }
8
- if _, ok := p.store.FindAccount(target); !ok {
 
9
  return false
10
  }
11
  }
12
- if p.maxQueueSize <= 0 {
13
  return false
14
  }
15
- return len(p.waiters) < p.maxQueueSize
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  }
17
 
18
  func (p *Pool) notifyWaiterLocked() {
 
1
  package account
2
 
3
+ import "time"
4
+
5
  func (p *Pool) canQueueLocked(target string, exclude map[string]bool) bool {
6
  if target != "" {
7
  if exclude[target] {
8
  return false
9
  }
10
+ acc, ok := p.store.FindAccount(target)
11
+ if !ok || acc.IsMuted(time.Now()) {
12
  return false
13
  }
14
  }
15
+ if p.maxQueueSize <= 0 || len(p.waiters) >= p.maxQueueSize {
16
  return false
17
  }
18
+ // 没有任何可用候选(全部被排除/禁言)时不要排队,否则请求会一直等待
19
+ // 一个永远不会到来的释放信号。
20
+ return p.hasCandidateLocked(target, exclude)
21
+ }
22
+
23
+ func (p *Pool) hasCandidateLocked(target string, exclude map[string]bool) bool {
24
+ now := time.Now()
25
+ if target != "" {
26
+ acc, ok := p.store.FindAccount(target)
27
+ return ok && !acc.IsMuted(now)
28
+ }
29
+ for _, id := range p.queue {
30
+ if exclude[id] {
31
+ continue
32
+ }
33
+ acc, ok := p.store.FindAccount(id)
34
+ if ok && !acc.IsMuted(now) {
35
+ return true
36
+ }
37
+ }
38
+ return false
39
  }
40
 
41
  func (p *Pool) notifyWaiterLocked() {
internal/auth/request.go CHANGED
@@ -14,6 +14,7 @@ import (
14
 
15
  "ds2api/internal/account"
16
  "ds2api/internal/config"
 
17
  )
18
 
19
  type ctxKey string
@@ -31,7 +32,6 @@ var (
31
  // ErrLoginRateLimited 表示上游对密码登录返回了 TOO_MANY_REQUESTS(code 40029)。
32
  // 继续重试只会延长限流窗口,因此调用方需要退避。
33
  ErrLoginRateLimited = errors.New("deepseek login rate limited")
34
-
35
  // ErrLoginCooldown 表示上一次登录已触发限流或 MFA 挑战,当前处于冷却期。
36
  // 这不是上游错误,而是本地保护:冷却期内不再提交密码。
37
  ErrLoginCooldown = errors.New("deepseek login cooldown active")
@@ -41,6 +41,61 @@ var (
41
  errSessionProbeUnavailable = errors.New("session probe unavailable")
42
  )
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  // LoginChallengeError 表示上游要求额外的人机/多因素验证,而不是密码错误。
45
  // 典型场景:登录响应返回非空 mfa_ticket(需要邮箱/短信验证码或可信设备签名)。
46
  type LoginChallengeError struct {
@@ -129,6 +184,7 @@ func (r *Resolver) Determine(req *http.Request) (*RequestAuth, error) {
129
  }
130
  callerID := callerTokenID(callerKey)
131
  callerLabel := r.callerLabel(callerKey)
 
132
  injection := r.resolveInjection(callerKey)
133
  promptProfile := r.resolvePromptProfile(callerKey)
134
  promptStyle := r.promptStyle()
@@ -161,6 +217,7 @@ func (r *Resolver) Determine(req *http.Request) (*RequestAuth, error) {
161
  a.PromptStyle = promptStyle
162
  a.Skills = skills
163
  a.ToolsEnabled = toolsEnabled
 
164
  return a, nil
165
  }
166
 
@@ -230,6 +287,9 @@ func (r *Resolver) acquireManagedRequestAuth(ctx context.Context, callerID, targ
230
  if lastEnsureErr != nil {
231
  return nil, lastEnsureErr
232
  }
 
 
 
233
  return nil, ErrNoAccount
234
  }
235
  acc, ok := r.Pool.AcquireWait(ctx, target, tried)
@@ -237,6 +297,9 @@ func (r *Resolver) acquireManagedRequestAuth(ctx context.Context, callerID, targ
237
  if lastEnsureErr != nil {
238
  return nil, lastEnsureErr
239
  }
 
 
 
240
  return nil, ErrNoAccount
241
  }
242
 
 
14
 
15
  "ds2api/internal/account"
16
  "ds2api/internal/config"
17
+ "ds2api/internal/reqlog"
18
  )
19
 
20
  type ctxKey string
 
32
  // ErrLoginRateLimited 表示上游对密码登录返回了 TOO_MANY_REQUESTS(code 40029)。
33
  // 继续重试只会延长限流窗口,因此调用方需要退避。
34
  ErrLoginRateLimited = errors.New("deepseek login rate limited")
 
35
  // ErrLoginCooldown 表示上一次登录已触发限流或 MFA 挑战,当前处于冷却期。
36
  // 这不是上游错误,而是本地保护:冷却期内不再提交密码。
37
  ErrLoginCooldown = errors.New("deepseek login cooldown active")
 
41
  errSessionProbeUnavailable = errors.New("session probe unavailable")
42
  )
43
 
44
+ // AllAccountsMutedError 表示所有可用账号都被上游禁言,用于给出比
45
+ // “all accounts are busy” 更明确的原因。
46
+ type AllAccountsMutedError struct {
47
+ Count int
48
+ Until int64
49
+ }
50
+
51
+ func (e *AllAccountsMutedError) Error() string {
52
+ if e == nil {
53
+ return "all accounts are muted by upstream"
54
+ }
55
+ if e.Until > 0 {
56
+ until := time.Unix(e.Until, 0).In(time.FixedZone("CST", 8*3600))
57
+ return fmt.Sprintf("all %d account(s) are muted by upstream until %s", e.Count, until.Format("2006-01-02 15:04:05 MST"))
58
+ }
59
+ return fmt.Sprintf("all %d account(s) are muted by upstream", e.Count)
60
+ }
61
+
62
+ // IsNoAccountError 统一判断“没有可用账号”类错误,便于 HTTP 层映射为 429。
63
+ func IsNoAccountError(err error) bool {
64
+ if err == nil {
65
+ return false
66
+ }
67
+ if err == ErrNoAccount {
68
+ return true
69
+ }
70
+ var muted *AllAccountsMutedError
71
+ return errors.As(err, &muted)
72
+ }
73
+
74
+ func (r *Resolver) allAccountsMutedError() *AllAccountsMutedError {
75
+ if r == nil || r.Store == nil {
76
+ return nil
77
+ }
78
+ now := time.Now().Unix()
79
+ count := 0
80
+ var earliest int64
81
+ for _, acc := range r.Store.Accounts() {
82
+ if acc.Banned || acc.Role == "standby" {
83
+ continue
84
+ }
85
+ if acc.MutedUntil <= now {
86
+ continue
87
+ }
88
+ count++
89
+ if earliest == 0 || acc.MutedUntil < earliest {
90
+ earliest = acc.MutedUntil
91
+ }
92
+ }
93
+ if count == 0 {
94
+ return nil
95
+ }
96
+ return &AllAccountsMutedError{Count: count, Until: earliest}
97
+ }
98
+
99
  // LoginChallengeError 表示上游要求额外的人机/多因素验证,而不是密码错误。
100
  // 典型场景:登录响应返回非空 mfa_ticket(需要邮箱/短信验证码或可信设备签名)。
101
  type LoginChallengeError struct {
 
184
  }
185
  callerID := callerTokenID(callerKey)
186
  callerLabel := r.callerLabel(callerKey)
187
+ reqlog.SetAPIKey(req.Context(), callerLabel, reqlog.MaskKey(callerKey))
188
  injection := r.resolveInjection(callerKey)
189
  promptProfile := r.resolvePromptProfile(callerKey)
190
  promptStyle := r.promptStyle()
 
217
  a.PromptStyle = promptStyle
218
  a.Skills = skills
219
  a.ToolsEnabled = toolsEnabled
220
+ reqlog.SetAccount(req.Context(), a.AccountID)
221
  return a, nil
222
  }
223
 
 
287
  if lastEnsureErr != nil {
288
  return nil, lastEnsureErr
289
  }
290
+ if muted := r.allAccountsMutedError(); muted != nil {
291
+ return nil, muted
292
+ }
293
  return nil, ErrNoAccount
294
  }
295
  acc, ok := r.Pool.AcquireWait(ctx, target, tried)
 
297
  if lastEnsureErr != nil {
298
  return nil, lastEnsureErr
299
  }
300
+ if muted := r.allAccountsMutedError(); muted != nil {
301
+ return nil, muted
302
+ }
303
  return nil, ErrNoAccount
304
  }
305
 
internal/completionruntime/nonstream.go CHANGED
@@ -68,7 +68,7 @@ func StartCompletion(ctx context.Context, ds DeepSeekCaller, a *auth.RequestAuth
68
  payload := stdReq.CompletionPayload(sessionID)
69
  resp, err := ds.CallCompletion(ctx, a, payload, pow, maxAttempts)
70
  if err != nil {
71
- return StartResult{SessionID: sessionID, Payload: payload, Pow: pow, Request: stdReq}, &assistantturn.OutputError{Status: http.StatusInternalServerError, Message: "Failed to get completion.", Code: "error"}
72
  }
73
  return StartResult{SessionID: sessionID, Payload: payload, Pow: pow, Response: resp, Request: stdReq}, nil
74
  }
 
68
  payload := stdReq.CompletionPayload(sessionID)
69
  resp, err := ds.CallCompletion(ctx, a, payload, pow, maxAttempts)
70
  if err != nil {
71
+ return StartResult{SessionID: sessionID, Payload: payload, Pow: pow, Request: stdReq}, mapUpstreamCallError(ctx, err)
72
  }
73
  return StartResult{SessionID: sessionID, Payload: payload, Pow: pow, Response: resp, Request: stdReq}, nil
74
  }
internal/completionruntime/upstream_error.go ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package completionruntime
2
+
3
+ import (
4
+ "context"
5
+ "errors"
6
+ "fmt"
7
+ "net/http"
8
+ "time"
9
+
10
+ "ds2api/internal/assistantturn"
11
+ dsclient "ds2api/internal/deepseek/client"
12
+ "ds2api/internal/reqlog"
13
+ )
14
+
15
+ // mapUpstreamCallError 把上游返回的 JSON 业务错误映射成带明确 code 的
16
+ // OutputError,避免统一落到 “Failed to get completion.” / 503。
17
+ func mapUpstreamCallError(ctx context.Context, err error) *assistantturn.OutputError {
18
+ if err == nil {
19
+ return nil
20
+ }
21
+ var bizErr *dsclient.UpstreamBizError
22
+ if !errors.As(err, &bizErr) {
23
+ reqlog.SetUpstream(ctx, err.Error())
24
+ return &assistantturn.OutputError{
25
+ Status: http.StatusBadGateway,
26
+ Message: "Failed to get completion: " + err.Error(),
27
+ Code: "upstream_error",
28
+ }
29
+ }
30
+ reqlog.SetUpstream(ctx, bizErr.Error())
31
+ if bizErr.IsMuted() {
32
+ message := "DeepSeek account is muted by upstream"
33
+ if bizErr.MutedUntil > 0 {
34
+ until := time.Unix(bizErr.MutedUntil, 0).In(time.FixedZone("CST", 8*3600))
35
+ message = fmt.Sprintf("DeepSeek account is muted by upstream until %s.", until.Format("2006-01-02 15:04:05 MST"))
36
+ }
37
+ return &assistantturn.OutputError{
38
+ Status: http.StatusTooManyRequests,
39
+ Message: message,
40
+ Code: "account_muted",
41
+ }
42
+ }
43
+ switch bizErr.Code {
44
+ case 40300:
45
+ return &assistantturn.OutputError{
46
+ Status: http.StatusBadGateway,
47
+ Message: "Upstream rejected the request with MISSING_HEADER (PoW header missing or expired).",
48
+ Code: "upstream_missing_header",
49
+ }
50
+ case 40301:
51
+ return &assistantturn.OutputError{
52
+ Status: http.StatusBadGateway,
53
+ Message: "Upstream rejected the PoW response (invalid or already used).",
54
+ Code: "upstream_invalid_pow",
55
+ }
56
+ }
57
+ return &assistantturn.OutputError{
58
+ Status: http.StatusBadGateway,
59
+ Message: "Upstream returned an error response: " + bizErr.Error(),
60
+ Code: "upstream_error",
61
+ }
62
+ }
internal/config/config.go CHANGED
@@ -5,6 +5,7 @@ import (
5
  "encoding/hex"
6
  "fmt"
7
  "strings"
 
8
  "unicode/utf8"
9
  )
10
 
@@ -49,6 +50,14 @@ type Account struct {
49
  DeviceID string `json:"device_id,omitempty"` // 可选:用户从自己手机抓包填入的数美 device_id(Base64 blob)。未填则基于账号稳定生成。
50
  RangersID string `json:"rangers_id,omitempty"` // 可选:用户从自己手机抓包填入的火山 x-rangers-id。未填则基于账号稳定生成。
51
  XDeviceID string `json:"x_device_id,omitempty"` // 可选:真实 Android 客户端派生的 x-device-id(Android ID + BRAND 的 AES 结果)。未填则不发送该头。
 
 
 
 
 
 
 
 
52
  }
53
 
54
  type APIKey struct {
 
5
  "encoding/hex"
6
  "fmt"
7
  "strings"
8
+ "time"
9
  "unicode/utf8"
10
  )
11
 
 
50
  DeviceID string `json:"device_id,omitempty"` // 可选:用户从自己手机抓包填入的数美 device_id(Base64 blob)。未填则基于账号稳定生成。
51
  RangersID string `json:"rangers_id,omitempty"` // 可选:用户从自己手机抓包填入的火山 x-rangers-id。未填则基于账号稳定生成。
52
  XDeviceID string `json:"x_device_id,omitempty"` // 可选:真实 Android 客户端派生的 x-device-id(Android ID + BRAND 的 AES 结果)。未填则不发送该头。
53
+ // MutedUntil 是上游返回的禁言截止时间(Unix 秒)。大于当前时间时账号池会跳过该账号,
54
+ // 避免继续消耗请求;到期后自动恢复。
55
+ MutedUntil int64 `json:"muted_until,omitempty"`
56
+ }
57
+
58
+ // IsMuted 判断账号当前是否仍处于上游禁言期。
59
+ func (a Account) IsMuted(now time.Time) bool {
60
+ return a.MutedUntil > now.Unix()
61
  }
62
 
63
  type APIKey struct {
internal/config/paths.go CHANGED
@@ -69,3 +69,19 @@ func ChatHistoryPath() string {
69
  func StaticAdminDir() string {
70
  return ResolvePath("DS2API_STATIC_ADMIN_DIR", "static/admin")
71
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  func StaticAdminDir() string {
70
  return ResolvePath("DS2API_STATIC_ADMIN_DIR", "static/admin")
71
  }
72
+
73
+ // RequestLogDir 是请求日志轮转文件的写入目录。Vercel 运行时只有 /tmp 可写。
74
+ func RequestLogDir() string {
75
+ if IsVercel() && strings.TrimSpace(os.Getenv("DS2API_REQUEST_LOG_DIR")) == "" {
76
+ return "/tmp/ds2api-logs"
77
+ }
78
+ return ResolvePath("DS2API_REQUEST_LOG_DIR", "data/logs")
79
+ }
80
+
81
+ // LogKeysPath 是日志读取 API Key 的持久化文件。
82
+ func LogKeysPath() string {
83
+ if IsVercel() && strings.TrimSpace(os.Getenv("DS2API_LOG_KEYS_PATH")) == "" {
84
+ return "/tmp/ds2api_log_keys.json"
85
+ }
86
+ return ResolvePath("DS2API_LOG_KEYS_PATH", "data/log_api_keys.json")
87
+ }
internal/config/store.go CHANGED
@@ -8,6 +8,7 @@ import (
8
  "slices"
9
  "strings"
10
  "sync"
 
11
  )
12
 
13
  type Store struct {
@@ -247,6 +248,44 @@ func (s *Store) UpdateAccountToken(identifier, token string) error {
247
  return s.saveLocked()
248
  }
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  // UpdateAccountDeviceID 持久化账号最新签发的数美 device_id,后续登录复用以保持
251
  // 设备身份稳定(与浏览器端复用 SMID 的行为一致)。
252
  func (s *Store) UpdateAccountDeviceID(identifier, deviceID string) error {
 
8
  "slices"
9
  "strings"
10
  "sync"
11
+ "time"
12
  )
13
 
14
  type Store struct {
 
248
  return s.saveLocked()
249
  }
250
 
251
+ // UpdateAccountMute 记录上游禁言截止时间(Unix 秒)。until 为 0 时清除禁言。
252
+ func (s *Store) UpdateAccountMute(identifier string, until int64) error {
253
+ identifier = strings.TrimSpace(identifier)
254
+ if identifier == "" {
255
+ return errors.New("empty account identifier")
256
+ }
257
+ s.mu.Lock()
258
+ defer s.mu.Unlock()
259
+ idx, ok := s.findAccountIndexLocked(identifier)
260
+ if !ok {
261
+ return errors.New("account not found")
262
+ }
263
+ if s.cfg.Accounts[idx].MutedUntil == until {
264
+ return nil
265
+ }
266
+ s.cfg.Accounts[idx].MutedUntil = until
267
+ return s.saveLocked()
268
+ }
269
+
270
+ // ClearExpiredMutes 清理已经到期的禁言标记,返回是否有改动。
271
+ func (s *Store) ClearExpiredMutes(now time.Time) bool {
272
+ s.mu.Lock()
273
+ defer s.mu.Unlock()
274
+ changed := false
275
+ for i := range s.cfg.Accounts {
276
+ if s.cfg.Accounts[i].MutedUntil > 0 && s.cfg.Accounts[i].MutedUntil <= now.Unix() {
277
+ s.cfg.Accounts[i].MutedUntil = 0
278
+ changed = true
279
+ }
280
+ }
281
+ if changed {
282
+ if err := s.saveLocked(); err != nil {
283
+ Logger.Warn("[account] clear expired mute state failed", "error", err)
284
+ }
285
+ }
286
+ return changed
287
+ }
288
+
289
  // UpdateAccountDeviceID 持久化账号最新签发的数美 device_id,后续登录复用以保持
290
  // 设备身份稳定(与浏览器端复用 SMID 的行为一致)。
291
  func (s *Store) UpdateAccountDeviceID(identifier, deviceID string) error {
internal/deepseek/client/client_auth.go CHANGED
@@ -9,6 +9,7 @@ import (
9
  "fmt"
10
  "net/http"
11
  "strings"
 
12
  "unicode"
13
 
14
  "ds2api/internal/auth"
@@ -100,6 +101,26 @@ func (c *Client) loginWithDevice(ctx context.Context, acc config.Account, regene
100
  if strings.TrimSpace(token) == "" {
101
  return "", errors.New("missing login token")
102
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  return token, nil
104
  }
105
 
 
9
  "fmt"
10
  "net/http"
11
  "strings"
12
+ "time"
13
  "unicode"
14
 
15
  "ds2api/internal/auth"
 
101
  if strings.TrimSpace(token) == "" {
102
  return "", errors.New("missing login token")
103
  }
104
+ // 登录响应已经带回禁言状态:user.chat.is_muted / mute_until。
105
+ // 及时落库能让账号池直接跳过该账号,而不是等聊天接口返回 5xx 才发现。
106
+ if muted, until, present := ParseLoginMute(bizData); present {
107
+ if muted && until > time.Now().Unix() {
108
+ if err := c.Store.UpdateAccountMute(acc.Identifier(), until); err != nil {
109
+ config.Logger.Warn("[login] persist mute state failed", "account", acc.Identifier(), "error", err)
110
+ } else {
111
+ config.Logger.Warn("[login] account is muted", "account", acc.Identifier(), "until", until)
112
+ }
113
+ } else if !muted {
114
+ // 上游已解除禁言时清除本地标记,账号池会自动恢复该账号。
115
+ if existing, ok := c.Store.FindAccount(acc.Identifier()); ok && existing.MutedUntil != 0 {
116
+ if err := c.Store.UpdateAccountMute(acc.Identifier(), 0); err != nil {
117
+ config.Logger.Warn("[login] clear mute state failed", "account", acc.Identifier(), "error", err)
118
+ } else {
119
+ config.Logger.Info("[login] account mute cleared", "account", acc.Identifier())
120
+ }
121
+ }
122
+ }
123
+ }
124
  return token, nil
125
  }
126
 
internal/deepseek/client/client_completion.go CHANGED
@@ -34,6 +34,16 @@ func (c *Client) CallCompletion(ctx context.Context, a *auth.RequestAuth, payloa
34
  if captureSession != nil {
35
  resp.Body = captureSession.WrapBody(resp.Body, resp.StatusCode)
36
  }
 
 
 
 
 
 
 
 
 
 
37
  if resp.StatusCode == http.StatusOK {
38
  resp = c.wrapCompletionWithAutoContinue(ctx, a, payload, powResp, resp)
39
  }
 
34
  if captureSession != nil {
35
  resp.Body = captureSession.WrapBody(resp.Body, resp.StatusCode)
36
  }
37
+ // 上游在账号禁言、PoW 头缺失/失效等场景会返回 HTTP 200 + JSON,
38
+ // 而不是 SSE。必须在这里识别,否则会被当成空流,最终对外表现为 503。
39
+ if IsNonSSEError(resp) {
40
+ if bizErr := DecodeUpstreamBizError(resp); bizErr != nil {
41
+ if bizErr.IsMuted() {
42
+ RecordAccountMute(c.Store, a, bizErr.MutedUntil)
43
+ }
44
+ return nil, bizErr
45
+ }
46
+ }
47
  if resp.StatusCode == http.StatusOK {
48
  resp = c.wrapCompletionWithAutoContinue(ctx, a, payload, powResp, resp)
49
  }
internal/deepseek/client/client_continue.go CHANGED
@@ -82,6 +82,15 @@ func (c *Client) callContinue(ctx context.Context, a *auth.RequestAuth, sessionI
82
  _ = resp.Body.Close()
83
  return nil, errors.New("continue failed")
84
  }
 
 
 
 
 
 
 
 
 
85
  return resp, nil
86
  }
87
 
 
82
  _ = resp.Body.Close()
83
  return nil, errors.New("continue failed")
84
  }
85
+ if IsNonSSEError(resp) {
86
+ if bizErr := DecodeUpstreamBizError(resp); bizErr != nil {
87
+ if bizErr.IsMuted() {
88
+ RecordAccountMute(c.Store, a, bizErr.MutedUntil)
89
+ }
90
+ _ = resp.Body.Close()
91
+ return nil, bizErr
92
+ }
93
+ }
94
  return resp, nil
95
  }
96
 
internal/deepseek/client/client_upstream_error.go ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package client
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "io"
8
+ "net/http"
9
+ "strings"
10
+
11
+ "ds2api/internal/auth"
12
+ "ds2api/internal/config"
13
+ )
14
+
15
+ // maxUpstreamJSONBody 限制读取上游 JSON 错误体的最大字节数,避免异常响应撑爆内存。
16
+ const maxUpstreamJSONBody = 64 << 10
17
+
18
+ // UpstreamBizError 表示上游以 HTTP 200 + JSON 返回的业务错误。
19
+ //
20
+ // 正常聊天响应是 text/event-stream;当账号被禁言、PoW 头缺失/失效或参数
21
+ // 非法时,上游会直接返回 application/json,例如:
22
+ //
23
+ // {"code":0,"data":{"biz_code":5,"biz_msg":"user is muted",
24
+ // "biz_data":{"is_muted":1,"mute_until":1826030258}}}
25
+ // {"code":40300,"msg":"MISSING_HEADER","data":null}
26
+ //
27
+ // 早期实现把这类响应当成空 SSE 流处理,最终对外表现为
28
+ // “Upstream service is unavailable and returned no output.”(503),
29
+ // 掩盖了真实原因。
30
+ type UpstreamBizError struct {
31
+ HTTPStatus int
32
+ Code int
33
+ BizCode int
34
+ Msg string
35
+ BizMsg string
36
+ MutedUntil int64
37
+ }
38
+
39
+ func (e *UpstreamBizError) Error() string {
40
+ if e == nil {
41
+ return ""
42
+ }
43
+ parts := make([]string, 0, 4)
44
+ if e.Code != 0 {
45
+ parts = append(parts, fmt.Sprintf("code=%d", e.Code))
46
+ }
47
+ if e.BizCode != 0 {
48
+ parts = append(parts, fmt.Sprintf("biz_code=%d", e.BizCode))
49
+ }
50
+ if strings.TrimSpace(e.Msg) != "" {
51
+ parts = append(parts, "msg="+strings.TrimSpace(e.Msg))
52
+ }
53
+ if strings.TrimSpace(e.BizMsg) != "" {
54
+ parts = append(parts, "biz_msg="+strings.TrimSpace(e.BizMsg))
55
+ }
56
+ if len(parts) == 0 {
57
+ return "upstream returned a non-SSE error response"
58
+ }
59
+ return "upstream error: " + strings.Join(parts, " ")
60
+ }
61
+
62
+ // IsMuted 判断该错误是否为账号禁言。
63
+ func (e *UpstreamBizError) IsMuted() bool {
64
+ if e == nil {
65
+ return false
66
+ }
67
+ if e.BizCode == 5 {
68
+ return true
69
+ }
70
+ msg := strings.ToLower(strings.TrimSpace(e.BizMsg + " " + e.Msg))
71
+ return strings.Contains(msg, "muted") || strings.Contains(msg, "禁言")
72
+ }
73
+
74
+ // IsNonSSEError 表示响应体是 JSON 业务错误,而不是正常的 SSE 流。
75
+ func IsNonSSEError(resp *http.Response) bool {
76
+ if resp == nil {
77
+ return false
78
+ }
79
+ ct := strings.ToLower(strings.TrimSpace(resp.Header.Get("Content-Type")))
80
+ return strings.Contains(ct, "application/json") || strings.Contains(ct, "text/json")
81
+ }
82
+
83
+ // DecodeUpstreamBizError 读取并解析 JSON 错误体;不是业务错误时返回 nil。
84
+ // 无论是否命中,响应体都会被替换成可重复读取的副本。
85
+ func DecodeUpstreamBizError(resp *http.Response) *UpstreamBizError {
86
+ if resp == nil || resp.Body == nil {
87
+ return nil
88
+ }
89
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, maxUpstreamJSONBody+1))
90
+ if err != nil {
91
+ resp.Body = io.NopCloser(bytes.NewReader(raw))
92
+ return nil
93
+ }
94
+ _ = resp.Body.Close()
95
+ resp.Body = io.NopCloser(bytes.NewReader(raw))
96
+ if len(raw) == 0 || len(raw) > maxUpstreamJSONBody {
97
+ return nil
98
+ }
99
+ trimmed := bytes.TrimSpace(raw)
100
+ if len(trimmed) == 0 || trimmed[0] != '{' {
101
+ return nil
102
+ }
103
+ var payload struct {
104
+ Code int `json:"code"`
105
+ Msg string `json:"msg"`
106
+ Data *struct {
107
+ BizCode int `json:"biz_code"`
108
+ BizMsg string `json:"biz_msg"`
109
+ BizData *struct {
110
+ IsMuted float64 `json:"is_muted"`
111
+ MuteUntil float64 `json:"mute_until"`
112
+ Message any `json:"msg"`
113
+ Rotate any `json:"rotate"`
114
+ ChatState any `json:"chat"`
115
+ } `json:"biz_data"`
116
+ } `json:"data"`
117
+ }
118
+ if err := json.Unmarshal(trimmed, &payload); err != nil {
119
+ return nil
120
+ }
121
+ code := payload.Code
122
+ bizCode := 0
123
+ msg := payload.Msg
124
+ bizMsg := ""
125
+ var mutedUntil int64
126
+ if payload.Data != nil {
127
+ bizCode = payload.Data.BizCode
128
+ bizMsg = payload.Data.BizMsg
129
+ if payload.Data.BizData != nil {
130
+ mutedUntil = int64(payload.Data.BizData.MuteUntil)
131
+ }
132
+ }
133
+ if code == 0 && bizCode == 0 {
134
+ return nil
135
+ }
136
+ return &UpstreamBizError{
137
+ HTTPStatus: resp.StatusCode,
138
+ Code: code,
139
+ BizCode: bizCode,
140
+ Msg: msg,
141
+ BizMsg: bizMsg,
142
+ MutedUntil: mutedUntil,
143
+ }
144
+ }
145
+
146
+ // RecordAccountMute 把账号禁言状态落库,并同步到当前请求的账号副本,
147
+ // 便于账号池在后续请求中跳过该账号。
148
+ func RecordAccountMute(store *config.Store, a *auth.RequestAuth, until int64) {
149
+ if until <= 0 {
150
+ return
151
+ }
152
+ if a != nil {
153
+ a.Account.MutedUntil = until
154
+ }
155
+ if store == nil {
156
+ return
157
+ }
158
+ identifier := ""
159
+ if a != nil {
160
+ identifier = a.AccountID
161
+ if strings.TrimSpace(identifier) == "" {
162
+ identifier = a.Account.Identifier()
163
+ }
164
+ }
165
+ if strings.TrimSpace(identifier) == "" {
166
+ return
167
+ }
168
+ if existing, ok := store.FindAccount(identifier); ok && existing.MutedUntil == until {
169
+ return
170
+ }
171
+ if err := store.UpdateAccountMute(identifier, until); err != nil {
172
+ config.Logger.Warn("[account_muted] persist mute state failed", "account", identifier, "until", until, "error", err)
173
+ return
174
+ }
175
+ config.Logger.Warn("[account_muted] account muted by upstream", "account", identifier, "until", until)
176
+ }
177
+
178
+ // ParseLoginMute 从登录响应的 biz_data.user.chat 中解析禁言状态。
179
+ // present 为 false 表示响应里没有 chat 字段(不能据此清除已有状态)。
180
+ func ParseLoginMute(bizData map[string]any) (muted bool, until int64, present bool) {
181
+ user, _ := bizData["user"].(map[string]any)
182
+ if user == nil {
183
+ return false, 0, false
184
+ }
185
+ chat, _ := user["chat"].(map[string]any)
186
+ if chat == nil {
187
+ return false, 0, false
188
+ }
189
+ until = int64(intFrom(chat["mute_until"]))
190
+ muted = intFrom(chat["is_muted"]) != 0 || until > 0
191
+ return muted, until, true
192
+ }
internal/deepseek/client/client_upstream_error_test.go ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package client
2
+
3
+ import (
4
+ "io"
5
+ "net/http"
6
+ "strings"
7
+ "testing"
8
+ )
9
+
10
+ func jsonResponse(body string) *http.Response {
11
+ return &http.Response{
12
+ StatusCode: http.StatusOK,
13
+ Header: http.Header{"Content-Type": []string{"application/json"}},
14
+ Body: io.NopCloser(strings.NewReader(body)),
15
+ }
16
+ }
17
+
18
+ func TestDecodeUpstreamBizErrorMuted(t *testing.T) {
19
+ resp := jsonResponse(`{"code":0,"msg":"","data":{"biz_code":5,"biz_msg":"user is muted","biz_data":{"is_muted":1,"mute_until":1826030258.0,"msg":null}}}`)
20
+ if !IsNonSSEError(resp) {
21
+ t.Fatal("expected json response to be detected")
22
+ }
23
+ bizErr := DecodeUpstreamBizError(resp)
24
+ if bizErr == nil {
25
+ t.Fatal("expected biz error")
26
+ }
27
+ if !bizErr.IsMuted() {
28
+ t.Fatalf("expected muted, got %#v", bizErr)
29
+ }
30
+ if bizErr.MutedUntil != 1826030258 {
31
+ t.Fatalf("unexpected mute_until: %d", bizErr.MutedUntil)
32
+ }
33
+ // 响应体必须被恢复,便于上层继续读取。
34
+ body, _ := io.ReadAll(resp.Body)
35
+ if !strings.Contains(string(body), "user is muted") {
36
+ t.Fatalf("body not restored: %s", body)
37
+ }
38
+ }
39
+
40
+ func TestDecodeUpstreamBizErrorMissingHeader(t *testing.T) {
41
+ resp := jsonResponse(`{"code":40300,"msg":"MISSING_HEADER","data":null}`)
42
+ bizErr := DecodeUpstreamBizError(resp)
43
+ if bizErr == nil || bizErr.Code != 40300 || bizErr.IsMuted() {
44
+ t.Fatalf("unexpected decode result: %#v", bizErr)
45
+ }
46
+ }
47
+
48
+ func TestDecodeUpstreamBizErrorIgnoresSuccess(t *testing.T) {
49
+ resp := jsonResponse(`{"code":0,"msg":"","data":{"biz_code":0,"biz_data":{}}}`)
50
+ if bizErr := DecodeUpstreamBizError(resp); bizErr != nil {
51
+ t.Fatalf("expected nil for success payload, got %#v", bizErr)
52
+ }
53
+ }
54
+
55
+ func TestParseLoginMute(t *testing.T) {
56
+ muted, until, present := ParseLoginMute(map[string]any{
57
+ "user": map[string]any{
58
+ "chat": map[string]any{"is_muted": 1.0, "mute_until": 1826030258.0},
59
+ },
60
+ })
61
+ if !present || !muted || until != 1826030258 {
62
+ t.Fatalf("unexpected parse: muted=%v until=%d present=%v", muted, until, present)
63
+ }
64
+ if _, _, present := ParseLoginMute(map[string]any{"user": map[string]any{}}); present {
65
+ t.Fatal("expected chat absence to be reported as not present")
66
+ }
67
+ }
internal/httpapi/admin/accounts/handler_accounts_crud.go CHANGED
@@ -71,6 +71,7 @@ func (h *Handler) listAccounts(w http.ResponseWriter, r *http.Request) {
71
  "test_status": testStatus,
72
  "role": acc.Role,
73
  "banned": acc.Banned,
 
74
  "device_id": acc.DeviceID,
75
  "device_id_preview": maskSecretPreview(acc.DeviceID),
76
  "rangers_id": acc.RangersID,
 
71
  "test_status": testStatus,
72
  "role": acc.Role,
73
  "banned": acc.Banned,
74
+ "muted_until": acc.MutedUntil,
75
  "device_id": acc.DeviceID,
76
  "device_id_preview": maskSecretPreview(acc.DeviceID),
77
  "rangers_id": acc.RangersID,
internal/httpapi/admin/accounts/handler_accounts_testing.go CHANGED
@@ -154,6 +154,12 @@ func (h *Handler) testAccount(ctx context.Context, acc config.Account, model, me
154
  if strings.TrimSpace(message) == "" {
155
  result["success"] = true
156
  result["message"] = "Token 刷新成功(登录与会话创建成功)"
 
 
 
 
 
 
157
  if warning, _ := result["config_warning"].(string); strings.TrimSpace(warning) != "" {
158
  result["message"] = result["message"].(string) + ";" + warning
159
  }
 
154
  if strings.TrimSpace(message) == "" {
155
  result["success"] = true
156
  result["message"] = "Token 刷新成功(登录与会话创建成功)"
157
+ if latest, ok := h.Store.FindAccount(identifier); ok && latest.MutedUntil > time.Now().Unix() {
158
+ until := time.Unix(latest.MutedUntil, 0).In(time.FixedZone("CST", 8*3600))
159
+ result["muted"] = true
160
+ result["muted_until"] = latest.MutedUntil
161
+ result["message"] = "Token 刷新成功,但账号已被上游禁言至 " + until.Format("2006-01-02 15:04:05 MST") + ",聊天请求会被拒绝"
162
+ }
163
  if warning, _ := result["config_warning"].(string); strings.TrimSpace(warning) != "" {
164
  result["message"] = result["message"].(string) + ";" + warning
165
  }
internal/httpapi/admin/handler.go CHANGED
@@ -9,6 +9,7 @@ import (
9
  adminconfig "ds2api/internal/httpapi/admin/configmgmt"
10
  admindevcapture "ds2api/internal/httpapi/admin/devcapture"
11
  adminhistory "ds2api/internal/httpapi/admin/history"
 
12
  adminmodelprofiles "ds2api/internal/httpapi/admin/modelprofiles"
13
  adminproxies "ds2api/internal/httpapi/admin/proxies"
14
  adminrawsamples "ds2api/internal/httpapi/admin/rawsamples"
@@ -18,6 +19,7 @@ import (
18
  adminvercel "ds2api/internal/httpapi/admin/vercel"
19
  adminversion "ds2api/internal/httpapi/admin/version"
20
  "ds2api/internal/proxyhealth"
 
21
  )
22
 
23
  type Handler struct {
@@ -27,6 +29,8 @@ type Handler struct {
27
  OpenAI adminshared.OpenAIChatCaller
28
  ChatHistory *chathistory.Store
29
  Checker *proxyhealth.Checker
 
 
30
  }
31
 
32
  func RegisterRoutes(r chi.Router, h *Handler) {
@@ -43,6 +47,7 @@ func RegisterRoutes(r chi.Router, h *Handler) {
43
  modelProfilesHandler := &adminmodelprofiles.Handler{Store: deps.Store, Pool: deps.Pool, DS: deps.DS, OpenAI: deps.OpenAI, ChatHistory: deps.ChatHistory}
44
  devCaptureHandler := &admindevcapture.Handler{Store: deps.Store, Pool: deps.Pool, DS: deps.DS, OpenAI: deps.OpenAI, ChatHistory: deps.ChatHistory}
45
  versionHandler := &adminversion.Handler{Store: deps.Store, Pool: deps.Pool, DS: deps.DS, OpenAI: deps.OpenAI, ChatHistory: deps.ChatHistory}
 
46
 
47
  adminauth.RegisterPublicRoutes(r, authHandler)
48
  r.Group(func(pr chi.Router) {
@@ -59,6 +64,7 @@ func RegisterRoutes(r chi.Router, h *Handler) {
59
  admindevcapture.RegisterRoutes(pr, devCaptureHandler)
60
  adminhistory.RegisterRoutes(pr, historyHandler)
61
  adminversion.RegisterRoutes(pr, versionHandler)
 
62
  })
63
  }
64
 
 
9
  adminconfig "ds2api/internal/httpapi/admin/configmgmt"
10
  admindevcapture "ds2api/internal/httpapi/admin/devcapture"
11
  adminhistory "ds2api/internal/httpapi/admin/history"
12
+ adminlogs "ds2api/internal/httpapi/admin/logs"
13
  adminmodelprofiles "ds2api/internal/httpapi/admin/modelprofiles"
14
  adminproxies "ds2api/internal/httpapi/admin/proxies"
15
  adminrawsamples "ds2api/internal/httpapi/admin/rawsamples"
 
19
  adminvercel "ds2api/internal/httpapi/admin/vercel"
20
  adminversion "ds2api/internal/httpapi/admin/version"
21
  "ds2api/internal/proxyhealth"
22
+ "ds2api/internal/reqlog"
23
  )
24
 
25
  type Handler struct {
 
29
  OpenAI adminshared.OpenAIChatCaller
30
  ChatHistory *chathistory.Store
31
  Checker *proxyhealth.Checker
32
+ Logs *reqlog.Store
33
+ LogKeys *reqlog.KeyStore
34
  }
35
 
36
  func RegisterRoutes(r chi.Router, h *Handler) {
 
47
  modelProfilesHandler := &adminmodelprofiles.Handler{Store: deps.Store, Pool: deps.Pool, DS: deps.DS, OpenAI: deps.OpenAI, ChatHistory: deps.ChatHistory}
48
  devCaptureHandler := &admindevcapture.Handler{Store: deps.Store, Pool: deps.Pool, DS: deps.DS, OpenAI: deps.OpenAI, ChatHistory: deps.ChatHistory}
49
  versionHandler := &adminversion.Handler{Store: deps.Store, Pool: deps.Pool, DS: deps.DS, OpenAI: deps.OpenAI, ChatHistory: deps.ChatHistory}
50
+ logsHandler := &adminlogs.Handler{Store: h.Logs, Keys: h.LogKeys}
51
 
52
  adminauth.RegisterPublicRoutes(r, authHandler)
53
  r.Group(func(pr chi.Router) {
 
64
  admindevcapture.RegisterRoutes(pr, devCaptureHandler)
65
  adminhistory.RegisterRoutes(pr, historyHandler)
66
  adminversion.RegisterRoutes(pr, versionHandler)
67
+ adminlogs.RegisterAdminRoutes(pr, logsHandler)
68
  })
69
  }
70
 
internal/httpapi/openai/chat/handler_chat.go CHANGED
@@ -15,6 +15,7 @@ import (
15
  dsprotocol "ds2api/internal/deepseek/protocol"
16
  openaifmt "ds2api/internal/format/openai"
17
  "ds2api/internal/promptcompat"
 
18
  "ds2api/internal/sse"
19
  streamengine "ds2api/internal/stream"
20
  )
@@ -41,7 +42,7 @@ func (h *Handler) ChatCompletions(w http.ResponseWriter, r *http.Request) {
41
  if err != nil {
42
  status := http.StatusUnauthorized
43
  detail := err.Error()
44
- if err == auth.ErrNoAccount {
45
  status = http.StatusTooManyRequests
46
  }
47
  writeOpenAIError(w, status, detail)
@@ -84,6 +85,8 @@ func (h *Handler) ChatCompletions(w http.ResponseWriter, r *http.Request) {
84
  return
85
  }
86
  historySession := startChatHistory(h.ChatHistory, r, a, stdReq)
 
 
87
 
88
  if !stdReq.Stream {
89
  result, outErr := completionruntime.ExecuteNonStreamWithRetry(r.Context(), h.DS, a, stdReq, completionruntime.Options{
 
15
  dsprotocol "ds2api/internal/deepseek/protocol"
16
  openaifmt "ds2api/internal/format/openai"
17
  "ds2api/internal/promptcompat"
18
+ "ds2api/internal/reqlog"
19
  "ds2api/internal/sse"
20
  streamengine "ds2api/internal/stream"
21
  )
 
42
  if err != nil {
43
  status := http.StatusUnauthorized
44
  detail := err.Error()
45
+ if auth.IsNoAccountError(err) {
46
  status = http.StatusTooManyRequests
47
  }
48
  writeOpenAIError(w, status, detail)
 
85
  return
86
  }
87
  historySession := startChatHistory(h.ChatHistory, r, a, stdReq)
88
+ reqlog.SetModel(r.Context(), stdReq.ResponseModel)
89
+ reqlog.SetStream(r.Context(), stdReq.Stream)
90
 
91
  if !stdReq.Stream {
92
  result, outErr := completionruntime.ExecuteNonStreamWithRetry(r.Context(), h.DS, a, stdReq, completionruntime.Options{
internal/httpapi/openai/chat/vercel_stream.go CHANGED
@@ -34,7 +34,7 @@ func (h *Handler) handleVercelStreamPrepare(w http.ResponseWriter, r *http.Reque
34
  a, err := h.Auth.Determine(r)
35
  if err != nil {
36
  status := http.StatusUnauthorized
37
- if err == auth.ErrNoAccount {
38
  status = http.StatusTooManyRequests
39
  }
40
  writeOpenAIError(w, status, err.Error())
 
34
  a, err := h.Auth.Determine(r)
35
  if err != nil {
36
  status := http.StatusUnauthorized
37
+ if auth.IsNoAccountError(err) {
38
  status = http.StatusTooManyRequests
39
  }
40
  writeOpenAIError(w, status, err.Error())
internal/httpapi/openai/embeddings/embeddings_handler.go CHANGED
@@ -27,7 +27,7 @@ func (h *Handler) Embeddings(w http.ResponseWriter, r *http.Request) {
27
  if err != nil {
28
  status := http.StatusUnauthorized
29
  detail := err.Error()
30
- if err == auth.ErrNoAccount {
31
  status = http.StatusTooManyRequests
32
  }
33
  shared.WriteOpenAIError(w, status, detail)
 
27
  if err != nil {
28
  status := http.StatusUnauthorized
29
  detail := err.Error()
30
+ if auth.IsNoAccountError(err) {
31
  status = http.StatusTooManyRequests
32
  }
33
  shared.WriteOpenAIError(w, status, detail)
internal/httpapi/openai/files/handler_files.go CHANGED
@@ -35,7 +35,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
35
  if err != nil {
36
  status := http.StatusUnauthorized
37
  detail := err.Error()
38
- if err == auth.ErrNoAccount {
39
  status = http.StatusTooManyRequests
40
  }
41
  shared.WriteOpenAIError(w, status, detail)
@@ -98,7 +98,7 @@ func (h *Handler) RetrieveFile(w http.ResponseWriter, r *http.Request) {
98
  if err != nil {
99
  status := http.StatusUnauthorized
100
  detail := err.Error()
101
- if err == auth.ErrNoAccount {
102
  status = http.StatusTooManyRequests
103
  }
104
  shared.WriteOpenAIError(w, status, detail)
 
35
  if err != nil {
36
  status := http.StatusUnauthorized
37
  detail := err.Error()
38
+ if auth.IsNoAccountError(err) {
39
  status = http.StatusTooManyRequests
40
  }
41
  shared.WriteOpenAIError(w, status, detail)
 
98
  if err != nil {
99
  status := http.StatusUnauthorized
100
  detail := err.Error()
101
+ if auth.IsNoAccountError(err) {
102
  status = http.StatusTooManyRequests
103
  }
104
  shared.WriteOpenAIError(w, status, detail)
internal/httpapi/openai/responses/responses_handler.go CHANGED
@@ -18,6 +18,7 @@ import (
18
  dsprotocol "ds2api/internal/deepseek/protocol"
19
  openaifmt "ds2api/internal/format/openai"
20
  "ds2api/internal/promptcompat"
 
21
  "ds2api/internal/responsehistory"
22
  "ds2api/internal/sse"
23
  streamengine "ds2api/internal/stream"
@@ -54,7 +55,7 @@ func (h *Handler) Responses(w http.ResponseWriter, r *http.Request) {
54
  if err != nil {
55
  status := http.StatusUnauthorized
56
  detail := err.Error()
57
- if err == auth.ErrNoAccount {
58
  status = http.StatusTooManyRequests
59
  }
60
  writeOpenAIError(w, status, detail)
@@ -98,6 +99,8 @@ func (h *Handler) Responses(w http.ResponseWriter, r *http.Request) {
98
  }
99
 
100
  responseID := "resp_" + strings.ReplaceAll(uuid.NewString(), "-", "")
 
 
101
  historySession := responsehistory.Start(responsehistory.StartParams{
102
  Store: h.ChatHistory,
103
  Request: r,
 
18
  dsprotocol "ds2api/internal/deepseek/protocol"
19
  openaifmt "ds2api/internal/format/openai"
20
  "ds2api/internal/promptcompat"
21
+ "ds2api/internal/reqlog"
22
  "ds2api/internal/responsehistory"
23
  "ds2api/internal/sse"
24
  streamengine "ds2api/internal/stream"
 
55
  if err != nil {
56
  status := http.StatusUnauthorized
57
  detail := err.Error()
58
+ if auth.IsNoAccountError(err) {
59
  status = http.StatusTooManyRequests
60
  }
61
  writeOpenAIError(w, status, detail)
 
99
  }
100
 
101
  responseID := "resp_" + strings.ReplaceAll(uuid.NewString(), "-", "")
102
+ reqlog.SetModel(r.Context(), stdReq.ResponseModel)
103
+ reqlog.SetStream(r.Context(), stdReq.Stream)
104
  historySession := responsehistory.Start(responsehistory.StartParams{
105
  Store: h.ChatHistory,
106
  Request: r,
internal/httpapi/openai/shared/handler_errors.go CHANGED
@@ -10,6 +10,8 @@ func WriteOpenAIErrorWithCode(w http.ResponseWriter, status int, message, code s
10
  if code == "" {
11
  code = OpenAIErrorCode(status)
12
  }
 
 
13
  WriteJSON(w, status, map[string]any{
14
  "error": map[string]any{
15
  "message": message,
 
10
  if code == "" {
11
  code = OpenAIErrorCode(status)
12
  }
13
+ // 供请求日志中间件采集错误码,不参与业务逻辑。
14
+ w.Header().Set("X-Ds2-Error-Code", code)
15
  WriteJSON(w, status, map[string]any{
16
  "error": map[string]any{
17
  "message": message,
internal/proxyhealth/checker.go CHANGED
@@ -12,13 +12,13 @@ import (
12
  )
13
 
14
  const (
15
- defaultCheckInterval = 5 * time.Hour
16
- bgRetryDelay = 1 * time.Minute
17
- bgMaxRetries = 2
18
- connectivityTimeout = 15 * time.Second
19
- onDemandRetryDelay = 3 * time.Second
20
- onDemandMaxRetries = 1
21
- onDemandConnectTimeout = 10 * time.Second
22
  )
23
 
24
  // Checker periodically tests proxy connectivity and auto-bans failing proxies.
 
12
  )
13
 
14
  const (
15
+ defaultCheckInterval = 5 * time.Hour
16
+ bgRetryDelay = 1 * time.Minute
17
+ bgMaxRetries = 2
18
+ connectivityTimeout = 15 * time.Second
19
+ onDemandRetryDelay = 3 * time.Second
20
+ onDemandMaxRetries = 1
21
+ onDemandConnectTimeout = 10 * time.Second
22
  )
23
 
24
  // Checker periodically tests proxy connectivity and auto-bans failing proxies.
internal/reqlog/context.go ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package reqlog
2
+
3
+ import (
4
+ "context"
5
+ "strings"
6
+ "sync"
7
+ )
8
+
9
+ type ctxKey struct{}
10
+
11
+ // Record 是中间件挂在 request context 上的可变记录,业务代码可补充字段。
12
+ type Record struct {
13
+ mu sync.Mutex
14
+ e Entry
15
+ }
16
+
17
+ func WithRecord(ctx context.Context, rec *Record) context.Context {
18
+ return context.WithValue(ctx, ctxKey{}, rec)
19
+ }
20
+
21
+ func FromContext(ctx context.Context) *Record {
22
+ if ctx == nil {
23
+ return nil
24
+ }
25
+ rec, _ := ctx.Value(ctxKey{}).(*Record)
26
+ return rec
27
+ }
28
+
29
+ func (r *Record) set(fn func(*Entry)) {
30
+ if r == nil {
31
+ return
32
+ }
33
+ r.mu.Lock()
34
+ fn(&r.e)
35
+ r.mu.Unlock()
36
+ }
37
+
38
+ // Snapshot 返回当前记录的副本。
39
+ func (r *Record) Snapshot() Entry {
40
+ if r == nil {
41
+ return Entry{}
42
+ }
43
+ r.mu.Lock()
44
+ defer r.mu.Unlock()
45
+ return r.e
46
+ }
47
+
48
+ func SetAPIKey(ctx context.Context, name, masked string) {
49
+ FromContext(ctx).set(func(e *Entry) {
50
+ if name != "" {
51
+ e.APIKeyName = name
52
+ }
53
+ if masked != "" {
54
+ e.APIKey = masked
55
+ }
56
+ })
57
+ }
58
+
59
+ func SetAccount(ctx context.Context, account string) {
60
+ FromContext(ctx).set(func(e *Entry) { e.Account = account })
61
+ }
62
+
63
+ func SetModel(ctx context.Context, model string) {
64
+ FromContext(ctx).set(func(e *Entry) { e.Model = model })
65
+ }
66
+
67
+ func SetStream(ctx context.Context, stream bool) {
68
+ FromContext(ctx).set(func(e *Entry) { e.Stream = stream })
69
+ }
70
+
71
+ func SetErrorCode(ctx context.Context, code, message string) {
72
+ FromContext(ctx).set(func(e *Entry) {
73
+ if code != "" {
74
+ e.ErrorCode = code
75
+ }
76
+ if message != "" {
77
+ e.Error = truncate(message, 500)
78
+ }
79
+ })
80
+ }
81
+
82
+ func SetUpstream(ctx context.Context, detail string) {
83
+ FromContext(ctx).set(func(e *Entry) { e.Upstream = truncate(detail, 500) })
84
+ }
85
+
86
+ func truncate(s string, max int) string {
87
+ s = strings.TrimSpace(s)
88
+ if len(s) <= max {
89
+ return s
90
+ }
91
+ return s[:max] + "..."
92
+ }
93
+
94
+ // MaskKey 只保留密钥前 6 位,避免日志泄露完整凭证。
95
+ func MaskKey(key string) string {
96
+ key = strings.TrimSpace(key)
97
+ if key == "" {
98
+ return ""
99
+ }
100
+ if len(key) <= 6 {
101
+ return "***"
102
+ }
103
+ return key[:6] + "***"
104
+ }
internal/reqlog/keys.go ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package reqlog
2
+
3
+ import (
4
+ "crypto/rand"
5
+ "crypto/sha256"
6
+ "encoding/hex"
7
+ "encoding/json"
8
+ "errors"
9
+ "os"
10
+ "path/filepath"
11
+ "sort"
12
+ "strings"
13
+ "sync"
14
+ "time"
15
+ )
16
+
17
+ // LogKey 是只读日志 API 的访问凭证。只保存 SHA-256 哈希,明文仅在创建时返回一次。
18
+ type LogKey struct {
19
+ ID string `json:"id"`
20
+ Name string `json:"name"`
21
+ Prefix string `json:"prefix"`
22
+ Hash string `json:"hash"`
23
+ CreatedAt int64 `json:"created_at"`
24
+ ExpiresAt int64 `json:"expires_at,omitempty"`
25
+ LastUsedAt int64 `json:"last_used_at,omitempty"`
26
+ RevokedAt int64 `json:"revoked_at,omitempty"`
27
+ }
28
+
29
+ // Public 用于返回给管理界面,隐藏哈希。
30
+ type PublicLogKey struct {
31
+ ID string `json:"id"`
32
+ Name string `json:"name"`
33
+ Prefix string `json:"prefix"`
34
+ CreatedAt int64 `json:"created_at"`
35
+ ExpiresAt int64 `json:"expires_at,omitempty"`
36
+ LastUsedAt int64 `json:"last_used_at,omitempty"`
37
+ Revoked bool `json:"revoked"`
38
+ }
39
+
40
+ func (k LogKey) Public() PublicLogKey {
41
+ return PublicLogKey{
42
+ ID: k.ID,
43
+ Name: k.Name,
44
+ Prefix: k.Prefix,
45
+ CreatedAt: k.CreatedAt,
46
+ ExpiresAt: k.ExpiresAt,
47
+ LastUsedAt: k.LastUsedAt,
48
+ Revoked: k.RevokedAt > 0,
49
+ }
50
+ }
51
+
52
+ // KeyStore 负责日志 API Key 的生成、校验与持久化。
53
+ type KeyStore struct {
54
+ mu sync.RWMutex
55
+ path string
56
+ keys []LogKey
57
+ byHash map[string]int
58
+ }
59
+
60
+ const KeyPrefix = "ds2log_"
61
+
62
+ func NewKeyStore(path string) *KeyStore {
63
+ s := &KeyStore{path: strings.TrimSpace(path), byHash: map[string]int{}}
64
+ s.load()
65
+ return s
66
+ }
67
+
68
+ func (s *KeyStore) load() {
69
+ if s.path == "" {
70
+ return
71
+ }
72
+ b, err := os.ReadFile(s.path)
73
+ if err != nil {
74
+ if !os.IsNotExist(err) {
75
+ // 读取失败时保持空列表,避免影响服务启动。
76
+ return
77
+ }
78
+ return
79
+ }
80
+ var keys []LogKey
81
+ if err := json.Unmarshal(b, &keys); err != nil {
82
+ return
83
+ }
84
+ s.mu.Lock()
85
+ s.keys = keys
86
+ s.rebuildLocked()
87
+ s.mu.Unlock()
88
+ }
89
+
90
+ func (s *KeyStore) rebuildLocked() {
91
+ s.byHash = make(map[string]int, len(s.keys))
92
+ for i, k := range s.keys {
93
+ if k.Hash != "" {
94
+ s.byHash[k.Hash] = i
95
+ }
96
+ }
97
+ }
98
+
99
+ func (s *KeyStore) saveLocked() error {
100
+ if s.path == "" {
101
+ return nil
102
+ }
103
+ if err := os.MkdirAll(filepath.Dir(s.path), 0o750); err != nil {
104
+ return err
105
+ }
106
+ b, err := json.MarshalIndent(s.keys, "", " ")
107
+ if err != nil {
108
+ return err
109
+ }
110
+ tmp := s.path + ".tmp"
111
+ if err := os.WriteFile(tmp, b, 0o600); err != nil {
112
+ return err
113
+ }
114
+ return os.Rename(tmp, s.path)
115
+ }
116
+
117
+ // Create 生成新 key,返回明文与记录。
118
+ func (s *KeyStore) Create(name string, ttl time.Duration) (string, PublicLogKey, error) {
119
+ name = strings.TrimSpace(name)
120
+ if name == "" {
121
+ name = "log-reader"
122
+ }
123
+ buf := make([]byte, 24)
124
+ if _, err := rand.Read(buf); err != nil {
125
+ return "", PublicLogKey{}, err
126
+ }
127
+ plain := KeyPrefix + hex.EncodeToString(buf)
128
+ sum := sha256.Sum256([]byte(plain))
129
+ now := time.Now()
130
+ item := LogKey{
131
+ ID: "lk_" + hex.EncodeToString(buf[:6]),
132
+ Name: name,
133
+ Prefix: plain[:len(KeyPrefix)+6],
134
+ Hash: hex.EncodeToString(sum[:]),
135
+ CreatedAt: now.Unix(),
136
+ }
137
+ if ttl > 0 {
138
+ item.ExpiresAt = now.Add(ttl).Unix()
139
+ }
140
+ s.mu.Lock()
141
+ s.keys = append(s.keys, item)
142
+ s.rebuildLocked()
143
+ err := s.saveLocked()
144
+ s.mu.Unlock()
145
+ if err != nil {
146
+ return "", PublicLogKey{}, err
147
+ }
148
+ return plain, item.Public(), nil
149
+ }
150
+
151
+ // Verify 校验 token;成功后刷新 last_used_at(最多每分钟写一次盘)。
152
+ func (s *KeyStore) Verify(token string) (PublicLogKey, bool) {
153
+ token = strings.TrimSpace(token)
154
+ if token == "" || !strings.HasPrefix(token, KeyPrefix) {
155
+ return PublicLogKey{}, false
156
+ }
157
+ sum := sha256.Sum256([]byte(token))
158
+ hash := hex.EncodeToString(sum[:])
159
+ now := time.Now().Unix()
160
+ s.mu.Lock()
161
+ defer s.mu.Unlock()
162
+ idx, ok := s.byHash[hash]
163
+ if !ok {
164
+ return PublicLogKey{}, false
165
+ }
166
+ item := s.keys[idx]
167
+ if item.RevokedAt > 0 {
168
+ return PublicLogKey{}, false
169
+ }
170
+ if item.ExpiresAt > 0 && item.ExpiresAt <= now {
171
+ return PublicLogKey{}, false
172
+ }
173
+ if now-item.LastUsedAt >= 60 {
174
+ s.keys[idx].LastUsedAt = now
175
+ if err := s.saveLocked(); err != nil {
176
+ // 使用记录写盘失败不影响鉴权结果。
177
+ _ = err
178
+ }
179
+ }
180
+ return s.keys[idx].Public(), true
181
+ }
182
+
183
+ // List 返回全部 key(新的在前)。
184
+ func (s *KeyStore) List() []PublicLogKey {
185
+ s.mu.RLock()
186
+ defer s.mu.RUnlock()
187
+ out := make([]PublicLogKey, 0, len(s.keys))
188
+ for _, k := range s.keys {
189
+ out = append(out, k.Public())
190
+ }
191
+ sort.SliceStable(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt })
192
+ return out
193
+ }
194
+
195
+ var ErrKeyNotFound = errors.New("log key not found")
196
+
197
+ // Revoke 立即吊销 key。
198
+ func (s *KeyStore) Revoke(id string) error {
199
+ id = strings.TrimSpace(id)
200
+ s.mu.Lock()
201
+ defer s.mu.Unlock()
202
+ for i := range s.keys {
203
+ if s.keys[i].ID != id {
204
+ continue
205
+ }
206
+ if s.keys[i].RevokedAt == 0 {
207
+ s.keys[i].RevokedAt = time.Now().Unix()
208
+ return s.saveLocked()
209
+ }
210
+ return nil
211
+ }
212
+ return ErrKeyNotFound
213
+ }
214
+
215
+ // Delete 永久删除 key 记录。
216
+ func (s *KeyStore) Delete(id string) error {
217
+ id = strings.TrimSpace(id)
218
+ s.mu.Lock()
219
+ defer s.mu.Unlock()
220
+ for i := range s.keys {
221
+ if s.keys[i].ID != id {
222
+ continue
223
+ }
224
+ s.keys = append(s.keys[:i], s.keys[i+1:]...)
225
+ s.rebuildLocked()
226
+ return s.saveLocked()
227
+ }
228
+ return ErrKeyNotFound
229
+ }
internal/reqlog/middleware.go ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package reqlog
2
+
3
+ import (
4
+ "bufio"
5
+ "errors"
6
+ "fmt"
7
+ "net"
8
+ "net/http"
9
+ "strconv"
10
+ "strings"
11
+ "time"
12
+ )
13
+
14
+ // SkipFunc 返回 true 时该请求不记录(静态资源、日志接口自身等)。
15
+ type SkipFunc func(*http.Request) bool
16
+
17
+ // Middleware 记录每个请求的元数据。请求处理过程中业务代码可以通过
18
+ // context 上的 Record 补充账号、模型、上游错误等信息。
19
+ func Middleware(store *Store, skip SkipFunc) func(http.Handler) http.Handler {
20
+ return func(next http.Handler) http.Handler {
21
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
22
+ if store == nil || (skip != nil && skip(r)) {
23
+ next.ServeHTTP(w, r)
24
+ return
25
+ }
26
+ rec := &Record{e: Entry{
27
+ Time: time.Now().Format("2006-01-02T15:04:05.000Z07:00"),
28
+ Level: LevelInfo,
29
+ Method: r.Method,
30
+ Path: r.URL.Path,
31
+ }}
32
+ rec.e.ClientIP = clientIP(r)
33
+ rec.e.UserAgent = truncate(r.UserAgent(), 200)
34
+ if r.ContentLength > 0 {
35
+ rec.e.ReqBytes = r.ContentLength
36
+ }
37
+ if v := strings.TrimSpace(r.Header.Get("X-Ds2-Source")); v != "" {
38
+ rec.e.UserAgent = truncate(v+" | "+rec.e.UserAgent, 200)
39
+ }
40
+ if raw := bearerToken(r); raw != "" {
41
+ rec.e.APIKey = MaskKey(raw)
42
+ }
43
+ start := time.Now()
44
+ ww := &responseWriter{ResponseWriter: w, status: http.StatusOK}
45
+ next.ServeHTTP(ww, r.WithContext(WithRecord(r.Context(), rec)))
46
+ latency := time.Since(start)
47
+ entry := rec.Snapshot()
48
+ entry.Status = ww.status
49
+ entry.LatencyMS = latency.Milliseconds()
50
+ entry.RespBytes = ww.written
51
+ if code := strings.TrimSpace(ww.Header().Get("X-Ds2-Error-Code")); code != "" {
52
+ entry.ErrorCode = code
53
+ }
54
+ if entry.Status >= 500 {
55
+ entry.Level = LevelError
56
+ } else if entry.Status >= 400 {
57
+ entry.Level = LevelWarn
58
+ }
59
+ store.Add(entry)
60
+ })
61
+ }
62
+ }
63
+
64
+ func clientIP(r *http.Request) string {
65
+ if r == nil {
66
+ return ""
67
+ }
68
+ if ip := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); ip != "" {
69
+ if idx := strings.IndexByte(ip, ','); idx >= 0 {
70
+ ip = ip[:idx]
71
+ }
72
+ return strings.TrimSpace(ip)
73
+ }
74
+ if ip := strings.TrimSpace(r.Header.Get("X-Real-Ip")); ip != "" {
75
+ return ip
76
+ }
77
+ host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
78
+ if err != nil {
79
+ return r.RemoteAddr
80
+ }
81
+ return host
82
+ }
83
+
84
+ func bearerToken(r *http.Request) string {
85
+ auth := strings.TrimSpace(r.Header.Get("Authorization"))
86
+ if len(auth) > 7 && strings.EqualFold(auth[:7], "bearer ") {
87
+ return strings.TrimSpace(auth[7:])
88
+ }
89
+ if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" {
90
+ return key
91
+ }
92
+ if key := strings.TrimSpace(r.Header.Get("X-Goog-Api-Key")); key != "" {
93
+ return key
94
+ }
95
+ if key := strings.TrimSpace(r.URL.Query().Get("key")); key != "" && strings.HasPrefix(key, "ds2log_") {
96
+ return key
97
+ }
98
+ return ""
99
+ }
100
+
101
+ type responseWriter struct {
102
+ http.ResponseWriter
103
+ status int
104
+ written int64
105
+ wroteHeader bool
106
+ }
107
+
108
+ func (w *responseWriter) WriteHeader(status int) {
109
+ if w.wroteHeader {
110
+ return
111
+ }
112
+ w.status = status
113
+ w.wroteHeader = true
114
+ w.ResponseWriter.WriteHeader(status)
115
+ }
116
+
117
+ func (w *responseWriter) Write(b []byte) (int, error) {
118
+ if !w.wroteHeader {
119
+ w.WriteHeader(http.StatusOK)
120
+ }
121
+ n, err := w.ResponseWriter.Write(b)
122
+ w.written += int64(n)
123
+ return n, err
124
+ }
125
+
126
+ func (w *responseWriter) Flush() {
127
+ if f, ok := w.ResponseWriter.(http.Flusher); ok {
128
+ f.Flush()
129
+ }
130
+ }
131
+
132
+ func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
133
+ h, ok := w.ResponseWriter.(http.Hijacker)
134
+ if !ok {
135
+ return nil, nil, errors.New("hijacking not supported")
136
+ }
137
+ return h.Hijack()
138
+ }
139
+
140
+ func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
141
+
142
+ // ParseLimit 统一解析 limit 参数,限制在 [1, max] 区间。
143
+ func ParseLimit(raw string, def, max int) int {
144
+ v, err := strconv.Atoi(strings.TrimSpace(raw))
145
+ if err != nil || v <= 0 {
146
+ return def
147
+ }
148
+ if v > max {
149
+ return max
150
+ }
151
+ return v
152
+ }
153
+
154
+ func (w *responseWriter) String() string {
155
+ return fmt.Sprintf("status=%d bytes=%d", w.status, w.written)
156
+ }
internal/reqlog/store.go ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package reqlog
2
+
3
+ import (
4
+ "archive/zip"
5
+ "bufio"
6
+ "encoding/json"
7
+ "errors"
8
+ "fmt"
9
+ "io"
10
+ "os"
11
+ "path/filepath"
12
+ "sort"
13
+ "strings"
14
+ "sync"
15
+ "time"
16
+ )
17
+
18
+ // Entry 是一条请求日志。只记录元数据,不记录请求/响应正文,避免泄露用户内容。
19
+ type Entry struct {
20
+ ID string `json:"id"`
21
+ Time string `json:"time"`
22
+ Level string `json:"level"`
23
+ Method string `json:"method"`
24
+ Path string `json:"path"`
25
+ Status int `json:"status"`
26
+ LatencyMS int64 `json:"latency_ms"`
27
+ ClientIP string `json:"client_ip,omitempty"`
28
+ UserAgent string `json:"user_agent,omitempty"`
29
+ APIKey string `json:"api_key,omitempty"`
30
+ APIKeyName string `json:"api_key_name,omitempty"`
31
+ Account string `json:"account,omitempty"`
32
+ Model string `json:"model,omitempty"`
33
+ Stream bool `json:"stream,omitempty"`
34
+ ReqBytes int64 `json:"req_bytes,omitempty"`
35
+ RespBytes int64 `json:"resp_bytes,omitempty"`
36
+ ErrorCode string `json:"error_code,omitempty"`
37
+ Error string `json:"error,omitempty"`
38
+ Upstream string `json:"upstream,omitempty"`
39
+ Dropped bool `json:"-"`
40
+ }
41
+
42
+ // Options 控制内存窗口与文件轮转。
43
+ type Options struct {
44
+ Dir string
45
+ MemoryLimit int // 内存保留条数
46
+ MaxFileBytes int64 // 单个文件大小上限
47
+ MaxFiles int // 保留文件数
48
+ DisableFile bool
49
+ }
50
+
51
+ func DefaultOptions(dir string) Options {
52
+ return Options{
53
+ Dir: dir,
54
+ MemoryLimit: 2000,
55
+ MaxFileBytes: 8 << 20,
56
+ MaxFiles: 5,
57
+ }
58
+ }
59
+
60
+ // Store 同时提供内存环形窗口与按大小轮转的文件日志。
61
+ type Store struct {
62
+ mu sync.RWMutex
63
+ opts Options
64
+ entries []Entry
65
+ next int
66
+ full bool
67
+ seq uint64
68
+ file *os.File
69
+ fileSize int64
70
+ fileName string
71
+ fileErr error
72
+ }
73
+
74
+ func New(opts Options) *Store {
75
+ if opts.MemoryLimit <= 0 {
76
+ opts.MemoryLimit = 2000
77
+ }
78
+ if opts.MaxFileBytes <= 0 {
79
+ opts.MaxFileBytes = 8 << 20
80
+ }
81
+ if opts.MaxFiles <= 0 {
82
+ opts.MaxFiles = 5
83
+ }
84
+ s := &Store{opts: opts, entries: make([]Entry, opts.MemoryLimit)}
85
+ if !opts.DisableFile && strings.TrimSpace(opts.Dir) != "" {
86
+ if err := os.MkdirAll(opts.Dir, 0o750); err != nil {
87
+ s.fileErr = err
88
+ }
89
+ }
90
+ return s
91
+ }
92
+
93
+ func (s *Store) Options() Options { return s.opts }
94
+
95
+ func (s *Store) Add(e Entry) {
96
+ if e.Time == "" {
97
+ e.Time = time.Now().Format("2006-01-02T15:04:05.000Z07:00")
98
+ }
99
+ s.mu.Lock()
100
+ s.seq++
101
+ if e.ID == "" {
102
+ e.ID = fmt.Sprintf("%d-%06d", time.Now().UnixMilli(), s.seq%1000000)
103
+ }
104
+ s.entries[s.next] = e
105
+ s.next = (s.next + 1) % len(s.entries)
106
+ if s.next == 0 {
107
+ s.full = true
108
+ }
109
+ s.writeFileLocked(e)
110
+ s.mu.Unlock()
111
+ }
112
+
113
+ func (s *Store) entriesLocked() []Entry {
114
+ if !s.full {
115
+ return append([]Entry(nil), s.entries[:s.next]...)
116
+ }
117
+ out := make([]Entry, 0, len(s.entries))
118
+ out = append(out, s.entries[s.next:]...)
119
+ out = append(out, s.entries[:s.next]...)
120
+ return out
121
+ }
122
+
123
+ // Query 过滤内存中的日志,按时间倒序返回。
124
+ type Query struct {
125
+ Limit int
126
+ Level string
127
+ Status int
128
+ Keyword string
129
+ SinceUnix int64
130
+ UntilUnix int64
131
+ }
132
+
133
+ func (s *Store) Query(q Query) []Entry {
134
+ s.mu.RLock()
135
+ all := s.entriesLocked()
136
+ s.mu.RUnlock()
137
+ limit := q.Limit
138
+ if limit <= 0 || limit > len(all) {
139
+ limit = len(all)
140
+ }
141
+ keyword := strings.ToLower(strings.TrimSpace(q.Keyword))
142
+ out := make([]Entry, 0, limit)
143
+ for i := len(all) - 1; i >= 0 && len(out) < limit; i-- {
144
+ e := all[i]
145
+ if q.Level != "" && !strings.EqualFold(e.Level, q.Level) {
146
+ continue
147
+ }
148
+ if q.Status != 0 && e.Status != q.Status {
149
+ continue
150
+ }
151
+ if q.SinceUnix > 0 && entryUnix(e) < q.SinceUnix {
152
+ continue
153
+ }
154
+ if q.UntilUnix > 0 && entryUnix(e) > q.UntilUnix {
155
+ continue
156
+ }
157
+ if keyword != "" && !entryMatches(e, keyword) {
158
+ continue
159
+ }
160
+ out = append(out, e)
161
+ }
162
+ return out
163
+ }
164
+
165
+ func entryUnix(e Entry) int64 {
166
+ t, err := time.Parse(time.RFC3339Nano, e.Time)
167
+ if err != nil {
168
+ return 0
169
+ }
170
+ return t.Unix()
171
+ }
172
+
173
+ func entryMatches(e Entry, keyword string) bool {
174
+ fields := []string{e.Path, e.Account, e.Model, e.ErrorCode, e.Error, e.Upstream, e.APIKeyName, e.APIKey, e.ClientIP}
175
+ for _, f := range fields {
176
+ if f != "" && strings.Contains(strings.ToLower(f), keyword) {
177
+ return true
178
+ }
179
+ }
180
+ return strings.Contains(strings.ToLower(e.Method), keyword) || strings.Contains(strings.ToLower(e.UserAgent), keyword)
181
+ }
182
+
183
+ // Stats 返回内存窗口的聚合信息。
184
+ func (s *Store) Stats() map[string]any {
185
+ s.mu.RLock()
186
+ all := s.entriesLocked()
187
+ fileErr := s.fileErr
188
+ s.mu.RUnlock()
189
+ total := len(all)
190
+ errors := 0
191
+ warns := 0
192
+ lastHour := 0
193
+ cutoff := time.Now().Add(-time.Hour).Unix()
194
+ for _, e := range all {
195
+ if e.Status >= 500 || e.Level == LevelError {
196
+ errors++
197
+ }
198
+ if e.Status >= 400 && e.Status < 500 {
199
+ warns++
200
+ }
201
+ if entryUnix(e) >= cutoff {
202
+ lastHour++
203
+ }
204
+ }
205
+ out := map[string]any{
206
+ "total": total,
207
+ "errors": errors,
208
+ "client_errors": warns,
209
+ "last_hour": lastHour,
210
+ "memory_limit": len(s.entries),
211
+ }
212
+ if fileErr != nil {
213
+ out["file_error"] = fileErr.Error()
214
+ }
215
+ return out
216
+ }
217
+
218
+ func (s *Store) ensureFileLocked() error {
219
+ if s.opts.DisableFile || strings.TrimSpace(s.opts.Dir) == "" {
220
+ return nil
221
+ }
222
+ if s.file != nil {
223
+ return nil
224
+ }
225
+ if err := os.MkdirAll(s.opts.Dir, 0o750); err != nil {
226
+ s.fileErr = err
227
+ return err
228
+ }
229
+ name := "requests-" + time.Now().Format("20060102-150405") + ".jsonl"
230
+ f, err := os.OpenFile(filepath.Join(s.opts.Dir, name), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o640)
231
+ if err != nil {
232
+ s.fileErr = err
233
+ return err
234
+ }
235
+ st, _ := f.Stat()
236
+ s.file = f
237
+ s.fileName = name
238
+ if st != nil {
239
+ s.fileSize = st.Size()
240
+ } else {
241
+ s.fileSize = 0
242
+ }
243
+ s.fileErr = nil
244
+ return nil
245
+ }
246
+
247
+ func (s *Store) writeFileLocked(e Entry) {
248
+ if s.opts.DisableFile || strings.TrimSpace(s.opts.Dir) == "" {
249
+ return
250
+ }
251
+ if err := s.ensureFileLocked(); err != nil {
252
+ return
253
+ }
254
+ if s.file == nil {
255
+ return
256
+ }
257
+ if s.fileSize >= s.opts.MaxFileBytes {
258
+ if err := s.rotateLocked(); err != nil {
259
+ s.fileErr = err
260
+ return
261
+ }
262
+ s.trimFilesLocked()
263
+ }
264
+ b, err := json.Marshal(e)
265
+ if err != nil {
266
+ return
267
+ }
268
+ b = append(b, '\n')
269
+ n, err := s.file.Write(b)
270
+ s.fileSize += int64(n)
271
+ if err != nil {
272
+ s.fileErr = err
273
+ return
274
+ }
275
+ s.fileErr = nil
276
+ }
277
+
278
+ func (s *Store) rotateLocked() error {
279
+ if s.file != nil {
280
+ if err := s.file.Close(); err != nil {
281
+ return err
282
+ }
283
+ s.file = nil
284
+ }
285
+ return s.ensureFileLocked()
286
+ }
287
+
288
+ func (s *Store) trimFilesLocked() {
289
+ files, err := s.listFilesLocked()
290
+ if err != nil || len(files) <= s.opts.MaxFiles {
291
+ return
292
+ }
293
+ for _, name := range files[s.opts.MaxFiles:] {
294
+ if name == s.fileName {
295
+ continue
296
+ }
297
+ _ = os.Remove(filepath.Join(s.opts.Dir, name))
298
+ }
299
+ }
300
+
301
+ func (s *Store) listFilesLocked() ([]string, error) {
302
+ entries, err := os.ReadDir(s.opts.Dir)
303
+ if err != nil {
304
+ return nil, err
305
+ }
306
+ names := make([]string, 0, len(entries))
307
+ for _, de := range entries {
308
+ if de.IsDir() || !strings.HasSuffix(de.Name(), ".jsonl") {
309
+ continue
310
+ }
311
+ names = append(names, de.Name())
312
+ }
313
+ sort.Sort(sort.Reverse(sort.StringSlice(names)))
314
+ return names, nil
315
+ }
316
+
317
+ // Files 返回轮转文件(新到旧)。
318
+ func (s *Store) Files() []map[string]any {
319
+ s.mu.RLock()
320
+ defer s.mu.RUnlock()
321
+ if s.opts.DisableFile || strings.TrimSpace(s.opts.Dir) == "" {
322
+ return nil
323
+ }
324
+ names, err := s.listFilesLocked()
325
+ if err != nil {
326
+ return nil
327
+ }
328
+ out := make([]map[string]any, 0, len(names))
329
+ for _, name := range names {
330
+ info, statErr := os.Stat(filepath.Join(s.opts.Dir, name))
331
+ if statErr != nil {
332
+ continue
333
+ }
334
+ out = append(out, map[string]any{
335
+ "name": name,
336
+ "size": info.Size(),
337
+ "modified_at": info.ModTime().Format(time.RFC3339),
338
+ })
339
+ }
340
+ return out
341
+ }
342
+
343
+ var ErrInvalidFileName = errors.New("invalid log file name")
344
+
345
+ // ResolveFile 返回安全的绝对路径,拒绝路径穿越。
346
+ func (s *Store) ResolveFile(name string) (string, error) {
347
+ name = strings.TrimSpace(name)
348
+ if name == "" || name != filepath.Base(name) || strings.Contains(name, "..") {
349
+ return "", ErrInvalidFileName
350
+ }
351
+ if !strings.HasSuffix(name, ".jsonl") {
352
+ return "", ErrInvalidFileName
353
+ }
354
+ path := filepath.Join(s.opts.Dir, name)
355
+ if st, err := os.Stat(path); err != nil || st.IsDir() {
356
+ return "", os.ErrNotExist
357
+ }
358
+ return path, nil
359
+ }
360
+
361
+ // Tail 读取单个文件最后 limit 行(limit<=0 表示全部)。
362
+ func (s *Store) Tail(name string, limit int) ([]Entry, error) {
363
+ path, err := s.ResolveFile(name)
364
+ if err != nil {
365
+ return nil, err
366
+ }
367
+ f, err := os.Open(path)
368
+ if err != nil {
369
+ return nil, err
370
+ }
371
+ defer func() { _ = f.Close() }()
372
+ scanner := bufio.NewScanner(f)
373
+ scanner.Buffer(make([]byte, 0, 64*1024), 1<<20)
374
+ entries := make([]Entry, 0, 256)
375
+ for scanner.Scan() {
376
+ var e Entry
377
+ if err := json.Unmarshal(scanner.Bytes(), &e); err != nil {
378
+ continue
379
+ }
380
+ entries = append(entries, e)
381
+ }
382
+ if err := scanner.Err(); err != nil {
383
+ return nil, err
384
+ }
385
+ if limit > 0 && len(entries) > limit {
386
+ entries = entries[len(entries)-limit:]
387
+ }
388
+ return entries, nil
389
+ }
390
+
391
+ func (s *Store) listFiles() ([]string, error) {
392
+ s.mu.RLock()
393
+ defer s.mu.RUnlock()
394
+ return s.listFilesLocked()
395
+ }
396
+
397
+ // WriteZip 把指定文件(为空表示全部)打包输出。
398
+ func (s *Store) WriteZip(w io.Writer, names []string) error {
399
+ if len(names) == 0 {
400
+ files, err := s.listFiles()
401
+ if err != nil {
402
+ return err
403
+ }
404
+ names = files
405
+ }
406
+ zw := zip.NewWriter(w)
407
+ for _, name := range names {
408
+ path, err := s.ResolveFile(name)
409
+ if err != nil {
410
+ continue
411
+ }
412
+ src, err := os.Open(path)
413
+ if err != nil {
414
+ continue
415
+ }
416
+ info, statErr := src.Stat()
417
+ if statErr != nil {
418
+ _ = src.Close()
419
+ continue
420
+ }
421
+ header, err := zip.FileInfoHeader(info)
422
+ if err != nil {
423
+ _ = src.Close()
424
+ continue
425
+ }
426
+ header.Name = name
427
+ header.Method = zip.Deflate
428
+ dst, err := zw.CreateHeader(header)
429
+ if err != nil {
430
+ _ = src.Close()
431
+ return err
432
+ }
433
+ if _, err := io.Copy(dst, src); err != nil {
434
+ _ = src.Close()
435
+ return err
436
+ }
437
+ _ = src.Close()
438
+ }
439
+ return zw.Close()
440
+ }
441
+
442
+ // Close 关闭当前文件句柄。
443
+ func (s *Store) Close() error {
444
+ s.mu.Lock()
445
+ defer s.mu.Unlock()
446
+ if s.file == nil {
447
+ return nil
448
+ }
449
+ err := s.file.Close()
450
+ s.file = nil
451
+ return err
452
+ }
453
+
454
+ const (
455
+ LevelInfo = "info"
456
+ LevelWarn = "warn"
457
+ LevelError = "error"
458
+ )
internal/reqlog/store_test.go ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package reqlog
2
+
3
+ import (
4
+ "bytes"
5
+ "os"
6
+ "path/filepath"
7
+ "testing"
8
+ "time"
9
+ )
10
+
11
+ func TestStoreQueryAndStats(t *testing.T) {
12
+ dir := t.TempDir()
13
+ s := New(Options{Dir: dir, MemoryLimit: 3, MaxFileBytes: 1 << 20, MaxFiles: 2})
14
+ defer func() { _ = s.Close() }()
15
+
16
+ now := time.Now()
17
+ s.Add(Entry{Time: now.Format(time.RFC3339Nano), Level: LevelInfo, Method: "POST", Path: "/v1/chat/completions", Status: 200, LatencyMS: 10, Account: "a@example.com", Model: "deepseek-v4", ErrorCode: ""})
18
+ s.Add(Entry{Time: now.Format(time.RFC3339Nano), Level: LevelWarn, Method: "POST", Path: "/v1/chat/completions", Status: 429, ErrorCode: "account_muted"})
19
+ s.Add(Entry{Time: now.Format(time.RFC3339Nano), Level: LevelError, Method: "GET", Path: "/v1/models", Status: 502, ErrorCode: "upstream_error"})
20
+ s.Add(Entry{Time: now.Format(time.RFC3339Nano), Level: LevelInfo, Method: "GET", Path: "/v1/models", Status: 200})
21
+
22
+ // 内存窗口只保留最近 3 条,最旧的 200 请求被淘汰。
23
+ if got := s.Query(Query{Limit: 10}); len(got) != 3 {
24
+ t.Fatalf("expected 3 entries in window, got %d", len(got))
25
+ }
26
+ if got := s.Query(Query{Limit: 10, Keyword: "account_muted"}); len(got) != 1 {
27
+ t.Fatalf("keyword filter failed: %#v", got)
28
+ }
29
+ if got := s.Query(Query{Limit: 10, Status: 200}); len(got) != 1 {
30
+ t.Fatalf("status filter failed: %#v", got)
31
+ }
32
+ stats := s.Stats()
33
+ if stats["errors"].(int) != 1 || stats["client_errors"].(int) != 1 {
34
+ t.Fatalf("unexpected stats: %#v", stats)
35
+ }
36
+ files := s.Files()
37
+ if len(files) != 1 {
38
+ t.Fatalf("expected one rotated file, got %#v", files)
39
+ }
40
+ name := files[0]["name"].(string)
41
+ entries, err := s.Tail(name, 2)
42
+ if err != nil {
43
+ t.Fatalf("tail failed: %v", err)
44
+ }
45
+ if len(entries) != 2 {
46
+ t.Fatalf("expected 2 tail entries, got %d", len(entries))
47
+ }
48
+ }
49
+
50
+ func TestStoreRejectsPathTraversal(t *testing.T) {
51
+ s := New(Options{Dir: t.TempDir(), MemoryLimit: 10, MaxFileBytes: 1 << 20, MaxFiles: 1})
52
+ defer func() { _ = s.Close() }()
53
+ if _, err := s.ResolveFile("../etc/passwd"); err == nil {
54
+ t.Fatal("expected traversal to be rejected")
55
+ }
56
+ if _, err := s.ResolveFile("nested/requests.jsonl"); err == nil {
57
+ t.Fatal("expected nested path to be rejected")
58
+ }
59
+ }
60
+
61
+ func TestStoreZip(t *testing.T) {
62
+ dir := t.TempDir()
63
+ s := New(Options{Dir: dir, MemoryLimit: 10, MaxFileBytes: 1 << 20, MaxFiles: 3})
64
+ defer func() { _ = s.Close() }()
65
+ s.Add(Entry{Time: time.Now().Format(time.RFC3339Nano), Method: "GET", Path: "/v1/models", Status: 200})
66
+ var buf bytes.Buffer
67
+ if err := s.WriteZip(&buf, nil); err != nil {
68
+ t.Fatalf("zip failed: %v", err)
69
+ }
70
+ if buf.Len() == 0 {
71
+ t.Fatal("expected non-empty zip")
72
+ }
73
+ }
74
+
75
+ func TestKeyStoreLifecycle(t *testing.T) {
76
+ path := filepath.Join(t.TempDir(), "keys.json")
77
+ ks := NewKeyStore(path)
78
+ plain, item, err := ks.Create("ops", time.Hour)
79
+ if err != nil {
80
+ t.Fatalf("create failed: %v", err)
81
+ }
82
+ if plain == "" || item.Prefix == "" || item.Revoked {
83
+ t.Fatalf("unexpected created key: %#v", item)
84
+ }
85
+ if _, ok := ks.Verify(plain); !ok {
86
+ t.Fatal("expected key to verify")
87
+ }
88
+ if _, ok := ks.Verify("ds2log_deadbeef"); ok {
89
+ t.Fatal("expected unknown key to fail")
90
+ }
91
+
92
+ // 重新加载后仍然可用,且磁盘上不保存明文。
93
+ reloaded := NewKeyStore(path)
94
+ if _, ok := reloaded.Verify(plain); !ok {
95
+ t.Fatal("expected key to survive reload")
96
+ }
97
+ raw, err := os.ReadFile(path)
98
+ if err != nil {
99
+ t.Fatalf("read keys file: %v", err)
100
+ }
101
+ if bytes.Contains(raw, []byte(plain)) {
102
+ t.Fatal("plaintext key must not be persisted")
103
+ }
104
+
105
+ if err := ks.Delete(item.ID); err != nil {
106
+ t.Fatalf("delete failed: %v", err)
107
+ }
108
+ if _, ok := ks.Verify(plain); ok {
109
+ t.Fatal("expected deleted key to fail")
110
+ }
111
+ }
112
+
113
+ func TestKeyStoreExpiry(t *testing.T) {
114
+ ks := NewKeyStore("")
115
+ plain, _, err := ks.Create("short", time.Millisecond)
116
+ if err != nil {
117
+ t.Fatalf("create failed: %v", err)
118
+ }
119
+ time.Sleep(5 * time.Millisecond)
120
+ if _, ok := ks.Verify(plain); ok {
121
+ t.Fatal("expected expired key to fail")
122
+ }
123
+ }
internal/server/router.go CHANGED
@@ -9,6 +9,7 @@ import (
9
  "net/url"
10
  "os"
11
  "runtime"
 
12
  "strings"
13
  "time"
14
 
@@ -21,6 +22,7 @@ import (
21
  "ds2api/internal/config"
22
  dsclient "ds2api/internal/deepseek/client"
23
  "ds2api/internal/httpapi/admin"
 
24
  "ds2api/internal/httpapi/claude"
25
  "ds2api/internal/httpapi/gemini"
26
  "ds2api/internal/httpapi/ollama"
@@ -31,6 +33,7 @@ import (
31
  "ds2api/internal/httpapi/openai/shared"
32
  "ds2api/internal/httpapi/requestbody"
33
  "ds2api/internal/proxyhealth"
 
34
  "ds2api/internal/webui"
35
  )
36
 
@@ -40,6 +43,8 @@ type App struct {
40
  Resolver *auth.Resolver
41
  DS *dsclient.Client
42
  ProxyChecker *proxyhealth.Checker
 
 
43
  Router http.Handler
44
  }
45
 
@@ -77,13 +82,17 @@ func NewApp() (*App, error) {
77
  claudeHandler := &claude.Handler{Store: store, Auth: resolver, DS: dsClient, OpenAI: chatHandler, ChatHistory: chatHistoryStore}
78
  geminiHandler := &gemini.Handler{Store: store, Auth: resolver, DS: dsClient, OpenAI: chatHandler, ChatHistory: chatHistoryStore}
79
  proxyChecker := proxyhealth.NewChecker(store, pool)
80
- adminHandler := &admin.Handler{Store: store, Pool: pool, DS: dsClient, OpenAI: chatHandler, ChatHistory: chatHistoryStore, Checker: proxyChecker}
 
 
 
81
  ollamaHandler := &ollama.Handler{Store: store}
82
  webuiHandler := webui.NewHandler()
83
 
84
  r := chi.NewRouter()
85
  r.Use(middleware.RequestID)
86
  r.Use(middleware.RealIP)
 
87
  r.Use(filteredLogger())
88
  r.Use(middleware.Recoverer)
89
  r.Use(cors)
@@ -127,6 +136,7 @@ func NewApp() (*App, error) {
127
  r.Route("/admin", func(ar chi.Router) {
128
  admin.RegisterRoutes(ar, adminHandler)
129
  })
 
130
  webui.RegisterRoutes(r, webuiHandler)
131
  r.NotFound(func(w http.ResponseWriter, req *http.Request) {
132
  if strings.HasPrefix(req.URL.Path, "/admin/") && webuiHandler.HandleAdminFallback(w, req) {
@@ -137,7 +147,50 @@ func NewApp() (*App, error) {
137
 
138
  proxyChecker.Start()
139
 
140
- return &App{Store: store, Pool: pool, Resolver: resolver, DS: dsClient, ProxyChecker: proxyChecker, Router: r}, nil
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  }
142
 
143
  func timeout(d time.Duration) func(http.Handler) http.Handler {
 
9
  "net/url"
10
  "os"
11
  "runtime"
12
+ "strconv"
13
  "strings"
14
  "time"
15
 
 
22
  "ds2api/internal/config"
23
  dsclient "ds2api/internal/deepseek/client"
24
  "ds2api/internal/httpapi/admin"
25
+ adminlogs "ds2api/internal/httpapi/admin/logs"
26
  "ds2api/internal/httpapi/claude"
27
  "ds2api/internal/httpapi/gemini"
28
  "ds2api/internal/httpapi/ollama"
 
33
  "ds2api/internal/httpapi/openai/shared"
34
  "ds2api/internal/httpapi/requestbody"
35
  "ds2api/internal/proxyhealth"
36
+ "ds2api/internal/reqlog"
37
  "ds2api/internal/webui"
38
  )
39
 
 
43
  Resolver *auth.Resolver
44
  DS *dsclient.Client
45
  ProxyChecker *proxyhealth.Checker
46
+ RequestLogs *reqlog.Store
47
+ LogKeys *reqlog.KeyStore
48
  Router http.Handler
49
  }
50
 
 
82
  claudeHandler := &claude.Handler{Store: store, Auth: resolver, DS: dsClient, OpenAI: chatHandler, ChatHistory: chatHistoryStore}
83
  geminiHandler := &gemini.Handler{Store: store, Auth: resolver, DS: dsClient, OpenAI: chatHandler, ChatHistory: chatHistoryStore}
84
  proxyChecker := proxyhealth.NewChecker(store, pool)
85
+ requestLogs := reqlog.New(reqlogOptions())
86
+ logKeys := reqlog.NewKeyStore(config.LogKeysPath())
87
+ adminHandler := &admin.Handler{Store: store, Pool: pool, DS: dsClient, OpenAI: chatHandler, ChatHistory: chatHistoryStore, Checker: proxyChecker, Logs: requestLogs, LogKeys: logKeys}
88
+ logsHandler := &adminlogs.Handler{Store: requestLogs, Keys: logKeys}
89
  ollamaHandler := &ollama.Handler{Store: store}
90
  webuiHandler := webui.NewHandler()
91
 
92
  r := chi.NewRouter()
93
  r.Use(middleware.RequestID)
94
  r.Use(middleware.RealIP)
95
+ r.Use(reqlog.Middleware(requestLogs, skipRequestLog))
96
  r.Use(filteredLogger())
97
  r.Use(middleware.Recoverer)
98
  r.Use(cors)
 
136
  r.Route("/admin", func(ar chi.Router) {
137
  admin.RegisterRoutes(ar, adminHandler)
138
  })
139
+ adminlogs.RegisterPublicRoutes(r, logsHandler)
140
  webui.RegisterRoutes(r, webuiHandler)
141
  r.NotFound(func(w http.ResponseWriter, req *http.Request) {
142
  if strings.HasPrefix(req.URL.Path, "/admin/") && webuiHandler.HandleAdminFallback(w, req) {
 
147
 
148
  proxyChecker.Start()
149
 
150
+ return &App{Store: store, Pool: pool, Resolver: resolver, DS: dsClient, ProxyChecker: proxyChecker, RequestLogs: requestLogs, LogKeys: logKeys, Router: r}, nil
151
+ }
152
+
153
+ // reqlogOptions 从环境变量读取请求日志的内存窗口与轮转参数。
154
+ func reqlogOptions() reqlog.Options {
155
+ opts := reqlog.DefaultOptions(config.RequestLogDir())
156
+ if v := strings.TrimSpace(os.Getenv("DS2API_REQUEST_LOG_MEMORY")); v != "" {
157
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
158
+ opts.MemoryLimit = n
159
+ }
160
+ }
161
+ if v := strings.TrimSpace(os.Getenv("DS2API_REQUEST_LOG_MAX_MB")); v != "" {
162
+ if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 {
163
+ opts.MaxFileBytes = n << 20
164
+ }
165
+ }
166
+ if v := strings.TrimSpace(os.Getenv("DS2API_REQUEST_LOG_MAX_FILES")); v != "" {
167
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
168
+ opts.MaxFiles = n
169
+ }
170
+ }
171
+ if v := strings.TrimSpace(os.Getenv("DS2API_REQUEST_LOG_DISABLE_FILE")); v == "1" || strings.EqualFold(v, "true") {
172
+ opts.DisableFile = true
173
+ }
174
+ return opts
175
+ }
176
+
177
+ // skipRequestLog 过滤静态资源、健康检查和日志接口自身,避免噪声与递归。
178
+ func skipRequestLog(r *http.Request) bool {
179
+ if r == nil || r.URL == nil {
180
+ return true
181
+ }
182
+ p := r.URL.Path
183
+ switch p {
184
+ case "/healthz", "/readyz", "/favicon.ico":
185
+ return true
186
+ }
187
+ if strings.HasPrefix(p, "/logs/") || strings.HasPrefix(p, "/admin/logs") {
188
+ return true
189
+ }
190
+ if strings.HasPrefix(p, "/assets/") || strings.HasPrefix(p, "/admin/assets/") || strings.HasPrefix(p, "/static/") {
191
+ return true
192
+ }
193
+ return false
194
  }
195
 
196
  func timeout(d time.Duration) func(http.Handler) http.Handler {
webui/src/features/account/AccountsTable.jsx CHANGED
@@ -113,10 +113,12 @@ export default function AccountsTable({
113
  const isActive = acc.test_status === 'ok' || acc.has_token
114
  const isStandby = acc.role === 'standby'
115
  const isBanned = acc.banned
 
 
116
  return (
117
  <div key={i} className={clsx(
118
  "p-4 flex flex-col md:flex-row md:items-center justify-between gap-4 transition-colors",
119
- isBanned ? "bg-red-500/5 hover:bg-red-500/10" : isStandby ? "bg-amber-500/5 hover:bg-amber-500/10" : "hover:bg-muted/50"
120
  )}>
121
  <div className="flex items-center gap-3 min-w-0">
122
  <div className={clsx(
@@ -143,7 +145,7 @@ export default function AccountsTable({
143
  <div className="text-xs text-muted-foreground truncate mt-0.5">{acc.remark}</div>
144
  )}
145
  <div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
146
- <span>{isBanned ? t('accountManager.bannedStatus') : isStandby ? t('accountManager.standbyStatus') : acc.test_status === 'failed' ? t('accountManager.testStatusFailed') : isActive ? t('accountManager.sessionActive') : runtimeUnknown ? t('accountManager.runtimeStatusUnknown') : t('accountManager.reauthRequired')}</span>
147
  {isStandby && !isBanned && (
148
  <span className="font-mono bg-amber-500/10 text-amber-500 px-1.5 py-0.5 rounded text-[10px]">
149
  {t('accountManager.roleStandby')}
@@ -154,6 +156,11 @@ export default function AccountsTable({
154
  {t('accountManager.bannedBadge')}
155
  </span>
156
  )}
 
 
 
 
 
157
  {acc.token_preview && (
158
  <span className="font-mono bg-muted px-1.5 py-0.5 rounded text-[10px]">
159
  {acc.token_preview}
 
113
  const isActive = acc.test_status === 'ok' || acc.has_token
114
  const isStandby = acc.role === 'standby'
115
  const isBanned = acc.banned
116
+ const mutedUntilMs = Number(acc.muted_until || 0) * 1000
117
+ const isMuted = !isBanned && mutedUntilMs > Date.now()
118
  return (
119
  <div key={i} className={clsx(
120
  "p-4 flex flex-col md:flex-row md:items-center justify-between gap-4 transition-colors",
121
+ isBanned ? "bg-red-500/5 hover:bg-red-500/10" : isMuted ? "bg-orange-500/5 hover:bg-orange-500/10" : isStandby ? "bg-amber-500/5 hover:bg-amber-500/10" : "hover:bg-muted/50"
122
  )}>
123
  <div className="flex items-center gap-3 min-w-0">
124
  <div className={clsx(
 
145
  <div className="text-xs text-muted-foreground truncate mt-0.5">{acc.remark}</div>
146
  )}
147
  <div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
148
+ <span>{isBanned ? t('accountManager.bannedStatus') : isMuted ? t('accountManager.mutedStatus', { time: new Date(mutedUntilMs).toLocaleString() }) : isStandby ? t('accountManager.standbyStatus') : acc.test_status === 'failed' ? t('accountManager.testStatusFailed') : isActive ? t('accountManager.sessionActive') : runtimeUnknown ? t('accountManager.runtimeStatusUnknown') : t('accountManager.reauthRequired')}</span>
149
  {isStandby && !isBanned && (
150
  <span className="font-mono bg-amber-500/10 text-amber-500 px-1.5 py-0.5 rounded text-[10px]">
151
  {t('accountManager.roleStandby')}
 
156
  {t('accountManager.bannedBadge')}
157
  </span>
158
  )}
159
+ {isMuted && (
160
+ <span className="font-mono bg-orange-500/10 text-orange-500 px-1.5 py-0.5 rounded text-[10px]">
161
+ {t('accountManager.mutedBadge')}
162
+ </span>
163
+ )}
164
  {acc.token_preview && (
165
  <span className="font-mono bg-muted px-1.5 py-0.5 rounded text-[10px]">
166
  {acc.token_preview}
webui/src/features/account/QueueCards.jsx CHANGED
@@ -57,6 +57,16 @@ export default function QueueCards({ queueStatus, t }) {
57
  <span className="text-xs text-muted-foreground">{t('accountManager.accountsUnit')}</span>
58
  </div>
59
  </div>
 
 
 
 
 
 
 
 
 
 
60
  </div>
61
  )
62
  }
 
57
  <span className="text-xs text-muted-foreground">{t('accountManager.accountsUnit')}</span>
58
  </div>
59
  </div>
60
+ <div className="bg-card border border-orange-500/20 rounded-xl p-4 flex flex-col justify-between shadow-sm relative overflow-hidden group">
61
+ <div className="absolute right-0 top-0 p-4 opacity-5 group-hover:opacity-10 transition-opacity">
62
+ <ShieldOff className="w-16 h-16 text-orange-500" />
63
+ </div>
64
+ <p className="text-xs font-medium text-orange-500/80 uppercase tracking-widest">{t('accountManager.mutedBadge')}</p>
65
+ <div className="mt-2 flex items-baseline gap-2">
66
+ <span className="text-3xl font-bold text-orange-500">{queueStatus.muted_count ?? '-'}</span>
67
+ <span className="text-xs text-muted-foreground">{t('accountManager.accountsUnit')}</span>
68
+ </div>
69
+ </div>
70
  </div>
71
  )
72
  }
webui/src/features/account/useAccountActions.js CHANGED
@@ -301,9 +301,11 @@ export function useAccountActions({ apiFetch, t, onMessage, onRefresh, config, f
301
  }
302
 
303
  const statusMessage = data.success
304
- ? t('apiTester.testSuccess', { account: accountID, time: data.response_time })
 
 
305
  : `${accountID}: ${data.message}`
306
- onMessage(data.success ? 'success' : 'error', statusMessage)
307
  fetchAccounts()
308
  onRefresh()
309
  } catch (e) {
 
301
  }
302
 
303
  const statusMessage = data.success
304
+ ? (data.muted
305
+ ? `${accountID}: ${data.message}`
306
+ : t('accountManager.tokenRefreshSuccess', { account: accountID, time: data.response_time }))
307
  : `${accountID}: ${data.message}`
308
+ onMessage(data.success && !data.muted ? 'success' : (data.success ? 'warning' : 'error'), statusMessage)
309
  fetchAccounts()
310
  onRefresh()
311
  } catch (e) {
webui/src/layout/DashboardShell.jsx CHANGED
@@ -13,6 +13,7 @@ import {
13
  Globe,
14
  Layers,
15
  History,
 
16
  Loader2
17
  } from 'lucide-react'
18
  import clsx from 'clsx'
@@ -23,6 +24,7 @@ import { useI18n } from '../i18n'
23
  const AccountManagerContainer = lazy(() => import('../features/account/AccountManagerContainer'))
24
  const ApiTesterContainer = lazy(() => import('../features/apiTester/ApiTesterContainer'))
25
  const ChatHistoryContainer = lazy(() => import('../features/chatHistory/ChatHistoryContainer'))
 
26
  const BatchImport = lazy(() => import('../components/BatchImport'))
27
  const VercelSyncContainer = lazy(() => import('../features/vercel/VercelSyncContainer'))
28
  const SettingsContainer = lazy(() => import('../features/settings/SettingsContainer'))
@@ -52,6 +54,7 @@ export default function DashboardShell({ token, onLogout, config, fetchConfig, s
52
  { id: 'proxies', label: t('nav.proxies.label'), icon: Globe, description: t('nav.proxies.desc') },
53
  { id: 'test', label: t('nav.test.label'), icon: Server, description: t('nav.test.desc') },
54
  { id: 'history', label: t('nav.history.label'), icon: History, description: t('nav.history.desc') },
 
55
  { id: 'import', label: t('nav.import.label'), icon: Upload, description: t('nav.import.desc') },
56
  { id: 'vercel', label: t('nav.vercel.label'), icon: Cloud, description: t('nav.vercel.desc') },
57
  { id: 'settings', label: t('nav.settings.label'), icon: SettingsIcon, description: t('nav.settings.desc') },
@@ -122,6 +125,8 @@ export default function DashboardShell({ token, onLogout, config, fetchConfig, s
122
  return <ApiTesterContainer config={config} onMessage={showMessage} authFetch={authFetch} />
123
  case 'history':
124
  return <ChatHistoryContainer onMessage={showMessage} authFetch={authFetch} />
 
 
125
  case 'import':
126
  return <BatchImport onRefresh={fetchConfig} onMessage={showMessage} authFetch={authFetch} />
127
  case 'vercel':
@@ -262,9 +267,12 @@ export default function DashboardShell({ token, onLogout, config, fetchConfig, s
262
  <div className={clsx(
263
  "p-4 rounded-lg border flex items-center gap-3 animate-in fade-in slide-in-from-top-2",
264
  message.type === 'error' ? "bg-destructive/10 border-destructive/20 text-destructive" :
265
- "bg-emerald-500/10 border-emerald-500/20 text-emerald-500"
 
266
  )}>
267
- {message.type === 'error' ? <X className="w-5 h-5" /> : <div className="w-5 h-5 rounded-full border-2 border-emerald-500 flex items-center justify-center text-[10px]">✓</div>}
 
 
268
  {message.text}
269
  </div>
270
  )}
 
13
  Globe,
14
  Layers,
15
  History,
16
+ FileText,
17
  Loader2
18
  } from 'lucide-react'
19
  import clsx from 'clsx'
 
24
  const AccountManagerContainer = lazy(() => import('../features/account/AccountManagerContainer'))
25
  const ApiTesterContainer = lazy(() => import('../features/apiTester/ApiTesterContainer'))
26
  const ChatHistoryContainer = lazy(() => import('../features/chatHistory/ChatHistoryContainer'))
27
+ const LogsContainer = lazy(() => import('../features/logs/LogsContainer'))
28
  const BatchImport = lazy(() => import('../components/BatchImport'))
29
  const VercelSyncContainer = lazy(() => import('../features/vercel/VercelSyncContainer'))
30
  const SettingsContainer = lazy(() => import('../features/settings/SettingsContainer'))
 
54
  { id: 'proxies', label: t('nav.proxies.label'), icon: Globe, description: t('nav.proxies.desc') },
55
  { id: 'test', label: t('nav.test.label'), icon: Server, description: t('nav.test.desc') },
56
  { id: 'history', label: t('nav.history.label'), icon: History, description: t('nav.history.desc') },
57
+ { id: 'logs', label: t('nav.logs.label'), icon: FileText, description: t('nav.logs.desc') },
58
  { id: 'import', label: t('nav.import.label'), icon: Upload, description: t('nav.import.desc') },
59
  { id: 'vercel', label: t('nav.vercel.label'), icon: Cloud, description: t('nav.vercel.desc') },
60
  { id: 'settings', label: t('nav.settings.label'), icon: SettingsIcon, description: t('nav.settings.desc') },
 
125
  return <ApiTesterContainer config={config} onMessage={showMessage} authFetch={authFetch} />
126
  case 'history':
127
  return <ChatHistoryContainer onMessage={showMessage} authFetch={authFetch} />
128
+ case 'logs':
129
+ return <LogsContainer onMessage={showMessage} authFetch={authFetch} />
130
  case 'import':
131
  return <BatchImport onRefresh={fetchConfig} onMessage={showMessage} authFetch={authFetch} />
132
  case 'vercel':
 
267
  <div className={clsx(
268
  "p-4 rounded-lg border flex items-center gap-3 animate-in fade-in slide-in-from-top-2",
269
  message.type === 'error' ? "bg-destructive/10 border-destructive/20 text-destructive" :
270
+ message.type === 'warning' ? "bg-amber-500/10 border-amber-500/20 text-amber-600" :
271
+ "bg-emerald-500/10 border-emerald-500/20 text-emerald-500"
272
  )}>
273
+ {message.type === 'error' ? <X className="w-5 h-5" /> :
274
+ message.type === 'warning' ? <span className="w-5 h-5 rounded-full border-2 border-amber-500 flex items-center justify-center text-[10px]">!</span> :
275
+ <div className="w-5 h-5 rounded-full border-2 border-emerald-500 flex items-center justify-center text-[10px]">✓</div>}
276
  {message.text}
277
  </div>
278
  )}
webui/src/locales/en.json CHANGED
@@ -40,6 +40,10 @@
40
  "settings": {
41
  "label": "Settings",
42
  "desc": "Edit runtime and security settings online"
 
 
 
 
43
  }
44
  },
45
  "sidebar": {
@@ -223,7 +227,10 @@
223
  "envModeRiskDesc": "Detected DS2API_CONFIG_JSON. If DS2API_ENV_WRITEBACK is not enabled, Admin UI edits are in-memory only and may be lost after restart.",
224
  "envModeWritebackPendingTitle": "Env mode + auto-persistence enabled (pending file handoff)",
225
  "envModeWritebackActiveTitle": "Env mode + auto-persistence active",
226
- "envModeWritebackDesc": "The app will auto-create/write the config file and transition to file-backed mode. Current persistence path: {path}"
 
 
 
227
  },
228
  "proxyManager": {
229
  "title": "Proxy IPs",
@@ -708,5 +715,54 @@
708
  "three": "Update the env var in Vercel:",
709
  "four": "Trigger a redeploy to apply the updated environment variables."
710
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711
  }
712
  }
 
40
  "settings": {
41
  "label": "Settings",
42
  "desc": "Edit runtime and security settings online"
43
+ },
44
+ "logs": {
45
+ "label": "Request logs",
46
+ "desc": "Inspect request records, rotated logs and read-only log keys"
47
  }
48
  },
49
  "sidebar": {
 
227
  "envModeRiskDesc": "Detected DS2API_CONFIG_JSON. If DS2API_ENV_WRITEBACK is not enabled, Admin UI edits are in-memory only and may be lost after restart.",
228
  "envModeWritebackPendingTitle": "Env mode + auto-persistence enabled (pending file handoff)",
229
  "envModeWritebackActiveTitle": "Env mode + auto-persistence active",
230
+ "envModeWritebackDesc": "The app will auto-create/write the config file and transition to file-backed mode. Current persistence path: {path}",
231
+ "mutedStatus": "Muted upstream until {time}",
232
+ "mutedBadge": "Muted",
233
+ "tokenRefreshSuccess": "Token refreshed: {account} ({time}ms)"
234
  },
235
  "proxyManager": {
236
  "title": "Proxy IPs",
 
715
  "three": "Update the env var in Vercel:",
716
  "four": "Trigger a redeploy to apply the updated environment variables."
717
  }
718
+ },
719
+ "logs": {
720
+ "loadFailed": "Failed to load logs",
721
+ "downloadFailed": "Download failed",
722
+ "copyFailed": "Copy failed",
723
+ "statsTotal": "Requests in window",
724
+ "statsErrors": "5xx errors",
725
+ "statsClientErrors": "4xx requests",
726
+ "statsLastHour": "Last hour",
727
+ "searchPlaceholder": "Search path / account / model / error code...",
728
+ "allLevels": "All levels",
729
+ "allStatus": "All status",
730
+ "autoRefresh": "Auto refresh (5s)",
731
+ "refresh": "Refresh",
732
+ "manageKeys": "Log keys",
733
+ "colTime": "Time",
734
+ "colRequest": "Request",
735
+ "colStatus": "Status",
736
+ "colLatency": "Latency",
737
+ "colAccount": "Account",
738
+ "colModel": "Model",
739
+ "colKey": "Caller",
740
+ "colError": "Error",
741
+ "loading": "Loading...",
742
+ "empty": "No request logs yet",
743
+ "rotatedFiles": "Rotated log files",
744
+ "downloadAll": "Download all",
745
+ "noFiles": "No rotated files yet",
746
+ "download": "Download",
747
+ "detailTitle": "Request detail",
748
+ "keysTitle": "Read-only log keys",
749
+ "keysHint": "This key can only read logs under /logs/api. It cannot change settings or read chat content. The secret is shown once.",
750
+ "keyName": "Name",
751
+ "keyTTL": "TTL",
752
+ "day": "day",
753
+ "days": "days",
754
+ "neverExpire": "Never",
755
+ "creating": "Creating...",
756
+ "generateKey": "Generate key",
757
+ "keyOnce": "Save it now — it will not be shown again",
758
+ "noKeys": "No log keys yet",
759
+ "createdAt": "created",
760
+ "expiresAt": "expires",
761
+ "revoked": "revoked",
762
+ "revoke": "Delete",
763
+ "keyCreateFailed": "Failed to create key",
764
+ "keyDeleteConfirm": "Delete this log key? Calls using it will stop working immediately.",
765
+ "keyDeleted": "Log key deleted",
766
+ "keyDeleteFailed": "Failed to delete key"
767
  }
768
  }
webui/src/locales/zh.json CHANGED
@@ -40,6 +40,10 @@
40
  "settings": {
41
  "label": "设置中心",
42
  "desc": "在线修改系统设置与配置"
 
 
 
 
43
  }
44
  },
45
  "sidebar": {
@@ -223,7 +227,10 @@
223
  "envModeRiskDesc": "检测到 DS2API_CONFIG_JSON。若未开启 DS2API_ENV_WRITEBACK,管理台改动仅在内存生效,重启可能丢失。",
224
  "envModeWritebackPendingTitle": "环境变量模式 + 自动持久化已开启(等待落盘)",
225
  "envModeWritebackActiveTitle": "环境变量模式 + 自动持久化已生效",
226
- "envModeWritebackDesc": "程序会自动创建/写入配置文件并在后续切换为文件模式。当前持久化路径:{path}"
 
 
 
227
  },
228
  "proxyManager": {
229
  "title": "代理 IP",
@@ -708,5 +715,54 @@
708
  "three": "更新 Vercel 项目中的环境变量:",
709
  "four": "触发重新部署以应用新的环境变量。"
710
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711
  }
712
  }
 
40
  "settings": {
41
  "label": "设置中心",
42
  "desc": "在线修改系统设置与配置"
43
+ },
44
+ "logs": {
45
+ "label": "请求日志",
46
+ "desc": "查看请求记录、轮转日志与日志读取密钥"
47
  }
48
  },
49
  "sidebar": {
 
227
  "envModeRiskDesc": "检测到 DS2API_CONFIG_JSON。若未开启 DS2API_ENV_WRITEBACK,管理台改动仅在内存生效,重启可能丢失。",
228
  "envModeWritebackPendingTitle": "环境变量模式 + 自动持久化已开启(等待落盘)",
229
  "envModeWritebackActiveTitle": "环境变量模式 + 自动持久化已生效",
230
+ "envModeWritebackDesc": "程序会自动创建/写入配置文件并在后续切换为文件模式。当前持久化路径:{path}",
231
+ "mutedStatus": "上游禁言至 {time}",
232
+ "mutedBadge": "已禁言",
233
+ "tokenRefreshSuccess": "刷新成功:{account}(耗时 {time}ms)"
234
  },
235
  "proxyManager": {
236
  "title": "代理 IP",
 
715
  "three": "更新 Vercel 项目中的环境变量:",
716
  "four": "触发重新部署以应用新的环境变量。"
717
  }
718
+ },
719
+ "logs": {
720
+ "loadFailed": "日志加载失败",
721
+ "downloadFailed": "下载失败",
722
+ "copyFailed": "复制失败",
723
+ "statsTotal": "窗口内请求",
724
+ "statsErrors": "5xx 错误",
725
+ "statsClientErrors": "4xx 请求",
726
+ "statsLastHour": "最近 1 小时",
727
+ "searchPlaceholder": "搜索路径 / 账号 / 模型 / 错误码...",
728
+ "allLevels": "全部级别",
729
+ "allStatus": "全部状态",
730
+ "autoRefresh": "自动刷新(5s)",
731
+ "refresh": "刷新",
732
+ "manageKeys": "日志密钥",
733
+ "colTime": "时间",
734
+ "colRequest": "请求",
735
+ "colStatus": "状态",
736
+ "colLatency": "耗时",
737
+ "colAccount": "账号",
738
+ "colModel": "模型",
739
+ "colKey": "调用方",
740
+ "colError": "错误码",
741
+ "loading": "加载中...",
742
+ "empty": "暂无请求日志",
743
+ "rotatedFiles": "轮转日志文件",
744
+ "downloadAll": "打包下载",
745
+ "noFiles": "还没有轮转文件",
746
+ "download": "下载",
747
+ "detailTitle": "请求详情",
748
+ "keysTitle": "日志读取密钥",
749
+ "keysHint": "该密钥只能读取 /logs/api 下的日志与下载接口,无法修改配置或读取聊天内容。明文只在创建时显示一次。",
750
+ "keyName": "名称",
751
+ "keyTTL": "有效期",
752
+ "day": "天",
753
+ "days": "天",
754
+ "neverExpire": "永不过期",
755
+ "creating": "生成中...",
756
+ "generateKey": "生成密钥",
757
+ "keyOnce": "请立即保存,此密钥只显示一次",
758
+ "noKeys": "还没有日志密钥",
759
+ "createdAt": "创建于",
760
+ "expiresAt": "到期",
761
+ "revoked": "已吊销",
762
+ "revoke": "删除",
763
+ "keyCreateFailed": "密钥生成失败",
764
+ "keyDeleteConfirm": "确定删除该日志密钥?使用该密钥的调用会立即失效。",
765
+ "keyDeleted": "日志密钥已删除",
766
+ "keyDeleteFailed": "删除失败"
767
  }
768
  }