mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat: add authenticated web management console
This commit is contained in:
1 parent
40024ea5e8
commit
fdae1902a0
16 files changed
+1953
-73
No files matched your search
+1
-1
@@ -7,6 +7,6 @@ WORKDIR /app
|
||||
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint
|
||||
RUN chmod 0755 /usr/local/bin/docker-entrypoint
|
||||
|
||||
EXPOSE 8080
|
||||
EXPOSE 8080 8081
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint"]
|
||||
@@ -18,6 +18,10 @@
|
||||
- 代理失败后自动迁移绑定,key 失败后进行短时冷却
|
||||
- 根据真实上游流量识别代理故障,并每 15 分钟通过 Cloudflare trace 并行复查异常代理
|
||||
- 为不同会话生成不同的 OpenCode 会话 ID,并支持 `x-opencode-session`、`x-session-id` 和 `conversation-id` 显式指定会话
|
||||
- 内置独立端口 WebUI,可管理配置、查看运行指标、key/proxy 状态与实时日志
|
||||
- WebUI 使用账号密码、服务端 session、HttpOnly Cookie、CSRF 与登录限速保护
|
||||
- WebUI 保存后原子写入配置并热切换 Gateway;无效配置不会影响当前流量
|
||||
- stdout 输出结构化 JSON 日志,最近事件与一小时滚动指标保存在有限内存中
|
||||
|
||||
## API 路径
|
||||
|
||||
@@ -33,6 +37,18 @@
|
||||
|
||||
模型目录的过期阈值为 `models.refresh_seconds` 的两倍,且不低于 60 秒。刚启动时短暂返回 `503 starting` 属于正常现象,模型列表首次刷新成功后会变为 `200 ok`。
|
||||
|
||||
## WebUI
|
||||
|
||||
示例配置会在独立的 `8081` 端口启动管理界面:
|
||||
|
||||
```text
|
||||
http://服务器地址:8081
|
||||
```
|
||||
|
||||
首次账号为 `admin`,密码来自 `webui.password`。服务第一次成功启动时会使用 Argon2id 将密码转换为带盐哈希,写入 `webui.password_hash`,并从配置中删除明文密码。请在首次登录后立即修改示例密码。
|
||||
|
||||
WebUI 可查看最近一小时的请求率、成功率、状态码与延迟分位,监控活跃请求/流、模型、key 冷却和 proxy 健康状态;实时日志通过 SSE 推送。监控和最近日志仅保存在内存,服务重启后清空,stdout 日志仍可由 Docker 或日志平台收集。
|
||||
|
||||
## 编译
|
||||
|
||||
需要 Go 1.24 或更高版本。
|
||||
@@ -54,19 +70,20 @@ docker compose up -d
|
||||
|
||||
```bash
|
||||
cp config.example.json config.json
|
||||
# 编辑 config.json 中的 server_keys、zen_keys 或 go_keys
|
||||
# 编辑 server_keys、zen_keys/go_keys,并修改 webui.password
|
||||
docker compose restart
|
||||
```
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8080/healthz
|
||||
# 浏览器打开 http://127.0.0.1:8081
|
||||
docker compose logs -f
|
||||
```
|
||||
|
||||
如需修改宿主机端口:
|
||||
|
||||
```bash
|
||||
OPENCODE2API_PORT=18080 docker compose up -d
|
||||
OPENCODE2API_PORT=18080 OPENCODE2API_WEBUI_PORT=18081 docker compose up -d
|
||||
```
|
||||
|
||||
## 配置
|
||||
@@ -109,7 +126,15 @@ cp config.example.json config.json
|
||||
"failure_cooldown_seconds": 15
|
||||
},
|
||||
"logging": {
|
||||
"level": "info"
|
||||
"level": "info",
|
||||
"ring_size": 2000
|
||||
},
|
||||
"webui": {
|
||||
"enabled": true,
|
||||
"listen": "0.0.0.0:8081",
|
||||
"username": "admin",
|
||||
"password": "change-this-admin-password",
|
||||
"session_ttl_minutes": 720
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -223,9 +248,29 @@ socks5://127.0.0.1:1080 # 备用代理
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `logging.level` | 日志级别,支持 `info` 和 `debug`。生产环境建议使用 `info`。 |
|
||||
| `logging.level` | 日志级别,支持 `debug`、`info`、`warn` 和 `error`,可通过 WebUI 热切换。 |
|
||||
| `logging.ring_size` | WebUI 最近日志环容量,范围 100–50000,默认 2000。stdout 不受此容量限制。 |
|
||||
|
||||
日志不会输出完整上游 key、本地 key、Authorization、`x-api-key` 或请求消息正文。
|
||||
每条 stdout 日志都是单行 JSON,包含时间、级别、组件、事件以及适用的 request ID、模型、tier、状态码、耗时和重试次数。日志不会输出完整上游 key、本地 key、Authorization、Cookie、代理认证信息或请求消息正文。
|
||||
|
||||
### `webui`
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `webui.enabled` | 是否在独立端口启动管理服务。旧配置未包含该段时默认关闭。 |
|
||||
| `webui.listen` | 管理服务监听地址,示例为 `0.0.0.0:8081`。 |
|
||||
| `webui.username` | 单一管理员账号。 |
|
||||
| `webui.password` | 仅用于首次初始化的明文密码,至少 10 个字符;启动后自动删除。 |
|
||||
| `webui.password_hash` | 自动生成的 Argon2id 哈希,不应手动编辑,也不会由 WebUI API 返回。 |
|
||||
| `webui.session_ttl_minutes` | 登录 session 有效时间,范围 5–10080 分钟。 |
|
||||
|
||||
WebUI 中普通配置响应只包含 key 尾码/指纹及脱敏 proxy。需要查看完整值时必须再次输入管理密码,敏感响应禁止浏览器缓存。
|
||||
|
||||
### 配置保存与热重载
|
||||
|
||||
WebUI 保存时先解析并验证完整候选配置、创建新的连接池和 Gateway,然后写入临时文件、保留 `config.json.bak` 并替换 `config.json`,最后原子切换新请求使用的运行实例。写入或初始化失败时旧实例继续工作;切换前已开始的请求不会中断。
|
||||
|
||||
keys、proxy、上游、重试、模型、性能、优先 tier 和日志级别会立即生效。`listen`、`webui.listen` 与 `webui.enabled` 会保存但需要重启进程。WebUI 也提供“从磁盘重载”,外部编辑后的配置仍会经过相同的验证与回滚流程。保存后的 JSON 会被规范化,原有注释不会保留。
|
||||
|
||||
|
||||
## 会话 ID
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"embed"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const adminCookieName = "opencode2api_session"
|
||||
|
||||
//go:embed webui/*
|
||||
var webAssets embed.FS
|
||||
|
||||
type adminSession struct {
|
||||
Username string
|
||||
AuthVersion string
|
||||
CSRF string
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
type loginWindow struct {
|
||||
Started time.Time
|
||||
Count int
|
||||
}
|
||||
|
||||
type AdminServer struct {
|
||||
manager *RuntimeManager
|
||||
monitor *Monitor
|
||||
logs *LogHub
|
||||
logger *slog.Logger
|
||||
mu sync.Mutex
|
||||
sessions map[string]adminSession
|
||||
attempts map[string]loginWindow
|
||||
}
|
||||
|
||||
func NewAdminServer(manager *RuntimeManager, monitor *Monitor, logs *LogHub, logger *slog.Logger) *AdminServer {
|
||||
return &AdminServer{manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow)}
|
||||
}
|
||||
|
||||
func (a *AdminServer) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/auth/login", a.handleLogin)
|
||||
mux.Handle("GET /api/auth/session", a.authenticate(http.HandlerFunc(a.handleSession)))
|
||||
mux.Handle("POST /api/auth/logout", a.authenticate(a.csrf(http.HandlerFunc(a.handleLogout))))
|
||||
mux.Handle("GET /api/config", a.authenticate(http.HandlerFunc(a.handleGetConfig)))
|
||||
mux.Handle("PUT /api/config", a.authenticate(a.csrf(http.HandlerFunc(a.handlePutConfig))))
|
||||
mux.Handle("POST /api/config/reload", a.authenticate(a.csrf(http.HandlerFunc(a.handleReload))))
|
||||
mux.Handle("POST /api/config/reveal", a.authenticate(a.csrf(http.HandlerFunc(a.handleReveal))))
|
||||
mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount))))
|
||||
mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor)))
|
||||
mux.Handle("GET /api/logs", a.authenticate(http.HandlerFunc(a.handleLogs)))
|
||||
mux.Handle("GET /api/logs/stream", a.authenticate(http.HandlerFunc(a.handleLogStream)))
|
||||
mux.Handle("/", a.staticHandler())
|
||||
return a.securityHeaders(recoveryMiddleware(a.logger, mux))
|
||||
}
|
||||
|
||||
func (a *AdminServer) staticHandler() http.Handler {
|
||||
assets, err := fs.Sub(webAssets, "webui")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
files := http.FileServer(http.FS(assets))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
writeAdminError(w, http.StatusNotFound, "not_found", "management endpoint not found")
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/" && r.URL.Path != "/index.html" {
|
||||
if _, err := fs.Stat(assets, strings.TrimPrefix(r.URL.Path, "/")); err != nil {
|
||||
r.URL.Path = "/"
|
||||
}
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AdminServer) securityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
client := clientIP(r)
|
||||
if !a.allowLogin(client) {
|
||||
writeAdminError(w, http.StatusTooManyRequests, "rate_limited", "too many login attempts; try again later")
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
cfg := a.manager.Config()
|
||||
usernameMatch := len(input.Username) == len(cfg.WebUI.Username) && subtle.ConstantTimeCompare([]byte(input.Username), []byte(cfg.WebUI.Username)) == 1
|
||||
passwordMatch := verifyPassword(cfg.WebUI.PasswordHash, input.Password)
|
||||
if !usernameMatch || !passwordMatch {
|
||||
a.recordLoginFailure(client)
|
||||
a.logger.Warn("admin login failed", "component", "auth", "event", "login_failed", "client_ip", client)
|
||||
writeAdminError(w, http.StatusUnauthorized, "invalid_credentials", "invalid username or password")
|
||||
return
|
||||
}
|
||||
token, err := randomToken(32)
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session")
|
||||
return
|
||||
}
|
||||
csrf, err := randomToken(24)
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusInternalServerError, "internal_error", "could not create session")
|
||||
return
|
||||
}
|
||||
expires := time.Now().Add(time.Duration(cfg.WebUI.SessionTTLMinutes) * time.Minute)
|
||||
a.mu.Lock()
|
||||
delete(a.attempts, client)
|
||||
a.cleanupSessionsLocked(time.Now())
|
||||
if len(a.sessions) >= 2048 {
|
||||
a.removeEarliestSessionLocked()
|
||||
}
|
||||
a.sessions[tokenDigest(token)] = adminSession{Username: cfg.WebUI.Username, AuthVersion: secretFingerprint(cfg.WebUI.PasswordHash), CSRF: csrf, Expires: expires}
|
||||
a.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, Expires: expires, MaxAge: int(time.Until(expires).Seconds()), Secure: false})
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
a.logger.Info("admin login succeeded", "component", "auth", "event", "login_succeeded", "client_ip", client)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"username": cfg.WebUI.Username, "csrf_token": csrf, "expires_at": expires.UTC()})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleSession(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := sessionFromContext(r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"authenticated": true, "username": session.Username, "csrf_token": session.CSRF, "expires_at": session.Expires.UTC()})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, _ := r.Cookie(adminCookieName)
|
||||
if cookie != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.sessions, tokenDigest(cookie.Value))
|
||||
a.mu.Unlock()
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type sessionContextKey struct{}
|
||||
|
||||
func (a *AdminServer) authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie(adminCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required")
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
a.mu.Lock()
|
||||
session, ok := a.sessions[tokenDigest(cookie.Value)]
|
||||
if ok && now.After(session.Expires) {
|
||||
delete(a.sessions, tokenDigest(cookie.Value))
|
||||
ok = false
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if !ok {
|
||||
writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session expired or invalid")
|
||||
return
|
||||
}
|
||||
cfg := a.manager.Config()
|
||||
if session.Username != cfg.WebUI.Username || session.AuthVersion != secretFingerprint(cfg.WebUI.PasswordHash) {
|
||||
writeAdminError(w, http.StatusUnauthorized, "authentication_required", "session is no longer valid")
|
||||
return
|
||||
}
|
||||
r = r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, session))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func sessionFromContext(r *http.Request) (adminSession, bool) {
|
||||
session, ok := r.Context().Value(sessionContextKey{}).(adminSession)
|
||||
return session, ok
|
||||
}
|
||||
|
||||
func (a *AdminServer) csrf(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, ok := sessionFromContext(r)
|
||||
if !ok || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(session.CSRF)) != 1 {
|
||||
writeAdminError(w, http.StatusForbidden, "csrf_failed", "invalid CSRF token")
|
||||
return
|
||||
}
|
||||
if origin := r.Header.Get("Origin"); origin != "" {
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || !strings.EqualFold(parsed.Host, r.Host) {
|
||||
writeAdminError(w, http.StatusForbidden, "origin_failed", "request origin does not match this server")
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type SecretView struct {
|
||||
ID string `json:"id"`
|
||||
Display string `json:"display"`
|
||||
}
|
||||
|
||||
type ConfigView struct {
|
||||
Listen string `json:"listen"`
|
||||
ServerKeys []SecretView `json:"server_keys"`
|
||||
ZenKeys []SecretView `json:"zen_keys"`
|
||||
GoKeys []SecretView `json:"go_keys"`
|
||||
Proxies []SecretView `json:"proxies"`
|
||||
ProxyFile string `json:"proxyfile"`
|
||||
Upstream UpstreamConfig `json:"upstream"`
|
||||
Retry RetryConfig `json:"retry"`
|
||||
Models ModelsConfig `json:"models"`
|
||||
Performance PerformanceConfig `json:"performance"`
|
||||
Logging LoggingConfig `json:"logging"`
|
||||
Prefer Tier `json:"prefer"`
|
||||
WebUI WebUIView `json:"webui"`
|
||||
Effective EffectiveView `json:"effective"`
|
||||
Restart []string `json:"restart_required_fields,omitempty"`
|
||||
}
|
||||
|
||||
type EffectiveView struct {
|
||||
Listen string `json:"listen"`
|
||||
WebUIListen string `json:"webui_listen"`
|
||||
WebUIEnabled bool `json:"webui_enabled"`
|
||||
}
|
||||
|
||||
type WebUIView struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Listen string `json:"listen"`
|
||||
Username string `json:"username"`
|
||||
SessionTTLMinutes int `json:"session_ttl_minutes"`
|
||||
}
|
||||
|
||||
type SecretInput struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
type ConfigUpdate struct {
|
||||
Listen string `json:"listen"`
|
||||
ServerKeys []SecretInput `json:"server_keys"`
|
||||
ZenKeys []SecretInput `json:"zen_keys"`
|
||||
GoKeys []SecretInput `json:"go_keys"`
|
||||
Proxies []SecretInput `json:"proxies"`
|
||||
ProxyFile string `json:"proxyfile"`
|
||||
Upstream UpstreamConfig `json:"upstream"`
|
||||
Retry RetryConfig `json:"retry"`
|
||||
Models ModelsConfig `json:"models"`
|
||||
Performance PerformanceConfig `json:"performance"`
|
||||
Logging LoggingConfig `json:"logging"`
|
||||
Prefer Tier `json:"prefer"`
|
||||
WebUI WebUIView `json:"webui"`
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleGetConfig(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, a.configView())
|
||||
}
|
||||
|
||||
func (a *AdminServer) handlePutConfig(w http.ResponseWriter, r *http.Request) {
|
||||
var update ConfigUpdate
|
||||
if err := decodeAdminJSON(w, r, &update); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
current := a.manager.Config()
|
||||
serverKeys, err := resolveSecrets(update.ServerKeys, current.ServerKeys)
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_server_keys", err.Error())
|
||||
return
|
||||
}
|
||||
zenKeys, err := resolveSecrets(update.ZenKeys, current.ZenKeys)
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_zen_keys", err.Error())
|
||||
return
|
||||
}
|
||||
goKeys, err := resolveSecrets(update.GoKeys, current.GoKeys)
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_go_keys", err.Error())
|
||||
return
|
||||
}
|
||||
proxies, err := resolveSecrets(update.Proxies, current.Proxies)
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_proxies", err.Error())
|
||||
return
|
||||
}
|
||||
candidate := Config{
|
||||
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Proxies: proxies, ProxyFile: update.ProxyFile,
|
||||
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
|
||||
WebUI: WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
|
||||
}
|
||||
result, err := a.manager.Apply(candidate, true)
|
||||
if err != nil {
|
||||
a.logger.Warn("configuration update rejected", "component", "config", "event", "config_rejected", "error", err)
|
||||
writeAdminError(w, http.StatusBadRequest, "configuration_rejected", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"result": result, "config": a.configView()})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleReload(w http.ResponseWriter, _ *http.Request) {
|
||||
result, err := a.manager.Reload()
|
||||
if err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "reload_failed", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleReveal(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
cfg := a.manager.Config()
|
||||
if !verifyPassword(cfg.WebUI.PasswordHash, input.Password) {
|
||||
writeAdminError(w, http.StatusForbidden, "verification_failed", "password verification failed")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
a.logger.Info("sensitive configuration revealed", "component", "auth", "event", "secrets_revealed", "client_ip", clientIP(r))
|
||||
writeJSON(w, http.StatusOK, map[string]any{"server_keys": cfg.ServerKeys, "zen_keys": cfg.ZenKeys, "go_keys": cfg.GoKeys, "proxies": cfg.Proxies})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleAccount(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
CurrentPassword string `json:"current_password"`
|
||||
Username string `json:"username"`
|
||||
NewPassword string `json:"new_password"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
cfg := a.manager.Config()
|
||||
if !verifyPassword(cfg.WebUI.PasswordHash, input.CurrentPassword) {
|
||||
writeAdminError(w, http.StatusForbidden, "verification_failed", "current password is incorrect")
|
||||
return
|
||||
}
|
||||
if username := strings.TrimSpace(input.Username); username != "" {
|
||||
cfg.WebUI.Username = username
|
||||
}
|
||||
if input.NewPassword != "" {
|
||||
cfg.WebUI.Password = input.NewPassword
|
||||
}
|
||||
if _, err := a.manager.Apply(cfg, true); err != nil {
|
||||
writeAdminError(w, http.StatusBadRequest, "account_update_failed", err.Error())
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.sessions = make(map[string]adminSession)
|
||||
a.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
|
||||
a.logger.Info("admin account updated", "component", "auth", "event", "account_updated", "client_ip", clientIP(r))
|
||||
writeJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleMonitor(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"version": version, "metrics": a.monitor.Snapshot(), "resources": a.manager.Resources()})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
events, gap := a.logs.Recent(after, limit)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"events": events, "gap": gap})
|
||||
}
|
||||
|
||||
func (a *AdminServer) handleLogStream(w http.ResponseWriter, r *http.Request) {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
writeAdminError(w, http.StatusInternalServerError, "stream_unsupported", "streaming is unavailable")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
after, _ := strconv.ParseUint(r.Header.Get("Last-Event-ID"), 10, 64)
|
||||
if queryAfter, err := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64); err == nil && queryAfter > after {
|
||||
after = queryAfter
|
||||
}
|
||||
recent, gap := a.logs.Recent(after, 2000)
|
||||
if gap {
|
||||
_ = encodeSSE(w, "gap", 0, map[string]any{"message": "older log events have expired"})
|
||||
}
|
||||
for _, event := range recent {
|
||||
if err := encodeSSE(w, "log", event.Sequence, event); err != nil {
|
||||
return
|
||||
}
|
||||
after = event.Sequence
|
||||
}
|
||||
flusher.Flush()
|
||||
stream, unsubscribe := a.logs.Subscribe()
|
||||
defer unsubscribe()
|
||||
cookie, _ := r.Cookie(adminCookieName)
|
||||
keepAlive := time.NewTicker(20 * time.Second)
|
||||
defer keepAlive.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case event := <-stream:
|
||||
if after > 0 && event.Sequence > after+1 {
|
||||
_ = encodeSSE(w, "gap", 0, map[string]any{"message": "slow client missed log events", "after": after, "next": event.Sequence})
|
||||
}
|
||||
if err := encodeSSE(w, "log", event.Sequence, event); err != nil {
|
||||
return
|
||||
}
|
||||
after = event.Sequence
|
||||
flusher.Flush()
|
||||
case <-keepAlive.C:
|
||||
if cookie == nil || !a.sessionTokenValid(cookie.Value) {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, ": keepalive\n\n")
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *AdminServer) sessionTokenValid(token string) bool {
|
||||
a.mu.Lock()
|
||||
session, ok := a.sessions[tokenDigest(token)]
|
||||
if ok && time.Now().After(session.Expires) {
|
||||
delete(a.sessions, tokenDigest(token))
|
||||
ok = false
|
||||
}
|
||||
a.mu.Unlock()
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
cfg := a.manager.Config()
|
||||
return session.Username == cfg.WebUI.Username && session.AuthVersion == secretFingerprint(cfg.WebUI.PasswordHash)
|
||||
}
|
||||
|
||||
func (a *AdminServer) configView() ConfigView {
|
||||
cfg := a.manager.Config()
|
||||
effective, restart := a.manager.RestartStatus()
|
||||
return ConfigView{
|
||||
Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false),
|
||||
Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models,
|
||||
Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer,
|
||||
WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes},
|
||||
Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled},
|
||||
Restart: restart,
|
||||
}
|
||||
}
|
||||
|
||||
func maskSecrets(values []string, proxy bool) []SecretView {
|
||||
result := make([]SecretView, 0, len(values))
|
||||
for _, value := range values {
|
||||
display := maskValue(value)
|
||||
if proxy {
|
||||
display = redactURL(value)
|
||||
}
|
||||
result = append(result, SecretView{ID: secretFingerprint(value), Display: display})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func maskValue(value string) string {
|
||||
runes := []rune(value)
|
||||
if len(runes) <= 4 {
|
||||
return "••••"
|
||||
}
|
||||
return "••••" + string(runes[len(runes)-4:])
|
||||
}
|
||||
|
||||
func resolveSecrets(inputs []SecretInput, existing []string) ([]string, error) {
|
||||
known := make(map[string]string, len(existing))
|
||||
for _, value := range existing {
|
||||
known[secretFingerprint(value)] = value
|
||||
}
|
||||
result := make([]string, 0, len(inputs))
|
||||
for _, input := range inputs {
|
||||
switch {
|
||||
case strings.TrimSpace(input.Value) != "":
|
||||
result = append(result, strings.TrimSpace(input.Value))
|
||||
case input.ID != "":
|
||||
value, ok := known[input.ID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown or stale secret id %q", input.ID)
|
||||
}
|
||||
result = append(result, value)
|
||||
default:
|
||||
return nil, errors.New("each item must contain id or value")
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *AdminServer) allowLogin(client string) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
now := time.Now()
|
||||
if len(a.attempts) > 1024 {
|
||||
for address, candidate := range a.attempts {
|
||||
if now.Sub(candidate.Started) > 5*time.Minute {
|
||||
delete(a.attempts, address)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, exists := a.attempts[client]; !exists && len(a.attempts) >= 4096 {
|
||||
return false
|
||||
}
|
||||
window := a.attempts[client]
|
||||
if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute {
|
||||
return true
|
||||
}
|
||||
return window.Count < 5
|
||||
}
|
||||
|
||||
func (a *AdminServer) recordLoginFailure(client string) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
now := time.Now()
|
||||
window := a.attempts[client]
|
||||
if window.Started.IsZero() || now.Sub(window.Started) > 5*time.Minute {
|
||||
window = loginWindow{Started: now}
|
||||
}
|
||||
window.Count++
|
||||
a.attempts[client] = window
|
||||
}
|
||||
|
||||
func (a *AdminServer) cleanupSessionsLocked(now time.Time) {
|
||||
for token, session := range a.sessions {
|
||||
if now.After(session.Expires) {
|
||||
delete(a.sessions, token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *AdminServer) removeEarliestSessionLocked() {
|
||||
var earliestToken string
|
||||
var earliest time.Time
|
||||
for token, session := range a.sessions {
|
||||
if earliestToken == "" || session.Expires.Before(earliest) {
|
||||
earliestToken, earliest = token, session.Expires
|
||||
}
|
||||
}
|
||||
if earliestToken != "" {
|
||||
delete(a.sessions, earliestToken)
|
||||
}
|
||||
}
|
||||
|
||||
func randomToken(length int) (string, error) {
|
||||
data := make([]byte, length)
|
||||
if _, err := rand.Read(data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func tokenDigest(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err == nil {
|
||||
return host
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
if err == nil {
|
||||
return errors.New("multiple JSON values")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeAdminError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
|
||||
}
|
||||
@@ -8,8 +8,10 @@ services:
|
||||
environment:
|
||||
CONFIG_PATH: /app/config.json
|
||||
LISTEN_ADDRESS: 0.0.0.0:8080
|
||||
WEBUI_LISTEN_ADDRESS: 0.0.0.0:8081
|
||||
ports:
|
||||
- "${OPENCODE2API_PORT:-8080}:8080"
|
||||
- "${OPENCODE2API_WEBUI_PORT:-8081}:8081"
|
||||
volumes:
|
||||
- .:/app
|
||||
- opencode2api-state:/var/lib/opencode2api
|
||||
|
||||
+9
-1
@@ -27,6 +27,14 @@
|
||||
"failure_cooldown_seconds": 15
|
||||
},
|
||||
"logging": {
|
||||
"level": "info"
|
||||
"level": "info",
|
||||
"ring_size": 2000
|
||||
},
|
||||
"webui": {
|
||||
"enabled": true,
|
||||
"listen": "0.0.0.0:8081",
|
||||
"username": "admin",
|
||||
"password": "change-this-admin-password",
|
||||
"session_ttl_minutes": 720
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -25,7 +26,10 @@ type Config struct {
|
||||
Models ModelsConfig `json:"models"`
|
||||
Performance PerformanceConfig `json:"performance"`
|
||||
Logging LoggingConfig `json:"logging"`
|
||||
WebUI WebUIConfig `json:"webui"`
|
||||
Prefer Tier `json:"prefer"`
|
||||
|
||||
effectiveProxies []string
|
||||
}
|
||||
|
||||
type UpstreamConfig struct {
|
||||
@@ -44,7 +48,17 @@ type ModelsConfig struct {
|
||||
}
|
||||
|
||||
type LoggingConfig struct {
|
||||
Level string `json:"level"`
|
||||
Level string `json:"level"`
|
||||
RingSize int `json:"ring_size"`
|
||||
}
|
||||
|
||||
type WebUIConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Listen string `json:"listen"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password,omitempty"`
|
||||
PasswordHash string `json:"password_hash,omitempty"`
|
||||
SessionTTLMinutes int `json:"session_ttl_minutes"`
|
||||
}
|
||||
|
||||
type PerformanceConfig struct {
|
||||
@@ -71,7 +85,8 @@ func LoadConfig(path string) (Config, error) {
|
||||
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300},
|
||||
Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}},
|
||||
Performance: PerformanceConfig{MaxIdleConns: 2048, MaxIdleConnsPerHost: 256, MaxConnsPerHost: 0, IdleConnTimeoutSeconds: 120, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15},
|
||||
Logging: LoggingConfig{Level: "info"},
|
||||
Logging: LoggingConfig{Level: "info", RingSize: 2000},
|
||||
WebUI: WebUIConfig{Listen: "0.0.0.0:8081", SessionTTLMinutes: 720},
|
||||
Prefer: TierGo,
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
@@ -82,11 +97,17 @@ func LoadConfig(path string) (Config, error) {
|
||||
if err := ensureJSONEOF(dec); err != nil {
|
||||
return Config{}, fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
return NormalizeConfig(path, cfg)
|
||||
}
|
||||
|
||||
// NormalizeConfig resolves external inputs and validates a Config supplied by
|
||||
// either the JSON file or the authenticated management API.
|
||||
func NormalizeConfig(path string, cfg Config) (Config, error) {
|
||||
trimList(&cfg.ServerKeys)
|
||||
trimList(&cfg.ZenKeys)
|
||||
trimList(&cfg.GoKeys)
|
||||
cfg.ProxyFile = strings.TrimSpace(cfg.ProxyFile)
|
||||
if err := loadProxyFiles(path, &cfg); err != nil {
|
||||
if err := resolveProxyFiles(path, &cfg); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.Prefer != TierZen && cfg.Prefer != TierGo {
|
||||
@@ -101,9 +122,6 @@ func LoadConfig(path string) (Config, error) {
|
||||
if len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 {
|
||||
return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key")
|
||||
}
|
||||
if len(cfg.Proxies) == 0 {
|
||||
cfg.Proxies = []string{"direct"}
|
||||
}
|
||||
if cfg.Retry.MaxAttempts < 1 {
|
||||
return Config{}, errors.New("retry.max_attempts must be at least 1")
|
||||
}
|
||||
@@ -116,7 +134,32 @@ func LoadConfig(path string) (Config, error) {
|
||||
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)")
|
||||
}
|
||||
for _, raw := range cfg.Proxies {
|
||||
if cfg.Logging.Level != "debug" && cfg.Logging.Level != "info" && cfg.Logging.Level != "warn" && cfg.Logging.Level != "error" {
|
||||
return Config{}, errors.New("logging.level must be debug, info, warn, or error")
|
||||
}
|
||||
if cfg.Logging.RingSize < 100 || cfg.Logging.RingSize > 50000 {
|
||||
return Config{}, errors.New("logging.ring_size must be between 100 and 50000")
|
||||
}
|
||||
if cfg.WebUI.Password != "" && len(cfg.WebUI.Password) < 10 {
|
||||
return Config{}, errors.New("webui.password must contain at least 10 characters")
|
||||
}
|
||||
if cfg.WebUI.Enabled {
|
||||
cfg.WebUI.Listen = strings.TrimSpace(cfg.WebUI.Listen)
|
||||
cfg.WebUI.Username = strings.TrimSpace(cfg.WebUI.Username)
|
||||
if cfg.WebUI.Listen == "" {
|
||||
return Config{}, errors.New("webui.listen must not be empty when webui is enabled")
|
||||
}
|
||||
if cfg.WebUI.Username == "" {
|
||||
return Config{}, errors.New("webui.username must not be empty when webui is enabled")
|
||||
}
|
||||
if cfg.WebUI.Password == "" && cfg.WebUI.PasswordHash == "" {
|
||||
return Config{}, errors.New("webui.password is required for first-time setup")
|
||||
}
|
||||
if cfg.WebUI.SessionTTLMinutes < 5 || cfg.WebUI.SessionTTLMinutes > 10080 {
|
||||
return Config{}, errors.New("webui.session_ttl_minutes must be between 5 and 10080")
|
||||
}
|
||||
}
|
||||
for _, raw := range cfg.RuntimeProxies() {
|
||||
if raw == "direct" {
|
||||
continue
|
||||
}
|
||||
@@ -138,6 +181,19 @@ func LoadConfig(path string) (Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// RuntimeProxies returns the resolved proxy list, including proxyfile entries.
|
||||
// Config.Proxies intentionally remains the list stored in config.json so a
|
||||
// save never duplicates values loaded from proxyfile.
|
||||
func (cfg Config) RuntimeProxies() []string {
|
||||
if len(cfg.effectiveProxies) > 0 {
|
||||
return cfg.effectiveProxies
|
||||
}
|
||||
if len(cfg.Proxies) > 0 {
|
||||
return cfg.Proxies
|
||||
}
|
||||
return []string{"direct"}
|
||||
}
|
||||
|
||||
func ensureJSONEOF(dec *json.Decoder) error {
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); err != io.EOF {
|
||||
@@ -217,8 +273,9 @@ func stripJSONComments(data []byte) ([]byte, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func loadProxyFiles(configPath string, cfg *Config) error {
|
||||
func resolveProxyFiles(configPath string, cfg *Config) error {
|
||||
trimList(&cfg.Proxies)
|
||||
effective := append([]string(nil), cfg.Proxies...)
|
||||
if cfg.ProxyFile != "" {
|
||||
resolved := cfg.ProxyFile
|
||||
if !filepath.IsAbs(resolved) {
|
||||
@@ -228,16 +285,106 @@ func loadProxyFiles(configPath string, cfg *Config) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("load proxy file %s: %w", resolved, err)
|
||||
}
|
||||
cfg.Proxies = append(cfg.Proxies, proxies...)
|
||||
effective = append(effective, proxies...)
|
||||
}
|
||||
|
||||
cfg.Proxies = uniqueStrings(cfg.Proxies)
|
||||
if len(cfg.Proxies) == 0 {
|
||||
cfg.Proxies = []string{"direct"}
|
||||
effective = uniqueStrings(effective)
|
||||
if len(effective) == 0 {
|
||||
effective = []string{"direct"}
|
||||
}
|
||||
cfg.effectiveProxies = effective
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveConfigAtomic writes normalized JSON and keeps the preceding file as
|
||||
// config.json.bak. The temporary file is created beside the target so the
|
||||
// final rename stays on the same filesystem.
|
||||
func SaveConfigAtomic(path string, cfg Config) error {
|
||||
cfg.PasswordForSave()
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode config: %w", err)
|
||||
}
|
||||
data = append(data, '\n')
|
||||
dir := filepath.Dir(path)
|
||||
temp, err := os.CreateTemp(dir, ".config-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary config: %w", err)
|
||||
}
|
||||
tempPath := temp.Name()
|
||||
defer os.Remove(tempPath)
|
||||
if _, err = temp.Write(data); err == nil {
|
||||
err = temp.Sync()
|
||||
}
|
||||
closeErr := temp.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("write temporary config: %w", err)
|
||||
}
|
||||
if info, statErr := os.Stat(path); statErr == nil {
|
||||
_ = os.Chmod(tempPath, info.Mode().Perm())
|
||||
}
|
||||
|
||||
backup := path + ".bak"
|
||||
if runtime.GOOS == "windows" {
|
||||
_ = os.Remove(backup)
|
||||
if _, statErr := os.Stat(path); statErr == nil {
|
||||
if err := os.Rename(path, backup); err != nil {
|
||||
return fmt.Errorf("backup config: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tempPath, path); err != nil {
|
||||
_ = os.Rename(backup, path)
|
||||
return fmt.Errorf("replace config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, statErr := os.Stat(path); statErr == nil {
|
||||
if err := copyFile(path, backup); err != nil {
|
||||
return fmt.Errorf("backup config: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tempPath, path); err != nil {
|
||||
return fmt.Errorf("replace config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PasswordForSave ensures resolved-only data is excluded. The method is kept
|
||||
// separate to make accidental persistence of effective proxy values obvious.
|
||||
func (cfg *Config) PasswordForSave() {
|
||||
cfg.effectiveProxies = nil
|
||||
}
|
||||
|
||||
func copyFile(source, target string) error {
|
||||
in, err := os.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
mode := os.FileMode(0600)
|
||||
if info, statErr := in.Stat(); statErr == nil {
|
||||
mode = info.Mode().Perm()
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_ = out.Chmod(mode)
|
||||
_, copyErr := io.Copy(out, in)
|
||||
syncErr := out.Sync()
|
||||
closeErr := out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if syncErr != nil {
|
||||
return syncErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
||||
func readProxyFile(path string) ([]string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ app_dir=${APP_DIR:-/app}
|
||||
state_dir=${STATE_DIR:-/var/lib/opencode2api}
|
||||
config_path=${CONFIG_PATH:-$app_dir/config.json}
|
||||
listen_address=${LISTEN_ADDRESS:-0.0.0.0:8080}
|
||||
webui_listen_address=${WEBUI_LISTEN_ADDRESS:-0.0.0.0:8081}
|
||||
binary_path=$state_dir/opencode2api
|
||||
fingerprint_path=$state_dir/source.sha256
|
||||
|
||||
@@ -13,8 +14,12 @@ mkdir -p "$state_dir"
|
||||
if [ -f "$config_path" ]; then
|
||||
active_config=$config_path
|
||||
else
|
||||
active_config=$app_dir/config.example.json
|
||||
printf '%s\n' "config.json not found; starting with config.example.json. Copy it to config.json and set real keys before sending API requests."
|
||||
generated_config=$state_dir/config.json
|
||||
if [ ! -f "$generated_config" ]; then
|
||||
cp "$app_dir/config.example.json" "$generated_config"
|
||||
fi
|
||||
active_config=$generated_config
|
||||
printf '%s\n' "config.json not found; using a persistent generated copy. Set real API keys and change the WebUI password before use."
|
||||
fi
|
||||
|
||||
source_fingerprint() {
|
||||
@@ -23,7 +28,7 @@ source_fingerprint() {
|
||||
go env GOOS GOARCH CGO_ENABLED
|
||||
find "$app_dir" \
|
||||
-path "$app_dir/.git" -prune -o \
|
||||
-type f \( -name '*.go' -o -name 'go.mod' -o -name 'go.sum' \) -print \
|
||||
-type f \( -name '*.go' -o -name 'go.mod' -o -name 'go.sum' -o -path "$app_dir/webui/*" \) -print \
|
||||
| LC_ALL=C sort \
|
||||
| while IFS= read -r source_file; do
|
||||
sha256sum "$source_file"
|
||||
@@ -49,4 +54,4 @@ else
|
||||
printf '%s\n' "Source is unchanged; starting the cached opencode2api binary."
|
||||
fi
|
||||
|
||||
exec "$binary_path" -config "$active_config" -listen "$listen_address"
|
||||
exec "$binary_path" -config "$active_config" -listen "$listen_address" -web-listen "$webui_listen_address"
|
||||
+45
-19
@@ -30,6 +30,7 @@ type Gateway struct {
|
||||
zenNodes *nodePool
|
||||
goNodes *nodePool
|
||||
catalog *modelCatalog
|
||||
monitor *Monitor
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
@@ -64,8 +65,8 @@ type healthProxies struct {
|
||||
Unhealthy int `json:"unhealthy"`
|
||||
}
|
||||
|
||||
func NewGateway(cfg Config, logger *slog.Logger) (*Gateway, error) {
|
||||
transports, err := newTransportPool(cfg.Proxies, cfg.Performance, time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)
|
||||
func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, error) {
|
||||
transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -85,6 +86,7 @@ func NewGateway(cfg Config, logger *slog.Logger) (*Gateway, error) {
|
||||
zenNodes: zenNodes,
|
||||
goNodes: goNodes,
|
||||
catalog: newModelCatalog(cfg.Prefer, cfg.Models.Protocols),
|
||||
monitor: monitor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -212,6 +214,10 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
model := stringAt(payload, "model")
|
||||
meta := metaFromRequest(r)
|
||||
if meta != nil {
|
||||
meta.Model = model
|
||||
}
|
||||
if model == "" {
|
||||
writeAPIError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model")
|
||||
return
|
||||
@@ -225,6 +231,9 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
||||
writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model")
|
||||
return
|
||||
}
|
||||
if meta != nil {
|
||||
meta.Tier = string(route.Tier)
|
||||
}
|
||||
upstreamURL := g.cfg.Upstream.Zen
|
||||
if route.Tier == TierGo {
|
||||
upstreamURL = g.cfg.Upstream.Go
|
||||
@@ -240,12 +249,15 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
ids := deriveRequestIDs(r, payload)
|
||||
if meta != nil {
|
||||
meta.Request = ids.Request
|
||||
}
|
||||
stream := boolAt(payload, "stream")
|
||||
requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
|
||||
defer cancel()
|
||||
resp, err := g.doUpstream(requestCtx, route, encoded, ids)
|
||||
if err != nil {
|
||||
g.logger.Warn("upstream request failed", "request_id", ids.Request, "tier", route.Tier, "error", err)
|
||||
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", route.Tier, "error", err)
|
||||
writeAPIError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request)
|
||||
return
|
||||
}
|
||||
@@ -256,6 +268,13 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
if stream {
|
||||
if meta != nil {
|
||||
meta.Stream = true
|
||||
}
|
||||
if g.monitor != nil {
|
||||
g.monitor.activeStreams.Add(1)
|
||||
defer g.monitor.activeStreams.Add(-1)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
@@ -266,7 +285,7 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
||||
err = transcodeStream(w, resp.Body, route.Protocol, external, model)
|
||||
}
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
g.logger.Debug("stream ended with error", "request_id", ids.Request, "error", err)
|
||||
g.logger.Debug("downstream stream ended with an error", "component", "stream", "event", "stream_failed", "request_id", ids.Request, "model", model, "tier", route.Tier, "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -278,7 +297,7 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
||||
if external != route.Protocol {
|
||||
responseBody, err = convertResponse(route.Protocol, external, responseBody)
|
||||
if err != nil {
|
||||
g.logger.Warn("response conversion failed", "request_id", ids.Request, "error", err)
|
||||
g.logger.Warn("response protocol conversion failed", "component", "conversion", "event", "response_conversion_failed", "request_id", ids.Request, "model", model, "source_protocol", route.Protocol, "target_protocol", external, "error", err)
|
||||
writeAPIError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request)
|
||||
return
|
||||
}
|
||||
@@ -303,6 +322,11 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
return nil, fmt.Errorf("no %s nodes configured", route.Tier)
|
||||
}
|
||||
for attempt := 1; attempt <= g.cfg.Retry.MaxAttempts; attempt++ {
|
||||
// Attempts are exposed only as aggregate request metadata and never
|
||||
// include the selected credential.
|
||||
if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil {
|
||||
meta.Attempts = attempt
|
||||
}
|
||||
node := cursor.Next()
|
||||
if node == nil {
|
||||
break
|
||||
@@ -334,7 +358,9 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
} else {
|
||||
req.Header.Set("Authorization", "Bearer "+node.key)
|
||||
}
|
||||
attemptStarted := time.Now()
|
||||
resp, err := proxy.client.Do(req)
|
||||
attemptDuration := time.Since(attemptStarted)
|
||||
status := 0
|
||||
if resp != nil {
|
||||
status = resp.StatusCode
|
||||
@@ -342,7 +368,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
proxyFailed := g.syncProxyResult(ctx, proxy, status, err)
|
||||
if err == nil && resp.StatusCode/100 == 2 {
|
||||
nodes.MarkSuccess(node)
|
||||
g.logger.Debug("upstream accepted request", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "proxy", redactURL(proxy.name))
|
||||
g.logger.Debug("upstream accepted request", "component", "upstream", "event", "attempt_succeeded", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "key_id", secretFingerprint(node.key), "proxy", redactURL(proxy.name), "status", resp.StatusCode, "duration_ms", attemptDuration.Milliseconds())
|
||||
return resp, nil
|
||||
}
|
||||
// Request-shape errors are deterministic and must be returned to the
|
||||
@@ -350,7 +376,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
// throttling, server, and transport failures remain retryable.
|
||||
if err == nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests {
|
||||
nodes.MarkSuccess(node)
|
||||
g.logger.Debug("upstream rejected request without retry", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(proxy.name))
|
||||
g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "key_id", secretFingerprint(node.key), "status", resp.StatusCode, "proxy", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds())
|
||||
return resp, nil
|
||||
}
|
||||
if proxyFailed {
|
||||
@@ -363,9 +389,9 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
lastResponse = resp
|
||||
lastErr = err
|
||||
if err != nil {
|
||||
g.logger.Debug("upstream transport error", "request_id", ids.Request, "attempt", attempt, "proxy", redactURL(proxy.name), "error", err)
|
||||
g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "key_id", secretFingerprint(node.key), "proxy", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds(), "error", err)
|
||||
} else {
|
||||
g.logger.Debug("upstream rejected request", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(proxy.name))
|
||||
g.logger.Debug("upstream returned a retryable response", "component", "upstream", "event", "attempt_retryable_response", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "key_id", secretFingerprint(node.key), "status", resp.StatusCode, "proxy", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds())
|
||||
}
|
||||
}
|
||||
if lastResponse != nil {
|
||||
@@ -428,7 +454,7 @@ func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool)
|
||||
zenMoved = g.zenNodes.RebindProxy(proxy.index)
|
||||
goMoved = g.goNodes.RebindProxy(proxy.index)
|
||||
if wasHealthy || zenMoved+goMoved > 0 {
|
||||
g.logger.Warn("proxy unavailable", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
|
||||
g.logger.Warn("proxy became unavailable", "component", "proxy", "event", "proxy_unavailable", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
|
||||
}
|
||||
return zenMoved, goMoved
|
||||
}
|
||||
@@ -440,7 +466,7 @@ func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) {
|
||||
zenMoved = g.zenNodes.RestoreProxy(proxy.index)
|
||||
goMoved = g.goNodes.RestoreProxy(proxy.index)
|
||||
if zenMoved+goMoved > 0 {
|
||||
g.logger.Info("proxy restored", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
|
||||
g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
|
||||
}
|
||||
return zenMoved, goMoved
|
||||
}
|
||||
@@ -471,21 +497,21 @@ func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string
|
||||
if !result.wasHealthy {
|
||||
g.restoreProxy(result.proxy)
|
||||
}
|
||||
g.logger.Debug("proxy health check passed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name))
|
||||
g.logger.Debug("proxy health check passed", "component", "proxy", "event", "health_check_passed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name))
|
||||
return
|
||||
}
|
||||
if !result.failed {
|
||||
g.logger.Debug("proxy health check inconclusive", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err)
|
||||
g.logger.Debug("proxy health check was inconclusive", "component", "proxy", "event", "health_check_inconclusive", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err)
|
||||
return
|
||||
}
|
||||
if g.transports.hasHealthy() {
|
||||
zenMoved, goMoved := g.rebindUnavailableProxy(result.proxy, result.wasHealthy)
|
||||
if result.wasHealthy || zenMoved+goMoved > 0 {
|
||||
g.logger.Warn("proxy health check failed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err)
|
||||
g.logger.Warn("proxy health check failed", "component", "proxy", "event", "health_check_failed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err)
|
||||
return
|
||||
}
|
||||
}
|
||||
g.logger.Debug("proxy health check still failing", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err)
|
||||
g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err)
|
||||
}
|
||||
|
||||
func protocolPath(protocol Protocol) string {
|
||||
@@ -509,7 +535,7 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) {
|
||||
wg.Wait()
|
||||
if zen != nil || goModels != nil {
|
||||
g.catalog.Replace(zen, goModels)
|
||||
g.logger.Info("model catalog refreshed", "models", len(g.catalog.List()))
|
||||
g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List()))
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
@@ -548,9 +574,9 @@ func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool)
|
||||
return models
|
||||
}
|
||||
nodes.MarkFailure(node, nil, err)
|
||||
g.logger.Debug("model refresh attempt failed", "upstream", base, "attempt", attempt+1, "error", err)
|
||||
g.logger.Debug("model catalog refresh attempt failed", "component", "models", "event", "refresh_attempt_failed", "upstream", redactURL(base), "attempt", attempt+1, "error", err)
|
||||
}
|
||||
g.logger.Warn("model refresh failed", "upstream", base)
|
||||
g.logger.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", redactURL(base))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -593,7 +619,7 @@ func recoveryMiddleware(logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if value := recover(); value != nil {
|
||||
logger.Error("request panic", "error", value)
|
||||
logger.Error("request handler panicked", "component", "http", "event", "request_panic", "error", value)
|
||||
writeAPIError(w, ProtocolChat, http.StatusInternalServerError, "internal server error", "server_error", "")
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
module opencode2api
|
||||
|
||||
go 1.24
|
||||
|
||||
require golang.org/x/crypto v0.41.0
|
||||
|
||||
require golang.org/x/sys v0.35.0 // indirect
|
||||
@@ -0,0 +1,4 @@
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
@@ -15,7 +15,8 @@ var version = "dev"
|
||||
|
||||
func main() {
|
||||
configPath := flag.String("config", "config.json", "path to config.json")
|
||||
listen := flag.String("listen", "", "override the configured listen address")
|
||||
listen := flag.String("listen", "", "override the configured API listen address")
|
||||
webListen := flag.String("web-listen", "", "override the configured WebUI listen address")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := LoadConfig(*configPath)
|
||||
@@ -26,40 +27,55 @@ func main() {
|
||||
if *listen != "" {
|
||||
cfg.Listen = *listen
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if cfg.Logging.Level == "debug" {
|
||||
level = slog.LevelDebug
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
|
||||
gateway, err := NewGateway(cfg, logger)
|
||||
if err != nil {
|
||||
logger.Error("failed to initialize gateway", "error", err)
|
||||
os.Exit(1)
|
||||
if *webListen != "" {
|
||||
cfg.WebUI.Listen = *webListen
|
||||
}
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
gateway.StartProxyHealthChecks(ctx)
|
||||
gateway.StartModelRefresh(ctx)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: cfg.Listen,
|
||||
Handler: gateway.Handler(),
|
||||
ReadHeaderTimeout: 15 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
level := new(slog.LevelVar)
|
||||
setLogLevel(level, cfg.Logging.Level)
|
||||
hub := NewLogHub(cfg.Logging.RingSize)
|
||||
redactor := NewSecretRedactor()
|
||||
redactor.Replace(cfg)
|
||||
logger := NewStructuredLogger(level, hub, redactor)
|
||||
monitor := NewMonitor()
|
||||
manager, err := NewRuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level)
|
||||
if err != nil {
|
||||
logger.Error("failed to initialize runtime", "component", "runtime", "event", "runtime_initialization_failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
go func() {
|
||||
logger.Info("opencode2api listening", "address", cfg.Listen, "version", version)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("server stopped", "error", err)
|
||||
cancel()
|
||||
defer manager.Shutdown()
|
||||
|
||||
apiServer := &http.Server{
|
||||
Addr: cfg.Listen, Handler: manager.Handler(), ReadHeaderTimeout: 15 * time.Second, IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
servers := []*http.Server{apiServer}
|
||||
go serveHTTP(cancel, logger, apiServer, "api")
|
||||
|
||||
if cfg.WebUI.Enabled {
|
||||
admin := NewAdminServer(manager, monitor, hub, logger)
|
||||
webServer := &http.Server{
|
||||
Addr: cfg.WebUI.Listen, Handler: admin.Handler(), ReadHeaderTimeout: 15 * time.Second, IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
}()
|
||||
servers = append(servers, webServer)
|
||||
go serveHTTP(cancel, logger, webServer, "webui")
|
||||
}
|
||||
|
||||
<-ctx.Done()
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer shutdownCancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("graceful shutdown failed", "error", err)
|
||||
for _, server := range servers {
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("graceful shutdown failed", "component", "server", "event", "shutdown_failed", "address", server.Addr, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func serveHTTP(cancel context.CancelFunc, logger *slog.Logger, server *http.Server, component string) {
|
||||
logger.Info("server listening", "component", component, "event", "server_started", "address", server.Addr, "version", version)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("server stopped unexpectedly", "component", component, "event", "server_failed", "address", server.Addr, "error", err)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
@@ -48,11 +48,11 @@ type modelCatalog struct {
|
||||
}
|
||||
|
||||
type modelCatalogSnapshot struct {
|
||||
Zen int
|
||||
Go int
|
||||
Total int
|
||||
Exposed int
|
||||
UpdatedAt time.Time
|
||||
Zen int `json:"zen"`
|
||||
Go int `json:"go"`
|
||||
Total int `json:"total"`
|
||||
Exposed int `json:"exposed"`
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog {
|
||||
@@ -75,6 +75,26 @@ func (c *modelCatalog) Replace(zen, goModels []string) {
|
||||
c.updatedAt = time.Now()
|
||||
}
|
||||
|
||||
func (c *modelCatalog) CopyState(source *modelCatalog) {
|
||||
if source == nil {
|
||||
return
|
||||
}
|
||||
source.mu.RLock()
|
||||
zen := make(map[string]bool, len(source.zen))
|
||||
goModels := make(map[string]bool, len(source.goModels))
|
||||
for model, available := range source.zen {
|
||||
zen[model] = available
|
||||
}
|
||||
for model, available := range source.goModels {
|
||||
goModels[model] = available
|
||||
}
|
||||
updatedAt := source.updatedAt
|
||||
source.mu.RUnlock()
|
||||
c.mu.Lock()
|
||||
c.zen, c.goModels, c.updatedAt = zen, goModels, updatedAt
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys bool) (modelRoute, error) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
@@ -0,0 +1,559 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LogEvent struct {
|
||||
Sequence uint64 `json:"sequence"`
|
||||
Time time.Time `json:"time"`
|
||||
Level string `json:"level"`
|
||||
Message string `json:"message"`
|
||||
Component string `json:"component,omitempty"`
|
||||
Fields map[string]any `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
type logSubscriber struct {
|
||||
ch chan LogEvent
|
||||
}
|
||||
|
||||
type LogHub struct {
|
||||
mu sync.RWMutex
|
||||
buffer []LogEvent
|
||||
start int
|
||||
count int
|
||||
next uint64
|
||||
subscribers map[uint64]*logSubscriber
|
||||
nextSub uint64
|
||||
}
|
||||
|
||||
func NewLogHub(capacity int) *LogHub {
|
||||
if capacity < 100 {
|
||||
capacity = 100
|
||||
}
|
||||
return &LogHub{buffer: make([]LogEvent, capacity), subscribers: make(map[uint64]*logSubscriber)}
|
||||
}
|
||||
|
||||
func (h *LogHub) Resize(capacity int) {
|
||||
if capacity < 100 {
|
||||
capacity = 100
|
||||
}
|
||||
h.mu.Lock()
|
||||
if capacity == len(h.buffer) {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
keep := min(h.count, capacity)
|
||||
next := make([]LogEvent, capacity)
|
||||
for i := 0; i < keep; i++ {
|
||||
source := (h.start + h.count - keep + i) % len(h.buffer)
|
||||
next[i] = h.buffer[source]
|
||||
}
|
||||
h.buffer, h.start, h.count = next, 0, keep
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *LogHub) Publish(event LogEvent) {
|
||||
h.mu.Lock()
|
||||
h.next++
|
||||
event.Sequence = h.next
|
||||
if h.count < len(h.buffer) {
|
||||
index := (h.start + h.count) % len(h.buffer)
|
||||
h.buffer[index] = event
|
||||
h.count++
|
||||
} else {
|
||||
h.buffer[h.start] = event
|
||||
h.start = (h.start + 1) % len(h.buffer)
|
||||
}
|
||||
for _, sub := range h.subscribers {
|
||||
select {
|
||||
case sub.ch <- event:
|
||||
default:
|
||||
// A slow browser must never block request processing. Its reconnect
|
||||
// cursor will make the gap visible on the next subscription.
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *LogHub) Recent(after uint64, limit int) ([]LogEvent, bool) {
|
||||
if limit < 1 || limit > len(h.buffer) {
|
||||
limit = len(h.buffer)
|
||||
}
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
oldest := uint64(0)
|
||||
if h.count > 0 {
|
||||
oldest = h.buffer[h.start].Sequence
|
||||
}
|
||||
gap := after > 0 && oldest > 0 && after+1 < oldest
|
||||
out := make([]LogEvent, 0, min(limit, h.count))
|
||||
for i := 0; i < h.count; i++ {
|
||||
event := h.buffer[(h.start+i)%len(h.buffer)]
|
||||
if event.Sequence > after {
|
||||
out = append(out, event)
|
||||
}
|
||||
}
|
||||
if len(out) > limit {
|
||||
out = out[len(out)-limit:]
|
||||
}
|
||||
return out, gap
|
||||
}
|
||||
|
||||
func (h *LogHub) Subscribe() (<-chan LogEvent, func()) {
|
||||
h.mu.Lock()
|
||||
h.nextSub++
|
||||
id := h.nextSub
|
||||
sub := &logSubscriber{ch: make(chan LogEvent, 128)}
|
||||
h.subscribers[id] = sub
|
||||
h.mu.Unlock()
|
||||
return sub.ch, func() {
|
||||
h.mu.Lock()
|
||||
delete(h.subscribers, id)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
type SecretRedactor struct {
|
||||
values atomic.Value
|
||||
}
|
||||
|
||||
func NewSecretRedactor() *SecretRedactor {
|
||||
r := &SecretRedactor{}
|
||||
r.values.Store([]string(nil))
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *SecretRedactor) Replace(cfg Config) {
|
||||
values := make([]string, 0, len(cfg.ServerKeys)+len(cfg.ZenKeys)+len(cfg.GoKeys)+2)
|
||||
values = append(values, cfg.ServerKeys...)
|
||||
values = append(values, cfg.ZenKeys...)
|
||||
values = append(values, cfg.GoKeys...)
|
||||
if cfg.WebUI.Password != "" {
|
||||
values = append(values, cfg.WebUI.Password)
|
||||
}
|
||||
for _, value := range []string{cfg.Upstream.Zen, cfg.Upstream.Go} {
|
||||
if parsed, err := url.Parse(value); err == nil && parsed.User != nil {
|
||||
values = append(values, value, parsed.User.Username())
|
||||
if password, ok := parsed.User.Password(); ok {
|
||||
values = append(values, password)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, value := range cfg.RuntimeProxies() {
|
||||
if value != "direct" {
|
||||
values = append(values, value)
|
||||
if parsed, err := url.Parse(value); err == nil && parsed.User != nil {
|
||||
values = append(values, parsed.User.Username())
|
||||
if password, ok := parsed.User.Password(); ok {
|
||||
values = append(values, password)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(values, func(i, j int) bool { return len(values[i]) > len(values[j]) })
|
||||
r.values.Store(values)
|
||||
}
|
||||
|
||||
func (r *SecretRedactor) String(value string) string {
|
||||
for _, secret := range r.values.Load().([]string) {
|
||||
if len(secret) >= 4 {
|
||||
value = strings.ReplaceAll(value, secret, "***")
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
type hubHandler struct {
|
||||
base slog.Handler
|
||||
hub *LogHub
|
||||
redactor *SecretRedactor
|
||||
attrs []slog.Attr
|
||||
groups []string
|
||||
}
|
||||
|
||||
func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *SecretRedactor) *slog.Logger {
|
||||
return newStructuredLogger(os.Stdout, level, hub, redactor)
|
||||
}
|
||||
|
||||
func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *SecretRedactor) *slog.Logger {
|
||||
base := slog.NewJSONHandler(output, &slog.HandlerOptions{Level: level, ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
|
||||
return sanitizeLogAttr(redactor, attr)
|
||||
}})
|
||||
return slog.New(&hubHandler{base: base, hub: hub, redactor: redactor})
|
||||
}
|
||||
|
||||
func sanitizeLogAttr(redactor *SecretRedactor, attr slog.Attr) slog.Attr {
|
||||
attr.Value = attr.Value.Resolve()
|
||||
lower := strings.ToLower(attr.Key)
|
||||
if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") {
|
||||
return slog.String(attr.Key, "***")
|
||||
}
|
||||
switch attr.Value.Kind() {
|
||||
case slog.KindString:
|
||||
attr.Value = slog.StringValue(redactor.String(attr.Value.String()))
|
||||
case slog.KindAny:
|
||||
if err, ok := attr.Value.Any().(error); ok {
|
||||
attr.Value = slog.StringValue(redactor.String(err.Error()))
|
||||
}
|
||||
}
|
||||
return attr
|
||||
}
|
||||
|
||||
func (h *hubHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return h.base.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||
if err := h.base.Handle(ctx, record); err != nil {
|
||||
return err
|
||||
}
|
||||
fields := make(map[string]any, record.NumAttrs()+len(h.attrs))
|
||||
for _, attr := range h.attrs {
|
||||
h.addAttr(fields, attr)
|
||||
}
|
||||
record.Attrs(func(attr slog.Attr) bool {
|
||||
h.addAttr(fields, attr)
|
||||
return true
|
||||
})
|
||||
component, _ := fields["component"].(string)
|
||||
delete(fields, "component")
|
||||
h.hub.Publish(LogEvent{
|
||||
Time: record.Time.UTC(),
|
||||
Level: strings.ToLower(record.Level.String()),
|
||||
Message: h.redactor.String(record.Message),
|
||||
Component: component,
|
||||
Fields: fields,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *hubHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
clone := *h
|
||||
clone.base = h.base.WithAttrs(attrs)
|
||||
clone.attrs = append(append([]slog.Attr(nil), h.attrs...), attrs...)
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (h *hubHandler) WithGroup(name string) slog.Handler {
|
||||
clone := *h
|
||||
clone.base = h.base.WithGroup(name)
|
||||
clone.groups = append(append([]string(nil), h.groups...), name)
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) {
|
||||
attr.Value = attr.Value.Resolve()
|
||||
key := attr.Key
|
||||
if len(h.groups) > 0 {
|
||||
key = strings.Join(append(append([]string(nil), h.groups...), key), ".")
|
||||
}
|
||||
lower := strings.ToLower(key)
|
||||
if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") {
|
||||
fields[key] = "***"
|
||||
return
|
||||
}
|
||||
var value any
|
||||
switch attr.Value.Kind() {
|
||||
case slog.KindString:
|
||||
value = h.redactor.String(attr.Value.String())
|
||||
case slog.KindInt64:
|
||||
value = attr.Value.Int64()
|
||||
case slog.KindUint64:
|
||||
value = attr.Value.Uint64()
|
||||
case slog.KindFloat64:
|
||||
value = attr.Value.Float64()
|
||||
case slog.KindBool:
|
||||
value = attr.Value.Bool()
|
||||
case slog.KindDuration:
|
||||
value = attr.Value.Duration().String()
|
||||
case slog.KindTime:
|
||||
value = attr.Value.Time().UTC()
|
||||
default:
|
||||
value = h.redactor.String(fmt.Sprint(attr.Value.Any()))
|
||||
}
|
||||
fields[key] = value
|
||||
}
|
||||
|
||||
type requestMeta struct {
|
||||
Model string
|
||||
Tier string
|
||||
Request string
|
||||
Attempts int
|
||||
Stream bool
|
||||
}
|
||||
|
||||
type requestMetaKey struct{}
|
||||
|
||||
func metaFromRequest(r *http.Request) *requestMeta {
|
||||
meta, _ := r.Context().Value(requestMetaKey{}).(*requestMeta)
|
||||
return meta
|
||||
}
|
||||
|
||||
type metricBucket struct {
|
||||
minute int64
|
||||
total uint64
|
||||
success uint64
|
||||
errors uint64
|
||||
duration uint64
|
||||
histogram [11]uint64
|
||||
endpoints map[string]uint64
|
||||
models map[string]uint64
|
||||
tiers map[string]uint64
|
||||
statuses map[string]uint64
|
||||
}
|
||||
|
||||
func (b *metricBucket) reset(minute int64) {
|
||||
*b = metricBucket{
|
||||
minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64),
|
||||
tiers: make(map[string]uint64), statuses: make(map[string]uint64),
|
||||
}
|
||||
}
|
||||
|
||||
type Monitor struct {
|
||||
started time.Time
|
||||
active atomic.Int64
|
||||
activeStreams atomic.Int64
|
||||
total atomic.Uint64
|
||||
success atomic.Uint64
|
||||
errors atomic.Uint64
|
||||
mu sync.Mutex
|
||||
buckets [60]metricBucket
|
||||
}
|
||||
|
||||
func NewMonitor() *Monitor { return &Monitor{started: time.Now().UTC()} }
|
||||
|
||||
var latencyBounds = [...]uint64{50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000}
|
||||
|
||||
func (m *Monitor) Record(endpoint string, status int, duration time.Duration, meta *requestMeta) {
|
||||
m.total.Add(1)
|
||||
if status >= 200 && status < 400 {
|
||||
m.success.Add(1)
|
||||
} else {
|
||||
m.errors.Add(1)
|
||||
}
|
||||
minute := time.Now().Unix() / 60
|
||||
m.mu.Lock()
|
||||
bucket := &m.buckets[minute%60]
|
||||
if bucket.minute != minute {
|
||||
bucket.reset(minute)
|
||||
}
|
||||
bucket.total++
|
||||
if status >= 200 && status < 400 {
|
||||
bucket.success++
|
||||
} else {
|
||||
bucket.errors++
|
||||
}
|
||||
milliseconds := uint64(max(duration.Milliseconds(), 0))
|
||||
bucket.duration += milliseconds
|
||||
index := len(latencyBounds)
|
||||
for i, bound := range latencyBounds {
|
||||
if milliseconds <= bound {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
bucket.histogram[index]++
|
||||
bucket.endpoints[endpoint]++
|
||||
bucket.statuses[fmt.Sprint(status)]++
|
||||
if meta != nil {
|
||||
if meta.Model != "" {
|
||||
bucket.models[meta.Model]++
|
||||
}
|
||||
if meta.Tier != "" {
|
||||
bucket.tiers[meta.Tier]++
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
type MonitorSnapshot struct {
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
UptimeSeconds int64 `json:"uptime_seconds"`
|
||||
Active int64 `json:"active_requests"`
|
||||
ActiveStreams int64 `json:"active_streams"`
|
||||
Lifetime MetricSummary `json:"lifetime"`
|
||||
Window MetricSummary `json:"last_hour"`
|
||||
Series []MetricSeries `json:"series"`
|
||||
Endpoints map[string]uint64 `json:"endpoints"`
|
||||
Models map[string]uint64 `json:"models"`
|
||||
Tiers map[string]uint64 `json:"tiers"`
|
||||
Statuses map[string]uint64 `json:"statuses"`
|
||||
}
|
||||
|
||||
type MetricSummary struct {
|
||||
Total uint64 `json:"total"`
|
||||
Success uint64 `json:"success"`
|
||||
Errors uint64 `json:"errors"`
|
||||
SuccessRate float64 `json:"success_rate"`
|
||||
AverageMS float64 `json:"average_ms,omitempty"`
|
||||
P50MS uint64 `json:"p50_ms,omitempty"`
|
||||
P95MS uint64 `json:"p95_ms,omitempty"`
|
||||
P99MS uint64 `json:"p99_ms,omitempty"`
|
||||
}
|
||||
|
||||
type MetricSeries struct {
|
||||
Minute time.Time `json:"minute"`
|
||||
Total uint64 `json:"total"`
|
||||
Success uint64 `json:"success"`
|
||||
Errors uint64 `json:"errors"`
|
||||
}
|
||||
|
||||
func (m *Monitor) Snapshot() MonitorSnapshot {
|
||||
nowMinute := time.Now().Unix() / 60
|
||||
window := MetricSummary{}
|
||||
var histogram [11]uint64
|
||||
endpoints, models, tiers, statuses := map[string]uint64{}, map[string]uint64{}, map[string]uint64{}, map[string]uint64{}
|
||||
series := make([]MetricSeries, 0, 60)
|
||||
m.mu.Lock()
|
||||
for offset := int64(59); offset >= 0; offset-- {
|
||||
minute := nowMinute - offset
|
||||
bucket := &m.buckets[minute%60]
|
||||
entry := MetricSeries{Minute: time.Unix(minute*60, 0).UTC()}
|
||||
if bucket.minute == minute {
|
||||
entry.Total, entry.Success, entry.Errors = bucket.total, bucket.success, bucket.errors
|
||||
window.Total += bucket.total
|
||||
window.Success += bucket.success
|
||||
window.Errors += bucket.errors
|
||||
window.AverageMS += float64(bucket.duration)
|
||||
for i := range histogram {
|
||||
histogram[i] += bucket.histogram[i]
|
||||
}
|
||||
mergeCounts(endpoints, bucket.endpoints)
|
||||
mergeCounts(models, bucket.models)
|
||||
mergeCounts(tiers, bucket.tiers)
|
||||
mergeCounts(statuses, bucket.statuses)
|
||||
}
|
||||
series = append(series, entry)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if window.Total > 0 {
|
||||
window.SuccessRate = float64(window.Success) / float64(window.Total)
|
||||
window.AverageMS /= float64(window.Total)
|
||||
window.P50MS = histogramPercentile(histogram, window.Total, 0.50)
|
||||
window.P95MS = histogramPercentile(histogram, window.Total, 0.95)
|
||||
window.P99MS = histogramPercentile(histogram, window.Total, 0.99)
|
||||
}
|
||||
lifetime := MetricSummary{Total: m.total.Load(), Success: m.success.Load(), Errors: m.errors.Load()}
|
||||
if lifetime.Total > 0 {
|
||||
lifetime.SuccessRate = float64(lifetime.Success) / float64(lifetime.Total)
|
||||
}
|
||||
return MonitorSnapshot{
|
||||
StartedAt: m.started, UptimeSeconds: int64(time.Since(m.started).Seconds()), Active: m.active.Load(),
|
||||
ActiveStreams: m.activeStreams.Load(), Lifetime: lifetime, Window: window, Series: series,
|
||||
Endpoints: endpoints, Models: models, Tiers: tiers, Statuses: statuses,
|
||||
}
|
||||
}
|
||||
|
||||
func mergeCounts(target, source map[string]uint64) {
|
||||
for key, value := range source {
|
||||
target[key] += value
|
||||
}
|
||||
}
|
||||
|
||||
func histogramPercentile(histogram [11]uint64, total uint64, percentile float64) uint64 {
|
||||
target := uint64(float64(total)*percentile + 0.999)
|
||||
var count uint64
|
||||
for i, value := range histogram {
|
||||
count += value
|
||||
if count >= target {
|
||||
if i < len(latencyBounds) {
|
||||
return latencyBounds[i]
|
||||
}
|
||||
return latencyBounds[len(latencyBounds)-1] + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int64
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
if w.status != 0 {
|
||||
return
|
||||
}
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(data []byte) (int, error) {
|
||||
if w.status == 0 {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
n, err := w.ResponseWriter.Write(data)
|
||||
w.bytes += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *statusWriter) Flush() {
|
||||
_ = http.NewResponseController(w.ResponseWriter).Flush()
|
||||
}
|
||||
|
||||
func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|
||||
|
||||
func monitorMiddleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
meta := &requestMeta{}
|
||||
r = r.WithContext(context.WithValue(r.Context(), requestMetaKey{}, meta))
|
||||
writer := &statusWriter{ResponseWriter: w}
|
||||
monitor.active.Add(1)
|
||||
defer func() {
|
||||
monitor.active.Add(-1)
|
||||
status := writer.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
duration := time.Since(started)
|
||||
monitor.Record(r.URL.Path, status, duration, meta)
|
||||
logger.Info("request completed", "component", "http", "event", "request_complete", "method", r.Method,
|
||||
"path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "bytes", writer.bytes,
|
||||
"request_id", meta.Request, "model", meta.Model, "tier", meta.Tier, "attempts", meta.Attempts, "stream", meta.Stream)
|
||||
}()
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
|
||||
func setLogLevel(level *slog.LevelVar, value string) {
|
||||
switch value {
|
||||
case "debug":
|
||||
level.Set(slog.LevelDebug)
|
||||
case "warn":
|
||||
level.Set(slog.LevelWarn)
|
||||
case "error":
|
||||
level.Set(slog.LevelError)
|
||||
default:
|
||||
level.Set(slog.LevelInfo)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeSSE(w http.ResponseWriter, event string, id uint64, value any) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if id > 0 {
|
||||
_, _ = fmt.Fprintf(w, "id: %d\n", id)
|
||||
}
|
||||
if event != "" {
|
||||
_, _ = fmt.Fprintf(w, "event: %s\n", event)
|
||||
}
|
||||
_, err = fmt.Fprintf(w, "data: %s\n\n", data)
|
||||
return err
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory = 64 * 1024
|
||||
argonIterations = 3
|
||||
argonParallelism = 2
|
||||
argonSaltLength = 16
|
||||
argonKeyLength = 32
|
||||
)
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
if len(password) < 10 {
|
||||
return "", errors.New("webui password must contain at least 10 characters")
|
||||
}
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", argonMemory, argonIterations, argonParallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil
|
||||
}
|
||||
|
||||
func verifyPassword(encoded, password string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||
return false
|
||||
}
|
||||
parameters := strings.Split(parts[3], ",")
|
||||
if len(parameters) != 3 {
|
||||
return false
|
||||
}
|
||||
memory, err1 := parseArgonParameter(parameters[0], "m")
|
||||
iterations, err2 := parseArgonParameter(parameters[1], "t")
|
||||
parallelism, err3 := parseArgonParameter(parameters[2], "p")
|
||||
if err1 != nil || err2 != nil || err3 != nil || memory < 8*parallelism || memory > 256*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 16 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 8 || len(salt) > 64 {
|
||||
return false
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(expected) < 16 || len(expected) > 64 {
|
||||
return false
|
||||
}
|
||||
actual := argon2.IDKey([]byte(password), salt, uint32(iterations), uint32(memory), uint8(parallelism), uint32(len(expected)))
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
|
||||
func parseArgonParameter(value, name string) (uint64, error) {
|
||||
prefix := name + "="
|
||||
if !strings.HasPrefix(value, prefix) {
|
||||
return 0, errors.New("invalid parameter")
|
||||
}
|
||||
return strconv.ParseUint(strings.TrimPrefix(value, prefix), 10, 32)
|
||||
}
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type gatewayRuntime struct {
|
||||
config Config
|
||||
gateway *Gateway
|
||||
handler http.Handler
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type ApplyResult struct {
|
||||
Applied bool `json:"applied"`
|
||||
RestartRequired bool `json:"restart_required"`
|
||||
RestartFields []string `json:"restart_fields,omitempty"`
|
||||
}
|
||||
|
||||
type RuntimeManager struct {
|
||||
configPath string
|
||||
root context.Context
|
||||
logger *slog.Logger
|
||||
monitor *Monitor
|
||||
hub *LogHub
|
||||
redactor *SecretRedactor
|
||||
level *slog.LevelVar
|
||||
current atomic.Pointer[gatewayRuntime]
|
||||
updateMu sync.Mutex
|
||||
effective effectiveListeners
|
||||
}
|
||||
|
||||
type effectiveListeners struct {
|
||||
API string
|
||||
WebUI string
|
||||
WebUIEnabled bool
|
||||
}
|
||||
|
||||
func NewRuntimeManager(root context.Context, configPath string, cfg Config, logger *slog.Logger, monitor *Monitor, hub *LogHub, redactor *SecretRedactor, level *slog.LevelVar) (*RuntimeManager, error) {
|
||||
manager := &RuntimeManager{
|
||||
configPath: configPath, root: root, logger: logger, monitor: monitor, hub: hub, redactor: redactor, level: level,
|
||||
effective: effectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled},
|
||||
}
|
||||
if cfg.WebUI.Password != "" {
|
||||
hash, err := hashPassword(cfg.WebUI.Password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hash webui password: %w", err)
|
||||
}
|
||||
cfg.WebUI.PasswordHash = hash
|
||||
cfg.WebUI.Password = ""
|
||||
if err := SaveConfigAtomic(configPath, cfg); err != nil {
|
||||
return nil, fmt.Errorf("persist webui password migration: %w", err)
|
||||
}
|
||||
// The automatically-created backup contains the one-time plaintext
|
||||
// bootstrap password and must not be retained.
|
||||
_ = os.Remove(configPath + ".bak")
|
||||
}
|
||||
runtime, err := manager.build(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manager.current.Store(runtime)
|
||||
manager.redactor.Replace(cfg)
|
||||
setLogLevel(manager.level, cfg.Logging.Level)
|
||||
manager.start(runtime)
|
||||
return manager, nil
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) build(cfg Config) (*gatewayRuntime, error) {
|
||||
gateway, err := NewGateway(cfg, m.logger, m.monitor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &gatewayRuntime{config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}}, nil
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) start(runtime *gatewayRuntime) {
|
||||
// Store the context through a lightweight wrapper so cancel stops catalog
|
||||
// and proxy checks while in-flight HTTP requests continue on the old pools.
|
||||
runtimeCtx, cancel := context.WithCancel(m.root)
|
||||
runtime.cancel = cancel
|
||||
runtime.gateway.StartProxyHealthChecks(runtimeCtx)
|
||||
runtime.gateway.StartModelRefresh(runtimeCtx)
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Handler() http.Handler {
|
||||
dynamic := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
runtime := m.current.Load()
|
||||
if runtime == nil {
|
||||
http.Error(w, "service unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
runtime.handler.ServeHTTP(w, r)
|
||||
})
|
||||
return monitorMiddleware(m.monitor, m.logger, dynamic)
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Config() Config {
|
||||
runtime := m.current.Load()
|
||||
if runtime == nil {
|
||||
return Config{}
|
||||
}
|
||||
return cloneConfig(runtime.config)
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) {
|
||||
cfg := m.Config()
|
||||
fields := make([]string, 0, 3)
|
||||
if cfg.Listen != m.effective.API {
|
||||
fields = append(fields, "listen")
|
||||
}
|
||||
if cfg.WebUI.Listen != m.effective.WebUI {
|
||||
fields = append(fields, "webui.listen")
|
||||
}
|
||||
if cfg.WebUI.Enabled != m.effective.WebUIEnabled {
|
||||
fields = append(fields, "webui.enabled")
|
||||
}
|
||||
return m.effective, fields
|
||||
}
|
||||
|
||||
func cloneConfig(cfg Config) Config {
|
||||
cfg.ServerKeys = append([]string(nil), cfg.ServerKeys...)
|
||||
cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...)
|
||||
cfg.GoKeys = append([]string(nil), cfg.GoKeys...)
|
||||
cfg.Proxies = append([]string(nil), cfg.Proxies...)
|
||||
cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...)
|
||||
if cfg.Models.Protocols != nil {
|
||||
protocols := make(map[string]string, len(cfg.Models.Protocols))
|
||||
for key, value := range cfg.Models.Protocols {
|
||||
protocols[key] = value
|
||||
}
|
||||
cfg.Models.Protocols = protocols
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Apply(candidate Config, persist bool) (ApplyResult, error) {
|
||||
m.updateMu.Lock()
|
||||
defer m.updateMu.Unlock()
|
||||
|
||||
current := m.current.Load()
|
||||
hadPlaintextPassword := candidate.WebUI.Password != ""
|
||||
if hadPlaintextPassword {
|
||||
hash, err := hashPassword(candidate.WebUI.Password)
|
||||
if err != nil {
|
||||
return ApplyResult{}, err
|
||||
}
|
||||
candidate.WebUI.PasswordHash = hash
|
||||
candidate.WebUI.Password = ""
|
||||
}
|
||||
normalized, err := NormalizeConfig(m.configPath, candidate)
|
||||
if err != nil {
|
||||
return ApplyResult{}, err
|
||||
}
|
||||
next, err := m.build(normalized)
|
||||
if err != nil {
|
||||
return ApplyResult{}, fmt.Errorf("initialize runtime: %w", err)
|
||||
}
|
||||
if current != nil {
|
||||
next.gateway.catalog.CopyState(current.gateway.catalog)
|
||||
}
|
||||
if persist || hadPlaintextPassword {
|
||||
if err := SaveConfigAtomic(m.configPath, normalized); err != nil {
|
||||
next.cancel()
|
||||
return ApplyResult{}, err
|
||||
}
|
||||
}
|
||||
|
||||
result := ApplyResult{Applied: true}
|
||||
if normalized.Listen != m.effective.API {
|
||||
result.RestartFields = append(result.RestartFields, "listen")
|
||||
}
|
||||
if normalized.WebUI.Listen != m.effective.WebUI {
|
||||
result.RestartFields = append(result.RestartFields, "webui.listen")
|
||||
}
|
||||
if normalized.WebUI.Enabled != m.effective.WebUIEnabled {
|
||||
result.RestartFields = append(result.RestartFields, "webui.enabled")
|
||||
}
|
||||
result.RestartRequired = len(result.RestartFields) > 0
|
||||
m.redactor.Replace(normalized)
|
||||
setLogLevel(m.level, normalized.Logging.Level)
|
||||
if current == nil || normalized.Logging.RingSize != current.config.Logging.RingSize {
|
||||
m.hub.Resize(normalized.Logging.RingSize)
|
||||
}
|
||||
m.start(next)
|
||||
previous := m.current.Swap(next)
|
||||
if previous != nil {
|
||||
previous.cancel()
|
||||
}
|
||||
m.logger.Info("configuration applied", "component", "config", "event", "config_applied", "restart_required", result.RestartRequired, "restart_fields", result.RestartFields)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Reload() (ApplyResult, error) {
|
||||
cfg, err := LoadConfig(m.configPath)
|
||||
if err != nil {
|
||||
return ApplyResult{}, err
|
||||
}
|
||||
hadPlaintextPassword := cfg.WebUI.Password != ""
|
||||
result, err := m.Apply(cfg, false)
|
||||
if err == nil && hadPlaintextPassword {
|
||||
_ = os.Remove(m.configPath + ".bak")
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Shutdown() {
|
||||
if current := m.current.Load(); current != nil {
|
||||
current.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
type ResourceSnapshot struct {
|
||||
Models modelCatalogSnapshot `json:"models"`
|
||||
Keys []KeyStatus `json:"keys"`
|
||||
Proxies []ProxyStatus `json:"proxies"`
|
||||
}
|
||||
|
||||
type KeyStatus struct {
|
||||
ID string `json:"id"`
|
||||
Tier string `json:"tier"`
|
||||
Index int `json:"index"`
|
||||
ProxyIndex int `json:"proxy_index"`
|
||||
Failures uint32 `json:"failures"`
|
||||
CooldownUntil *time.Time `json:"cooldown_until,omitempty"`
|
||||
}
|
||||
|
||||
type ProxyStatus struct {
|
||||
Index int `json:"index"`
|
||||
Address string `json:"address"`
|
||||
Healthy bool `json:"healthy"`
|
||||
Checking bool `json:"checking"`
|
||||
ZenKeys int `json:"zen_keys"`
|
||||
GoKeys int `json:"go_keys"`
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Resources() ResourceSnapshot {
|
||||
runtime := m.current.Load()
|
||||
if runtime == nil {
|
||||
return ResourceSnapshot{}
|
||||
}
|
||||
gateway := runtime.gateway
|
||||
result := ResourceSnapshot{Models: gateway.catalog.Snapshot()}
|
||||
result.Keys = append(result.Keys, keyStatuses("zen", gateway.zenNodes)...)
|
||||
result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...)
|
||||
gateway.zenNodes.bindingsMu.Lock()
|
||||
zenBindings := append([]int(nil), gateway.zenNodes.bindingCount...)
|
||||
gateway.zenNodes.bindingsMu.Unlock()
|
||||
gateway.goNodes.bindingsMu.Lock()
|
||||
goBindings := append([]int(nil), gateway.goNodes.bindingCount...)
|
||||
gateway.goNodes.bindingsMu.Unlock()
|
||||
for _, proxy := range gateway.transports.items {
|
||||
status := ProxyStatus{Index: proxy.index, Address: redactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load()}
|
||||
if proxy.index < len(zenBindings) {
|
||||
status.ZenKeys = zenBindings[proxy.index]
|
||||
}
|
||||
if proxy.index < len(goBindings) {
|
||||
status.GoKeys = goBindings[proxy.index]
|
||||
}
|
||||
result.Proxies = append(result.Proxies, status)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func keyStatuses(tier string, pool *nodePool) []KeyStatus {
|
||||
result := make([]KeyStatus, 0, len(pool.nodes))
|
||||
for _, node := range pool.nodes {
|
||||
status := KeyStatus{ID: secretFingerprint(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Failures: node.failures.Load()}
|
||||
if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() {
|
||||
value := time.Unix(0, until).UTC()
|
||||
status.CooldownUntil = &value
|
||||
}
|
||||
result = append(result, status)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func secretFingerprint(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return hex.EncodeToString(sum[:])[:10]
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>opencode2api Control</title>
|
||||
<style>
|
||||
:root{color-scheme:dark;--bg:#091014;--panel:#111b20;--panel2:#17242a;--line:#263940;--text:#ecf5f2;--muted:#8fa7a2;--accent:#43d6a3;--accent2:#66a8ff;--bad:#ff6b7a;--warn:#f1bd5a;--shadow:0 18px 55px #0006}*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 15% -15%,#164535 0,transparent 35%),var(--bg);color:var(--text);font:14px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}button,input,textarea,select{font:inherit}button{cursor:pointer}.hidden{display:none!important}.login{min-height:100vh;display:grid;place-items:center;padding:24px}.login-card{width:min(420px,100%);background:#101b20ee;border:1px solid var(--line);border-radius:22px;padding:34px;box-shadow:var(--shadow)}.brand{font-size:24px;font-weight:750;letter-spacing:-.5px}.brand span{color:var(--accent)}.sub{color:var(--muted);margin:7px 0 25px}.field{display:grid;gap:7px;margin:13px 0}.field label{color:#b8cac6;font-size:12px;font-weight:650;text-transform:uppercase;letter-spacing:.07em}.input,input,textarea,select{width:100%;background:#0c1519;border:1px solid var(--line);border-radius:9px;color:var(--text);padding:10px 12px;outline:none}.input:focus,input:focus,textarea:focus,select:focus{border-color:var(--accent)}textarea{resize:vertical;min-height:90px}.primary,.ghost,.danger{border:0;border-radius:9px;padding:10px 15px;font-weight:700}.primary{background:var(--accent);color:#062219}.ghost{background:#1a2a30;color:var(--text);border:1px solid var(--line)}.danger{background:#402027;color:#ffb6bd}.wide{width:100%}.error{color:#ff9ca6;min-height:20px}.layout{display:grid;grid-template-columns:240px 1fr;min-height:100vh}.sidebar{position:sticky;top:0;height:100vh;border-right:1px solid var(--line);padding:25px 18px;background:#0b1418cc;backdrop-filter:blur(12px)}.sidebar .brand{padding:0 8px 24px}.nav{display:grid;gap:5px}.nav button{border:0;background:transparent;color:var(--muted);text-align:left;padding:11px 13px;border-radius:9px}.nav button.active,.nav button:hover{background:#17272c;color:var(--text)}.sidebar-foot{position:absolute;left:18px;right:18px;bottom:20px;color:var(--muted);font-size:12px}.main{min-width:0;padding:28px 34px 60px}.topbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px}.topbar h1{font-size:24px;margin:0}.toolbar{display:flex;gap:9px;align-items:center}.badge{display:inline-flex;align-items:center;gap:7px;padding:5px 9px;border-radius:99px;background:#153027;color:#8dffcf;font-size:12px}.badge:before{content:"";width:7px;height:7px;border-radius:50%;background:var(--accent)}.notice{border:1px solid #725b27;background:#2c2515;color:#f4d691;border-radius:10px;padding:11px 14px;margin-bottom:18px}.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px}.card,.section{background:linear-gradient(145deg,#121e23,#0e181c);border:1px solid var(--line);border-radius:13px;box-shadow:0 8px 25px #0002}.card{padding:17px}.card .label{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.08em}.metric{font-size:27px;font-weight:750;margin-top:8px}.metric small{font-size:12px;color:var(--muted);font-weight:500}.section{padding:20px;margin-top:15px}.section h2{font-size:16px;margin:0 0 15px}.split{display:grid;grid-template-columns:1fr 1fr;gap:15px}.table{width:100%;border-collapse:collapse}.table th,.table td{text-align:left;border-bottom:1px solid #203139;padding:9px 7px}.table th{font-size:11px;text-transform:uppercase;color:var(--muted)}.ok{color:var(--accent)}.bad{color:var(--bad)}.warn{color:var(--warn)}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 15px}.form-grid .full{grid-column:1/-1}.chips{display:flex;gap:7px;flex-wrap:wrap;margin-bottom:8px}.chip{display:flex;gap:8px;align-items:center;background:#1a2a30;border:1px solid var(--line);padding:5px 8px;border-radius:7px;color:#bcd0cb;font-family:ui-monospace,monospace}.chip button{border:0;background:transparent;color:#f8959e;padding:0}.actions{display:flex;gap:9px;justify-content:flex-end;margin-top:18px}.logs{height:58vh;overflow:auto;background:#081014;border:1px solid var(--line);border-radius:10px;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px}.log{display:grid;grid-template-columns:90px 55px 110px minmax(180px,1fr);gap:10px;padding:7px 10px;border-bottom:1px solid #162329}.log:hover{background:#101d22}.log .time,.log .component{color:var(--muted)}.log .level{font-weight:800}.log .fields{grid-column:4;color:#86a29b;white-space:pre-wrap;overflow-wrap:anywhere}.filters{display:grid;grid-template-columns:150px 170px 1fr auto;gap:9px;margin-bottom:11px}.modal{position:fixed;inset:0;background:#000b;display:grid;place-items:center;padding:20px;z-index:5}.modal-card{width:min(720px,100%);max-height:80vh;overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:22px;box-shadow:var(--shadow)}pre{white-space:pre-wrap;overflow-wrap:anywhere;color:#c8ded8}.toast{positiLine truncated
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<section id="login" class="login">
|
||||
<form id="login-form" class="login-card">
|
||||
<div class="brand">opencode<span>2api</span></div><div class="sub">Control plane · 管理登录</div>
|
||||
<div class="field"><label>账号</label><input id="login-user" autocomplete="username" required></div>
|
||||
<div class="field"><label>密码</label><input id="login-pass" type="password" autocomplete="current-password" required></div>
|
||||
<div id="login-error" class="error"></div><button class="primary wide">登录控制台</button>
|
||||
</form>
|
||||
</section>
|
||||
<div id="app" class="layout hidden">
|
||||
<aside class="sidebar"><div class="brand">opencode<span>2api</span></div><nav class="nav">
|
||||
<button data-page="overview" class="active">总览</button><button data-page="config">配置</button><button data-page="logs">实时日志</button><button data-page="account">账号</button>
|
||||
</nav><div class="sidebar-foot"><div id="version">version —</div></div></aside>
|
||||
<main class="main">
|
||||
<header class="topbar"><div><h1 id="page-title">运行总览</h1><div class="sub" id="page-sub">最近一小时的服务状态</div></div><div class="toolbar"><span class="badge">Live</span><button id="logout" class="ghost">退出登录</button></div></header>
|
||||
<div id="restart-notice" class="notice hidden"></div>
|
||||
<section id="page-overview" class="page">
|
||||
<div class="grid"><div class="card"><div class="label">请求总数</div><div id="m-total" class="metric">—</div></div><div class="card"><div class="label">成功率</div><div id="m-rate" class="metric">—</div></div><div class="card"><div class="label">P95 延迟</div><div id="m-p95" class="metric">—</div></div><div class="card"><div class="label">活跃 / 流式</div><div id="m-active" class="metric">—</div></div></div>
|
||||
<div class="split"><div class="section"><h2>Proxy 状态</h2><table class="table"><thead><tr><th>路由</th><th>状态</th><th>绑定</th></tr></thead><tbody id="proxy-table"></tbody></table></div><div class="section"><h2>Key 池</h2><table class="table"><thead><tr><th>ID</th><th>Tier</th><th>状态</th></tr></thead><tbody id="key-table"></tbody></table></div></div>
|
||||
<div class="section"><h2>最近一小时聚合</h2><div id="breakdowns" class="split"></div></div>
|
||||
</section>
|
||||
<section id="page-config" class="page hidden">
|
||||
<form id="config-form">
|
||||
<div class="section"><h2>服务与管理端</h2><div class="form-grid"><div class="field"><label>API Listen</label><input id="c-listen"></div><div class="field"><label>优先 Tier</label><select id="c-prefer"><option value="go">Go</option><option value="zen">Zen</option></select></div><div class="field"><label>WebUI Listen</label><input id="c-web-listen"></div><div class="field"><label>Session TTL(分钟)</label><input id="c-session" type="number"></div><div class="field"><label><input id="c-web-enabled" type="checkbox" style="width:auto"> 启用 WebUI(修改需重启)</label></div></div></div>
|
||||
<div class="section"><h2>密钥池</h2><div class="form-grid"><div class="field full"><label>Server Keys</label><div id="server_keys-chips" class="chips"></div><textarea id="server_keys-new" placeholder="每行新增一个 key"></textarea></div><div class="field"><label>Zen Keys</label><div id="zen_keys-chips" class="chips"></div><textarea id="zen_keys-new" placeholder="每行新增一个 key"></textarea></div><div class="field"><label>Go Keys</label><div id="go_keys-chips" class="chips"></div><textarea id="go_keys-new" placeholder="每行新增一个 key"></textarea></div></div><button id="reveal" type="button" class="ghost">二次验证并查看完整值</button></div>
|
||||
<div class="section"><h2>Proxy</h2><div id="proxies-chips" class="chips"></div><div class="form-grid"><div class="field"><label>新增 Proxy(每行一个)</label><textarea id="proxies-new" placeholder="direct\nhttp://user:pass@host:port"></textarea></div><div class="field"><label>Proxy File</label><input id="c-proxyfile" placeholder="proxies.txt"></div></div></div>
|
||||
<div class="section"><h2>上游与重试</h2><div class="form-grid"><div class="field"><label>Zen URL</label><input id="c-up-zen"></div><div class="field"><label>Go URL</label><input id="c-up-go"></div><div class="field"><label>最大尝试次数</label><input id="c-attempts" type="number"></div><div class="field"><label>请求超时(秒)</label><input id="c-timeout" type="number"></div><div class="field"><label>模型刷新(秒)</label><input id="c-refresh" type="number"></div><div class="field"><label>模型协议覆盖(JSON)</label><textarea id="c-protocols" spellcheck="false">{}</textarea></div></div></div>
|
||||
<div class="section"><h2>性能与日志</h2><div class="form-grid"><div class="field"><label>Max Idle Conns</label><input id="c-idle" type="number"></div><div class="field"><label>Max Idle / Host</label><input id="c-idle-host" type="number"></div><div class="field"><label>Max Conns / Host(0 无限制)</label><input id="c-max-host" type="number"></div><div class="field"><label>Idle Timeout(秒)</label><input id="c-idle-timeout" type="number"></div><div class="field"><label>Connect Timeout(秒)</label><input id="c-connect" type="number"></div><div class="field"><label>Failure Cooldown(秒)</label><input id="c-cooldown" type="number"></div><div class="field"><label>日志级别</label><select id="c-level"><option>debug</option><option>info</option><option>warn</option><option>error</option></select></div><div class="field"><label>日志 Ring Size</label><input id="c-ring" type="number"></div></div><div class="actions"><button id="reload-config" type="button" class="ghost">从磁盘重载</button><button class="primary">验证、保存并立即应用</button></div></div>
|
||||
</form>
|
||||
</section>
|
||||
<section id="page-logs" class="page hidden"><div class="filters"><select id="log-level"><option value="">全部级别</option><option>debug</option><option>info</option><option>warn</option><option>error</option></select><input id="log-component" placeholder="模块"><input id="log-search" placeholder="搜索事件、request ID、模型…"><button id="log-pause" class="ghost">暂停</button></div><div id="log-list" class="logs"></div></section>
|
||||
<section id="page-account" class="page hidden"><form id="account-form" class="section" style="max-width:620px"><h2>更新管理账号</h2><div class="field"><label>新账号(留空保持不变)</label><input id="a-user"></div><div class="field"><label>当前密码</label><input id="a-current" type="password" required></div><div class="field"><label>新密码(留空保持不变,至少 10 个字符)</label><input id="a-new" type="password"></div><div class="actions"><button class="primary">更新并重新登录</button></div></form></section>
|
||||
</main>
|
||||
</div>
|
||||
<div id="modal" class="modal hidden"><div class="modal-card"><div class="topbar"><h2>敏感配置</h2><button id="modal-close" class="ghost">关闭</button></div><pre id="modal-content"></pre></div></div><div id="toast" class="toast hidden"></div>
|
||||
<script>
|
||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; let csrf='',config=null,logEvents=[],eventSource=null,paused=false,monitorTimer=null,logRenderPending=false;
|
||||
async function api(path,options={}){options.headers={...(options.headers||{}),'Accept':'application/json'};if(options.body){options.headers['Content-Type']='application/json'}if(csrf&&!['GET','HEAD'].includes(options.method||'GET'))options.headers['X-CSRF-Token']=csrf;const response=await fetch(path,options);if(response.status===401){showLogin();throw new Error('登录已失效')}if(response.status===204)return null;const data=await response.json().catch(()=>({}));if(!response.ok)throw new Error(data.error?.message||`HTTP ${response.status}`);return data}
|
||||
function toast(message,bad=false){const el=$('#toast');el.textContent=message;el.style.background=bad?'#402027':'#183129';el.classList.remove('hidden');setTimeout(()=>el.classList.add('hidden'),3500)}
|
||||
function showLogin(){csrf='';$('#app').classList.add('hidden');$('#login').classList.remove('hidden');if(eventSource)eventSource.close();clearInterval(monitorTimer)}
|
||||
async function boot(){try{const s=await api('/api/auth/session');csrf=s.csrf_token;$('#login').classList.add('hidden');$('#app').classList.remove('hidden');await loadConfig();await refreshMonitor();monitorTimer=setInterval(refreshMonitor,3000);connectLogs()}catch(e){showLogin()}}
|
||||
$('#login-form').addEventListener('submit',async e=>{e.preventDefault();$('#login-error').textContent='';try{const s=await api('/api/auth/login',{method:'POST',body:JSON.stringify({username:$('#login-user').value,password:$('#login-pass').value})});csrf=s.csrf_token;$('#login-pass').value='';$('#login').classList.add('hidden');$('#app').classList.remove('hidden');await loadConfig();await refreshMonitor();monitorTimer=setInterval(refreshMonitor,3000);connectLogs()}catch(err){$('#login-error').textContent=err.message}});
|
||||
$('#logout').onclick=async()=>{try{await api('/api/auth/logout',{method:'POST'})}finally{showLogin()}};
|
||||
const titles={overview:['运行总览','最近一小时的服务状态'],config:['配置中心','验证后原子保存并立即应用'],logs:['实时日志','结构化事件流'],account:['账号安全','修改后会撤销所有登录会话']};
|
||||
$$('.nav button').forEach(b=>b.onclick=()=>{$$('.nav button').forEach(x=>x.classList.toggle('active',x===b));$$('.page').forEach(x=>x.classList.add('hidden'));$(`#page-${b.dataset.page}`).classList.remove('hidden');$('#page-title').textContent=titles[b.dataset.page][0];$('#page-sub').textContent=titles[b.dataset.page][1]});
|
||||
async function loadConfig(){config=await api('/api/config');fillConfig(config)}
|
||||
function fillConfig(c){$('#c-listen').value=c.listen;$('#c-prefer').value=c.prefer;$('#c-web-listen').value=c.webui.listen;$('#c-session').value=c.webui.session_ttl_minutes;$('#c-web-enabled').checked=c.webui.enabled;$('#c-proxyfile').value=c.proxyfile;$('#c-up-zen').value=c.upstream.zen;$('#c-up-go').value=c.upstream.go;$('#c-attempts').value=c.retry.max_attempts;$('#c-timeout').value=c.retry.timeout_seconds;$('#c-refresh').value=c.models.refresh_seconds;$('#c-protocols').value=JSON.stringify(c.models.protocols||{},null,2);$('#c-idle').value=c.performance.max_idle_conns;$('#c-idle-host').value=c.performance.max_idle_conns_per_host;$('#c-max-host').value=c.performance.max_conns_per_host;$('#c-idle-timeout').value=c.performance.idle_conn_timeout_seconds;$('#c-connect').value=c.performance.connect_timeout_seconds;$('#c-cooldown').value=c.performance.failure_cooldown_seconds;$('#c-level').value=c.logging.level;$('#c-ring').value=c.logging.ring_size;['server_keys','zen_keys','go_keys','proxies'].forEach(renderChips);const restart=$('#restart-notice');if(c.restart_required_fields?.length){restart.textContent=`以下配置已保存但尚未生效:${c.restart_required_fields.join(', ')}。当前 API ${c.effective.listen}、WebUI ${c.effective.webui_listen}。请重启服务。`;restart.classList.remove('hidden')}else restart.classList.add('hidden')}
|
||||
function renderChips(name){const host=$(`#${name}-chips`);host.innerHTML='';(config[name]||[]).forEach(item=>{const chip=document.createElement('span');chip.className='chip';chip.dataset.id=item.id;chip.innerHTML=`<span></span><button type="button" title="移除">×</button>`;chip.querySelector('span').textContent=item.display;chip.querySelector('button').onclick=()=>chip.remove();host.appendChild(chip)})}
|
||||
function secretInputs(name){const kept=[...$(`#${name}-chips`).children].map(x=>({id:x.dataset.id}));const added=$(`#${name}-new`).value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean).map(value=>({value}));return kept.concat(added)}
|
||||
function number(id){return Number($(id).value)}
|
||||
$('#config-form').addEventListener('submit',async e=>{e.preventDefault();try{const update={listen:$('#c-listen').value,server_keys:secretInputs('server_keys'),zen_keys:secretInputs('zen_keys'),go_keys:secretInputs('go_keys'),proxies:secretInputs('proxies'),proxyfile:$('#c-proxyfile').value,prefer:$('#c-prefer').value,upstream:{zen:$('#c-up-zen').value,go:$('#c-up-go').value},retry:{max_attempts:number('#c-attempts'),timeout_seconds:number('#c-timeout')},models:{refresh_seconds:number('#c-refresh'),protocols:JSON.parse($('#c-protocols').value||'{}')},performance:{max_idle_conns:number('#c-idle'),max_idle_conns_per_host:number('#c-idle-host'),max_conns_per_host:number('#c-max-host'),idle_conn_timeout_seconds:number('#c-idle-timeout'),connect_timeout_seconds:number('#c-connect'),failure_cooldown_seconds:number('#c-cooldown')},logging:{level:$('#c-level').value,ring_size:number('#c-ring')},webui:{enabled:$('#c-web-enabled').checked,listen:$('#c-web-listen').value,username:config.webui.username,session_ttl_minutes:number('#c-session')}};const result=await api('/api/config',{method:'PUT',body:JSON.stringify(update)});config=result.config;['server_keys','zen_keys','go_keys','proxies'].forEach(n=>$(`#${n}-new`).value='');fillConfig(config);toast(result.result.restart_required?`已应用;${result.result.restart_fields.join(', ')} 需重启`:'配置已保存并立即应用')}catch(err){toast(err.message,true)}});
|
||||
$('#reload-config').onclick=async()=>{try{const r=await api('/api/config/reload',{method:'POST',body:'{}'});await loadConfig();toast(r.restart_required?'磁盘配置已重载,监听字段需重启':'磁盘配置已重载')}catch(e){toast(e.message,true)}};
|
||||
$('#reveal').onclick=async()=>{const password=prompt('请再次输入管理密码');if(password===null)return;try{const values=await api('/api/config/reveal',{method:'POST',body:JSON.stringify({password})});$('#modal-content').textContent=JSON.stringify(values,null,2);$('#modal').classList.remove('hidden')}catch(e){toast(e.message,true)}};$('#modal-close').onclick=()=>{$('#modal').classList.add('hidden');$('#modal-content').textContent=''};
|
||||
$('#account-form').addEventListener('submit',async e=>{e.preventDefault();try{await api('/api/account',{method:'PUT',body:JSON.stringify({current_password:$('#a-current').value,username:$('#a-user').value,new_password:$('#a-new').value})});toast('账号已更新,请重新登录');setTimeout(showLogin,800)}catch(err){toast(err.message,true)}});
|
||||
async function refreshMonitor(){try{const data=await api('/api/monitor');$('#version').textContent=`version ${data.version}`;const m=data.metrics;$('#m-total').textContent=m.last_hour.total.toLocaleString();$('#m-rate').innerHTML=`${(m.last_hour.success_rate*100).toFixed(1)}<small>%</small>`;$('#m-p95').innerHTML=`${m.last_hour.p95_ms||0}<small> ms</small>`;$('#m-active').innerHTML=`${m.active_requests}<small> / ${m.active_streams}</small>`;$('#proxy-table').innerHTML=data.resources.proxies.map(p=>`<tr><td>${esc(p.address)}</td><td class="${p.healthy?'ok':'bad'}">${p.healthy?'正常':'不可用'}</td><td>Z ${p.zen_keys} · G ${p.go_keys}</td></tr>`).join('')||'<tr><td colspan="3">无数据</td></tr>';$('#key-table').innerHTML=data.resources.keys.map(k=>`<tr><td>${k.id}</td><td>${k.tier}</td><td class="${k.cooldown_until?'warn':'ok'}">${k.cooldown_until?'冷却中':'可用'}</td></tr>`).join('')||'<tr><td colspan="3">无数据</td></tr>';$('#breakdowns').innerHTML=breakdown('端点',m.endpoints)+breakdown('状态码',m.statuses)+breakdown('模型',m.models)+breakdown('Tier',m.tiers)}catch(e){}}
|
||||
function breakdown(title,data){return `<div><h3>${title}</h3><table class="table">${Object.entries(data).sort((a,b)=>b[1]-a[1]).slice(0,10).map(([k,v])=>`<tr><td>${esc(k)}</td><td>${v}</td></tr>`).join('')||'<tr><td>暂无请求</td></tr>'}</table></div>`}
|
||||
function connectLogs(){if(eventSource)eventSource.close();eventSource=new EventSource('/api/logs/stream');eventSource.addEventListener('log',e=>{const item=JSON.parse(e.data);logEvents.push(item);if(logEvents.length>2000)logEvents.shift();if(!paused&&!logRenderPending){logRenderPending=true;requestAnimationFrame(()=>{logRenderPending=false;renderLogs()})}});eventSource.addEventListener('gap',()=>toast('较早的日志已从内存清除',true))}
|
||||
function renderLogs(){const level=$('#log-level').value,component=$('#log-component').value.toLowerCase(),query=$('#log-search').value.toLowerCase();const rows=logEvents.filter(x=>(!level||x.level===level)&&(!component||(x.component||'').toLowerCase().includes(component))&&(!query||JSON.stringify(x).toLowerCase().includes(query))).slice(-500);$('#log-list').innerHTML=rows.map(x=>`<div class="log"><span class="time">${new Date(x.time).toLocaleTimeString()}</span><span class="level ${x.level==='error'?'bad':x.level==='warn'?'warn':x.level==='info'?'ok':''}">${x.level}</span><span class="component">${esc(x.component||'core')}</span><span>${esc(x.message)}</span><span class="fields">${esc(JSON.stringify(x.fields||{}))}</span></div>`).join('');$('#log-list').scrollTop=$('#log-list').scrollHeight}
|
||||
['#log-level','#log-component','#log-search'].forEach(id=>$(id).addEventListener('input',renderLogs));$('#log-pause').onclick=()=>{paused=!paused;$('#log-pause').textContent=paused?'继续':'暂停';if(!paused)renderLogs()};function esc(v){const d=document.createElement('div');d.textContent=String(v);return d.innerHTML}boot();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user