diff --git a/README.md b/README.md index 43b73aa..e09316a 100644 --- a/README.md +++ b/README.md @@ -398,7 +398,7 @@ Request outcomes describe the completed inference. A failed SSE response or trun Upstream **attempt** records measure the HTTP exchange through receipt of response headers. Their success and latency are separate from completion of the full JSON body or stream. -Token statistics use reported usage only. Input tokens include cache reads and writes; cached tokens separately count cache reads. Missing usage is not estimated, and coverage shows how many routed inference requests reported usage. +Token statistics use reported usage only. Input tokens include cache reads and writes; cached tokens separately count cache reads. Missing usage is not estimated, and coverage shows how many routed inference requests reported usage. `usage.server_keys` splits requests and tokens by the local server key the caller authenticated with (its fingerprint, as shown in `/api/api-keys`); Playground traffic is counted under `playground`. | Data | Storage / retention | | --------------------------------------------------------- | -------------------------------------------------------------------------------------------- | diff --git a/README.zh-CN.md b/README.zh-CN.md index 7d2656a..6120219 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -393,7 +393,7 @@ Key、代理、上游地址、重试、模型、日志和路由偏好立即对 上游**尝试记录**统计的是收到响应头为止的 HTTP 交互,其成功状态和耗时与完整 JSON 响应或流的最终完成情况分开计算。 -Token 统计仅使用上游报告的 usage。输入 Token 包含缓存读取和写入,缓存 Token 单独统计缓存读取量。缺失 usage 时不估算 Token,覆盖率表示已经建立路由的推理请求中有多少报告了 usage。 +Token 统计仅使用上游报告的 usage。输入 Token 包含缓存读取和写入,缓存 Token 单独统计缓存读取量。缺失 usage 时不估算 Token,覆盖率表示已经建立路由的推理请求中有多少报告了 usage。`usage.server_keys` 按调用方认证所用的本地 server key(指纹,与 `/api/api-keys` 的 ID 一致)拆分请求数和 Token;Playground 流量计入 `playground`。 | 数据 | 保存位置或保留规则 | | ----------------------------------------------- | ------------------------------------------------------------------------- | diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index af9bdd2..6852e4f 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -20,7 +20,8 @@ - 管理的是网关的 `server_keys`,不修改 OpenCode Go 的上游 Key。 - 自动生成 192 位随机密钥;自定义密钥为 16–256 位英文字母、数字、`-`、`_` 或 `.`。 -- 列表只显示名称、尾码、状态和创建时间。创建后可复制完整密钥及环境变量。 +- 列表只显示名称、尾码、状态、用量和创建时间。创建后可复制完整密钥及环境变量。 +- 用量按认证命中的 Key 统计请求数和 token,分近 1 小时和累计两个窗口;`GET /api/monitor` 的 `usage.server_keys` 给出同一份数据,各项之和等于聚合口径。Playground 调试流量单独归入 `playground`,不计入任何 Key。与其他监控数据一样只存于内存:热重载保留,进程重启后清零。 - 变更热应用;停用和删除后,新请求返回 401。在途请求可以完成。至少保留一个启用的 Key。 - 所有管理接口需要登录,写操作需要 CSRF Token。 - 元数据以 `server_key_metadata` 保存在原配置中,按 Key 指纹关联;已有 `server_keys` 自动兼容。 diff --git a/internal/admin/api_keys.go b/internal/admin/api_keys.go index a5c3d4d..30cb49f 100644 --- a/internal/admin/api_keys.go +++ b/internal/admin/api_keys.go @@ -11,17 +11,27 @@ import ( "opencode2api/internal/config" "opencode2api/internal/httpx" + "opencode2api/internal/telemetry" ) type APIKeyView struct { - ID string `json:"id"` - Name string `json:"name"` - Display string `json:"display"` - Enabled bool `json:"enabled"` - CreatedAt *time.Time `json:"created_at,omitempty"` + ID string `json:"id"` + Name string `json:"name"` + Display string `json:"display"` + Enabled bool `json:"enabled"` + CreatedAt *time.Time `json:"created_at,omitempty"` + Usage APIKeyUsage `json:"usage"` } -func apiKeyViews(cfg config.Config) []APIKeyView { +// APIKeyUsage is in-memory like the rest of the monitor: it restarts from zero +// with the process and survives hot reloads. +type APIKeyUsage struct { + Lifetime telemetry.ServerKeyUsage `json:"lifetime"` + Window telemetry.ServerKeyUsage `json:"last_hour"` +} + +func (a *Server) apiKeyViews(cfg config.Config) []APIKeyView { + lifetime, window := a.monitor.ServerKeyUsage() items := make([]APIKeyView, 0, len(cfg.ServerKeys)) for i, key := range cfg.ServerKeys { id := config.Fingerprint(key) @@ -30,7 +40,10 @@ func apiKeyViews(cfg config.Config) []APIKeyView { if name == "" { name = fmt.Sprintf("已有 Key %d", i+1) } - item := APIKeyView{ID: id, Name: name, Display: config.MaskValue(key), Enabled: !meta.Disabled} + item := APIKeyView{ + ID: id, Name: name, Display: config.MaskValue(key), Enabled: !meta.Disabled, + Usage: APIKeyUsage{Lifetime: lifetime[id], Window: window[id]}, + } if !meta.CreatedAt.IsZero() { created := meta.CreatedAt item.CreatedAt = &created @@ -42,7 +55,7 @@ func apiKeyViews(cfg config.Config) []APIKeyView { func (a *Server) handleListAPIKeys(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Cache-Control", "no-store") - httpx.WriteJSON(w, http.StatusOK, map[string]any{"keys": apiKeyViews(a.manager.Config())}) + httpx.WriteJSON(w, http.StatusOK, map[string]any{"keys": a.apiKeyViews(a.manager.Config())}) } func validateKeyName(name string) error { @@ -105,7 +118,7 @@ func (a *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Cache-Control", "no-store") - httpx.WriteJSON(w, 201, map[string]any{"key": key, "keys": apiKeyViews(a.manager.Config())}) + httpx.WriteJSON(w, 201, map[string]any{"key": key, "keys": a.apiKeyViews(a.manager.Config())}) } func changeAPIKey(cfg *config.Config, id string, name *string, enabled *bool, remove bool) error { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 5fe54b9..ff6a002 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -110,18 +110,18 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { if auth := r.Header.Get("Authorization"); strings.HasPrefix(strings.ToLower(auth), "bearer ") { candidates = append(candidates, strings.TrimSpace(auth[7:])) } - valid := false + matched := "" for _, key := range g.cfg.ServerKeys { if !g.cfg.ServerKeyEnabled(key) { continue } for _, candidate := range candidates { if len(candidate) == len(key) && subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1 { - valid = true + matched = key } } } - if !valid { + if matched == "" { protocol := wire.Chat if r.URL.Path == "/v1/messages" { protocol = wire.Anthropic @@ -129,6 +129,14 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { wire.WriteError(w, protocol, http.StatusUnauthorized, "invalid local API key", "authentication_error", "") return } + if meta := telemetry.MetaFromRequest(r); meta != nil { + // The Playground borrows the first enabled key to pass this check, so + // its traffic gets its own bucket instead of being billed to that key. + meta.ServerKeyID = config.Fingerprint(matched) + if isDiagnosticRequest(r.Context()) { + meta.ServerKeyID = telemetry.PlaygroundServerKey + } + } next(w, r) } } diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go index 8f9cedd..bafd796 100644 --- a/internal/telemetry/http.go +++ b/internal/telemetry/http.go @@ -31,6 +31,10 @@ type RequestMeta struct { Stop string Tail string Stream bool + // ServerKeyID is the fingerprint of the local server key the caller + // authenticated with, so usage can be split per caller. KeyID is the + // upstream account that served the request. + ServerKeyID string // Shaped marks a key-tier free-model request whose wire body was // normalized to agent shape (stream + core tools) like the anonymous // lane. Non-streaming responses for shaped requests arrive as SSE @@ -42,6 +46,10 @@ type RequestMeta struct { Outcome string } +// PlaygroundServerKey buckets admin Playground traffic, which authenticates +// with whichever server key is enabled first and is not that caller's usage. +const PlaygroundServerKey = "playground" + type requestMetaKey struct{} // WithRequestMeta shares request-local outcomes across HTTP and gateway layers. @@ -117,8 +125,8 @@ func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.H if meta.Channel != "" { logger.Info("request routed", "component", "http", "event", "request_routed", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "request_id", meta.Request, - "model", meta.Model, "model_alias", meta.ModelAlias, "session", meta.Session, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, - "anonymous", meta.Anonymous, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome, + "model", meta.Model, "model_alias", meta.ModelAlias, "session", meta.Session, "server_key_id", meta.ServerKeyID, "tier", meta.Tier, "key_id", meta.KeyID, + "channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome, "stop", meta.Stop, "in", meta.Usage.Input, "out", meta.Usage.Output, "reasoning_tokens", meta.Usage.Reasoning, "cached", meta.Usage.Cached, "tail", meta.Tail) } logger.Debug("request completed", "component", "http", "event", "request_complete", "method", r.Method, diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go index e76683b..30b4573 100644 --- a/internal/telemetry/metrics.go +++ b/internal/telemetry/metrics.go @@ -26,6 +26,7 @@ type metricBucket struct { usageModels map[string]TokenCounts usageTiers map[string]TokenCounts usageSessions map[string]TokenCounts + usageKeys map[string]ServerKeyUsage } func (b *metricBucket) reset(minute int64) { @@ -33,7 +34,7 @@ func (b *metricBucket) reset(minute int64) { minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64), tiers: make(map[string]uint64), statuses: make(map[string]uint64), usageModels: make(map[string]TokenCounts), usageTiers: make(map[string]TokenCounts), - usageSessions: make(map[string]TokenCounts), + usageSessions: make(map[string]TokenCounts), usageKeys: make(map[string]ServerKeyUsage), } } @@ -56,6 +57,14 @@ type UsagePeriod struct { // upstream IP bucket on the anonymous lane, so this shows which // conversation is draining the daily budget. Sessions map[string]TokenCounts `json:"sessions"` + // ServerKeys maps the local server key fingerprint (or "playground") to + // its share of Requests and Tokens, so the entries sum to the totals. + ServerKeys map[string]ServerKeyUsage `json:"server_keys"` +} + +type ServerKeyUsage struct { + Requests uint64 `json:"requests"` + TokenCounts } type UsageSnapshot struct { @@ -97,20 +106,21 @@ type UpstreamAttempt struct { // client inference request. It is kept separately from UpstreamAttempt, // because a single request can try several keys before it succeeds. type UpstreamRequest struct { - Time time.Time `json:"time"` - RequestID string `json:"request_id"` - Session string `json:"session,omitempty"` - Model string `json:"model"` - Tier string `json:"tier,omitempty"` - KeyID string `json:"key_id,omitempty"` - Channel string `json:"channel"` - Anonymous bool `json:"anonymous"` - Proxy string `json:"proxy_node,omitempty"` - Attempts int `json:"attempts"` - Status int `json:"status"` - DurationMS int64 `json:"duration_ms"` - Success bool `json:"success"` - Outcome string `json:"outcome"` + Time time.Time `json:"time"` + RequestID string `json:"request_id"` + Session string `json:"session,omitempty"` + ServerKeyID string `json:"server_key_id,omitempty"` + Model string `json:"model"` + Tier string `json:"tier,omitempty"` + KeyID string `json:"key_id,omitempty"` + Channel string `json:"channel"` + Anonymous bool `json:"anonymous"` + Proxy string `json:"proxy_node,omitempty"` + Attempts int `json:"attempts"` + Status int `json:"status"` + DurationMS int64 `json:"duration_ms"` + Success bool `json:"success"` + Outcome string `json:"outcome"` } type attemptBucket struct { @@ -318,10 +328,12 @@ func (m *Monitor) Record(endpoint string, status int, duration time.Duration, me addTokenMap(m.lifetimeUsage.Tiers, meta.Tier, tokens) addTokenMap(bucket.usageSessions, meta.Session, tokens) m.addLifetimeSessionLocked(meta.Session, tokens) + addServerKeyUsage(bucket.usageKeys, meta.ServerKeyID, ServerKeyUsage{Requests: 1, TokenCounts: tokens}) + addServerKeyUsage(m.lifetimeUsage.ServerKeys, meta.ServerKeyID, ServerKeyUsage{Requests: 1, TokenCounts: tokens}) } if meta.Request != "" && meta.Model != "" { request := UpstreamRequest{ - Time: time.Now().UTC(), RequestID: meta.Request, Session: meta.Session, Model: meta.Model, Tier: meta.Tier, + Time: time.Now().UTC(), RequestID: meta.Request, Session: meta.Session, ServerKeyID: meta.ServerKeyID, Model: meta.Model, Tier: meta.Tier, KeyID: meta.KeyID, Channel: meta.Channel, Anonymous: meta.Anonymous, Proxy: meta.Proxy, Attempts: meta.Attempts, Status: status, DurationMS: max(duration.Milliseconds(), 0), Success: success, @@ -424,6 +436,27 @@ type MetricSeries struct { UsageReported uint64 `json:"usage_reported"` } +// ServerKeyUsage returns per-server-key usage for the lifetime and the last +// hour. The API key list polls it, so it skips building a full Snapshot. +func (m *Monitor) ServerKeyUsage() (lifetime, window map[string]ServerKeyUsage) { + nowMinute := time.Now().Unix() / 60 + lifetime, window = make(map[string]ServerKeyUsage), make(map[string]ServerKeyUsage) + m.mu.Lock() + defer m.mu.Unlock() + for key, value := range m.lifetimeUsage.ServerKeys { + lifetime[key] = value + } + for offset := int64(0); offset < 60; offset++ { + minute := nowMinute - offset + if bucket := &m.buckets[minute%60]; bucket.minute == minute { + for key, value := range bucket.usageKeys { + addServerKeyUsage(window, key, value) + } + } + } + return lifetime, window +} + func (m *Monitor) Snapshot() MonitorSnapshot { nowMinute := time.Now().Unix() / 60 window := MetricSummary{} @@ -461,6 +494,9 @@ func (m *Monitor) Snapshot() MonitorSnapshot { mergeTokenMaps(usageWindow.Models, bucket.usageModels) mergeTokenMaps(usageWindow.Tiers, bucket.usageTiers) mergeTokenMaps(usageWindow.Sessions, bucket.usageSessions) + for key, value := range bucket.usageKeys { + addServerKeyUsage(usageWindow.ServerKeys, key, value) + } } attemptBucket := &m.attemptBuckets[minute%60] if attemptBucket.minute == minute { @@ -507,7 +543,7 @@ func mergeCounts(target, source map[string]uint64) { } func newUsagePeriod() UsagePeriod { - return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts), Sessions: make(map[string]TokenCounts)} + return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts), Sessions: make(map[string]TokenCounts), ServerKeys: make(map[string]ServerKeyUsage)} } func tokenCounts(usage protocol.Usage) TokenCounts { @@ -534,6 +570,16 @@ func addTokenMap(target map[string]TokenCounts, key string, value TokenCounts) { target[key] = current } +func addServerKeyUsage(target map[string]ServerKeyUsage, key string, value ServerKeyUsage) { + if key == "" { + return + } + current := target[key] + current.Requests += value.Requests + addTokenCounts(¤t.TokenCounts, value.TokenCounts) + target[key] = current +} + func mergeTokenMaps(target, source map[string]TokenCounts) { for key, value := range source { addTokenMap(target, key, value) @@ -572,6 +618,9 @@ func cloneUsagePeriod(source UsagePeriod) UsagePeriod { mergeTokenMaps(result.Models, source.Models) mergeTokenMaps(result.Tiers, source.Tiers) mergeTokenMaps(result.Sessions, source.Sessions) + for key, value := range source.ServerKeys { + addServerKeyUsage(result.ServerKeys, key, value) + } return result } diff --git a/webui/app.js b/webui/app.js index ec41c23..6f4219b 100644 --- a/webui/app.js +++ b/webui/app.js @@ -1110,6 +1110,9 @@ function renderAPIKeys(keys) { appendCell(row, key.name); appendCell(row, key.display, "mono"); appendCell(row, key.enabled ? "已启用" : "已停用", key.enabled ? "status ok" : "status warn"); + const usage = key.usage || {}, + summary = (value = {}) => `${formatTokens(value.requests)} 次 · ${formatTokens(value.total_tokens)} tokens`; + appendCell(row, `${summary(usage.last_hour)} / ${summary(usage.lifetime)}`); appendCell(row, key.created_at ? localTime(key.created_at) : "已有配置"); const cell = document.createElement("td"), actions = document.createElement("div"); @@ -1144,7 +1147,7 @@ function renderAPIKeys(keys) { row.appendChild(cell); host.appendChild(row); } - if (!keys.length) emptyRow(host, 5, "暂无 API Key"); + if (!keys.length) emptyRow(host, 6, "暂无 API Key"); } $("#api-key-form").onsubmit = async (event) => { event.preventDefault(); diff --git a/webui/index.html b/webui/index.html index 66bd888..10299c1 100644 --- a/webui/index.html +++ b/webui/index.html @@ -896,6 +896,7 @@