diff --git a/.gitignore b/.gitignore index 8718a5cf..c08257d9 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,8 @@ test/ *.rotation.json .rotation-*.tmp +*.freequota.json +.freequota-*.tmp # Local credentials, deployment backups, and verification artifacts .local/ diff --git a/README.it.md b/README.it.md index 22f44d82..7ee88073 100644 --- a/README.it.md +++ b/README.it.md @@ -234,6 +234,10 @@ La disponibilità viene appresa dal traffico reale per impostazione predefinita. `warp.pool_size` è il massimo di uscite adattato alla concorrenza, da 1 a 32, predefinito 2. `warp.stack` ammette `ipv6` (predefinito), `ipv4` o `dual`. Cambiare uscita non garantisce nuova quota upstream. `warp.source_ipv6` è facoltativo, richiede stack IPv6 e prefisso `/64` o più corto; su Windows gli indirizzi sorgente scelti devono essere già assegnati a un'interfaccia. Il gateway non configura la rete del computer. +### Stima dell'uso dei modelli gratuiti + +Il gateway conta le richieste ai modelli gratuiti dei client accettate per uscita — ogni proxy configurato, `direct` e ogni blocco di uscita WARP — per il giorno UTC corrente. Solo le risposte 2xx alle richieste dei client contano come utilizzo; le probe di disponibilità sono escluse. Un `FreeUsageLimitError` registra il limite minimo di quell'uscita solo quando il suo `Retry-After` punta alla mezzanotte UTC successiva e l'uscita ha già servito una richiesta nello stesso giorno; rifiuti di forma, throttling brevi e rifiuti su un'uscita nuova non insegnano nulla. Il limite minimo resta su quell'uscita attraverso la mezzanotte; `free_quota.assumed_daily_limit` è il valore usato per un'uscita che non ha ancora insegnato il proprio (`0` lascia sconosciuto). I conteggi locali si azzerano a mezzanotte UTC; l'azzeramento upstream non è verificato. Lo stato vive accanto alla configurazione in `config.json.freequota.json`; un file mancante o corrotto azzera solo la stima. `GET /api/free-quotas` restituisce la stima; la WebUI la mostra nella pagina Modelli e quote. + ## Gestione e OAuth La WebUI comprende panoramica, diagnostica/Playground/log, accesso client, chiavi API, modelli/quota, rotazione, configurazione e account. Supporta cinese semplificato, inglese, vietnamita e italiano; lingua e tema sono conservati nel browser. La [guida di gestione](docs/management.it.md) contiene i dettagli degli endpoint. diff --git a/README.md b/README.md index 6a7e10a8..b5d41baa 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,10 @@ Availability is learned from real traffic by default. Synthetic checks run only `warp.pool_size` is a concurrency-driven exit ceiling from 1 to 32, default 2. `warp.stack` accepts `ipv6` (default), `ipv4`, or `dual`. Replacing an exit does not guarantee a fresh upstream allowance. `warp.source_ipv6` is optional, requires the IPv6 stack and a prefix of `/64` or shorter, and on Windows the selected source addresses must already be assigned to an interface. It does not configure host networking. +### Free-model usage estimate + +The gateway counts accepted free-model client requests per egress — each configured proxy, `direct`, and each WARP exit block — for the current UTC day. Only 2xx responses to client requests count as usage; availability probes are excluded. A `FreeUsageLimitError` records that egress's allowance floor only when its `Retry-After` points at the next UTC midnight and the egress already served a request that day; shape refusals, short throttles and refusals on a fresh exit teach nothing. The floor stays with that egress across midnight; `free_quota.assumed_daily_limit` is the prior for an egress that has not taught its own (`0` leaves it unknown). Local counters reset at UTC midnight; the upstream reset time is not verified. State lives beside the configuration in `config.json.freequota.json`; a missing or corrupt file only resets the estimate. `GET /api/free-quotas` serves it, and the WebUI shows it under Model & quotas. + ## Management and OAuth The WebUI has overview, diagnostics/Playground/logs, client access, API keys, models/quota, rotation, configuration, and account pages. It supports Simplified Chinese, English, Vietnamese, and Italian; language/theme choices are stored in the browser. See the [management guide](docs/management.md) for endpoint details. diff --git a/README.vi.md b/README.vi.md index 5b3720f2..d171bf30 100644 --- a/README.vi.md +++ b/README.vi.md @@ -234,6 +234,10 @@ Mặc định học khả dụng từ lưu lượng thật. Yêu cầu thử t `warp.pool_size` là trần số lối ra điều chỉnh theo đồng thời, từ 1 đến 32, mặc định 2. `warp.stack` nhận `ipv6` (mặc định), `ipv4`, `dual`. Thay lối ra không bảo đảm có hạn mức mới. `warp.source_ipv6` là tùy chọn, cần stack IPv6 và prefix `/64` hoặc ngắn hơn; trên Windows, địa chỉ nguồn được chọn phải được gán sẵn cho giao diện. Gateway không cấu hình mạng của máy. +### Ước lượng mức dùng model miễn phí + +Gateway đếm request model miễn phí từ client được chấp nhận theo từng exit — mỗi proxy đã cấu hình, `direct`, và từng dải địa chỉ exit WARP — trong ngày UTC hiện tại. Chỉ phản hồi 2xx cho request của client mới tính là đã dùng; probe khả dụng không được tính. `FreeUsageLimitError` chỉ ghi nhận mức sàn hạn mức của exit đó khi `Retry-After` trỏ tới nửa đêm UTC kế tiếp và exit đã phục vụ ít nhất một request trong ngày; lỗi hình dạng request, throttle ngắn và từ chối trên exit mới không dạy được gì. Mức sàn chỉ thuộc exit đó và giữ qua nửa đêm; `free_quota.assumed_daily_limit` là prior cho exit chưa tự chứng minh (`0` = chưa biết). Bộ đếm cục bộ đặt lại lúc nửa đêm UTC; thời điểm đặt lại của upstream chưa được xác minh. Trạng thái nằm cạnh cấu hình trong `config.json.freequota.json`; file thiếu hoặc hỏng chỉ đặt lại ước lượng. `GET /api/free-quotas` trả về ước lượng, WebUI hiển thị ở trang Model & quotas. + ## Quản trị và OAuth WebUI có tổng quan, chẩn đoán/Playground/log, hướng dẫn client, key API, mô hình/hạn mức, luân chuyển, cấu hình và tài khoản. Hỗ trợ tiếng Trung giản thể, Anh, Việt và Ý; lựa chọn ngôn ngữ/giao diện lưu trong trình duyệt. Chi tiết endpoint có trong [hướng dẫn quản trị](docs/management.vi.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 5dbf8322..8a61b6d9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -236,6 +236,10 @@ OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认 `warp.pool_size` 是随并发调整的出口上限,范围 1–32,默认 2。`warp.stack` 为 `ipv6`(默认)、`ipv4` 或 `dual`。替换出口不保证获得新的上游额度。可选 `warp.source_ipv6` 要求 IPv6 堆栈及 `/64` 或更短前缀;Windows 下实际选择的源地址必须已分配到网卡,程序不会配置主机网络。 +### 免费模型用量估算 + +网关按出口统计当天(UTC)客户端已接受的免费模型请求——每个已配置代理、`direct`,以及每个 WARP 出口地址段。只有客户端请求的 2xx 响应计为用量;可用性探测不计入。`FreeUsageLimitError` 只有在该出口当天已经成功应答过请求、且 `Retry-After` 指向下一个 UTC 零点时才记录该出口的额度下限,因此请求形状拒绝、短暂限流和新出口上的拒绝都不会产生学习。学到的下限只属于该出口并跨日保留;`free_quota.assumed_daily_limit` 是尚未学到下限的出口使用的先验值(`0` 表示未知)。本地计数在 UTC 零点重置,上游重置时间未经验证。状态保存在配置文件旁的 `config.json.freequota.json`;文件缺失或损坏只会重置估算。`GET /api/free-quotas` 返回该估算,WebUI 在「模型与额度」页展示。 + ## 管理与 OAuth WebUI 包含概览、诊断/Playground/日志、接入、API Key、模型与额度、轮转、配置、账号页面,提供简中、英语、越南语及意大利语。语言与主题选择保存在浏览器。完整操作与端点见[管理指南](docs/management.zh-CN.md)。 diff --git a/config.example.json b/config.example.json index ed5fc203..fcf30e4c 100644 --- a/config.example.json +++ b/config.example.json @@ -29,6 +29,9 @@ "free_only": false, "active_probes": false }, + "free_quota": { + "assumed_daily_limit": 200 + }, "performance": { "max_idle_conns": 2048, "max_idle_conns_per_host": 256, diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index 3453c89d..5acfb79c 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -79,6 +79,17 @@ Key、代理、上游、超时、模型、偏好、reasoning 和日志设置热 | `logging.dump_request_bodies` | `false`;还需 debug 才输出,每个准备好的请求体最多 64 KiB。 | | `models.active_probes` | `false`;真实流量提供默认可用性观察。 | +### 免费模型用量估算 + +「免费模型」标签页还显示当天(UTC)按出口统计的免费模型请求,数据来自 `GET /api/free-quotas`。 + +- 只统计客户端请求中上游返回 2xx 的响应;重试按每次真实请求分别计数,可用性探测不计入。 +- 出口为代理 URL、`direct` 或 WARP 出口网段。 +- 额度是估计值:只有当某个出口当天已经产生用量,并且收到的 `FreeUsageLimitError` 带有指向下一个 UTC 零点的 `Retry-After` 时,才把当时的用量记为该出口的下限。请求形状拒绝和短暂节流不会改变估计;学到的下限只属于该出口,跨 UTC 日保留。 +- `free_quota.assumed_daily_limit`(默认 200,`0` 表示未知)用于尚未学到下限的出口。该字段只能在 `config.json` 中修改,管理页面保存其他配置时会保留它。 +- 本地计数在 UTC 零点重置;上游是否同时重置未经验证。已用尽的出口不会在零点立即重新列出,而是在新一天的首个 2xx 请求后重新出现,且只反映本网关的观测。 +- 状态保存在配置文件旁的 `config.json.freequota.json`;文件缺失或损坏只会清空估计。 + ## Go OAuth 与 Zen PAYG OAuth 「模型与额度」有两个独立面板。Go 使用订阅路由;Zen 使用 Console 工作区按量计费(PAYG),**推理会消耗该工作区 credits**。Go 登录不代表获得 Zen 权限或余额,不会自动连接 PAYG。 diff --git a/internal/admin/free_quotas.go b/internal/admin/free_quotas.go new file mode 100644 index 00000000..d937bff8 --- /dev/null +++ b/internal/admin/free_quotas.go @@ -0,0 +1,15 @@ +package admin + +import ( + "net/http" + + "opencode2api/internal/httpx" +) + +// handleFreeQuotas returns the current UTC day's free-model usage per egress. +// The upstream exposes no remaining-quota endpoint, so every number is a local +// estimate learned from traffic this gateway already sent. +func (a *Server) handleFreeQuotas(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Cache-Control", "no-store") + httpx.WriteJSON(w, http.StatusOK, a.manager.FreeQuotas()) +} diff --git a/internal/admin/server.go b/internal/admin/server.go index 6cbf4e2f..c08d296a 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -91,6 +91,7 @@ func (a *Server) Handler() http.Handler { mux.Handle("POST /api/zen/auth/poll", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthPoll)))) mux.Handle("DELETE /api/zen/auth", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthCancel)))) mux.Handle("DELETE /api/zen/connection", a.authenticate(a.csrf(http.HandlerFunc(a.handleZenOAuthDisconnect)))) + mux.Handle("GET /api/free-quotas", a.authenticate(http.HandlerFunc(a.handleFreeQuotas))) mux.Handle("GET /api/api-keys", a.authenticate(http.HandlerFunc(a.handleListAPIKeys))) mux.Handle("POST /api/api-keys", a.authenticate(a.csrf(http.HandlerFunc(a.handleCreateAPIKey)))) mux.Handle("PATCH /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleUpdateAPIKey)))) @@ -277,7 +278,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { ZenOAuth: current.ZenOAuth, Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, ProxyBindings: proxyBindings, - Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, + Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, FreeQuota: current.FreeQuota, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } diff --git a/internal/config/config.go b/internal/config/config.go index 49cbb28c..d779bcba 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -44,6 +44,7 @@ type Config struct { Upstream UpstreamConfig `json:"upstream"` Retry RetryConfig `json:"retry"` Models ModelsConfig `json:"models"` + FreeQuota FreeQuotaConfig `json:"free_quota"` Performance PerformanceConfig `json:"performance"` Logging LoggingConfig `json:"logging"` WebUI WebUIConfig `json:"webui"` @@ -216,6 +217,25 @@ type AnonymousBackoffConfig struct { MaxHours int `json:"max_hours,omitempty"` } +// DefaultAssumedFreeQuotaLimit is the per-egress free-model allowance the +// console shows until an egress teaches its own. +const DefaultAssumedFreeQuotaLimit = 200 + +// FreeQuotaConfig tunes the passive free-model usage estimate. An absent +// AssumedDailyLimit uses DefaultAssumedFreeQuotaLimit; zero shows unknown. +type FreeQuotaConfig struct { + AssumedDailyLimit *int `json:"assumed_daily_limit,omitempty"` +} + +// AssumedLimit returns the configured starting allowance, or the default when +// the pointer is nil. +func (f FreeQuotaConfig) AssumedLimit() int { + if f.AssumedDailyLimit == nil { + return DefaultAssumedFreeQuotaLimit + } + return *f.AssumedDailyLimit +} + // Normalize fills the defaults and rejects nonsensical windows. func (b *AnonymousBackoffConfig) Normalize() error { if b == nil { @@ -462,6 +482,9 @@ func Normalize(path string, cfg Config) (Config, error) { if cfg.Models.RefreshSeconds < 1 { return Config{}, errors.New("models.refresh_seconds must be at least 1") } + if limit := cfg.FreeQuota.AssumedDailyLimit; limit != nil && (*limit < 0 || *limit > 1000000) { + return Config{}, errors.New("free_quota.assumed_daily_limit must be between 0 and 1000000") + } if cfg.Performance.MaxIdleConns < 1 || cfg.Performance.MaxIdleConnsPerHost < 1 || cfg.Performance.MaxConnsPerHost < 0 || cfg.Performance.IdleConnTimeoutSeconds < 1 || cfg.Performance.ConnectTimeoutSeconds < 1 || cfg.Performance.FailureCooldownSeconds < 1 { return Config{}, errors.New("performance values must be positive (max_conns_per_host may be zero for unlimited)") } diff --git a/internal/freequota/tracker.go b/internal/freequota/tracker.go new file mode 100644 index 00000000..8dc9149a --- /dev/null +++ b/internal/freequota/tracker.go @@ -0,0 +1,307 @@ +// Package freequota counts accepted free-model requests per egress for the +// current UTC day and records a per-egress allowance floor. +// +// The upstream exposes no remaining-quota endpoint and no rate-limit headers. +// Two facts are observable: N accepted requests prove the allowance is at +// least N, and a genuine daily-limit refusal proves usage reached it. Shape +// refusals share the free-limit body, so a refusal teaches nothing unless its +// Retry-After points at the next UTC midnight; short throttles and refusals +// without that hint teach nothing either. +package freequota + +import ( + "bytes" + "encoding/json" + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +const ( + // saveInterval bounds how often counters reach disk. The snapshot served to + // operators is read from memory and is always current. + saveInterval = 2 * time.Second + // minRetryAfter separates a daily reset from a transient throttle. + minRetryAfter = time.Minute + // midnightSkew bounds how close a Retry-After must land to the next UTC + // midnight to count as a daily-quota refusal. + midnightSkew = 5 * time.Minute +) + +// Options configures the estimate. AssumedDailyLimit is the per-egress +// allowance shown until an egress teaches its own; zero shows unknown. +type Options struct{ AssumedDailyLimit int } + +// Event is one finished upstream attempt for a free model. Body is only read +// for a 429 and must already be restored by the caller. +type Event struct { + Time time.Time + Egress string + Status int + Body []byte + RetryAfter time.Duration + TransportError bool +} + +// Scope is one egress's estimate for the current day. +type Scope struct { + Egress string `json:"egress"` + Used int `json:"used"` + Limit int `json:"limit"` + LimitSource string `json:"limit_source"` + Remaining *int `json:"remaining"` + Exhausted bool `json:"exhausted"` +} + +// Snapshot is the whole estimate for the current UTC day. +type Snapshot struct { + ResetsAt time.Time `json:"resets_at"` + AssumedDailyLimit int `json:"assumed_daily_limit"` + TotalUsed int `json:"total_used"` + Scopes []Scope `json:"scopes"` +} + +type scopeState struct { + Day string `json:"day,omitempty"` + Used int `json:"used,omitempty"` + Limit int `json:"limit,omitempty"` + Exhausted bool `json:"exhausted,omitempty"` +} + +type persisted struct { + Scopes map[string]*scopeState `json:"scopes"` +} + +// Tracker keeps per-egress counters for the current day. It is safe for +// concurrent use. An empty path makes the state memory-only. +type Tracker struct { + mu sync.Mutex + saveMu sync.Mutex + opts Options + path string + scopes map[string]*scopeState + now func() time.Time + lastSave time.Time +} + +// Open loads path. A missing or corrupt file yields an empty tracker: the file +// only holds an estimate, so it is never fatal. +func Open(path string, opts Options) *Tracker { + t := &Tracker{ + opts: opts, + path: strings.TrimSpace(path), + scopes: make(map[string]*scopeState), + now: time.Now, + } + t.load() + return t +} + +// Configure updates the runtime options without discarding today's counts. +func (t *Tracker) Configure(opts Options) { + t.mu.Lock() + t.opts = opts + t.mu.Unlock() +} + +// Close flushes pending counters. +func (t *Tracker) Close() { + if t.path == "" { + return + } + t.save() +} + +// Record accounts one attempt. Only accepted requests count as usage, and only +// a daily-quota refusal that follows usage on the same egress bounds its +// allowance; transport errors, blocks and other statuses spend nothing. +func (t *Tracker) Record(ev Event) { + when := ev.Time + if when.IsZero() { + when = t.now() + } + when = when.UTC() + day := when.Format("2006-01-02") + egress := strings.TrimSpace(ev.Egress) + if egress == "" { + egress = "direct" + } + + t.mu.Lock() + scope := t.scopes[egress] + if scope == nil { + scope = &scopeState{} + t.scopes[egress] = scope + } + if day < scope.Day { + t.mu.Unlock() + return + } + if day > scope.Day { + scope.Day = day + scope.Used = 0 + scope.Exhausted = false + } + + switch { + case ev.TransportError, ev.Status == http.StatusForbidden: + // The attempt never reached a model: no usage, no evidence. + case isSuccess(ev.Status): + scope.Used++ + scope.Exhausted = false + case isDailyLimit(ev.Status, ev.Body, ev.RetryAfter, when): + // A refusal proves exhaustion only when the egress has already accepted + // as much as its allowance. Below that the refusal can be scoped to one + // conversation rather than this egress, so it teaches nothing. + if scope.Used > 0 && (t.opts.AssumedDailyLimit <= 0 || scope.Used >= t.opts.AssumedDailyLimit) { + if scope.Used > scope.Limit { + scope.Limit = scope.Used + } + scope.Exhausted = true + } + } + + due := when.Sub(t.lastSave) >= saveInterval + if due { + t.lastSave = when + } + t.mu.Unlock() + if due { + t.save() + } +} + +// Snapshot renders the current UTC day. Only egresses with accepted requests +// today are listed; one that has no traffic today appears after its first. +func (t *Tracker) Snapshot() Snapshot { + now := t.now().UTC() + day := now.Format("2006-01-02") + t.mu.Lock() + defer t.mu.Unlock() + result := Snapshot{ + ResetsAt: nextReset(now), + AssumedDailyLimit: t.opts.AssumedDailyLimit, + Scopes: []Scope{}, + } + for egress, state := range t.scopes { + if state.Day != day || state.Used <= 0 { + continue + } + item := Scope{Egress: egress, Used: state.Used, Exhausted: state.Exhausted} + switch { + case state.Limit > 0: + item.Limit, item.LimitSource = state.Limit, "learned" + case t.opts.AssumedDailyLimit > 0: + item.Limit, item.LimitSource = t.opts.AssumedDailyLimit, "assumed" + default: + item.LimitSource = "unknown" + } + if item.Limit > 0 { + // A limit is a floor: accepted requests alone can prove more usage + // than an older refusal taught. + if item.Used > item.Limit { + item.Limit = item.Used + } + remaining := item.Limit - item.Used + if item.Exhausted { + remaining = 0 + } + item.Remaining = &remaining + } + result.TotalUsed += item.Used + result.Scopes = append(result.Scopes, item) + } + sort.Slice(result.Scopes, func(i, j int) bool { + if result.Scopes[i].Used != result.Scopes[j].Used { + return result.Scopes[i].Used > result.Scopes[j].Used + } + return result.Scopes[i].Egress < result.Scopes[j].Egress + }) + return result +} + +func (t *Tracker) load() { + if t.path == "" { + return + } + data, err := os.ReadFile(t.path) + if err != nil { + return + } + var saved persisted + if err := json.Unmarshal(data, &saved); err != nil || saved.Scopes == nil { + return + } + for egress, state := range saved.Scopes { + if state != nil && strings.TrimSpace(egress) != "" { + t.scopes[egress] = state + } + } +} + +func (t *Tracker) save() { + if t.path == "" { + return + } + // Serialize the whole write so a slow older save cannot rename over a newer + // one and persist stale counters. + t.saveMu.Lock() + defer t.saveMu.Unlock() + t.mu.Lock() + data, err := json.MarshalIndent(persisted{Scopes: t.scopes}, "", " ") + t.mu.Unlock() + if err != nil { + return + } + data = append(data, '\n') + dir := filepath.Dir(t.path) + if err := os.MkdirAll(dir, 0o755); err != nil { + return + } + temp, err := os.CreateTemp(dir, ".freequota-*.tmp") + if err != nil { + return + } + tempPath := temp.Name() + defer os.Remove(tempPath) + if _, err = temp.Write(data); err == nil { + err = temp.Sync() + } + if closeErr := temp.Close(); err == nil { + err = closeErr + } + if err == nil { + _ = os.Rename(tempPath, t.path) + } +} + +func isSuccess(status int) bool { return status >= 200 && status < 300 } + +func isFreeLimit(status int, body []byte) bool { + if status != http.StatusTooManyRequests || len(body) == 0 { + return false + } + lower := bytes.ToLower(body) + return bytes.Contains(lower, []byte("freeusagelimiterror")) || + bytes.Contains(lower, []byte("free usage limit")) +} + +func isDailyLimit(status int, body []byte, retryAfter time.Duration, when time.Time) bool { + if !isFreeLimit(status, body) || retryAfter < minRetryAfter { + return false + } + delta := nextReset(when).Sub(when.Add(retryAfter)) + if delta < 0 { + delta = -delta + } + return delta <= midnightSkew +} + +func nextReset(when time.Time) time.Time { + utc := when.UTC() + return time.Date(utc.Year(), utc.Month(), utc.Day()+1, 0, 0, 0, 0, time.UTC) +} diff --git a/internal/freequota/tracker_test.go b/internal/freequota/tracker_test.go new file mode 100644 index 00000000..18ae6ac3 --- /dev/null +++ b/internal/freequota/tracker_test.go @@ -0,0 +1,303 @@ +package freequota + +import ( + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +var freeLimitBody = []byte(`{"error":{"message":"Free usage limit reached.","type":"FreeUsageLimitError"}}`) + +func at(day int, hour int) time.Time { + return time.Date(2026, 11, day, hour, 0, 0, 0, time.UTC) +} + +func newTracker(t *testing.T, assumed int) *Tracker { + t.Helper() + tracker := Open(filepath.Join(t.TempDir(), "state.json"), Options{AssumedDailyLimit: assumed}) + tracker.now = func() time.Time { return at(16, 12) } + return tracker +} + +func ok(tracker *Tracker, egress string, when time.Time) { + tracker.Record(Event{Time: when, Egress: egress, Status: 200}) +} + +func quota(tracker *Tracker, egress string, when time.Time) { + tracker.Record(Event{Time: when, Egress: egress, Status: 429, Body: freeLimitBody, + RetryAfter: nextReset(when).Sub(when)}) +} + +func TestOnlyAcceptedRequestsCount(t *testing.T) { + tracker := newTracker(t, 200) + ok(tracker, "p1", at(16, 9)) + ok(tracker, "p1", at(16, 9)) + tracker.Record(Event{Time: at(16, 9), Egress: "p1", Status: 400}) + tracker.Record(Event{Time: at(16, 9), Egress: "p1", Status: 403}) + tracker.Record(Event{Time: at(16, 9), Egress: "p1", TransportError: true}) + tracker.Record(Event{Time: at(16, 9), Egress: "p1", Status: 429}) + + got := tracker.Snapshot() + if got.TotalUsed != 2 { + t.Fatalf("TotalUsed = %d, want 2", got.TotalUsed) + } + if len(got.Scopes) != 1 || got.Scopes[0].Used != 2 { + t.Fatalf("scopes = %+v, want one scope with Used 2", got.Scopes) + } + if got.Scopes[0].Limit != 200 || got.Scopes[0].LimitSource != "assumed" { + t.Fatalf("limit = %d/%s, want 200/assumed", got.Scopes[0].Limit, got.Scopes[0].LimitSource) + } +} + +func TestRefusalWithoutUsageTeachesNothing(t *testing.T) { + tracker := newTracker(t, 200) + quota(tracker, "p1", at(16, 9)) + + got := tracker.Snapshot() + if len(got.Scopes) != 0 { + t.Fatalf("scopes = %+v, want none: a refusal on a fresh egress is not evidence", got.Scopes) + } +} + +func TestRefusalBelowAssumedTeachesNothing(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 7; i++ { + ok(tracker, "p1", at(16, 9)) + } + quota(tracker, "p1", at(16, 10)) + + got := tracker.Snapshot() + if len(got.Scopes) != 1 { + t.Fatalf("scopes = %+v, want one", got.Scopes) + } + scope := got.Scopes[0] + if scope.Exhausted || scope.Limit != 200 || scope.LimitSource != "assumed" { + t.Fatalf("scope = %+v, want an untouched assumed limit: a refusal under the allowance may be session-scoped", scope) + } + if scope.Remaining == nil || *scope.Remaining != 193 { + t.Fatalf("remaining = %v, want 193", scope.Remaining) + } +} + +func TestRefusalAtAssumedLimitLearns(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 200; i++ { + ok(tracker, "p1", at(16, 9)) + } + quota(tracker, "p1", at(16, 10)) + + scope := tracker.Snapshot().Scopes[0] + if scope.Limit != 200 || scope.LimitSource != "learned" { + t.Fatalf("limit = %d/%s, want 200/learned", scope.Limit, scope.LimitSource) + } + if !scope.Exhausted { + t.Fatal("scope not marked exhausted") + } + if scope.Remaining == nil || *scope.Remaining != 0 { + t.Fatalf("remaining = %v, want 0", scope.Remaining) + } +} + +func TestShortRetryAfterDoesNotTeach(t *testing.T) { + tracker := newTracker(t, 200) + ok(tracker, "p1", at(16, 9)) + tracker.Record(Event{Time: at(16, 10), Egress: "p1", Status: 429, Body: freeLimitBody, + RetryAfter: 30 * time.Second}) + + scope := tracker.Snapshot().Scopes[0] + if scope.Exhausted || scope.Limit != 200 || scope.LimitSource != "assumed" { + t.Fatalf("scope = %+v, want an untouched assumed limit", scope) + } +} + +func TestOffMidnightRefusalDoesNotTeach(t *testing.T) { + tracker := newTracker(t, 200) + ok(tracker, "p1", at(16, 9)) + tracker.Record(Event{Time: at(16, 10), Egress: "p1", Status: 429, Body: freeLimitBody, + RetryAfter: 8 * time.Hour}) + + scope := tracker.Snapshot().Scopes[0] + if scope.Exhausted || scope.Limit != 200 || scope.LimitSource != "assumed" { + t.Fatalf("scope = %+v, want an untouched assumed limit", scope) + } +} + +func TestTransientRefusalClearsOnSuccess(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 200; i++ { + ok(tracker, "p1", at(16, 9)) + } + quota(tracker, "p1", at(16, 10)) + if !tracker.Snapshot().Scopes[0].Exhausted { + t.Fatal("expected exhausted after refusal") + } + ok(tracker, "p1", at(16, 10)) + + scope := tracker.Snapshot().Scopes[0] + if scope.Exhausted { + t.Fatal("a later success must clear the exhaustion") + } + if scope.Limit != 201 || scope.LimitSource != "learned" { + t.Fatalf("limit = %d/%s, want the used floor 201", scope.Limit, scope.LimitSource) + } + if scope.Used != 201 { + t.Fatalf("Used = %d, want 201", scope.Used) + } +} + +func TestLearnedLimitStaysOnItsEgress(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 200; i++ { + ok(tracker, "a", at(16, 9)) + } + quota(tracker, "a", at(16, 10)) + ok(tracker, "b", at(16, 11)) + + got := tracker.Snapshot() + if got.TotalUsed != 201 { + t.Fatalf("TotalUsed = %d, want 201", got.TotalUsed) + } + for _, scope := range got.Scopes { + switch scope.Egress { + case "a": + if scope.Limit != 200 || scope.LimitSource != "learned" || !scope.Exhausted { + t.Fatalf("a = %+v, want exhausted with the learned 200", scope) + } + case "b": + if scope.Limit != 200 || scope.LimitSource != "assumed" || scope.Exhausted { + t.Fatalf("b = %+v, want the configured assumed limit", scope) + } + if scope.Remaining == nil || *scope.Remaining != 199 { + t.Fatalf("b remaining = %v, want 199", scope.Remaining) + } + default: + t.Fatalf("unexpected scope %+v", scope) + } + } +} + +func TestDayRolloverKeepsLearnedLimit(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 200; i++ { + ok(tracker, "p1", at(16, 9)) + } + quota(tracker, "p1", at(16, 10)) + + tracker.now = func() time.Time { return at(17, 1) } + if got := tracker.Snapshot(); len(got.Scopes) != 0 || got.TotalUsed != 0 { + t.Fatalf("snapshot = %+v, want no rows before the first request of the new day", got) + } + ok(tracker, "p1", at(17, 1)) + + got := tracker.Snapshot() + if len(got.Scopes) != 1 { + t.Fatalf("scopes = %+v, want one", got.Scopes) + } + scope := got.Scopes[0] + if scope.Used != 1 || scope.Exhausted { + t.Fatalf("scope = %+v, want a fresh day", scope) + } + if scope.Limit != 200 || scope.LimitSource != "learned" { + t.Fatalf("limit = %d/%s, want the learned 200 to survive midnight", scope.Limit, scope.LimitSource) + } + if scope.Remaining == nil || *scope.Remaining != 199 { + t.Fatalf("remaining = %v, want 199", scope.Remaining) + } +} + +func TestBackdatedEventIgnored(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 3; i++ { + ok(tracker, "p1", at(16, 9)) + } + ok(tracker, "p1", at(15, 9)) + quota(tracker, "p1", at(15, 10)) + + got := tracker.Snapshot() + if got.TotalUsed != 3 || len(got.Scopes) != 1 { + t.Fatalf("snapshot = %+v, want yesterday's events ignored", got) + } + if got.Scopes[0].Exhausted { + t.Fatal("a backdated refusal must not exhaust today") + } +} + +func TestUnknownAssumedLimit(t *testing.T) { + tracker := newTracker(t, 0) + ok(tracker, "p1", at(16, 9)) + + scope := tracker.Snapshot().Scopes[0] + if scope.Limit != 0 || scope.LimitSource != "unknown" || scope.Remaining != nil { + t.Fatalf("scope = %+v, want an unknown limit with no remaining", scope) + } +} + +func TestConfigureKeepsCounts(t *testing.T) { + tracker := newTracker(t, 200) + for i := 0; i < 3; i++ { + ok(tracker, "p1", at(16, 9)) + } + tracker.Configure(Options{AssumedDailyLimit: 50}) + + scope := tracker.Snapshot().Scopes[0] + if scope.Used != 3 || scope.Limit != 50 || scope.LimitSource != "assumed" { + t.Fatalf("scope = %+v, want today's count with the new prior", scope) + } +} + +func TestPersistenceReload(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + tracker := Open(path, Options{AssumedDailyLimit: 200}) + tracker.now = func() time.Time { return at(16, 12) } + for i := 0; i < 200; i++ { + ok(tracker, "warp", at(16, 9)) + } + quota(tracker, "warp", at(16, 10)) + tracker.Close() + + reloaded := Open(path, Options{AssumedDailyLimit: 200}) + reloaded.now = func() time.Time { return at(16, 12) } + scope := reloaded.Snapshot().Scopes[0] + if scope.Used != 200 || scope.Limit != 200 || !scope.Exhausted { + t.Fatalf("scope = %+v, want used 200, learned 200, exhausted", scope) + } +} + +func TestConcurrentRecordAndSnapshot(t *testing.T) { + tracker := newTracker(t, 200) + var wg sync.WaitGroup + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + ok(tracker, "p1", at(16, 9)) + }() + } + for i := 0; i < 20; i++ { + wg.Add(1) + go func() { + defer wg.Done() + tracker.Snapshot() + }() + } + wg.Wait() + + if got := tracker.Snapshot(); got.TotalUsed != 100 { + t.Fatalf("TotalUsed = %d, want 100", got.TotalUsed) + } +} + +func TestCorruptStateIsNotFatal(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + tracker := Open(path, Options{AssumedDailyLimit: 200}) + tracker.now = func() time.Time { return at(16, 12) } + ok(tracker, "p1", at(16, 9)) + if tracker.Snapshot().TotalUsed != 1 { + t.Fatal("tracker did not start empty after a corrupt file") + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 24bb3113..d9355bef 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -27,6 +27,7 @@ import ( "time" "opencode2api/internal/config" + "opencode2api/internal/freequota" "opencode2api/internal/httpx" "opencode2api/internal/identity" "opencode2api/internal/jsonutil" @@ -87,6 +88,8 @@ type Gateway struct { catalog *models.ModelCatalog monitor *telemetry.Metrics availability *models.AvailabilityRegistry + // freeQuota counts free-model usage per egress. Nil disables tracking. + freeQuota *freequota.Tracker // attemptTimeout bounds a whole upstream attempt (dial + write + headers // and, when the first-event wait is enabled, the first event), not just // the header wait. Zero arms no per-attempt deadline: each attempt is then diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 7d31e241..45e2d768 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -14,6 +14,7 @@ import ( "time" "opencode2api/internal/config" + "opencode2api/internal/freequota" modelcatalog "opencode2api/internal/models" "opencode2api/internal/oauth" "opencode2api/internal/protocol" @@ -78,6 +79,9 @@ type RuntimeController struct { // and stack are unchanged. warpKey is the identity used for that reuse. warpPool *warp.Pool warpKey string + // freeQuota counts free-model usage across runtime rebuilds, so a config + // reload keeps today's counters. + freeQuota *freequota.Tracker } // EffectiveListeners are the listener settings the running process actually @@ -100,6 +104,11 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config, effective: EffectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled}, } manager.metadata = modelcatalog.PricingStore(configPath, logger) + freeQuotaPath := "" + if configPath != "" { + freeQuotaPath = configPath + ".freequota.json" + } + manager.freeQuota = freequota.Open(freeQuotaPath, freeQuotaOptions(cfg.FreeQuota)) // OpenCode metadata refreshes ride the active runtime's healthy proxy // transports and fall back to the registry's direct client when none are // available. @@ -230,6 +239,9 @@ func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { } return connection, nil } + if m.freeQuota != nil { + gateway.freeQuota = m.freeQuota + } availabilityPath := "" if m.configPath != "" { availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json" @@ -420,6 +432,9 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( return ApplyResult{}, err } } + if m.freeQuota != nil { + m.freeQuota.Configure(freeQuotaOptions(normalized.FreeQuota)) + } result := ApplyResult{Applied: true} if normalized.Listen != m.effective.API { @@ -492,6 +507,18 @@ func (m *RuntimeController) Shutdown() { m.warpPool = nil m.warpKey = "" } + if m.freeQuota != nil { + m.freeQuota.Close() + } +} + +// FreeQuotas reports the current UTC day's free-model usage estimate. +func (m *RuntimeController) FreeQuotas() freequota.Snapshot { + return m.freeQuota.Snapshot() +} + +func freeQuotaOptions(cfg config.FreeQuotaConfig) freequota.Options { + return freequota.Options{AssumedDailyLimit: cfg.AssumedLimit()} } // ResourceSnapshot is the operator view of the current runtime's models, keys, diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 48cb3fef..f287e94f 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -19,6 +19,7 @@ import ( "time" "opencode2api/internal/config" + "opencode2api/internal/freequota" "opencode2api/internal/httpx" "opencode2api/internal/identity" "opencode2api/internal/jsonutil" @@ -1293,6 +1294,21 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, } meta.Legs = append(meta.Legs, leg) } + if g.freeQuota != nil && g.catalog.IsFreeModel(route.ID) { + // The free quota is scoped to the egress block, so the tracker keys on + // the same label the request log uses: a proxy URL, "direct", or the + // rotated WARP exit's block. + egress := "direct" + if proxy != nil { + egress = config.RedactURL(proxy.name) + } + event := freequota.Event{Time: time.Now().UTC(), Egress: egress, Status: status, TransportError: err != nil} + if resp != nil && status == http.StatusTooManyRequests { + event.Body = peekResponseBody(resp) + event.RetryAfter = parseRetryAfter(resp.Header.Get("Retry-After")) + } + g.freeQuota.Record(event) + } if g.monitor == nil { return } diff --git a/webui/css/pages.css b/webui/css/pages.css index a545fe46..a0bcf10e 100644 --- a/webui/css/pages.css +++ b/webui/css/pages.css @@ -113,6 +113,10 @@ color: var(--text-3); } +.free-usage-metrics { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + .breakdown { display: grid; gap: var(--sp-2); diff --git a/webui/index.html b/webui/index.html index 0cf6b949..a07fd8a5 100644 --- a/webui/index.html +++ b/webui/index.html @@ -734,6 +734,48 @@