mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
Merge branch 'main' into fix/web-image-history-context
This commit is contained in:
65 files changed
+4214
-114
No files matched your search
@@ -138,7 +138,7 @@ The Gateway routes requests through the Provider Registry. Account Sync refreshe
|
||||
| Routing | Model discovery, Provider pinning, sticky sessions, quota/concurrency guards, and bounded failover |
|
||||
| Sessions | Stored responses, compact, prompt-cache affinity, and optional reasoning replay |
|
||||
| Media | Image generation/editing, video jobs, local archiving, and URL/Base64/SSE output |
|
||||
| Egress | HTTP/SOCKS/Resin, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr |
|
||||
| Egress | HTTP/SOCKS/Resin and Trojan/VLESS/Shadowsocks/VMess tunnels, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr |
|
||||
| Operations | Dashboard, model routes, client keys, audits, runtime settings, and media libraries |
|
||||
|
||||
### Provider boundaries
|
||||
@@ -339,7 +339,8 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
|
||||
Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console supports:
|
||||
|
||||
- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, and Resin
|
||||
- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Resin, Trojan, VLESS, Shadowsocks, and VMess
|
||||
- TCP, WebSocket, and TLS tunnel transports; unsupported variants are rejected during import
|
||||
- Subscription and text/Base64 import
|
||||
- Batch probes, filtering, deletion, assignment, and balancing
|
||||
- Fallback per scope: none, direct, or a fixed node
|
||||
@@ -347,6 +348,8 @@ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console
|
||||
- Immediate recovery probes after fixed-proxy transport failures, with per-node coalescing and bounded waiting for fast retry
|
||||
- Optional [Egress Quality Guard](./tools/egress-quality-guard/README.md) for active per-node model probes, guarded quarantine, and recovery; enable it with the built-in `quality-guard` Compose profile
|
||||
|
||||
Hysteria and TUIC are not supported yet. FlareSolverr accepts only HTTP/SOCKS proxy URLs, so automatic clearance refresh cannot use a tunnel share URL directly.
|
||||
|
||||
To enable the guard, add a `qualityGuard` section to `config.yaml`, then start
|
||||
the profile. The main service creates and reuses a non-exportable system probe
|
||||
identity automatically:
|
||||
@@ -386,7 +389,12 @@ For managed Web/Console Cloudflare Clearance:
|
||||
docker compose --profile flaresolverr up -d
|
||||
```
|
||||
|
||||
Then select `FlareSolverr` under **Runtime Settings → Media & Network → Clearance** and use `http://flaresolverr:8191`.
|
||||
Then use `http://flaresolverr:8191` under **Runtime Settings → Media & Network → Clearance** and select one of the managed modes:
|
||||
|
||||
- `FlareSolverr` proactively refreshes stale fixed-egress Clearance on the configured schedule.
|
||||
- `On demand` keeps the last successful Clearance regardless of age and solves again only after an upstream rejection explicitly invalidates it. Scheduled refresh does not launch a browser in this mode.
|
||||
|
||||
`Manual` never invokes FlareSolverr. The on-demand mode can make the first request without a managed Clearance; if Cloudflare rejects it, the next lease performs one deduplicated solve.
|
||||
|
||||
The egress layer retries only connection failures known to occur before request submission. It does not replay submitted generation requests, authentication failures, exhausted quotas, or upstream rate limits.
|
||||
|
||||
|
||||
+11
-3
@@ -139,7 +139,7 @@ flowchart LR
|
||||
| 路由 | 模型发现、Provider 限定、会话粘滞、额度/并发门禁和有界切换 |
|
||||
| 会话 | stored response、compact、Prompt Cache 亲和与可选 reasoning replay |
|
||||
| 媒体 | 图片生成与编辑、视频任务、本地归档及 URL/Base64/SSE 输出 |
|
||||
| 出口 | HTTP/SOCKS/Resin、订阅、探测、代理池、调配、回退与 FlareSolverr |
|
||||
| 出口 | HTTP/SOCKS/Resin 与 Trojan/VLESS/Shadowsocks/VMess 隧道、订阅、探测、代理池、调配、回退与 FlareSolverr |
|
||||
| 运维 | Dashboard、模型路由、客户端密钥、审计、运行设置和媒体库 |
|
||||
|
||||
### Provider 边界
|
||||
@@ -340,7 +340,8 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
|
||||
出口节点按 Build、Web、Console 或 Web 资源隔离。管理端支持:
|
||||
|
||||
- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H 与 Resin
|
||||
- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Resin、Trojan、VLESS、Shadowsocks 与 VMess
|
||||
- 隧道协议支持 TCP、WebSocket 和 TLS,未实现的传输形态会在导入时拒绝
|
||||
- 订阅和文本/Base64 导入
|
||||
- 批量探测、筛选、删除、分配与均衡
|
||||
- 按作用域配置无回退、直连或固定节点
|
||||
@@ -348,6 +349,8 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
- 固定代理传输失败后立即复测;同节点复测自动合并,后续绑定请求限时等待并在恢复后快速重试
|
||||
- 可选的[出口质量守护程序](./tools/egress-quality-guard/README.zh-CN.md),支持逐节点模型探测、防误杀隔离和自动恢复;通过内置的 `quality-guard` Compose profile 按需启用
|
||||
|
||||
Hysteria 与 TUIC 暂未支持。FlareSolverr 仅接受 HTTP/SOCKS 代理地址,因此自动刷新 Clearance 暂不能直接使用隧道分享链接。
|
||||
|
||||
首次启用时只需在 `config.yaml` 中增加 `qualityGuard` 并启动 profile。主程序会自动创建并稳定复用不可导出的系统探测身份:
|
||||
|
||||
```yaml
|
||||
@@ -380,7 +383,12 @@ socks5h://Default.{account}:RESIN_PROXY_TOKEN@resin:2260
|
||||
docker compose --profile flaresolverr up -d
|
||||
```
|
||||
|
||||
随后在 **运行设置 → 媒体与网络 → Clearance** 选择 `FlareSolverr`,地址填写 `http://flaresolverr:8191`。
|
||||
随后在 **运行设置 → 媒体与网络 → Clearance** 填写 `http://flaresolverr:8191`,并选择一种托管模式:
|
||||
|
||||
- `FlareSolverr` 按配置周期主动刷新固定出口中过期的 Clearance。
|
||||
- `按需刷新` 不按时间淘汰最后一次成功的 Clearance,只在上游明确拒绝并将其标记失效后重新求解;后台定时任务不会在该模式下启动浏览器。
|
||||
|
||||
`手动维护` 始终不会调用 FlareSolverr。按需模式允许首次请求不携带托管 Clearance;若被 Cloudflare 拒绝,下一次租约会执行一次经过并发去重的求解。
|
||||
|
||||
出口层只重试可以确认发生在请求提交前的连接故障,不会重放已经提交的生成请求、认证失败、额度耗尽或上游限流。
|
||||
|
||||
|
||||
@@ -3,16 +3,19 @@ module github.com/chenyme/grok2api/backend
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/Asutorufa/yuhaiin v0.3.8
|
||||
github.com/bdandy/go-socks4 v1.2.3
|
||||
github.com/bogdanfinn/fhttp v0.6.8
|
||||
github.com/bogdanfinn/tls-client v1.15.1
|
||||
github.com/bogdanfinn/websocket v1.5.5-barnius
|
||||
github.com/coder/websocket v1.8.14
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/redis/go-redis/v9 v9.21.0
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.16.6
|
||||
@@ -31,6 +34,7 @@ require (
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/bdandy/go-errors v1.2.2 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect
|
||||
github.com/bogdanfinn/utls v1.7.7-barnius // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
@@ -66,21 +70,30 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/prometheus/client_golang v1.20.5 // indirect
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.55.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/time v0.9.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
|
||||
+32
-2
@@ -1,3 +1,5 @@
|
||||
github.com/Asutorufa/yuhaiin v0.3.8 h1:HrEqvXNVYUviL2+Zu01AxRJiPayZa7lZvoYQlvgMkgc=
|
||||
github.com/Asutorufa/yuhaiin v0.3.8/go.mod h1:fLEwJOwgPumPQvGgJNJn392c63GyAaP4QCkZTj6LRyo=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
|
||||
@@ -10,6 +12,8 @@ github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11
|
||||
github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM=
|
||||
github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic=
|
||||
github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bogdanfinn/fhttp v0.6.8 h1:LiQyHOY3i0QoxxNB7nq27/nGNNbtPj0fuBPozhR7Ws4=
|
||||
github.com/bogdanfinn/fhttp v0.6.8/go.mod h1:A+EKDzMx2hb4IUbMx4TlkoHnaJEiLl8r/1Ss1Y+5e5M=
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.9-utls h1:tV6eDEiRbRCcepALSzxR94JUVD3N3ACIiRLgyc2Ep8s=
|
||||
@@ -34,6 +38,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -79,8 +85,8 @@ github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArs
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134 h1:c5FlPPgxOn7kJz3VoPLkQYQXGBS3EklQ4Zfi57uOuqQ=
|
||||
github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
@@ -127,11 +133,21 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
|
||||
github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
|
||||
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
|
||||
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
|
||||
github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=
|
||||
github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=
|
||||
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
|
||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
@@ -141,8 +157,12 @@ github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3b
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg=
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3/go.mod h1:HgjTstvQsPGkxUsCd2KWxErBblirPizecHcpD3ffK+s=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5 h1:PDSQv9y2S85Fl7VBeOMF9StzeXZyK1HakRm86CUbr28=
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5/go.mod h1:AGGpIoek4HRno4xzyFiAtLHkOpcoznZEkAccaI/rplM=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -182,12 +202,16 @@ go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d h1:0olWaB5pg3+oychR51GUVCEsGkeCU/2JxjBgIo4f3M0=
|
||||
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
|
||||
@@ -201,6 +225,7 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -211,6 +236,7 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -221,6 +247,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
|
||||
golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
@@ -247,6 +275,8 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
|
||||
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 h1:YAGAbMnGNRna7ajnsDuRjV1o/Mc2LDwEliRemNFDVF4=
|
||||
gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70/go.mod h1:5DMfjtclAbTIjbXqO1qCe2K5GKKxWz2JHvCChuTcJEM=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
|
||||
@@ -8,7 +8,12 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/batch"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
@@ -288,3 +293,111 @@ func TestDetectBuildAccountsStreamsInvalidOnlyForAll(t *testing.T) {
|
||||
_ = okAccount
|
||||
_ = invalidAccount
|
||||
}
|
||||
|
||||
func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) {
|
||||
const accountCount = 8
|
||||
service := newConcurrentInvalidBuildDetectService(t, accountCount)
|
||||
|
||||
started := make(chan struct{}, accountCount)
|
||||
release := make(chan struct{})
|
||||
var items []BuildDetectItemResult
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, detectErr := service.DetectBuildAccountsWithProgress(context.Background(), nil, true, nil, func(item BuildDetectItemResult) error {
|
||||
started <- struct{}{}
|
||||
<-release
|
||||
items = append(items, item)
|
||||
return nil
|
||||
})
|
||||
errCh <- detectErr
|
||||
}()
|
||||
|
||||
deadline := time.After(2 * time.Second)
|
||||
select {
|
||||
case <-started:
|
||||
case <-deadline:
|
||||
t.Fatal("itemObserver was not invoked")
|
||||
}
|
||||
close(release)
|
||||
if detectErr := <-errCh; detectErr != nil {
|
||||
t.Fatal(detectErr)
|
||||
}
|
||||
if len(items) != accountCount {
|
||||
t.Fatalf("serialized items = %d, want %d", len(items), accountCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectBuildAccountsObserverPanicDoesNotDeadlock(t *testing.T) {
|
||||
const accountCount = 8
|
||||
service := newConcurrentInvalidBuildDetectService(t, accountCount)
|
||||
|
||||
type detectResult struct {
|
||||
succeeded int
|
||||
failed int
|
||||
err error
|
||||
}
|
||||
var calls atomic.Int64
|
||||
resultCh := make(chan detectResult, 1)
|
||||
go func() {
|
||||
succeeded, failed, err := service.DetectBuildAccountsWithProgress(context.Background(), nil, true, nil, func(BuildDetectItemResult) error {
|
||||
if calls.Add(1) == 1 {
|
||||
panic("item observer panic")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
resultCh <- detectResult{succeeded: succeeded, failed: failed, err: err}
|
||||
}()
|
||||
|
||||
timer := time.NewTimer(2 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case result := <-resultCh:
|
||||
if result.err != nil {
|
||||
t.Fatal(result.err)
|
||||
}
|
||||
if result.succeeded != 0 || result.failed != accountCount {
|
||||
t.Fatalf("summary succeeded=%d failed=%d, want 0/%d", result.succeeded, result.failed, accountCount)
|
||||
}
|
||||
if got := calls.Load(); got != accountCount {
|
||||
t.Fatalf("observer calls = %d, want %d", got, accountCount)
|
||||
}
|
||||
case <-timer.C:
|
||||
t.Fatal("itemObserver panic deadlocked Build account detection")
|
||||
}
|
||||
}
|
||||
|
||||
func newConcurrentInvalidBuildDetectService(t *testing.T, accountCount int) *Service {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accessToken, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewAccountRepository(database)
|
||||
for index := range accountCount {
|
||||
if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index),
|
||||
SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken,
|
||||
Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{
|
||||
status: http.StatusUnauthorized,
|
||||
}), cipher, nil)
|
||||
service.SetDetectPool(batch.NewPool(accountCount))
|
||||
return service
|
||||
}
|
||||
@@ -3766,7 +3766,7 @@ func (s *Service) BatchRefreshBilling(ctx context.Context, ids []uint64) (int, i
|
||||
|
||||
// DetectBuildAccountsWithProgress 对指定或全部 Grok Build 账号发起探测请求;all 与 ids 必须且只能提供一个。
|
||||
// 该方法同时上报批量进度与单账号明细。
|
||||
// itemObserver 在每个账号完成后调用:选中检测会推送全部结果,全量检测仅推送已确认失效账号。
|
||||
// itemObserver 在每个账号完成后串行调用:选中检测会推送全部结果,全量检测仅推送已确认失效账号。
|
||||
func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uint64, all bool, progress BatchProgressObserver, itemObserver BuildDetectItemObserver) (int, int, error) {
|
||||
if all == (len(ids) > 0) {
|
||||
return 0, 0, invalidInput("必须明确选择全部账号或提供非空账号 ID")
|
||||
@@ -3799,7 +3799,7 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin
|
||||
return 0, 0, err
|
||||
}
|
||||
}
|
||||
var progressMu sync.Mutex
|
||||
var observerMu sync.Mutex
|
||||
var progressErr error
|
||||
completed := 0
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
@@ -3807,7 +3807,12 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin
|
||||
summary, err := batch.ForEachObserved(runCtx, ids, batch.Options{Workers: pool.Limit(), Pool: pool}, func(workCtx context.Context, id uint64) (BuildDetectItemResult, error) {
|
||||
item := s.detectBuildAccount(workCtx, id)
|
||||
if itemObserver != nil && (selectedMode || item.Outcome == BuildDetectOutcomeInvalid) {
|
||||
if notifyErr := itemObserver(item); notifyErr != nil {
|
||||
notifyErr := func() error {
|
||||
observerMu.Lock()
|
||||
defer observerMu.Unlock()
|
||||
return itemObserver(item)
|
||||
}()
|
||||
if notifyErr != nil {
|
||||
return item, notifyErr
|
||||
}
|
||||
}
|
||||
@@ -3823,8 +3828,8 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin
|
||||
if errors.As(result.Err, &panicErr) {
|
||||
s.logger.Error("account_bulk_task_panicked", "operation", "build_detect", "account_id", ids[index], "error", panicErr, "stack", string(panicErr.Stack))
|
||||
}
|
||||
progressMu.Lock()
|
||||
defer progressMu.Unlock()
|
||||
observerMu.Lock()
|
||||
defer observerMu.Unlock()
|
||||
completed++
|
||||
if progress != nil {
|
||||
if notifyErr := progress(completed, len(ids)); notifyErr != nil && progressErr == nil {
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
degradeWindow1h = "1h"
|
||||
degradeWindow6h = "6h"
|
||||
degradeWindow24h = "24h"
|
||||
degradeWindow7d = "7d"
|
||||
degradeRecentEventCap = 80
|
||||
degradeDefaultPage = 1
|
||||
degradeDefaultPageSize = 50
|
||||
degradeMaxPageSize = 100
|
||||
)
|
||||
|
||||
type DegradeThresholds struct {
|
||||
SoftTPS float64
|
||||
HardTPS float64
|
||||
MinGenMS int64
|
||||
MinOut int64
|
||||
FailClosed bool
|
||||
}
|
||||
|
||||
type DegradeAccountFilter struct {
|
||||
Search string
|
||||
Status string
|
||||
Class string
|
||||
MinHits int
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
type DegradeSummary struct {
|
||||
Window string
|
||||
GeneratedAt time.Time
|
||||
Thresholds DegradeThresholds
|
||||
Totals DegradeTotals
|
||||
Series []DegradeBucket
|
||||
Nodes []DegradeNode
|
||||
Accounts []DegradeAccount
|
||||
AccountPage DegradeAccountPage
|
||||
Events []DegradeEventView
|
||||
}
|
||||
|
||||
type DegradeTotals struct {
|
||||
Hits int64
|
||||
Accounts int64
|
||||
StillEnabled int64
|
||||
Disabled int64
|
||||
Deleted int64
|
||||
Hard int64
|
||||
Soft int64
|
||||
Burst int64
|
||||
MaxTPS float64
|
||||
}
|
||||
|
||||
type DegradeAccountPage struct {
|
||||
Page int
|
||||
PageSize int
|
||||
Total int64
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
type DegradeBucket struct {
|
||||
Label string `json:"label"`
|
||||
Count int64 `json:"count"`
|
||||
Severe int64 `json:"severe"`
|
||||
}
|
||||
|
||||
type DegradeNode struct {
|
||||
Name string `json:"name"`
|
||||
Hits int64 `json:"hits"`
|
||||
Accounts int64 `json:"accounts"`
|
||||
MaxTPS float64 `json:"maxTPS"`
|
||||
}
|
||||
|
||||
type DegradeAccount struct {
|
||||
ID uint64
|
||||
Name string
|
||||
Email string
|
||||
Hits int64
|
||||
MaxTPS float64
|
||||
Classes map[string]int64
|
||||
Nodes []string
|
||||
Last time.Time
|
||||
Enabled bool
|
||||
Found bool
|
||||
BFS int
|
||||
}
|
||||
|
||||
type DegradeEventView struct {
|
||||
ID uint64
|
||||
RequestID string
|
||||
AccountID *uint64
|
||||
AccountName string
|
||||
NodeName string
|
||||
OutputTokens int64
|
||||
TPS float64
|
||||
Class string
|
||||
CreatedAt time.Time
|
||||
Model string
|
||||
}
|
||||
|
||||
type degradeBucketSpec struct {
|
||||
Range repository.DegradeBucketRange
|
||||
Label string
|
||||
}
|
||||
|
||||
func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds, filter DegradeAccountFilter) (DegradeSummary, error) {
|
||||
window, start, end, err := resolveDegradeWindow(window, s.now().UTC())
|
||||
if err != nil {
|
||||
return DegradeSummary{}, err
|
||||
}
|
||||
thresholds = normalizeDegradeThresholds(thresholds)
|
||||
filter = normalizeDegradeAccountFilter(filter)
|
||||
bucketSpecs := degradeBucketSpecs(window, start, end)
|
||||
bucketRanges := make([]repository.DegradeBucketRange, 0, len(bucketSpecs))
|
||||
for _, spec := range bucketSpecs {
|
||||
bucketRanges = append(bucketRanges, spec.Range)
|
||||
}
|
||||
data, err := s.audits.SummarizeDegrade(ctx, repository.DegradeSummaryQuery{
|
||||
Start: start, End: end, SoftTPS: thresholds.SoftTPS, HardTPS: thresholds.HardTPS,
|
||||
MinGenerationMS: thresholds.MinGenMS, MinOutputTokens: thresholds.MinOut, FailClosed: thresholds.FailClosed,
|
||||
AccountSearch: filter.Search, AccountStatus: filter.Status, AccountClass: filter.Class, MinHits: filter.MinHits,
|
||||
AccountOffset: (filter.Page - 1) * filter.PageSize, AccountLimit: filter.PageSize,
|
||||
Buckets: bucketRanges, RecentLimit: degradeRecentEventCap,
|
||||
})
|
||||
if err != nil {
|
||||
return DegradeSummary{}, err
|
||||
}
|
||||
return buildDegradeSummary(window, end, thresholds, filter, bucketSpecs, data), nil
|
||||
}
|
||||
|
||||
func resolveDegradeWindow(value string, now time.Time) (string, time.Time, time.Time, error) {
|
||||
if value == "" {
|
||||
value = degradeWindow24h
|
||||
}
|
||||
var duration time.Duration
|
||||
switch value {
|
||||
case degradeWindow1h:
|
||||
duration = time.Hour
|
||||
case degradeWindow6h:
|
||||
duration = 6 * time.Hour
|
||||
case degradeWindow24h:
|
||||
duration = 24 * time.Hour
|
||||
case degradeWindow7d:
|
||||
duration = 7 * 24 * time.Hour
|
||||
default:
|
||||
return "", time.Time{}, time.Time{}, ErrInvalidPeriod
|
||||
}
|
||||
return value, now.Add(-duration), now, nil
|
||||
}
|
||||
|
||||
func normalizeDegradeThresholds(value DegradeThresholds) DegradeThresholds {
|
||||
if value.SoftTPS <= 0 || math.IsNaN(value.SoftTPS) || math.IsInf(value.SoftTPS, 0) {
|
||||
value.SoftTPS = auditdomain.DefaultDegradeSoftTPS
|
||||
}
|
||||
if value.HardTPS <= 0 || math.IsNaN(value.HardTPS) || math.IsInf(value.HardTPS, 0) {
|
||||
value.HardTPS = auditdomain.DefaultDegradeHardTPS
|
||||
}
|
||||
if value.SoftTPS >= value.HardTPS {
|
||||
value.SoftTPS = auditdomain.DefaultDegradeSoftTPS
|
||||
value.HardTPS = auditdomain.DefaultDegradeHardTPS
|
||||
}
|
||||
if value.MinGenMS <= 0 {
|
||||
value.MinGenMS = auditdomain.DefaultDegradeMinGenMS
|
||||
}
|
||||
if value.MinOut <= 0 {
|
||||
value.MinOut = auditdomain.DefaultDegradeMinOutput
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeDegradeAccountFilter(value DegradeAccountFilter) DegradeAccountFilter {
|
||||
value.Search = strings.TrimSpace(value.Search)
|
||||
if value.Status != "enabled" && value.Status != "disabled" && value.Status != "deleted" {
|
||||
value.Status = ""
|
||||
}
|
||||
if value.Class != auditdomain.DegradeClassBurst && value.Class != auditdomain.DegradeClassSoft && value.Class != auditdomain.DegradeClassHard {
|
||||
value.Class = ""
|
||||
}
|
||||
if value.MinHits < 1 {
|
||||
value.MinHits = 1
|
||||
}
|
||||
if value.Page < 1 {
|
||||
value.Page = degradeDefaultPage
|
||||
}
|
||||
if value.PageSize < 1 || value.PageSize > degradeMaxPageSize {
|
||||
value.PageSize = degradeDefaultPageSize
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, filter DegradeAccountFilter, bucketSpecs []degradeBucketSpec, data repository.DegradeSummaryResult) DegradeSummary {
|
||||
accounts := make([]DegradeAccount, 0, len(data.Accounts))
|
||||
for _, value := range data.Accounts {
|
||||
accounts = append(accounts, DegradeAccount{
|
||||
ID: value.ID, Name: value.Name, Email: value.Email, Hits: value.Hits, MaxTPS: round(value.MaxTPS, 1),
|
||||
Classes: map[string]int64{
|
||||
auditdomain.DegradeClassBurst: value.Burst,
|
||||
auditdomain.DegradeClassSoft: value.Soft,
|
||||
auditdomain.DegradeClassHard: value.Hard,
|
||||
},
|
||||
Nodes: value.Nodes, Last: value.Last, Enabled: value.Enabled, Found: value.Found, BFS: value.BuildBotFlagSource,
|
||||
})
|
||||
}
|
||||
nodes := make([]DegradeNode, 0, len(data.Nodes))
|
||||
for _, value := range data.Nodes {
|
||||
nodes = append(nodes, DegradeNode{Name: value.Name, Hits: value.Hits, Accounts: value.Accounts, MaxTPS: round(value.MaxTPS, 1)})
|
||||
}
|
||||
events := make([]DegradeEventView, 0, len(data.Events))
|
||||
for _, value := range data.Events {
|
||||
nodeName := value.EgressNodeName
|
||||
if nodeName == "" {
|
||||
nodeName = "?"
|
||||
}
|
||||
events = append(events, DegradeEventView{
|
||||
ID: value.ID, RequestID: value.RequestID, AccountID: value.AccountID, AccountName: value.AccountName,
|
||||
NodeName: nodeName, OutputTokens: value.OutputTokens, TPS: round(value.TPS, 2), Class: value.Class,
|
||||
CreatedAt: value.CreatedAt, Model: value.Model,
|
||||
})
|
||||
}
|
||||
series := make([]DegradeBucket, len(bucketSpecs))
|
||||
for index, spec := range bucketSpecs {
|
||||
series[index].Label = spec.Label
|
||||
}
|
||||
for _, value := range data.Buckets {
|
||||
if value.Index >= 0 && value.Index < len(series) {
|
||||
series[value.Index].Count = value.Count
|
||||
series[value.Index].Severe = value.Severe
|
||||
}
|
||||
}
|
||||
return DegradeSummary{
|
||||
Window: window, GeneratedAt: now, Thresholds: thresholds,
|
||||
Totals: DegradeTotals{
|
||||
Hits: data.Totals.Hits, Accounts: data.Totals.Accounts, StillEnabled: data.Totals.StillEnabled,
|
||||
Disabled: data.Totals.Disabled, Deleted: data.Totals.Deleted, Hard: data.Totals.Hard,
|
||||
Soft: data.Totals.Soft, Burst: data.Totals.Burst, MaxTPS: round(data.Totals.MaxTPS, 2),
|
||||
},
|
||||
Series: series, Nodes: nodes, Accounts: accounts,
|
||||
AccountPage: DegradeAccountPage{
|
||||
Page: data.AccountOffset/filter.PageSize + 1, PageSize: filter.PageSize, Total: data.AccountTotal,
|
||||
HasMore: int64(data.AccountOffset+filter.PageSize) < data.AccountTotal,
|
||||
},
|
||||
Events: events,
|
||||
}
|
||||
}
|
||||
|
||||
func degradeBucketSpecs(window string, start, end time.Time) []degradeBucketSpec {
|
||||
step := 5 * time.Minute
|
||||
label := func(value time.Time) string { return value.Format("15:04") }
|
||||
switch window {
|
||||
case degradeWindow7d:
|
||||
step = 2 * time.Hour
|
||||
label = func(value time.Time) string { return value.Format("01-02 15:00") }
|
||||
case degradeWindow24h:
|
||||
step = time.Hour
|
||||
label = func(value time.Time) string { return value.Format("15:00") }
|
||||
case degradeWindow6h:
|
||||
step = 20 * time.Minute
|
||||
}
|
||||
var result []degradeBucketSpec
|
||||
for cursor := start; cursor.Before(end); cursor = cursor.Add(step) {
|
||||
bucketEnd := cursor.Add(step)
|
||||
if bucketEnd.After(end) {
|
||||
bucketEnd = end
|
||||
}
|
||||
result = append(result, degradeBucketSpec{
|
||||
Range: repository.DegradeBucketRange{Start: cursor, End: bucketEnd},
|
||||
Label: label(cursor),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func round(value float64, places int) float64 {
|
||||
factor := math.Pow10(places)
|
||||
return math.Round(value*factor) / factor
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
)
|
||||
|
||||
func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewAuditRepository(database)
|
||||
now := time.Now().UTC()
|
||||
first := int64(100)
|
||||
accountID := uint64(7)
|
||||
records := []auditdomain.Record{
|
||||
{RequestID: "hard-1", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, AccountName: "hot", EgressNodeName: "node-a", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)},
|
||||
{RequestID: "quality_skip_me", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)},
|
||||
{RequestID: "non-stream", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: false, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)},
|
||||
}
|
||||
if err := repo.CreateBatch(ctx, records); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(repo, slog.Default(), 8, 4, time.Second)
|
||||
service.now = func() time.Time { return now }
|
||||
summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.Totals.Hits != 1 || summary.Totals.Accounts != 1 || summary.Totals.Hard != 1 {
|
||||
t.Fatalf("totals = %#v", summary.Totals)
|
||||
}
|
||||
if len(summary.Accounts) != 1 || summary.Accounts[0].ID != 7 || summary.Accounts[0].Hits != 1 {
|
||||
t.Fatalf("accounts = %#v", summary.Accounts)
|
||||
}
|
||||
if summary.Totals.Deleted != 1 || summary.Totals.Disabled != 0 || summary.Accounts[0].Found {
|
||||
t.Fatalf("deleted account state = totals %#v, account %#v", summary.Totals, summary.Accounts[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummaryDoesNotDropOlderAnomalyAfterTwentyThousandNewerRows(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-large.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewAuditRepository(database)
|
||||
now := time.Now().UTC()
|
||||
first := int64(100)
|
||||
accountID := uint64(7)
|
||||
records := make([]auditdomain.Record, 0, 20_001)
|
||||
records = append(records, auditdomain.Record{
|
||||
RequestID: "older-real-anomaly", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build",
|
||||
AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2_000,
|
||||
FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-2 * time.Hour),
|
||||
})
|
||||
for index := 0; index < 20_000; index++ {
|
||||
records = append(records, auditdomain.Record{
|
||||
RequestID: fmt.Sprintf("newer-healthy-%05d", index), ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build",
|
||||
AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 100,
|
||||
FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute - time.Duration(index)*time.Millisecond),
|
||||
})
|
||||
}
|
||||
if err := repo.CreateBatch(ctx, records); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(repo, slog.Default(), 8, 4, time.Second)
|
||||
service.now = func() time.Time { return now }
|
||||
summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.Totals.Hits != 1 || summary.Totals.Hard != 1 || len(summary.Events) != 1 || summary.Events[0].RequestID != "older-real-anomaly" {
|
||||
t.Fatalf("summary silently dropped older anomaly: totals=%#v events=%#v", summary.Totals, summary.Events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummaryMatchesFailClosedShortWindowPolicy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-policy.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewAuditRepository(database)
|
||||
now := time.Now().UTC()
|
||||
first := int64(50)
|
||||
accountID := uint64(9)
|
||||
if err := repo.Create(ctx, auditdomain.Record{
|
||||
RequestID: "short-window", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build",
|
||||
AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 200,
|
||||
FirstTokenMS: &first, DurationMS: 250, CreatedAt: now.Add(-time.Minute),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(repo, slog.Default(), 8, 4, time.Second)
|
||||
service.now = func() time.Time { return now }
|
||||
open, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000, FailClosed: false}, DegradeAccountFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
closed, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000, FailClosed: true}, DegradeAccountFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if open.Totals.Hard != 1 || open.Totals.Burst != 0 || closed.Totals.Hard != 0 || closed.Totals.Burst != 1 {
|
||||
t.Fatalf("open=%#v closed=%#v", open.Totals, closed.Totals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummaryPaginatesAccountsInRepository(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-page.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewAuditRepository(database)
|
||||
now := time.Now().UTC()
|
||||
first := int64(100)
|
||||
for id := uint64(1); id <= 3; id++ {
|
||||
accountID := id
|
||||
if err := repo.Create(ctx, auditdomain.Record{
|
||||
RequestID: fmt.Sprintf("page-account-%d", id), ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build",
|
||||
AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2_000,
|
||||
FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Duration(id) * time.Minute),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
service := NewService(repo, slog.Default(), 8, 4, time.Second)
|
||||
service.now = func() time.Time { return now }
|
||||
summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{Page: 2, PageSize: 2})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.AccountPage.Total != 3 || summary.AccountPage.HasMore || len(summary.Accounts) != 1 {
|
||||
t.Fatalf("page=%#v accounts=%#v", summary.AccountPage, summary.Accounts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummarySearchesEveryAccountIdentityField(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-search.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountValue, _, err := relational.NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, AuthType: accountdomain.AuthTypeOAuth,
|
||||
Name: "Searchable Build Account", SourceKey: "searchable-build",
|
||||
EncryptedAccessToken: "encrypted-token", AuthStatus: accountdomain.AuthStatusActive, Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
first := int64(100)
|
||||
if err := relational.NewAuditRepository(database).Create(ctx, auditdomain.Record{
|
||||
RequestID: "search-by-name", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build",
|
||||
AccountID: &accountValue.ID, AccountName: "stale audit name", StatusCode: 200, Streaming: true,
|
||||
OutputTokens: 2_000, FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second)
|
||||
service.now = func() time.Time { return now }
|
||||
summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{Search: "searchable build"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.AccountPage.Total != 1 || len(summary.Accounts) != 1 || summary.Accounts[0].ID != accountValue.ID {
|
||||
t.Fatalf("account search result = %#v", summary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-window.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second)
|
||||
if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}, DegradeAccountFilter{}); err != ErrInvalidPeriod {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
@@ -851,13 +852,27 @@ func NormalizeProxyURL(value string) (string, error) {
|
||||
}
|
||||
parseValue := strings.ReplaceAll(value, ProxyAccountPlaceholder, proxyAccountSentinel)
|
||||
parsed, err := url.Parse(parseValue)
|
||||
if err != nil || parsed.Host == "" || parsed.Hostname() == "" {
|
||||
if err != nil {
|
||||
return "", errors.New("代理地址格式无效")
|
||||
}
|
||||
switch strings.ToLower(parsed.Scheme) {
|
||||
scheme := strings.ToLower(parsed.Scheme)
|
||||
if tunnelproxy.IsSupportedScheme(scheme) {
|
||||
if hasAccountPlaceholder {
|
||||
return "", errors.New("隧道代理不支持 {account} 占位符")
|
||||
}
|
||||
normalized, normalizeErr := tunnelproxy.Normalize(value)
|
||||
if normalizeErr != nil {
|
||||
return "", normalizeErr
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
if parsed.Host == "" || parsed.Hostname() == "" {
|
||||
return "", errors.New("代理地址格式无效")
|
||||
}
|
||||
switch scheme {
|
||||
case "http", "https", "socks4", "socks4a", "socks5", "socks5h":
|
||||
default:
|
||||
return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5")
|
||||
return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4、SOCKS5、Trojan、VLESS、SS 或 VMess")
|
||||
}
|
||||
if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
|
||||
return "", errors.New("代理地址不能包含路径、查询参数或片段")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -21,23 +22,48 @@ func TestSanitizeCloudflareCookiesDropsControlsAndNonCloudflareValues(t *testing
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLValidatesStructure(t *testing.T) {
|
||||
vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`))
|
||||
for _, raw := range []string{
|
||||
"http://user:password@127.0.0.1:8080", "https://proxy.example:8443",
|
||||
"socks4://127.0.0.1:1080", "socks4a://proxy.example:1080",
|
||||
"socks5://user:password@127.0.0.1:1080", "socks5h://user:password@proxy.example:1080",
|
||||
"trojan://password@proxy.example:443?security=tls&sni=edge.example#remark",
|
||||
"vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example#remark",
|
||||
"ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark",
|
||||
vmess,
|
||||
} {
|
||||
value, err := NormalizeProxyURL(raw)
|
||||
if err != nil || value == "" {
|
||||
t.Fatalf("valid proxy %q = %q, err = %v", raw, value, err)
|
||||
}
|
||||
}
|
||||
for _, invalid := range []string{"file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes"} {
|
||||
for _, invalid := range []string{
|
||||
"file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes",
|
||||
"vless://uuid@127.0.0.1:443?encryption=none&flow=xtls-rprx-vision#remark",
|
||||
"ss://base64#remark", "vmess://base64#remark", "hysteria://127.0.0.1:443",
|
||||
"hysteria2://127.0.0.1:443", "tuic://user:pass@127.0.0.1:443", "tuicv5://user:pass@127.0.0.1:443",
|
||||
} {
|
||||
if _, err := NormalizeProxyURL(invalid); err == nil {
|
||||
t.Fatalf("invalid proxy accepted: %q", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) {
|
||||
base := "trojan://password@proxy.example:443?security=tls&sni=edge.example"
|
||||
one, err := NormalizeProxyURL(base + "#one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, err := NormalizeProxyURL(base + "#two")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if one != two || strings.Contains(one, "#") {
|
||||
t.Fatalf("normalized tunnel identities = %q and %q", one, two)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLAllowsAccountPlaceholderOnlyInUsername(t *testing.T) {
|
||||
value, err := NormalizeProxyURL("socks5h://Default.{account}:token@resin:2260")
|
||||
if err != nil {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
_ "github.com/bdandy/go-socks4"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
@@ -163,8 +164,14 @@ func subscriptionTransport(viaProxy string) (*http.Transport, error) {
|
||||
return nil, fmt.Errorf("创建订阅拉取 SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = subscriptionProxyDialContext(dialer)
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
dialer, err := tunnelproxy.NewDialer(viaProxy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建订阅拉取隧道代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialer.DialContext
|
||||
default:
|
||||
return nil, errors.New("订阅拉取代理协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5")
|
||||
return nil, errors.New("订阅拉取代理协议不受支持")
|
||||
}
|
||||
return transport, nil
|
||||
}
|
||||
@@ -361,7 +368,7 @@ func parseProxySubscription(value string) ([]subscriptionEntry, int, error) {
|
||||
return entries, decodedSkipped, nil
|
||||
}
|
||||
}
|
||||
return nil, skipped, errors.New("订阅中没有可用的 HTTP 或 SOCKS 代理")
|
||||
return nil, skipped, errors.New("订阅中没有可用的代理节点")
|
||||
}
|
||||
|
||||
func parseProxyLines(value string) ([]subscriptionEntry, int) {
|
||||
|
||||
@@ -76,6 +76,30 @@ func TestParseProxySubscriptionRejectsNoUsableEntries(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) {
|
||||
vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`))
|
||||
entries, skipped, err := parseProxySubscription(strings.Join([]string{
|
||||
"http://proxy.example:8080",
|
||||
"trojan://password@proxy.example:443#remark",
|
||||
"vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none#remark",
|
||||
"ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark",
|
||||
vmess,
|
||||
"hysteria2://proxy.example:443",
|
||||
"tuic://user:pass@proxy.example:443",
|
||||
}, "\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 5 || skipped != 2 || entries[0].ProxyURL != "http://proxy.example:8080" {
|
||||
t.Fatalf("entries=%#v skipped=%d", entries, skipped)
|
||||
}
|
||||
for _, entry := range entries[1:] {
|
||||
if strings.Contains(entry.ProxyURL, "#") {
|
||||
t.Fatalf("subscription remark was retained: %q", entry.ProxyURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPublicAddressRejectsNonPublicRanges(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"0.0.0.1", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.10.1",
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
accountapp "github.com/chenyme/grok2api/backend/internal/application/account"
|
||||
@@ -64,6 +65,8 @@ type ListFilter struct {
|
||||
Sort repository.SortQuery
|
||||
}
|
||||
|
||||
type SyncProgressObserver func(completed, total int)
|
||||
|
||||
// Service 负责上游模型发现、内部来源路由与对外模型名称维护。
|
||||
type Service struct {
|
||||
models repository.ModelRepository
|
||||
@@ -404,8 +407,13 @@ func (s *Service) BatchSetEnabled(ctx context.Context, ids []uint64, enabled boo
|
||||
|
||||
// Sync 从全部启用账号同步模型能力,并按 Provider 幂等更新公开路由表。
|
||||
func (s *Service) Sync(ctx context.Context) (int, error) {
|
||||
return s.SyncObserved(ctx, nil)
|
||||
}
|
||||
|
||||
// SyncObserved 执行全量模型同步,并按已完成账号数报告进度。
|
||||
func (s *Service) SyncObserved(ctx context.Context, observer SyncProgressObserver) (int, error) {
|
||||
result := s.syncAll.DoChan("all", func() (any, error) {
|
||||
return s.syncAllAccounts(ctx)
|
||||
return s.syncAllAccounts(ctx, observer)
|
||||
})
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -418,7 +426,7 @@ func (s *Service) Sync(ctx context.Context) (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) syncAllAccounts(ctx context.Context) (int, error) {
|
||||
func (s *Service) syncAllAccounts(ctx context.Context, observer SyncProgressObserver) (int, error) {
|
||||
if s.providers == nil {
|
||||
return 0, fmt.Errorf("Provider 注册表未初始化")
|
||||
}
|
||||
@@ -437,12 +445,20 @@ func (s *Service) syncAllAccounts(ctx context.Context) (int, error) {
|
||||
if len(credentials) == 0 {
|
||||
return 0, fmt.Errorf("没有可用于模型同步的账号")
|
||||
}
|
||||
results, summary, runErr := batch.Map(ctx, credentials, batch.Options{Workers: s.bulkPool.Limit(), Pool: s.bulkPool}, func(workCtx context.Context, value account.Credential) ([]string, error) {
|
||||
if observer != nil {
|
||||
observer(0, len(credentials))
|
||||
}
|
||||
var completed atomic.Int64
|
||||
results, summary, runErr := batch.MapObserved(ctx, credentials, batch.Options{Workers: s.bulkPool.Limit(), Pool: s.bulkPool}, func(workCtx context.Context, value account.Credential) ([]string, error) {
|
||||
adapter, ok := s.providers.Models(value.Provider)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Provider %s 未注册模型同步能力", value.Provider)
|
||||
}
|
||||
return s.syncAccountCapabilities(workCtx, value, adapter)
|
||||
}, func(_ int, _ batch.Result[[]string]) {
|
||||
if observer != nil {
|
||||
observer(int(completed.Add(1)), len(credentials))
|
||||
}
|
||||
})
|
||||
pool := s.bulkPool.Snapshot()
|
||||
s.logger.Info("model_bulk_sync_completed", "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", pool.Limit, "pool_active", pool.Active, "pool_queued", pool.Queued, "pool_peak", pool.Peak, "error", runErr)
|
||||
|
||||
@@ -58,6 +58,9 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) {
|
||||
input.Frontend.PublicAPIBaseURL = "https://public.example.com"
|
||||
input.ProviderConsole.BaseURL = "https://console.example.com"
|
||||
input.ProviderConsole.ChatTimeout = "6m"
|
||||
input.ProviderWeb.ClearanceProvided = true
|
||||
input.ProviderWeb.ClearanceMode = config.ClearanceModeOnDemand
|
||||
input.ProviderWeb.FlareSolverrURL = "http://flaresolverr:8191"
|
||||
input.Batch = BatchConfig{ImportConcurrency: 26, ConversionConcurrency: 27, SyncConcurrency: 28, RefreshConcurrency: 29, RandomDelay: "750ms"}
|
||||
|
||||
snapshot, err := service.Update(context.Background(), service.Get().Revision, input)
|
||||
@@ -85,6 +88,9 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) {
|
||||
if applied.Provider.Console.BaseURL != "https://console.example.com" || applied.Provider.Console.ChatTimeout.Value() != 6*time.Minute {
|
||||
t.Fatalf("console configuration was not applied: %#v", applied.Provider.Console)
|
||||
}
|
||||
if applied.Provider.Web.ClearanceMode != config.ClearanceModeOnDemand || applied.Provider.Web.FlareSolverrURL != "http://flaresolverr:8191" {
|
||||
t.Fatalf("on-demand Clearance configuration was not applied: %#v", applied.Provider.Web)
|
||||
}
|
||||
if len(snapshot.RestartRequired) != 1 || snapshot.RestartRequired[0] != "audit.bufferSize" {
|
||||
t.Fatalf("restartRequired = %#v", snapshot.RestartRequired)
|
||||
}
|
||||
@@ -92,7 +98,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Provider.Build.ResponseHeaderTimeout.Value() != 7*time.Minute || reloaded.Routing.MaxAttempts != 5 || !reloaded.Routing.PreferFreeBuild || !reloaded.Routing.SegmentedSelectorEnabled || reloaded.Routing.SegmentedMinCandidates != 5000 || reloaded.Routing.SegmentedWindowSize != 96 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" {
|
||||
if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Provider.Build.ResponseHeaderTimeout.Value() != 7*time.Minute || reloaded.Routing.MaxAttempts != 5 || !reloaded.Routing.PreferFreeBuild || !reloaded.Routing.SegmentedSelectorEnabled || reloaded.Routing.SegmentedMinCandidates != 5000 || reloaded.Routing.SegmentedWindowSize != 96 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" || reloaded.Provider.Web.ClearanceMode != config.ClearanceModeOnDemand {
|
||||
t.Fatalf("configuration was not persisted")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package audit
|
||||
|
||||
const (
|
||||
DegradeClassBurst = "buffered_burst"
|
||||
DegradeClassSoft = "soft_tps"
|
||||
DegradeClassHard = "hard_tps"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultDegradeSoftTPS = 500.0
|
||||
DefaultDegradeHardTPS = 1000.0
|
||||
DefaultDegradeMinGenMS = int64(1000)
|
||||
DefaultDegradeMinOutput = int64(32)
|
||||
)
|
||||
|
||||
// ClassifyOutputSpeed matches the quality-guard panel formula:
|
||||
// output tokens / (durationMs - firstTokenMs). In fail-closed mode, short
|
||||
// generation windows with a soft-or-higher rate are buffered_burst; otherwise
|
||||
// the hard and soft thresholds apply in that order.
|
||||
func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64, failClosed bool) (class string, tps float64, genMS int64) {
|
||||
genMS = durationMS - firstTokenMS
|
||||
if genMS <= 0 || outputTokens <= 0 {
|
||||
return "", 0, genMS
|
||||
}
|
||||
tps = float64(outputTokens) * 1000 / float64(genMS)
|
||||
if failClosed && minGenMS > 0 && genMS < minGenMS && tps >= softTPS {
|
||||
return DegradeClassBurst, tps, genMS
|
||||
}
|
||||
if tps >= hardTPS {
|
||||
return DegradeClassHard, tps, genMS
|
||||
}
|
||||
if tps >= softTPS {
|
||||
return DegradeClassSoft, tps, genMS
|
||||
}
|
||||
return "", tps, genMS
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package audit
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestClassifyOutputSpeed(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
output, first, duration int64
|
||||
soft, hard float64
|
||||
minGen int64
|
||||
failClosed bool
|
||||
wantClass string
|
||||
}{
|
||||
{name: "hard", output: 2000, first: 200, duration: 1200, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard},
|
||||
{name: "soft", output: 600, first: 200, duration: 1400, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassSoft},
|
||||
{name: "short window follows hard threshold by default", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard},
|
||||
{name: "burst short window when fail closed", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, failClosed: true, wantClass: DegradeClassBurst},
|
||||
{name: "healthy", output: 100, first: 200, duration: 2200, soft: 500, hard: 1000, minGen: 1000, wantClass: ""},
|
||||
{name: "zero generation", output: 100, first: 500, duration: 500, soft: 500, hard: 1000, minGen: 1000, wantClass: ""},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen, test.failClosed)
|
||||
if class != test.wantClass {
|
||||
t.Fatalf("class = %q, want %q", class, test.wantClass)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,12 +37,14 @@ var reasoningEffortSuffixes = []string{
|
||||
// generally accepted by the model family. Provider-specific wire restrictions are
|
||||
// applied by providerReasoningEffortOverrides:
|
||||
// - grok-4.5: low/medium/high (reasoning cannot be disabled; no xhigh/max)
|
||||
// - grok-4.6: low/medium/high/xhigh (xhigh is a real upstream effort; max stays guarded)
|
||||
// - grok-4.3: none/low/medium/high
|
||||
// - grok-4.20-multi-agent: low/medium/high/xhigh (effort controls agent count)
|
||||
//
|
||||
// Unknown models default to none-only and never expand into effort aliases.
|
||||
var grokReasoningCapabilities = map[string][]string{
|
||||
"grok-4.5": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh},
|
||||
"grok-4.6": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh},
|
||||
"grok-4.3": {ReasoningEffortNone, ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh},
|
||||
"grok-build-0.1": {ReasoningEffortNone},
|
||||
"grok-4.20-0309-reasoning": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh},
|
||||
|
||||
@@ -17,6 +17,9 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) {
|
||||
{model: "grok-4.20-0309-reasoning", want: []string{"low", "medium", "high"}},
|
||||
{model: "Console/grok-4.20-0309-reasoning", want: []string{}},
|
||||
{model: "grok-4.20-multi-agent-0309", want: []string{"low", "medium", "high", "xhigh"}},
|
||||
{model: "grok-4.6", want: []string{"low", "medium", "high", "xhigh"}},
|
||||
{model: "Build/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}},
|
||||
{model: "Console/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}},
|
||||
{model: "grok-build-0.1", want: []string{"none"}},
|
||||
{model: GrokComposer25Fast, want: []string{"none"}},
|
||||
{model: "unknown-model", want: []string{"none"}},
|
||||
@@ -38,6 +41,16 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) {
|
||||
if !SupportsReasoningEffort("grok-4.3", "none") || SupportsReasoningEffort("grok-4.3", "xhigh") {
|
||||
t.Fatal("grok-4.3 effort support mismatch")
|
||||
}
|
||||
if !SupportsReasoningEffort("grok-4.6", "xhigh") || !SupportsReasoningEffort("Build/grok-4.6-xhigh", "xhigh") {
|
||||
t.Fatal("grok-4.6 must advertise xhigh")
|
||||
}
|
||||
if !SupportsReasoningEffortForProvider(account.ProviderBuild, "grok-4.6", "xhigh") ||
|
||||
!SupportsReasoningEffortForProvider(account.ProviderConsole, "grok-4.6", "xhigh") {
|
||||
t.Fatal("grok-4.6 xhigh must remain available through Build and Console")
|
||||
}
|
||||
if SupportsReasoningEffort("grok-4.6", "none") || SupportsReasoningEffort("grok-4.6", "max") {
|
||||
t.Fatal("grok-4.6 must not advertise none/max")
|
||||
}
|
||||
if SupportsReasoningEffortForProvider(account.ProviderConsole, "grok-4.20-0309-reasoning", "low") ||
|
||||
!SupportsReasoningEffortForProvider(account.ProviderBuild, "grok-4.20-0309-reasoning", "low") {
|
||||
t.Fatal("grok-4.20 reasoning effort restriction must remain Console-specific")
|
||||
@@ -74,6 +87,8 @@ func TestParseReasoningModelAlias(t *testing.T) {
|
||||
{name: "grok-4.5 rejects xhigh", input: "grok-4.5-xhigh", wantOK: false},
|
||||
{name: "grok-4.3 none", input: "grok-4.3-none", wantBase: "grok-4.3", wantLevel: "none", wantOK: true},
|
||||
{name: "xhigh before high", input: "grok-4.20-multi-agent-0309-xhigh", wantBase: "grok-4.20-multi-agent-0309", wantLevel: "xhigh", wantOK: true},
|
||||
{name: "grok-4.6 xhigh", input: "grok-4.6-xhigh", wantBase: "grok-4.6", wantLevel: "xhigh", wantOK: true},
|
||||
{name: "grok-4.6 rejects max", input: "grok-4.6-max", wantOK: false},
|
||||
{name: "prefixed base", input: "Build/grok-4.5-medium", wantBase: "Build/grok-4.5", wantLevel: "medium", wantOK: true},
|
||||
{name: "base model not alias", input: "grok-4.5", wantOK: false},
|
||||
{name: "single-level model no alias", input: "grok-build-0.1-none", wantOK: false},
|
||||
@@ -94,6 +109,9 @@ func TestReasoningAliasPublicIDs(t *testing.T) {
|
||||
if got := ReasoningAliasPublicIDs("grok-4.5"); len(got) != 3 || got[0] != "grok-4.5-low" || got[2] != "grok-4.5-high" {
|
||||
t.Fatalf("grok-4.5 aliases = %#v", got)
|
||||
}
|
||||
if got := ReasoningAliasPublicIDs("grok-4.6"); len(got) != 4 || got[0] != "grok-4.6-low" || got[3] != "grok-4.6-xhigh" {
|
||||
t.Fatalf("grok-4.6 aliases = %#v", got)
|
||||
}
|
||||
if got := ReasoningAliasPublicIDs("Build/grok-4.3"); len(got) != 4 || got[0] != "grok-4.3-none" {
|
||||
t.Fatalf("grok-4.3 aliases = %#v", got)
|
||||
}
|
||||
@@ -106,4 +124,7 @@ func TestReasoningAliasPublicIDs(t *testing.T) {
|
||||
if got := ReasoningAliasPublicIDsForProvider(account.ProviderBuild, "grok-4.20-0309-reasoning"); len(got) != 3 {
|
||||
t.Fatalf("Console restriction leaked into Build aliases: %#v", got)
|
||||
}
|
||||
if got := ReasoningAliasPublicIDsForProvider(account.ProviderConsole, "grok-4.6"); len(got) != 4 || got[3] != "grok-4.6-xhigh" {
|
||||
t.Fatalf("Console grok-4.6 aliases = %#v", got)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ const (
|
||||
StatsigModeURL = "url"
|
||||
ClearanceModeManual = "manual"
|
||||
ClearanceModeFlareSolverr = "flaresolverr"
|
||||
ClearanceModeOnDemand = "on_demand"
|
||||
DefaultStatsigSignerURL = "https://grok.wodf.de/sign"
|
||||
DefaultFlareSolverrURL = "http://flaresolverr:8191"
|
||||
RecommendedBuildClientVersion = "0.2.119"
|
||||
@@ -567,12 +568,12 @@ func (c Config) Validate() error {
|
||||
}
|
||||
switch c.Provider.Web.ClearanceMode {
|
||||
case ClearanceModeManual:
|
||||
case ClearanceModeFlareSolverr:
|
||||
case ClearanceModeFlareSolverr, ClearanceModeOnDemand:
|
||||
if err := validateFlareSolverrURL(c.Provider.Web.FlareSolverrURL); err != nil {
|
||||
return fmt.Errorf("provider.web FlareSolverr URL 无效: %w", err)
|
||||
}
|
||||
default:
|
||||
return errors.New("provider.web Clearance 模式必须是 manual 或 flaresolverr")
|
||||
return errors.New("provider.web Clearance 模式必须是 manual、flaresolverr 或 on_demand")
|
||||
}
|
||||
if c.Provider.Web.ClearanceTimeout.Value() < 10*time.Second || c.Provider.Web.ClearanceTimeout.Value() > 5*time.Minute {
|
||||
return errors.New("provider.web Clearance 超时必须在 10 秒到 5 分钟之间")
|
||||
|
||||
@@ -501,6 +501,17 @@ func TestValidateStatsigModes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateOnDemandClearance(t *testing.T) {
|
||||
base := defaultConfig()
|
||||
base.Secrets.JWTSecret = "12345678901234567890123456789012"
|
||||
base.Secrets.CredentialEncryptionKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
|
||||
base.Provider.Web.ClearanceMode = ClearanceModeOnDemand
|
||||
base.Provider.Web.FlareSolverrURL = "http://flaresolverr:8191"
|
||||
if err := base.Validate(); err != nil {
|
||||
t.Fatalf("valid on-demand Clearance rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFlareSolverrClearance(t *testing.T) {
|
||||
base := defaultConfig()
|
||||
base.Secrets.JWTSecret = "12345678901234567890123456789012"
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
_ "github.com/bdandy/go-socks4"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
@@ -58,6 +59,12 @@ func newBuildClientWithOptions(proxyURL string, responseHeaderTimeout time.Durat
|
||||
return nil, fmt.Errorf("创建 Grok Build SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialContext(dialer)
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
dialer, err := tunnelproxy.NewDialer(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建 Grok Build 隧道代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialer.DialContext
|
||||
default:
|
||||
return nil, fmt.Errorf("Grok Build 不支持代理协议 %q", parsed.Scheme)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
application "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
|
||||
@@ -123,6 +125,39 @@ func TestNewBuildClientRejectsUnsupportedProxyScheme(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatedProxySchemesCreateBuildAndBrowserClients(t *testing.T) {
|
||||
vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`))
|
||||
for _, raw := range []string{
|
||||
"http://user:password@127.0.0.1:8080",
|
||||
"https://proxy.example:8443",
|
||||
"socks4://127.0.0.1:1080",
|
||||
"socks4a://proxy.example:1080",
|
||||
"socks5://user:password@127.0.0.1:1080",
|
||||
"socks5h://user:password@proxy.example:1080",
|
||||
"trojan://password@proxy.example:443?security=tls&sni=edge.example",
|
||||
"vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example",
|
||||
"ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388",
|
||||
vmess,
|
||||
} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
normalized, err := application.NormalizeProxyURL(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
build, err := newBuildClient(normalized, 5*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("build client: %v", err)
|
||||
}
|
||||
build.CloseIdleConnections()
|
||||
browser, err := newBrowserClient(normalized, DefaultUserAgent)
|
||||
if err != nil {
|
||||
t.Fatalf("browser client: %v", err)
|
||||
}
|
||||
browser.CloseIdleConnections()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildClientRoutesThroughSOCKS5HWithRemoteDNS(t *testing.T) {
|
||||
target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Header.Get("User-Agent") != "grok-shell/0.2.102 (linux; x86_64)" {
|
||||
|
||||
@@ -14,12 +14,14 @@ import (
|
||||
"time"
|
||||
|
||||
application "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
)
|
||||
|
||||
const maxFlareSolverrResponseBytes = 2 << 20
|
||||
|
||||
var (
|
||||
proxyCredentialPattern = regexp.MustCompile(`(?i)\b(https?|socks4a?|socks5h?)://[^\s/@:]+:[^\s/@]+@`)
|
||||
tunnelCredentialPattern = regexp.MustCompile(`(?i)\b(?:trojan|vless)://[^\s/@]+@|\b(?:ss|vmess)://[^\s,;]+`)
|
||||
bearerCredentialPattern = regexp.MustCompile(`(?i)\bbearer\s+[a-z0-9._~+/=-]+`)
|
||||
namedCredentialPattern = regexp.MustCompile(`(?i)\b(token|password|passwd|authorization|cookie)\s*[:=]\s*[^\s,;]+`)
|
||||
)
|
||||
@@ -44,6 +46,9 @@ type clearanceSolver interface {
|
||||
type flaresolverrSolver struct{}
|
||||
|
||||
func (flaresolverrSolver) Solve(ctx context.Context, cfg ClearanceConfig, proxyURL string) (clearanceSolution, error) {
|
||||
if parsedProxy, parseErr := url.Parse(proxyURL); parseErr == nil && tunnelproxy.IsSupportedScheme(parsedProxy.Scheme) {
|
||||
return clearanceSolution{}, errors.New("FlareSolverr 暂不支持 Trojan、VLESS、SS 或 VMess 隧道代理")
|
||||
}
|
||||
endpoint, err := flaresolverrEndpoint(cfg.FlareSolverrURL)
|
||||
if err != nil {
|
||||
return clearanceSolution{}, err
|
||||
@@ -139,6 +144,7 @@ func sanitizeFlareSolverrMessage(value string) string {
|
||||
}
|
||||
return candidate[:separator+3] + "***:***@"
|
||||
})
|
||||
value = tunnelCredentialPattern.ReplaceAllString(value, "[redacted tunnel proxy]")
|
||||
value = bearerCredentialPattern.ReplaceAllString(value, "Bearer [redacted]")
|
||||
value = namedCredentialPattern.ReplaceAllString(value, "$1=[redacted]")
|
||||
characters := []rune(value)
|
||||
|
||||
@@ -60,6 +60,13 @@ func TestFlareSolverrSolveAcceptsNoChallengeWithoutCloudflareCookies(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlareSolverrSolveRejectsTunnelProxy(t *testing.T) {
|
||||
_, err := (flaresolverrSolver{}).Solve(context.Background(), ClearanceConfig{}, "trojan://secret@proxy.example:443")
|
||||
if err == nil || !strings.Contains(err.Error(), "FlareSolverr") {
|
||||
t.Fatalf("tunnel proxy error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) {
|
||||
for input, expected := range map[string]string{
|
||||
"http://flaresolverr:8191": "http://flaresolverr:8191/v1",
|
||||
@@ -74,8 +81,8 @@ func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSanitizeFlareSolverrMessageRedactsCredentials(t *testing.T) {
|
||||
message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value")
|
||||
for _, secret := range []string{"user", "secret", "abc123", "Bearer.SECRET", "sso-value"} {
|
||||
message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 and trojan://tunnel-secret@proxy.example:443 and vmess://base64-secret failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value")
|
||||
for _, secret := range []string{"user", "secret", "tunnel-secret", "base64-secret", "abc123", "Bearer.SECRET", "sso-value"} {
|
||||
if strings.Contains(message, secret) {
|
||||
t.Fatalf("sanitized message leaked %q: %q", secret, message)
|
||||
}
|
||||
|
||||
@@ -812,7 +812,8 @@ func decodeProbeIP(body []byte) (string, error) {
|
||||
|
||||
func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity string, allowDirect bool, encryptedCredentialCookies string, boundNodeID uint64) (*Lease, bool, error) {
|
||||
now := time.Now().UTC()
|
||||
managedClearance := isGrokWebScope(scope) && m.clearanceMode() == "flaresolverr"
|
||||
clearanceMode := m.clearanceMode()
|
||||
managedClearance := isGrokWebScope(scope) && (clearanceMode == "flaresolverr" || clearanceMode == "on_demand")
|
||||
configured := false
|
||||
var available []domain.Node
|
||||
if boundNodeID != 0 {
|
||||
@@ -1817,7 +1818,14 @@ func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyUR
|
||||
state.lastUsedAt = now
|
||||
m.clearances[key] = state
|
||||
}
|
||||
if cfg.Mode != "flaresolverr" {
|
||||
if cfg.Mode == "on_demand" && !forceRefresh {
|
||||
m.clearanceMu.Unlock()
|
||||
if fallbackAllowed {
|
||||
return fallback.Cookies, fallback.UserAgent, nil
|
||||
}
|
||||
return existingCookies, existingUserAgent, nil
|
||||
}
|
||||
if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" {
|
||||
m.clearanceMu.Unlock()
|
||||
return existingCookies, existingUserAgent, nil
|
||||
}
|
||||
@@ -1843,7 +1851,7 @@ func (m *Manager) refreshNode(ctx context.Context, node domain.Node, proxyURL, k
|
||||
solver := m.solver
|
||||
lock := m.clearanceLock
|
||||
m.clearanceMu.Unlock()
|
||||
if cfg.Mode != "flaresolverr" {
|
||||
if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" {
|
||||
return clearanceSolution{}, errors.New("FlareSolverr Clearance 未启用")
|
||||
}
|
||||
timeout := cfg.Timeout
|
||||
@@ -1874,8 +1882,12 @@ func (m *Manager) refreshNode(ctx context.Context, node domain.Node, proxyURL, k
|
||||
return clearanceSolution{}, errors.New("另一个实例正在刷新 Cloudflare Clearance")
|
||||
}
|
||||
defer release()
|
||||
if !force {
|
||||
if solution, refreshedAt, ok := m.loadPersistedClearance(ctx, node.ID, fingerprint, bindingFingerprint, interval); ok {
|
||||
if solution, refreshedAt, ok := m.loadPersistedClearance(ctx, node.ID, fingerprint, bindingFingerprint, interval); ok {
|
||||
// A peer may have refreshed the rejected Clearance immediately before
|
||||
// this instance acquired the distributed lock. Reuse that newer result
|
||||
// instead of performing a duplicate browser solve. A force refresh with
|
||||
// no newer persisted generation must still reach the solver.
|
||||
if !force || (!refreshAfter.IsZero() && refreshedAt.After(refreshAfter)) {
|
||||
m.cacheClearance(key, solution, refreshedAt, solveVersion, fingerprint, bindingFingerprint, interval)
|
||||
return solution, nil
|
||||
}
|
||||
|
||||
@@ -1846,6 +1846,169 @@ func TestWebForbiddenStillRebuildsBrowserSession(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandClearanceRefreshesOnlyAfterRejection(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cookies, err := cipher.Encrypt("cf_clearance=existing")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := &mutableEgressRepository{node: domain.Node{
|
||||
ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1,
|
||||
EncryptedCloudflareCookie: cookies, UserAgent: "Chrome/existing",
|
||||
}}
|
||||
solver := &clearanceSolverStub{}
|
||||
manager := NewManager(repository, cipher)
|
||||
manager.solver = solver
|
||||
manager.UpdateClearanceConfig(ClearanceConfig{Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com", Timeout: time.Second, RefreshInterval: time.Hour})
|
||||
|
||||
first, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if solver.calls != 0 || first.CFCookies != "cf_clearance=existing" {
|
||||
t.Fatalf("initial calls=%d cookies=%q", solver.calls, first.CFCookies)
|
||||
}
|
||||
first.InvalidateClearance()
|
||||
first.Release()
|
||||
|
||||
second, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer second.Release()
|
||||
if solver.calls != 1 || second.CFCookies != "cf_clearance=value-1" {
|
||||
t.Fatalf("refresh calls=%d cookies=%q", solver.calls, second.CFCookies)
|
||||
}
|
||||
stored, err := cipher.Decrypt(repository.node.EncryptedCloudflareCookie)
|
||||
if err != nil || stored != "cf_clearance=value-1" {
|
||||
t.Fatalf("stored cookies=%q err=%v", stored, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandClearanceSkipsBackgroundRefresh(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := &mutableEgressRepository{node: domain.Node{ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1}}
|
||||
solver := &clearanceSolverStub{}
|
||||
manager := NewManager(repository, cipher)
|
||||
manager.solver = solver
|
||||
manager.UpdateClearanceConfig(ClearanceConfig{Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com", Timeout: time.Second, RefreshInterval: time.Nanosecond})
|
||||
|
||||
if err := manager.RefreshDueClearances(context.Background(), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if solver.calls != 0 {
|
||||
t.Fatalf("background refresh called solver %d times", solver.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandClearanceKeepsLastSuccessfulDirectSolutionPastRefreshInterval(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
solver := &clearanceSolverStub{}
|
||||
manager := NewManager(egressRepositoryTestStub{}, cipher)
|
||||
manager.solver = solver
|
||||
manager.UpdateClearanceConfig(ClearanceConfig{
|
||||
Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com",
|
||||
Timeout: time.Second, RefreshInterval: time.Nanosecond,
|
||||
})
|
||||
|
||||
initial, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.CFCookies != "" || solver.calls != 0 {
|
||||
t.Fatalf("initial lease cookies=%q calls=%d", initial.CFCookies, solver.calls)
|
||||
}
|
||||
initial.InvalidateClearance()
|
||||
initial.Release()
|
||||
|
||||
refreshed, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refreshed.CFCookies != "cf_clearance=value-1" || solver.calls != 1 {
|
||||
t.Fatalf("refreshed lease cookies=%q calls=%d", refreshed.CFCookies, solver.calls)
|
||||
}
|
||||
refreshed.Release()
|
||||
|
||||
// The interval is deliberately expired. on_demand must keep using the last
|
||||
// successful runtime-only solution until an upstream rejection invalidates it.
|
||||
reused, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reused.Release()
|
||||
if reused.CFCookies != "cf_clearance=value-1" || reused.UserAgent != "Chrome/146 test" || solver.calls != 1 {
|
||||
t.Fatalf("reused lease=%#v calls=%d", reused, solver.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandClearanceReusesPeerRefreshAfterDistributedLock(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := ClearanceConfig{
|
||||
Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com",
|
||||
Timeout: time.Second, RefreshInterval: time.Hour,
|
||||
}
|
||||
oldCookies, err := cipher.Encrypt("cf_clearance=old")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldRefreshedAt := time.Now().UTC().Add(-time.Minute)
|
||||
repository := &mutableEgressRepository{node: domain.Node{
|
||||
ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1,
|
||||
EncryptedCloudflareCookie: oldCookies, UserAgent: "Chrome/old",
|
||||
ClearanceFingerprint: clearanceFingerprint(config, ""), ClearanceBindingFingerprint: clearanceBindingFingerprint(config, ""),
|
||||
ClearanceRefreshedAt: &oldRefreshedAt,
|
||||
}}
|
||||
solver := &clearanceSolverStub{}
|
||||
firstManager := NewManager(repository, cipher)
|
||||
firstManager.solver = solver
|
||||
firstManager.SetClearanceLock(alwaysAcquiredDistributedLock{})
|
||||
firstManager.UpdateClearanceConfig(config)
|
||||
secondManager := NewManager(repository, cipher)
|
||||
secondManager.solver = solver
|
||||
secondManager.SetClearanceLock(alwaysAcquiredDistributedLock{})
|
||||
secondManager.UpdateClearanceConfig(config)
|
||||
|
||||
firstOld, err := firstManager.Acquire(context.Background(), domain.ScopeConsole, "first")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondOld, err := secondManager.Acquire(context.Background(), domain.ScopeConsole, "second")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstOld.InvalidateClearance()
|
||||
secondOld.InvalidateClearance()
|
||||
firstOld.Release()
|
||||
secondOld.Release()
|
||||
|
||||
firstFresh, err := firstManager.Acquire(context.Background(), domain.ScopeConsole, "first")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstFresh.Release()
|
||||
secondFresh, err := secondManager.Acquire(context.Background(), domain.ScopeConsole, "second")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer secondFresh.Release()
|
||||
if solver.calls != 1 || secondFresh.CFCookies != "cf_clearance=value-1" {
|
||||
t.Fatalf("peer refresh was not reused: calls=%d cookies=%q", solver.calls, secondFresh.CFCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlareSolverrRefreshesRejectedNodeBeforeNextLease(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
@@ -81,6 +82,12 @@ func newPinnedHTTPSClient(proxyURL, serverName string, tlsConfig *tls.Config) (*
|
||||
return nil, fmt.Errorf("创建固定地址 SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialContext(dialer)
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
dialer, err := tunnelproxy.NewDialer(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建固定地址隧道代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialer.DialContext
|
||||
default:
|
||||
return nil, fmt.Errorf("固定地址请求不支持代理协议 %q", parsed.Scheme)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
"github.com/bogdanfinn/tls-client/profiles"
|
||||
"github.com/bogdanfinn/websocket"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
)
|
||||
|
||||
type browserClient struct{ inner tlsclient.HttpClient }
|
||||
@@ -62,7 +64,19 @@ func newBrowserClient(proxyURL, userAgent string) (*browserClient, error) {
|
||||
tlsclient.WithNotFollowRedirects(),
|
||||
}
|
||||
if proxyURL != "" {
|
||||
options = append(options, tlsclient.WithProxyUrl(proxyURL))
|
||||
parsed, err := url.Parse(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析浏览器出口代理: %w", err)
|
||||
}
|
||||
if tunnelproxy.IsSupportedScheme(parsed.Scheme) {
|
||||
dialer, err := tunnelproxy.NewDialer(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建浏览器隧道代理: %w", err)
|
||||
}
|
||||
options = append(options, tlsclient.WithDialContext(dialer.DialContext))
|
||||
} else {
|
||||
options = append(options, tlsclient.WithProxyUrl(proxyURL))
|
||||
}
|
||||
}
|
||||
client, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(), options...)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -683,6 +684,309 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type degradeTotalsRow struct {
|
||||
Hits int64 `gorm:"column:hits"`
|
||||
Accounts int64 `gorm:"column:accounts"`
|
||||
StillEnabled int64 `gorm:"column:still_enabled"`
|
||||
Disabled int64 `gorm:"column:disabled"`
|
||||
Deleted int64 `gorm:"column:deleted"`
|
||||
Hard int64 `gorm:"column:hard"`
|
||||
Soft int64 `gorm:"column:soft"`
|
||||
Burst int64 `gorm:"column:burst"`
|
||||
MaxTPS float64 `gorm:"column:max_tps"`
|
||||
}
|
||||
|
||||
type degradeAccountRow struct {
|
||||
ID uint64 `gorm:"column:id"`
|
||||
Name string `gorm:"column:name"`
|
||||
Email string `gorm:"column:email"`
|
||||
Hits int64 `gorm:"column:hits"`
|
||||
MaxTPS float64 `gorm:"column:max_tps"`
|
||||
Burst int64 `gorm:"column:burst"`
|
||||
Soft int64 `gorm:"column:soft"`
|
||||
Hard int64 `gorm:"column:hard"`
|
||||
Last degradeTimestamp `gorm:"column:last_seen"`
|
||||
Enabled bool `gorm:"column:enabled"`
|
||||
Found bool `gorm:"column:found"`
|
||||
BuildBotFlagSource int `gorm:"column:build_bot_flag_source"`
|
||||
}
|
||||
|
||||
type degradeTimestamp time.Time
|
||||
|
||||
func (value *degradeTimestamp) Scan(input any) error {
|
||||
parsed, err := parseDegradeTimestamp(input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*value = degradeTimestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseDegradeTimestamp(input any) (time.Time, error) {
|
||||
if parsed, ok := input.(time.Time); ok {
|
||||
return parsed, nil
|
||||
}
|
||||
var raw string
|
||||
switch value := input.(type) {
|
||||
case string:
|
||||
raw = value
|
||||
case []byte:
|
||||
raw = string(value)
|
||||
case nil:
|
||||
return time.Time{}, nil
|
||||
default:
|
||||
return time.Time{}, fmt.Errorf("unsupported degrade timestamp type %T", input)
|
||||
}
|
||||
for _, layout := range []string{
|
||||
time.RFC3339Nano,
|
||||
"2006-01-02 15:04:05.999999999-07:00",
|
||||
"2006-01-02 15:04:05.999999999Z07:00",
|
||||
"2006-01-02 15:04:05.999999999",
|
||||
"2006-01-02 15:04:05-07:00",
|
||||
"2006-01-02 15:04:05",
|
||||
} {
|
||||
parsed, err := time.Parse(layout, raw)
|
||||
if err == nil {
|
||||
return parsed, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("invalid degrade timestamp")
|
||||
}
|
||||
|
||||
type degradeNodeRow struct {
|
||||
Name string `gorm:"column:name"`
|
||||
Hits int64 `gorm:"column:hits"`
|
||||
Accounts int64 `gorm:"column:accounts"`
|
||||
MaxTPS float64 `gorm:"column:max_tps"`
|
||||
}
|
||||
|
||||
type degradeBucketRow struct {
|
||||
Index int `gorm:"column:bucket_index"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
Severe int64 `gorm:"column:severe"`
|
||||
}
|
||||
|
||||
type degradeAccountNodeRow struct {
|
||||
AccountID uint64 `gorm:"column:account_id"`
|
||||
Name string `gorm:"column:name"`
|
||||
}
|
||||
|
||||
type degradeEventRow struct {
|
||||
ID uint64 `gorm:"column:id"`
|
||||
RequestID string `gorm:"column:request_id"`
|
||||
AccountID *uint64 `gorm:"column:account_id"`
|
||||
AccountName string `gorm:"column:account_name"`
|
||||
EgressNodeID *uint64 `gorm:"column:egress_node_id"`
|
||||
EgressNodeName string `gorm:"column:egress_node_name"`
|
||||
OutputTokens int64 `gorm:"column:output_tokens"`
|
||||
TPS float64 `gorm:"column:tps"`
|
||||
Class string `gorm:"column:degrade_class"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
Model string `gorm:"column:model_upstream_model"`
|
||||
}
|
||||
|
||||
func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository.DegradeSummaryQuery) (repository.DegradeSummaryResult, error) {
|
||||
if input.AccountLimit <= 0 || input.AccountLimit > 100 {
|
||||
input.AccountLimit = 50
|
||||
}
|
||||
if input.AccountOffset < 0 {
|
||||
input.AccountOffset = 0
|
||||
}
|
||||
if input.RecentLimit <= 0 || input.RecentLimit > 200 {
|
||||
input.RecentLimit = 80
|
||||
}
|
||||
var result repository.DegradeSummaryResult
|
||||
err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
classified := r.degradeClassifiedQuery(tx, input)
|
||||
var totals degradeTotalsRow
|
||||
if err := tx.Table("(?) AS d", classified).
|
||||
Select(`COUNT(*) AS hits,
|
||||
COUNT(DISTINCT d.account_id) AS accounts,
|
||||
COUNT(DISTINCT CASE WHEN p.id IS NOT NULL AND p.enabled = TRUE THEN d.account_id END) AS still_enabled,
|
||||
COUNT(DISTINCT CASE WHEN p.id IS NOT NULL AND p.enabled = FALSE THEN d.account_id END) AS disabled,
|
||||
COUNT(DISTINCT CASE WHEN p.id IS NULL THEN d.account_id END) AS deleted,
|
||||
COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard,
|
||||
COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft,
|
||||
COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst,
|
||||
COALESCE(MAX(d.tps), 0) AS max_tps`).
|
||||
Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id").
|
||||
Scan(&totals).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Totals = repository.DegradeTotals{
|
||||
Hits: totals.Hits, Accounts: totals.Accounts, StillEnabled: totals.StillEnabled,
|
||||
Disabled: totals.Disabled, Deleted: totals.Deleted, Hard: totals.Hard, Soft: totals.Soft,
|
||||
Burst: totals.Burst, MaxTPS: totals.MaxTPS,
|
||||
}
|
||||
|
||||
accountQuery := r.degradeAccountAggregate(tx, classified, input)
|
||||
if err := tx.Table("(?) AS filtered_accounts", accountQuery).Count(&result.AccountTotal).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
accountOffset := input.AccountOffset
|
||||
if result.AccountTotal > 0 && int64(accountOffset) >= result.AccountTotal {
|
||||
accountOffset = int((result.AccountTotal-1)/int64(input.AccountLimit)) * input.AccountLimit
|
||||
}
|
||||
result.AccountOffset = accountOffset
|
||||
var accountRows []degradeAccountRow
|
||||
if err := accountQuery.Order("hits DESC, max_tps DESC, id ASC").
|
||||
Offset(accountOffset).Limit(input.AccountLimit).Scan(&accountRows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
accountIDs := make([]uint64, 0, len(accountRows))
|
||||
accountsByID := make(map[uint64]*repository.DegradeAccount, len(accountRows))
|
||||
result.Accounts = make([]repository.DegradeAccount, 0, len(accountRows))
|
||||
for _, row := range accountRows {
|
||||
result.Accounts = append(result.Accounts, repository.DegradeAccount{
|
||||
ID: row.ID, Name: row.Name, Email: row.Email, Hits: row.Hits, MaxTPS: row.MaxTPS,
|
||||
Burst: row.Burst, Soft: row.Soft, Hard: row.Hard, Last: time.Time(row.Last), Enabled: row.Enabled,
|
||||
Found: row.Found, BuildBotFlagSource: row.BuildBotFlagSource,
|
||||
})
|
||||
accountIDs = append(accountIDs, row.ID)
|
||||
accountsByID[row.ID] = &result.Accounts[len(result.Accounts)-1]
|
||||
}
|
||||
if len(accountIDs) > 0 {
|
||||
var nodeRows []degradeAccountNodeRow
|
||||
if err := tx.Table("(?) AS d", classified).
|
||||
Select("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name").
|
||||
Where("d.account_id IN ?", accountIDs).
|
||||
Group("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?')").
|
||||
Order("d.account_id ASC, name ASC").Scan(&nodeRows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range nodeRows {
|
||||
if account := accountsByID[row.AccountID]; account != nil {
|
||||
account.Nodes = append(account.Nodes, row.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var nodeRows []degradeNodeRow
|
||||
if err := tx.Table("(?) AS d", classified).
|
||||
Select("COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name, COUNT(*) AS hits, COUNT(DISTINCT d.account_id) AS accounts, COALESCE(MAX(d.tps), 0) AS max_tps").
|
||||
Group("COALESCE(NULLIF(d.egress_node_name, ''), '?')").Order("hits DESC, name ASC").Scan(&nodeRows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Nodes = make([]repository.DegradeNode, 0, len(nodeRows))
|
||||
for _, row := range nodeRows {
|
||||
result.Nodes = append(result.Nodes, repository.DegradeNode{Name: row.Name, Hits: row.Hits, Accounts: row.Accounts, MaxTPS: row.MaxTPS})
|
||||
}
|
||||
|
||||
if len(input.Buckets) > 0 {
|
||||
caseSQL, caseArgs := degradeBucketCase(input.Buckets)
|
||||
bucketed := tx.Table("(?) AS d", classified).Select(caseSQL+" AS bucket_index, d.degrade_class", caseArgs...)
|
||||
var bucketRows []degradeBucketRow
|
||||
if err := tx.Table("(?) AS b", bucketed).
|
||||
Select("b.bucket_index, COUNT(*) AS count, COALESCE(SUM(CASE WHEN b.degrade_class IN ('hard_tps', 'buffered_burst') THEN 1 ELSE 0 END), 0) AS severe").
|
||||
Where("b.bucket_index >= 0").Group("b.bucket_index").Order("b.bucket_index ASC").Scan(&bucketRows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Buckets = make([]repository.DegradeBucket, 0, len(bucketRows))
|
||||
for _, row := range bucketRows {
|
||||
result.Buckets = append(result.Buckets, repository.DegradeBucket{Index: row.Index, Count: row.Count, Severe: row.Severe})
|
||||
}
|
||||
}
|
||||
|
||||
var eventRows []degradeEventRow
|
||||
if err := tx.Table("(?) AS d", classified).
|
||||
Select("d.id, d.request_id, d.account_id, d.account_name, d.egress_node_id, d.egress_node_name, d.output_tokens, d.tps, d.degrade_class, d.created_at, d.model_upstream_model").
|
||||
Order("d.created_at DESC, d.id DESC").Limit(input.RecentLimit).Scan(&eventRows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Events = make([]repository.DegradeEvent, 0, len(eventRows))
|
||||
for _, row := range eventRows {
|
||||
result.Events = append(result.Events, repository.DegradeEvent{
|
||||
ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName,
|
||||
EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, OutputTokens: row.OutputTokens,
|
||||
TPS: row.TPS, Class: row.Class, CreatedAt: row.CreatedAt, Model: row.Model,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (r *AuditRepository) degradeClassifiedQuery(tx *gorm.DB, input repository.DegradeSummaryQuery) *gorm.DB {
|
||||
castType := "REAL"
|
||||
if r.db.dialect == "postgres" {
|
||||
castType = "DOUBLE PRECISION"
|
||||
}
|
||||
generationExpression := "(a.duration_ms - a.first_token_ms)"
|
||||
// NULLIF keeps PostgreSQL safe even if its planner evaluates the throughput
|
||||
// expression before the duration guard in the WHERE clause.
|
||||
tpsExpression := fmt.Sprintf("(CAST(a.output_tokens AS %s) * 1000.0 / NULLIF(%s, 0))", castType, generationExpression)
|
||||
classExpression := fmt.Sprintf("CASE WHEN ? AND %s < ? THEN ? WHEN %s >= ? THEN ? ELSE ? END", generationExpression, tpsExpression)
|
||||
query := tx.Table("request_audits AS a").
|
||||
Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.created_at, a.model_upstream_model, "+tpsExpression+" AS tps, "+classExpression+" AS degrade_class",
|
||||
input.FailClosed, input.MinGenerationMS, audit.DegradeClassBurst, input.HardTPS, audit.DegradeClassHard, audit.DegradeClassSoft).
|
||||
Where("a.provider = ?", "grok_build").Where("a.streaming = ?", true).
|
||||
Where(auditSuccessPredicate).Where("a.output_tokens >= ?", input.MinOutputTokens).
|
||||
Where("a.first_token_ms IS NOT NULL").Where("a.duration_ms > a.first_token_ms").
|
||||
Where("a.request_id NOT LIKE ?", "quality_%").Where(tpsExpression+" >= ?", input.SoftTPS)
|
||||
if !input.Start.IsZero() {
|
||||
query = query.Where("a.created_at >= ?", input.Start)
|
||||
}
|
||||
if !input.End.IsZero() {
|
||||
query = query.Where("a.created_at < ?", input.End)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func (r *AuditRepository) degradeAccountAggregate(tx *gorm.DB, classified *gorm.DB, input repository.DegradeSummaryQuery) *gorm.DB {
|
||||
query := tx.Table("(?) AS d", classified).
|
||||
Select(`d.account_id AS id,
|
||||
COALESCE(NULLIF(p.name, ''), MAX(d.account_name), '') AS name,
|
||||
COALESCE(p.email, '') AS email,
|
||||
COUNT(*) AS hits,
|
||||
COALESCE(MAX(d.tps), 0) AS max_tps,
|
||||
COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst,
|
||||
COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft,
|
||||
COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard,
|
||||
MAX(d.created_at) AS last_seen,
|
||||
COALESCE(p.enabled, FALSE) AS enabled,
|
||||
CASE WHEN p.id IS NULL THEN FALSE ELSE TRUE END AS found,
|
||||
COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source`).
|
||||
Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id").
|
||||
Joins("LEFT JOIN account_credentials c ON c.account_id = d.account_id").
|
||||
Where("d.account_id IS NOT NULL").
|
||||
Group("d.account_id, p.id, p.name, p.email, p.enabled, c.build_bot_flag_source")
|
||||
if search := strings.TrimSpace(input.AccountSearch); search != "" {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where(
|
||||
"LOWER(COALESCE(p.email, '')) LIKE ? OR LOWER(COALESCE(p.name, '')) LIKE ? OR LOWER(COALESCE(d.account_name, '')) LIKE ? OR CAST(d.account_id AS TEXT) LIKE ?",
|
||||
pattern, pattern, pattern, pattern,
|
||||
)
|
||||
}
|
||||
switch input.AccountStatus {
|
||||
case "enabled":
|
||||
query = query.Where("p.id IS NOT NULL AND p.enabled = TRUE")
|
||||
case "disabled":
|
||||
query = query.Where("p.id IS NOT NULL AND p.enabled = FALSE")
|
||||
case "deleted":
|
||||
query = query.Where("p.id IS NULL")
|
||||
}
|
||||
if input.MinHits > 1 {
|
||||
query = query.Having("COUNT(*) >= ?", input.MinHits)
|
||||
}
|
||||
if input.AccountClass != "" {
|
||||
query = query.Having("SUM(CASE WHEN d.degrade_class = ? THEN 1 ELSE 0 END) > 0", input.AccountClass)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func degradeBucketCase(buckets []repository.DegradeBucketRange) (string, []any) {
|
||||
var builder strings.Builder
|
||||
args := make([]any, 0, len(buckets)*2)
|
||||
builder.WriteString("CASE")
|
||||
for index, bucket := range buckets {
|
||||
builder.WriteString(" WHEN d.created_at >= ? AND d.created_at < ? THEN ")
|
||||
builder.WriteString(strconv.Itoa(index))
|
||||
args = append(args, bucket.Start, bucket.End)
|
||||
}
|
||||
builder.WriteString(" ELSE -1 END")
|
||||
return builder.String(), args
|
||||
}
|
||||
|
||||
func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB {
|
||||
if value := strings.TrimSpace(search); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
|
||||
@@ -538,4 +538,15 @@ func TestAuditRepositoryStreamFailureKeepsHTTPStatusAndFiltersAsOther(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeTimestampScansPostgresTimeValue(t *testing.T) {
|
||||
expected := time.Date(2026, time.August, 14, 8, 30, 0, 123, time.UTC)
|
||||
var value degradeTimestamp
|
||||
if err := value.Scan(expected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual := time.Time(value); !actual.Equal(expected) {
|
||||
t.Fatalf("scanned timestamp = %s, want %s", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func uint64Pointer(value uint64) *uint64 { return &value }
|
||||
@@ -0,0 +1,79 @@
|
||||
package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
// Reproduces the reported behaviour: one alias collision inside a discovery
|
||||
// batch rolls back the whole transaction, so unrelated new models in the same
|
||||
// batch are silently dropped and can never be discovered again.
|
||||
//
|
||||
// Setup mirrors a real deployment: a route was renamed at some point, which
|
||||
// makes preserveModelRouteAlias register the old public ID as a compatibility
|
||||
// alias. Later the upstream catalog starts returning both the old model and a
|
||||
// brand new one.
|
||||
func TestUpsertDiscoveredAliasCollisionDropsWholeBatch(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "alias-batch.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
models := NewModelRepository(database)
|
||||
|
||||
// A discovered route exists under its original public ID.
|
||||
if err := models.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-4.5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
routes, _, err := models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 100}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var routeID uint64
|
||||
for _, route := range routes {
|
||||
if route.UpstreamModel == "grok-4.5" {
|
||||
routeID = route.ID
|
||||
}
|
||||
}
|
||||
if routeID == 0 {
|
||||
t.Fatalf("routes = %#v", routes)
|
||||
}
|
||||
|
||||
// Renaming it leaves "Build/grok-4.5" behind as a compatibility alias.
|
||||
existing, err := models.Get(ctx, routeID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
existing.PublicID = "Build/build-grok-4.5"
|
||||
if _, err := models.Update(ctx, existing, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Upstream now returns the old model plus a new one. The old model maps onto
|
||||
// the alias and conflicts; the new model does not.
|
||||
err = models.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-4.5", "grok-4.6"})
|
||||
t.Logf("UpsertDiscovered error = %v", err)
|
||||
|
||||
routes, _, listErr := models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 100}})
|
||||
if listErr != nil {
|
||||
t.Fatal(listErr)
|
||||
}
|
||||
found46 := false
|
||||
for _, route := range routes {
|
||||
if route.UpstreamModel == "grok-4.6" && route.Origin == model.OriginDiscovered {
|
||||
found46 = true
|
||||
}
|
||||
}
|
||||
if !found46 {
|
||||
t.Errorf("grok-4.6 was dropped because grok-4.5 collided with an alias in the same batch; routes = %#v", routes)
|
||||
}
|
||||
}
|
||||
@@ -705,7 +705,14 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account
|
||||
if publicIDs[key] {
|
||||
continue
|
||||
}
|
||||
// A discovered model whose canonical public ID is already reserved as
|
||||
// another route compatibility alias cannot be inserted. Skip it and
|
||||
// keep the rest of the batch: aborting here lets one historical rename
|
||||
// permanently hide every future model of this provider.
|
||||
if err := ensureModelPublicIDNotAlias(tx, publicID, 0); err != nil {
|
||||
if errors.Is(err, repository.ErrConflict) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
publicIDs[key] = true
|
||||
|
||||
@@ -90,6 +90,7 @@ var schemaIndexes = []string{
|
||||
"CREATE INDEX IF NOT EXISTS idx_audits_account_created_id ON request_audits(account_id, created_at DESC, id DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_audits_status_created_id ON request_audits(status_code, created_at DESC, id DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_audits_streaming_created_id ON request_audits(streaming, created_at DESC, id DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_audits_provider_streaming_created_id ON request_audits(provider, streaming, created_at DESC, id DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_audit_attempts_audit_number ON request_audit_attempts(audit_id, number)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_response_ownership_expires_id ON response_ownership(expires_at, response_id)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_response_ownership_account ON response_ownership(account_id)",
|
||||
|
||||
@@ -44,6 +44,8 @@ type Config struct {
|
||||
const (
|
||||
subscriptionTierTimeout = 10 * time.Second
|
||||
buildControlTimeout = 30 * time.Second
|
||||
buildGrok45Model = "grok-4.5"
|
||||
buildGrok46Model = "grok-4.6"
|
||||
)
|
||||
|
||||
// Adapter implements the Grok Build CLI Responses, model, Billing, and OAuth protocols.
|
||||
@@ -618,15 +620,17 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
|
||||
|
||||
// NormalizeAccountModelCapabilities normalizes capabilities that the OAuth
|
||||
// session contract exposes independently of the account's sparse /models list.
|
||||
// Composer is available to Build OAuth sessions even though the live catalog can
|
||||
// return only grok-4.5. Super always includes video 1.5; Free and Unknown remove
|
||||
// video 1.5 exactly. BuildAPIFallback is ignored.
|
||||
// Composer is available to Build OAuth sessions independently of the sparse
|
||||
// live catalog. Grok 4.6 sessions retain the still-supported Grok 4.5 route for
|
||||
// backwards compatibility. Super always includes video 1.5; Free and Unknown
|
||||
// remove video 1.5 exactly. BuildAPIFallback is ignored.
|
||||
func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string {
|
||||
super := account.IsBuildSuper(credential, billing)
|
||||
composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth
|
||||
result := make([]string, 0, len(models)+2)
|
||||
seen := make(map[string]struct{}, len(models)+2)
|
||||
hasVideo15 := false
|
||||
hasGrok46 := false
|
||||
for _, model := range models {
|
||||
model = strings.TrimSpace(model)
|
||||
if model == "" {
|
||||
@@ -641,9 +645,18 @@ func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *ac
|
||||
}
|
||||
hasVideo15 = true
|
||||
}
|
||||
if model == buildGrok46Model {
|
||||
hasGrok46 = true
|
||||
}
|
||||
seen[model] = struct{}{}
|
||||
result = append(result, model)
|
||||
}
|
||||
if credential.Provider == account.ProviderBuild && hasGrok46 {
|
||||
if _, exists := seen[buildGrok45Model]; !exists {
|
||||
seen[buildGrok45Model] = struct{}{}
|
||||
result = append(result, buildGrok45Model)
|
||||
}
|
||||
}
|
||||
if super && !hasVideo15 {
|
||||
result = append(result, buildVideoModel)
|
||||
}
|
||||
|
||||
@@ -628,6 +628,26 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAccountModelCapabilitiesKeepsGrok45ForBuildGrok46(t *testing.T) {
|
||||
adapter := &Adapter{}
|
||||
build := account.Credential{Provider: account.ProviderBuild}
|
||||
got := adapter.NormalizeAccountModelCapabilities([]string{buildGrok46Model}, nil, build)
|
||||
if len(got) != 2 || got[0] != buildGrok46Model || got[1] != buildGrok45Model {
|
||||
t.Fatalf("Build Grok 4.6 compatibility capabilities = %#v", got)
|
||||
}
|
||||
|
||||
got = adapter.NormalizeAccountModelCapabilities([]string{buildGrok45Model, buildGrok46Model, buildGrok45Model}, nil, build)
|
||||
if len(got) != 2 || got[0] != buildGrok45Model || got[1] != buildGrok46Model {
|
||||
t.Fatalf("Build Grok 4.5 compatibility was not deduplicated: %#v", got)
|
||||
}
|
||||
|
||||
console := account.Credential{Provider: account.ProviderConsole}
|
||||
got = adapter.NormalizeAccountModelCapabilities([]string{buildGrok46Model}, nil, console)
|
||||
if len(got) != 1 || got[0] != buildGrok46Model {
|
||||
t.Fatalf("Build compatibility leaked to Console: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokSessionIDFollowsConversationIdentity(t *testing.T) {
|
||||
explicit := "019f6b02-5bae-7cf3-b26e-73e85c861749"
|
||||
if value, err := grokSessionID(explicit); err != nil || value != explicit {
|
||||
|
||||
@@ -118,7 +118,9 @@ func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error
|
||||
|
||||
// normalizeBuildReasoningEffortPayload maps client aliases to levels accepted by
|
||||
// the selected Grok model. Grok 4.5 and unknown models retain the proven defensive
|
||||
// xhigh/max -> high behavior; explicitly supported xhigh models keep their value.
|
||||
// xhigh/max -> high behavior for models without an xhigh wire contract. Models
|
||||
// that explicitly support xhigh keep xhigh and map the client-only max alias to
|
||||
// that highest verified upstream level.
|
||||
func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, model string) bool {
|
||||
raw, exists := payload["reasoning"]
|
||||
if !exists || isEmptyJSON(raw) {
|
||||
@@ -156,7 +158,11 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo
|
||||
normalized = modeldomain.ReasoningEffortHigh
|
||||
}
|
||||
case "max":
|
||||
normalized = modeldomain.ReasoningEffortHigh
|
||||
if modeldomain.SupportsReasoningEffort(model, modeldomain.ReasoningEffortXHigh) {
|
||||
normalized = modeldomain.ReasoningEffortXHigh
|
||||
} else {
|
||||
normalized = modeldomain.ReasoningEffortHigh
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -52,8 +52,13 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) {
|
||||
{name: "4.5 uppercase max", model: "grok-4.5", effort: "MAX", want: "high"},
|
||||
{name: "multi-agent xhigh", model: "grok-4.20-multi-agent-0309", effort: "xhigh", want: "xhigh"},
|
||||
{name: "multi-agent uppercase xhigh", model: "grok-4.20-multi-agent-0309", effort: "XHIGH", want: "xhigh"},
|
||||
{name: "multi-agent max remains guarded", model: "grok-4.20-multi-agent-0309", effort: "max", want: "high"},
|
||||
{name: "multi-agent max maps to highest supported effort", model: "grok-4.20-multi-agent-0309", effort: "max", want: "xhigh"},
|
||||
{name: "4.6 xhigh", model: "grok-4.6", effort: "xhigh", want: "xhigh"},
|
||||
{name: "4.6 uppercase xhigh", model: "grok-4.6", effort: "XHIGH", want: "xhigh"},
|
||||
{name: "4.6 max maps to xhigh", model: "grok-4.6", effort: "max", want: "xhigh"},
|
||||
{name: "prefixed 4.6 uppercase max maps to xhigh", model: "Build/grok-4.6", effort: "MAX", want: "xhigh"},
|
||||
{name: "unknown xhigh remains guarded", model: "future-model", effort: "xhigh", want: "high"},
|
||||
{name: "unknown max remains guarded", model: "future-model", effort: "max", want: "high"},
|
||||
{name: "high", model: "grok-4.5", effort: "high", want: "high"},
|
||||
{name: "medium", model: "grok-4.5", effort: "medium", want: "medium"},
|
||||
}
|
||||
@@ -76,6 +81,54 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body []byte
|
||||
}{
|
||||
{name: "responses", body: []byte(`{"reasoning":{"effort":"max"},"input":"hello"}`)},
|
||||
{name: "chat completions", body: func() []byte {
|
||||
converted, _, err := conversation.ConvertRequestWithOptions(
|
||||
[]byte(`{"model":"public","messages":[{"role":"user","content":"hello"}],"reasoning_effort":"max"}`),
|
||||
"grok-4.6",
|
||||
conversation.OperationChat,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return converted
|
||||
}()},
|
||||
{name: "anthropic messages", body: func() []byte {
|
||||
converted, _, err := conversation.ConvertRequestWithOptions(
|
||||
[]byte(`{"model":"public","max_tokens":64,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}}`),
|
||||
"grok-4.6",
|
||||
conversation.OperationMessages,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return converted
|
||||
}()},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
normalized, err := normalizeBuildRequest(test.body, "grok-4.6")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(normalized, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reasoning, ok := payload["reasoning"].(map[string]any)
|
||||
if !ok || reasoning["effort"] != "xhigh" {
|
||||
t.Fatalf("reasoning = %#v, want max normalized to xhigh", payload["reasoning"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -336,6 +336,140 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) {
|
||||
spec, ok := Resolve("grok-4.3")
|
||||
if !ok {
|
||||
t.Fatal("grok-4.3 missing")
|
||||
}
|
||||
|
||||
t.Run("forwards enable_image_search on web_search", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"web_search","enable_image_search":true,"custom":true}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tools, _ := payload["tools"].([]any)
|
||||
if len(tools) != 1 {
|
||||
t.Fatalf("tools = %#v", tools)
|
||||
}
|
||||
webSearch, _ := tools[0].(map[string]any)
|
||||
if webSearch["type"] != "web_search" || webSearch["enable_image_understanding"] != true {
|
||||
t.Fatalf("web_search defaults = %#v", webSearch)
|
||||
}
|
||||
if webSearch["enable_image_search"] != true {
|
||||
t.Fatalf("enable_image_search not forwarded: %#v", webSearch)
|
||||
}
|
||||
if webSearch["custom"] != nil {
|
||||
t.Fatalf("unknown field custom should be stripped: %#v", webSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("omits enable_image_search when client does not set it", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"web_search"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
webSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if _, exists := webSearch["enable_image_search"]; exists {
|
||||
t.Fatalf("enable_image_search should be absent by default: %#v", webSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("forwards valid x_search from_date and to_date", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-07-01","to_date":"2026-07-23","noise":1}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true {
|
||||
t.Fatalf("x_search defaults = %#v", xSearch)
|
||||
}
|
||||
if xSearch["from_date"] != "2026-07-01" || xSearch["to_date"] != "2026-07-23" {
|
||||
t.Fatalf("date bounds not forwarded: %#v", xSearch)
|
||||
}
|
||||
if xSearch["noise"] != nil {
|
||||
t.Fatalf("unknown field noise should be stripped: %#v", xSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("drops invalid date formats", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-7-01","to_date":"2026-02-30"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["from_date"] != nil || xSearch["to_date"] != nil {
|
||||
t.Fatalf("invalid dates should be dropped: %#v", xSearch)
|
||||
}
|
||||
if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true {
|
||||
t.Fatalf("x_search defaults should remain: %#v", xSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("drops inverted date range", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-07-24","to_date":"2026-07-23"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["from_date"] != nil || xSearch["to_date"] != nil {
|
||||
t.Fatalf("inverted range should drop both bounds: %#v", xSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keeps only from_date when to_date absent", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-08-01"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["from_date"] != "2026-08-01" || xSearch["to_date"] != nil {
|
||||
t.Fatalf("single bound = %#v", xSearch)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizeRequestDoesNotInjectToolsForConsoleCatalog(t *testing.T) {
|
||||
for _, spec := range catalog {
|
||||
t.Run(spec.PublicID, func(t *testing.T) {
|
||||
@@ -1616,9 +1750,11 @@ func TestConsoleVideoPostsReferenceAudios(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Measured upstream ceiling: 8 references answer 400 "Too many reference images:
|
||||
// 8. Maximum allowed is 7." on both grok-imagine-video and grok-imagine-video-1.5.
|
||||
func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
references := make([]string, consoleMaxVideoImages+1)
|
||||
references := make([]string, consoleMaxVideoReferenceImages+1)
|
||||
for i := range references {
|
||||
references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png"
|
||||
}
|
||||
@@ -1632,7 +1768,7 @@ func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) {
|
||||
|
||||
func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
references := make([]string, consoleMaxVideoImages)
|
||||
references := make([]string, consoleMaxVideoReferenceImages)
|
||||
for i := range references {
|
||||
references[i] = "https://example.com/" + strings.Repeat("y", i+1) + ".png"
|
||||
}
|
||||
@@ -1645,6 +1781,51 @@ func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Measured: grok-imagine-video with reference_images and duration=15 answers
|
||||
// 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is
|
||||
// 10s." The image field (image-to-video) and grok-imagine-video-1.5 both keep 15s.
|
||||
func TestConsoleVideoRejectsLongReferenceDurationOnBaseModel(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 15,
|
||||
ReferenceURLs: []string{"https://example.com/ref.png"},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最长 10 秒") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The same 15s request must stay allowed for grok-imagine-video-1.5.
|
||||
func TestConsoleVideo15AllowsLongReferenceDuration(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-15s"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-15s":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-15s.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 15,
|
||||
ReferenceURLs: []string{"https://example.com/ref.png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-15s.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoUsesImagineVideo15Model(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
|
||||
@@ -29,9 +29,15 @@ const (
|
||||
consoleMediaOutputAttempts = 3
|
||||
consoleVideoPollEvery = 2 * time.Second
|
||||
consoleMaxEditImages = 3
|
||||
// Align with the gateway ceiling and official xAI video inputs:
|
||||
// image = first frame; reference_images = style/content references (may be length 1).
|
||||
consoleMaxVideoImages = mediadomain.MaxInputImages
|
||||
// Upstream enforces the two video image inputs separately (measured against
|
||||
// console.x.ai on both grok-imagine-video and grok-imagine-video-1.5):
|
||||
// image = first frame, image-to-video, at most 1
|
||||
// reference_images = style/content references, reference-to-video, at most 7
|
||||
// 8 references answer 400 "Too many reference images: 8. Maximum allowed is 7."
|
||||
// The two are mutually exclusive below and their limits are never summed, so a
|
||||
// combined ceiling would accept payloads that upstream then rejects.
|
||||
consoleMaxVideoFirstFrames = 1
|
||||
consoleMaxVideoReferenceImages = 7
|
||||
)
|
||||
|
||||
type consoleMediaUpstreamError struct {
|
||||
@@ -458,14 +464,25 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
if operation != provider.VideoOperationGenerate && modelName != "grok-imagine-video" {
|
||||
return provider.VideoResult{}, fmt.Errorf("%s 仅支持 grok-imagine-video", operation)
|
||||
}
|
||||
totalImages := consoleVideoImageCount(request)
|
||||
if totalImages > consoleMaxVideoImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张输入图,当前为 %d 张", modelName, consoleMaxVideoImages, totalImages)
|
||||
firstFrames, referenceImages := consoleVideoImageCounts(request)
|
||||
if firstFrames > consoleMaxVideoFirstFrames {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张首帧图,当前为 %d 张", modelName, consoleMaxVideoFirstFrames, firstFrames)
|
||||
}
|
||||
if referenceImages > consoleMaxVideoReferenceImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, consoleMaxVideoReferenceImages, referenceImages)
|
||||
}
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
if request.Duration < 1 || request.Duration > 15 {
|
||||
return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间")
|
||||
}
|
||||
// reference-to-video on the base model caps at 10s upstream; measured:
|
||||
// grok-imagine-video + reference_images + duration=15
|
||||
// -> 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s."
|
||||
// image-to-video (the image field) and grok-imagine-video-1.5 both keep 15s,
|
||||
// so the cap keys on reference_images plus the base model, not on duration alone.
|
||||
if modelName == "grok-imagine-video" && referenceImages > 0 && request.Duration > 10 {
|
||||
return provider.VideoResult{}, fmt.Errorf("%s 的参考图生视频最长 10 秒,当前为 %d 秒", modelName, request.Duration)
|
||||
}
|
||||
} else if operation == provider.VideoOperationExtend {
|
||||
// Official /v1/videos/extensions defaults to 6s and accepts 2-10s.
|
||||
if request.Duration == 0 {
|
||||
@@ -920,15 +937,14 @@ func trustedConsoleVideoHost(host string) bool {
|
||||
return host == "vidgen.x.ai" || strings.HasSuffix(host, ".vidgen.x.ai")
|
||||
}
|
||||
|
||||
func consoleVideoImageCount(request provider.VideoRequest) int {
|
||||
count := 0
|
||||
func consoleVideoImageCounts(request provider.VideoRequest) (firstFrames int, referenceImages int) {
|
||||
if strings.TrimSpace(request.ImageURL) != "" {
|
||||
count++
|
||||
firstFrames++
|
||||
}
|
||||
for _, raw := range request.ReferenceURLs {
|
||||
if strings.TrimSpace(raw) != "" {
|
||||
count++
|
||||
referenceImages++
|
||||
}
|
||||
}
|
||||
return count
|
||||
return firstFrames, referenceImages
|
||||
}
|
||||
@@ -229,12 +229,39 @@ func normalizeConsoleTools(payload map[string]any) bool {
|
||||
if enabled, ok := tool["enable_image_understanding"].(bool); ok {
|
||||
clean["enable_image_understanding"] = enabled
|
||||
}
|
||||
// Forward the image-search toggle (enable_image_search) so clients
|
||||
// can explicitly enable/disable it; absent when not requested.
|
||||
if enabled, ok := tool["enable_image_search"].(bool); ok {
|
||||
clean["enable_image_search"] = enabled
|
||||
}
|
||||
result = append(result, clean)
|
||||
case "x_search":
|
||||
clean := map[string]any{"type": "x_search", "enable_video_understanding": true}
|
||||
if enabled, ok := tool["enable_video_understanding"].(bool); ok {
|
||||
clean["enable_video_understanding"] = enabled
|
||||
}
|
||||
// Forward the X-search time bounds (from_date/to_date, YYYY-MM-DD).
|
||||
// Invalid formats and empty strings are dropped; if from_date is
|
||||
// later than to_date both are dropped to avoid an upstream 400.
|
||||
for _, field := range []string{"from_date", "to_date"} {
|
||||
text, ok := tool[field].(string)
|
||||
if !ok || text == "" {
|
||||
continue
|
||||
}
|
||||
if date, err := time.Parse("2006-01-02", text); err == nil && date.Format("2006-01-02") == text {
|
||||
clean[field] = text
|
||||
}
|
||||
}
|
||||
from, hasFrom := clean["from_date"].(string)
|
||||
to, hasTo := clean["to_date"].(string)
|
||||
if hasFrom && hasTo {
|
||||
fromDate, _ := time.Parse("2006-01-02", from)
|
||||
toDate, _ := time.Parse("2006-01-02", to)
|
||||
if fromDate.After(toDate) {
|
||||
delete(clean, "from_date")
|
||||
delete(clean, "to_date")
|
||||
}
|
||||
}
|
||||
result = append(result, clean)
|
||||
case "function":
|
||||
name, _ := tool["name"].(string)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -29,6 +30,8 @@ const (
|
||||
statsigResponseLimit = 4 << 10
|
||||
)
|
||||
|
||||
var errStatsigMetaMissing = errors.New("Grok index 缺少 grok-site-verification")
|
||||
|
||||
type statsigCacheEntry struct {
|
||||
value string
|
||||
expiresAt time.Time
|
||||
@@ -272,12 +275,55 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease *
|
||||
if lease == nil {
|
||||
return "", fmt.Errorf("Statsig 获取缺少出口租约")
|
||||
}
|
||||
requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/index", nil)
|
||||
return fetchStatsigMetaContentWithDo(ctx, baseURL, token, lease, lease.Do)
|
||||
}
|
||||
|
||||
func fetchStatsigMetaContentWithDo(ctx context.Context, baseURL, token string, lease *infraegress.Lease, do func(*http.Request) (*http.Response, error)) (string, error) {
|
||||
if do == nil {
|
||||
return "", fmt.Errorf("Statsig 获取缺少出口租约")
|
||||
}
|
||||
index, err := fetchStatsigMetaResponse(ctx, baseURL, token, lease, "/index", do)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if index.statusCode >= 200 && index.statusCode < 300 {
|
||||
// A successful index response without the verification meta remains a hard
|
||||
// protocol failure. Falling back here would hide a changed upstream page.
|
||||
return extractStatsigMetaContent(index.body)
|
||||
}
|
||||
if index.statusCode != http.StatusNotFound {
|
||||
return "", statsigMetaStatusError("/index", index.statusCode)
|
||||
}
|
||||
if content, extractErr := extractStatsigMetaContent(index.body); extractErr == nil {
|
||||
return content, nil
|
||||
} else if !errors.Is(extractErr, errStatsigMetaMissing) {
|
||||
return "", extractErr
|
||||
}
|
||||
|
||||
// /index currently returns a branded 404. Only that exact status with a
|
||||
// missing meta is allowed to fall back to the canonical root page.
|
||||
root, err := fetchStatsigMetaResponse(ctx, baseURL, token, lease, "/", do)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if root.statusCode < 200 || root.statusCode >= 300 {
|
||||
return "", statsigMetaStatusError("/", root.statusCode)
|
||||
}
|
||||
return extractStatsigMetaContent(root.body)
|
||||
}
|
||||
|
||||
type statsigMetaResponse struct {
|
||||
statusCode int
|
||||
body []byte
|
||||
}
|
||||
|
||||
func fetchStatsigMetaResponse(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (statsigMetaResponse, error) {
|
||||
requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+path, nil)
|
||||
if err != nil {
|
||||
return statsigMetaResponse{}, err
|
||||
}
|
||||
request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
request.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd")
|
||||
request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
@@ -287,28 +333,37 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease *
|
||||
request.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
request.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
request.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
request.Header.Set("User-Agent", lease.UserAgent)
|
||||
request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies))
|
||||
response, err := lease.Do(request)
|
||||
if lease != nil {
|
||||
request.Header.Set("User-Agent", lease.UserAgent)
|
||||
request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies))
|
||||
}
|
||||
response, err := do(request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return statsigMetaResponse{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("Grok index 返回 %d", response.StatusCode)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, statsigMetaBodyLimit+1))
|
||||
if err != nil {
|
||||
return "", err
|
||||
return statsigMetaResponse{}, err
|
||||
}
|
||||
if len(body) > statsigMetaBodyLimit {
|
||||
return "", fmt.Errorf("Grok index 超过安全上限")
|
||||
return statsigMetaResponse{}, statsigMetaOversizeError(path)
|
||||
}
|
||||
content, err := extractStatsigMetaContent(body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return statsigMetaResponse{statusCode: response.StatusCode, body: body}, nil
|
||||
}
|
||||
|
||||
func statsigMetaStatusError(path string, statusCode int) error {
|
||||
if path == "/" {
|
||||
return fmt.Errorf("Grok 首页返回 %d", statusCode)
|
||||
}
|
||||
return content, nil
|
||||
return fmt.Errorf("Grok index 返回 %d", statusCode)
|
||||
}
|
||||
|
||||
func statsigMetaOversizeError(path string) error {
|
||||
if path == "/" {
|
||||
return fmt.Errorf("Grok 首页超过安全上限")
|
||||
}
|
||||
return fmt.Errorf("Grok index 超过安全上限")
|
||||
}
|
||||
|
||||
func extractStatsigMetaContent(body []byte) (string, error) {
|
||||
@@ -317,7 +372,7 @@ func extractStatsigMetaContent(body []byte) (string, error) {
|
||||
switch tokenizer.Next() {
|
||||
case html.ErrorToken:
|
||||
if tokenizer.Err() == io.EOF {
|
||||
return "", fmt.Errorf("Grok index 缺少 grok-site-verification")
|
||||
return "", errStatsigMetaMissing
|
||||
}
|
||||
return "", tokenizer.Err()
|
||||
case html.StartTagToken, html.SelfClosingTagToken:
|
||||
|
||||
@@ -19,6 +19,172 @@ type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) }
|
||||
|
||||
type failingStatsigBody struct{}
|
||||
|
||||
func (failingStatsigBody) Read([]byte) (int, error) { return 0, errors.New("read failed") }
|
||||
func (failingStatsigBody) Close() error { return nil }
|
||||
|
||||
func TestFetchStatsigMetaContentFallsBackToRootWhenIndexHasNoVerification(t *testing.T) {
|
||||
var paths []string
|
||||
do := func(request *http.Request) (*http.Response, error) {
|
||||
paths = append(paths, request.URL.Path)
|
||||
switch request.URL.Path {
|
||||
case "/index":
|
||||
return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(`<html><head><meta name="robots" content="noindex"/></head></html>`)), Header: http.Header{}}, nil
|
||||
case "/":
|
||||
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`<html><head><meta name="grok-site-verification" content="root-meta"/></head></html>`)), Header: http.Header{}}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected path %q", request.URL.Path)
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
value, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err != nil || value != "root-meta" {
|
||||
t.Fatalf("value=%q err=%v paths=%v", value, err, paths)
|
||||
}
|
||||
if len(paths) != 2 || paths[0] != "/index" || paths[1] != "/" {
|
||||
t.Fatalf("paths=%v", paths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStatsigMetaContentDoesNotFallbackWhenIndex404HasVerification(t *testing.T) {
|
||||
var paths []string
|
||||
do := func(request *http.Request) (*http.Response, error) {
|
||||
paths = append(paths, request.URL.Path)
|
||||
if request.URL.Path != "/index" {
|
||||
t.Fatalf("unexpected fallback to %q", request.URL.Path)
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(`<html><head><meta name="grok-site―verification" content="index-meta"/></head></html>`)), Header: http.Header{}}, nil
|
||||
}
|
||||
value, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err != nil || value != "index-meta" {
|
||||
t.Fatalf("value=%q err=%v", value, err)
|
||||
}
|
||||
if len(paths) != 1 || paths[0] != "/index" {
|
||||
t.Fatalf("paths=%v", paths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStatsigMetaContentDoesNotFallbackWhenSuccessfulIndexHasNoVerification(t *testing.T) {
|
||||
var paths []string
|
||||
do := func(request *http.Request) (*http.Response, error) {
|
||||
paths = append(paths, request.URL.Path)
|
||||
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`<html><head></head></html>`)), Header: http.Header{}}, nil
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if !errors.Is(err, errStatsigMetaMissing) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(paths) != 1 || paths[0] != "/index" {
|
||||
t.Fatalf("successful index without verification must not fall back: paths=%v", paths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStatsigMetaContentRejectsNon404IndexStatuses(t *testing.T) {
|
||||
for _, status := range []int{http.StatusMovedPermanently, http.StatusForbidden, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusServiceUnavailable} {
|
||||
for _, withMeta := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("status_%d_meta_%t", status, withMeta), func(t *testing.T) {
|
||||
body := `<html><head></head></html>`
|
||||
if withMeta {
|
||||
body = `<html><head><meta name="grok-site-verification" content="error-meta"/></head></html>`
|
||||
}
|
||||
var calls int
|
||||
do := func(request *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if request.URL.Path != "/index" {
|
||||
t.Fatalf("unexpected fallback to %q", request.URL.Path)
|
||||
}
|
||||
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("Grok index 返回 %d", status)) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("calls=%d", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStatsigMetaContentRequiresSuccessfulRoot(t *testing.T) {
|
||||
for _, withMeta := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("meta_%t", withMeta), func(t *testing.T) {
|
||||
body := `<html><head></head></html>`
|
||||
if withMeta {
|
||||
body = `<html><head><meta name="grok-site-verification" content="root-error-meta"/></head></html>`
|
||||
}
|
||||
do := func(request *http.Request) (*http.Response, error) {
|
||||
if request.URL.Path == "/index" {
|
||||
return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(`<html><head></head></html>`)), Header: http.Header{}}, nil
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusServiceUnavailable, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err == nil || !strings.Contains(err.Error(), "Grok 首页返回 503") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStatsigMetaContentRequiresVerificationOnSuccessfulRoot(t *testing.T) {
|
||||
do := func(request *http.Request) (*http.Response, error) {
|
||||
status := http.StatusOK
|
||||
if request.URL.Path == "/index" {
|
||||
status = http.StatusNotFound
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: status,
|
||||
Body: io.NopCloser(strings.NewReader(`<html><head></head></html>`)),
|
||||
Header: http.Header{},
|
||||
}, nil
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if !errors.Is(err, errStatsigMetaMissing) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStatsigMetaContentDoesNotFallbackOnTransportReadOrOversizeFailure(t *testing.T) {
|
||||
t.Run("transport", func(t *testing.T) {
|
||||
var calls int
|
||||
do := func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return nil, errors.New("dial failed")
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err == nil || err.Error() != "dial failed" || calls != 1 {
|
||||
t.Fatalf("err=%v calls=%d", err, calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("read", func(t *testing.T) {
|
||||
var calls int
|
||||
do := func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return &http.Response{StatusCode: http.StatusNotFound, Body: failingStatsigBody{}, Header: http.Header{}}, nil
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err == nil || err.Error() != "read failed" || calls != 1 {
|
||||
t.Fatalf("err=%v calls=%d", err, calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversize", func(t *testing.T) {
|
||||
var calls int
|
||||
do := func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(strings.Repeat("x", statsigMetaBodyLimit+1))), Header: http.Header{}}, nil
|
||||
}
|
||||
_, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do)
|
||||
if err == nil || !strings.Contains(err.Error(), "超过安全上限") || calls != 1 {
|
||||
t.Fatalf("err=%v calls=%d", err, calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestExtractStatsigMetaContentAcceptsCurrentMetaName(t *testing.T) {
|
||||
for _, name := range []string{"grok-site―verification", "grok-site-verification"} {
|
||||
body := []byte(`<html><head><meta name="` + name + `" content="meta-value"/></head></html>`)
|
||||
|
||||
@@ -0,0 +1,745 @@
|
||||
package tunnelproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/vmess"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/google/uuid"
|
||||
sscore "github.com/shadowsocks/go-shadowsocks2/core"
|
||||
"github.com/shadowsocks/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Scheme string
|
||||
Server string
|
||||
Credential string
|
||||
Method string
|
||||
AlterID int
|
||||
Cipher string
|
||||
Transport string
|
||||
TLS bool
|
||||
ServerName string
|
||||
Insecure bool
|
||||
ALPN []string
|
||||
WebSocketHost string
|
||||
WebSocketPath string
|
||||
CanonicalProxyURL string
|
||||
}
|
||||
|
||||
const tunnelHandshakeTimeout = 10 * time.Second
|
||||
|
||||
func IsSupportedScheme(scheme string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(scheme)) {
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func Normalize(value string) (string, error) {
|
||||
config, err := Parse(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return config.CanonicalProxyURL, nil
|
||||
}
|
||||
|
||||
func Parse(value string) (Config, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.IndexFunc(value, func(character rune) bool { return character < 0x20 || character == 0x7f }) >= 0 {
|
||||
return Config{}, errors.New("隧道代理地址包含控制字符")
|
||||
}
|
||||
scheme, _, ok := strings.Cut(value, "://")
|
||||
if !ok || !IsSupportedScheme(scheme) {
|
||||
return Config{}, errors.New("不支持的隧道代理协议")
|
||||
}
|
||||
switch strings.ToLower(scheme) {
|
||||
case "ss":
|
||||
return parseShadowsocks(value)
|
||||
case "vmess":
|
||||
return parseVMess(value)
|
||||
default:
|
||||
return parseUserInfoProxy(value)
|
||||
}
|
||||
}
|
||||
|
||||
func parseUserInfoProxy(value string) (Config, error) {
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User == nil {
|
||||
return Config{}, errors.New("隧道代理地址格式无效")
|
||||
}
|
||||
scheme := strings.ToLower(parsed.Scheme)
|
||||
credential := parsed.User.Username()
|
||||
if credential == "" {
|
||||
return Config{}, errors.New("隧道代理凭据不能为空")
|
||||
}
|
||||
if _, hasPassword := parsed.User.Password(); hasPassword {
|
||||
return Config{}, errors.New("隧道代理凭据格式无效")
|
||||
}
|
||||
if parsed.Path != "" && parsed.Path != "/" {
|
||||
return Config{}, errors.New("隧道代理地址路径无效")
|
||||
}
|
||||
server, err := canonicalServer(parsed.Hostname(), parsed.Port())
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
query := parsed.Query()
|
||||
transport := strings.ToLower(firstNonEmpty(query.Get("type"), query.Get("network")))
|
||||
if transport == "" || transport == "none" {
|
||||
transport = "tcp"
|
||||
}
|
||||
if transport == "websocket" {
|
||||
transport = "ws"
|
||||
}
|
||||
if transport != "tcp" && transport != "ws" {
|
||||
return Config{}, fmt.Errorf("暂不支持 %s 传输", transport)
|
||||
}
|
||||
if flow := strings.TrimSpace(query.Get("flow")); flow != "" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow)
|
||||
}
|
||||
if scheme == "vless" {
|
||||
parsedUUID, err := uuid.Parse(credential)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("VLESS UUID 无效")
|
||||
}
|
||||
credential = parsedUUID.String()
|
||||
if encryption := strings.ToLower(strings.TrimSpace(query.Get("encryption"))); encryption != "" && encryption != "none" {
|
||||
return Config{}, errors.New("VLESS encryption 必须为 none")
|
||||
}
|
||||
}
|
||||
security := strings.ToLower(strings.TrimSpace(query.Get("security")))
|
||||
tlsEnabled := scheme == "trojan"
|
||||
switch security {
|
||||
case "", "tls":
|
||||
if security == "tls" {
|
||||
tlsEnabled = true
|
||||
}
|
||||
case "none":
|
||||
tlsEnabled = false
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security)
|
||||
}
|
||||
if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" {
|
||||
return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType)
|
||||
}
|
||||
insecure, err := queryBool(query, "allowInsecure", "insecure", "skip-cert-verify")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname())
|
||||
wsHost := firstNonEmpty(query.Get("host"), serverName)
|
||||
if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
wsPath := query.Get("path")
|
||||
if wsPath == "" {
|
||||
wsPath = "/"
|
||||
} else if !strings.HasPrefix(wsPath, "/") {
|
||||
wsPath = "/" + wsPath
|
||||
}
|
||||
if transport == "tcp" && (query.Get("path") != "" || query.Get("host") != "") {
|
||||
return Config{}, errors.New("TCP 隧道不能包含 WebSocket host/path")
|
||||
}
|
||||
config := Config{
|
||||
Scheme: scheme, Server: server, Credential: credential, Transport: transport,
|
||||
TLS: tlsEnabled, ServerName: serverName, Insecure: insecure,
|
||||
ALPN: splitList(query.Get("alpn")), WebSocketHost: wsHost, WebSocketPath: wsPath,
|
||||
}
|
||||
config.CanonicalProxyURL = canonicalUserInfoProxyURL(config)
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, fmt.Errorf("创建 %s 隧道配置: %w", strings.ToUpper(scheme), err)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func canonicalUserInfoProxyURL(config Config) string {
|
||||
query := make(url.Values)
|
||||
query.Set("type", config.Transport)
|
||||
if config.TLS {
|
||||
query.Set("security", "tls")
|
||||
} else {
|
||||
query.Set("security", "none")
|
||||
}
|
||||
if config.Scheme == "vless" {
|
||||
query.Set("encryption", "none")
|
||||
}
|
||||
query.Set("sni", config.ServerName)
|
||||
if config.Insecure {
|
||||
query.Set("allowInsecure", "1")
|
||||
}
|
||||
if len(config.ALPN) != 0 {
|
||||
query.Set("alpn", strings.Join(config.ALPN, ","))
|
||||
}
|
||||
if config.Transport == "ws" {
|
||||
query.Set("host", config.WebSocketHost)
|
||||
query.Set("path", config.WebSocketPath)
|
||||
}
|
||||
return (&url.URL{
|
||||
Scheme: config.Scheme,
|
||||
User: url.User(config.Credential),
|
||||
Host: config.Server,
|
||||
RawQuery: query.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
func parseShadowsocks(value string) (Config, error) {
|
||||
payload := value[len("ss://"):]
|
||||
if before, _, found := strings.Cut(payload, "#"); found {
|
||||
payload = before
|
||||
}
|
||||
if before, rawQuery, found := strings.Cut(payload, "?"); found {
|
||||
query, err := url.ParseQuery(rawQuery)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("Shadowsocks 查询参数无效")
|
||||
}
|
||||
if plugin := strings.TrimSpace(query.Get("plugin")); plugin != "" {
|
||||
return Config{}, errors.New("暂不支持 Shadowsocks plugin")
|
||||
}
|
||||
if len(query) != 0 {
|
||||
return Config{}, errors.New("Shadowsocks 查询参数无效")
|
||||
}
|
||||
payload = before
|
||||
}
|
||||
var userPart, serverPart string
|
||||
if separator := strings.LastIndex(payload, "@"); separator >= 0 {
|
||||
userPart, serverPart = payload[:separator], payload[separator+1:]
|
||||
decoded, err := url.PathUnescape(userPart)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("Shadowsocks 凭据无效")
|
||||
}
|
||||
if !strings.Contains(decoded, ":") {
|
||||
decoded, err = decodeBase64String(decoded)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("Shadowsocks 凭据不是有效的 Base64")
|
||||
}
|
||||
}
|
||||
userPart = decoded
|
||||
} else {
|
||||
decoded, err := decodeBase64String(payload)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("旧式 Shadowsocks 地址不是有效的 Base64")
|
||||
}
|
||||
separator := strings.LastIndex(decoded, "@")
|
||||
if separator < 0 {
|
||||
return Config{}, errors.New("旧式 Shadowsocks 地址格式无效")
|
||||
}
|
||||
userPart, serverPart = decoded[:separator], decoded[separator+1:]
|
||||
}
|
||||
method, password, ok := strings.Cut(userPart, ":")
|
||||
if !ok || strings.TrimSpace(method) == "" || password == "" {
|
||||
return Config{}, errors.New("Shadowsocks method/password 不能为空")
|
||||
}
|
||||
method = strings.ToLower(strings.TrimSpace(method))
|
||||
switch method {
|
||||
case "aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 Shadowsocks method %q", method)
|
||||
}
|
||||
serverURL, err := url.Parse("ss://" + serverPart)
|
||||
if err != nil || serverURL.User != nil || (serverURL.Path != "" && serverURL.Path != "/") || serverURL.RawQuery != "" || serverURL.Fragment != "" {
|
||||
return Config{}, errors.New("Shadowsocks 服务器地址无效")
|
||||
}
|
||||
server, err := canonicalServer(serverURL.Hostname(), serverURL.Port())
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
credential := method + ":" + password
|
||||
config := Config{
|
||||
Scheme: "ss", Server: server, Credential: password, Method: method, Transport: "tcp",
|
||||
CanonicalProxyURL: "ss://" + base64.RawURLEncoding.EncodeToString([]byte(credential)) + "@" + server,
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, fmt.Errorf("创建 Shadowsocks 隧道配置: %w", err)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type vmessShare struct {
|
||||
Version string `json:"v,omitempty"`
|
||||
Address string `json:"add"`
|
||||
Port string `json:"port"`
|
||||
UUID string `json:"id"`
|
||||
AlterID string `json:"aid"`
|
||||
Cipher string `json:"scy,omitempty"`
|
||||
Network string `json:"net"`
|
||||
TLS string `json:"tls,omitempty"`
|
||||
ServerName string `json:"sni,omitempty"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
AllowInsecure bool `json:"allowInsecure,omitempty"`
|
||||
}
|
||||
|
||||
func parseVMess(value string) (Config, error) {
|
||||
payload := value[len("vmess://"):]
|
||||
if before, _, found := strings.Cut(payload, "#"); found {
|
||||
payload = before
|
||||
}
|
||||
decoded, err := decodeBase64Bytes(payload)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("VMess 配置不是有效的 Base64")
|
||||
}
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal(decoded, &raw); err != nil {
|
||||
return Config{}, errors.New("VMess 配置不是有效的 JSON")
|
||||
}
|
||||
address := jsonString(raw, "add")
|
||||
port := jsonString(raw, "port")
|
||||
server, err := canonicalServer(address, port)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("VMess %w", err)
|
||||
}
|
||||
parsedUUID, err := uuid.Parse(jsonString(raw, "id"))
|
||||
if err != nil {
|
||||
return Config{}, errors.New("VMess UUID 无效")
|
||||
}
|
||||
userID := parsedUUID.String()
|
||||
alterID, err := strconv.Atoi(firstNonEmpty(jsonString(raw, "aid"), "0"))
|
||||
if err != nil || alterID < 0 || alterID > 65535 {
|
||||
return Config{}, errors.New("VMess alterId 无效")
|
||||
}
|
||||
cipher := strings.ToLower(firstNonEmpty(jsonString(raw, "scy"), jsonString(raw, "security"), "auto"))
|
||||
switch cipher {
|
||||
case "auto", "aes-128-gcm", "chacha20-poly1305", "none":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess cipher %q", cipher)
|
||||
}
|
||||
transport := strings.ToLower(firstNonEmpty(jsonString(raw, "net"), "tcp"))
|
||||
if transport == "websocket" {
|
||||
transport = "ws"
|
||||
}
|
||||
if transport != "tcp" && transport != "ws" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess %s 传输", transport)
|
||||
}
|
||||
if headerType := strings.ToLower(jsonString(raw, "type")); headerType != "" && headerType != "none" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess header type %q", headerType)
|
||||
}
|
||||
tlsMode := strings.ToLower(jsonString(raw, "tls"))
|
||||
if tlsMode != "" && tlsMode != "none" && tlsMode != "tls" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess TLS 模式 %q", tlsMode)
|
||||
}
|
||||
tlsEnabled := tlsMode == "tls"
|
||||
serverName := firstNonEmpty(jsonString(raw, "sni"), address)
|
||||
host := firstNonEmpty(jsonString(raw, "host"), serverName)
|
||||
if err := validateWebSocketHost(host); transport == "ws" && err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
path := jsonString(raw, "path")
|
||||
if path == "" {
|
||||
path = "/"
|
||||
} else if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
if transport == "tcp" && (jsonString(raw, "path") != "" || jsonString(raw, "host") != "") {
|
||||
return Config{}, errors.New("VMess TCP 隧道不能包含 WebSocket host/path")
|
||||
}
|
||||
insecure, err := jsonBool(raw, "allowInsecure")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
share := vmessShare{
|
||||
Version: "2", Address: address, Port: port, UUID: userID, AlterID: strconv.Itoa(alterID), Cipher: cipher,
|
||||
Network: transport, ServerName: serverName, AllowInsecure: insecure,
|
||||
}
|
||||
if transport == "ws" {
|
||||
share.Host = host
|
||||
share.Path = path
|
||||
}
|
||||
if tlsEnabled {
|
||||
share.TLS = "tls"
|
||||
}
|
||||
canonicalJSON, err := json.Marshal(share)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
config := Config{
|
||||
Scheme: "vmess", Server: server, Credential: userID, AlterID: alterID, Cipher: cipher,
|
||||
Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure,
|
||||
WebSocketHost: host, WebSocketPath: path,
|
||||
CanonicalProxyURL: "vmess://" + base64.RawStdEncoding.EncodeToString(canonicalJSON),
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, fmt.Errorf("创建 VMess 隧道配置: %w", err)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type Dialer struct {
|
||||
proxy netapi.Proxy
|
||||
shadowsocksCipher sscore.StreamConnCipher
|
||||
server string
|
||||
}
|
||||
|
||||
func NewDialer(value string) (*Dialer, error) {
|
||||
config, err := Parse(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if config.Scheme == "ss" {
|
||||
cipher, err := sscore.PickCipher(config.Method, nil, config.Credential)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Dialer{shadowsocksCipher: cipher, server: config.Server}, nil
|
||||
}
|
||||
proxy, err := buildProxy(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Dialer{proxy: proxy}, nil
|
||||
}
|
||||
|
||||
func (d *Dialer) Dial(network, address string) (net.Conn, error) {
|
||||
return d.DialContext(context.Background(), network, address)
|
||||
}
|
||||
|
||||
func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if d == nil || (d.proxy == nil && d.shadowsocksCipher == nil) {
|
||||
return nil, errors.New("隧道代理拨号器未初始化")
|
||||
}
|
||||
if !strings.HasPrefix(network, "tcp") {
|
||||
return nil, fmt.Errorf("隧道代理不支持网络 %q", network)
|
||||
}
|
||||
if d.shadowsocksCipher != nil {
|
||||
return d.dialShadowsocks(ctx, address)
|
||||
}
|
||||
target, err := netapi.ParseAddress(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.proxy.Conn(ctx, target)
|
||||
}
|
||||
|
||||
func (d *Dialer) dialShadowsocks(ctx context.Context, address string) (net.Conn, error) {
|
||||
target := socks.ParseAddr(address)
|
||||
if target == nil {
|
||||
return nil, errors.New("Shadowsocks 目标地址无效")
|
||||
}
|
||||
connection, err := newServerNetDialer().DialContext(ctx, "tcp", d.server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
connection = d.shadowsocksCipher.StreamConn(connection)
|
||||
if _, err := connection.Write(target); err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("写入 Shadowsocks 目标地址: %w", err)
|
||||
}
|
||||
return connection, nil
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
if config.Scheme == "ss" {
|
||||
_, err := sscore.PickCipher(config.Method, nil, config.Credential)
|
||||
return err
|
||||
}
|
||||
_, err := buildProxy(config)
|
||||
return err
|
||||
}
|
||||
|
||||
func buildProxy(config Config) (netapi.Proxy, error) {
|
||||
var current netapi.Proxy = &serverDialer{address: config.Server}
|
||||
if config.Transport == "ws" {
|
||||
current = &websocketProxy{config: config, dialer: current}
|
||||
} else if config.TLS {
|
||||
current = &tlsProxy{config: config, dialer: current}
|
||||
}
|
||||
switch config.Scheme {
|
||||
case "trojan":
|
||||
protocolConfig := &protocol.Trojan{}
|
||||
protocolConfig.SetPassword(config.Credential)
|
||||
return trojan.NewClient(protocolConfig, current)
|
||||
case "vless":
|
||||
protocolConfig := &protocol.Vless{}
|
||||
protocolConfig.SetUuid(config.Credential)
|
||||
return newOwnedVLESSProxy(protocolConfig, current)
|
||||
case "vmess":
|
||||
protocolConfig := &protocol.Vmess{}
|
||||
protocolConfig.SetUuid(config.Credential)
|
||||
protocolConfig.SetAlterId(strconv.Itoa(config.AlterID))
|
||||
protocolConfig.SetSecurity(config.Cipher)
|
||||
return vmess.NewClient(protocolConfig, current)
|
||||
default:
|
||||
return nil, errors.New("不支持的隧道代理协议")
|
||||
}
|
||||
}
|
||||
|
||||
// ownedVLESSProxy closes the transport connection when the upstream VLESS
|
||||
// client fails while writing its initial request. yuhaiin's VLESS client does
|
||||
// not transfer the failed connection back to its caller, so ownership must be
|
||||
// retained at this boundary to prevent failed retries from leaking sockets.
|
||||
type ownedVLESSProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config *protocol.Vless
|
||||
dialer netapi.Proxy
|
||||
}
|
||||
|
||||
func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy) (netapi.Proxy, error) {
|
||||
if _, err := vless.NewClient(config, dialer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ownedVLESSProxy{config: config, dialer: dialer}, nil
|
||||
}
|
||||
|
||||
func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
connection, err := p.dialer.Conn(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := vless.NewClient(p.config, &singleConnectionProxy{connection: connection})
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, err
|
||||
}
|
||||
result, err := client.Conn(ctx, address)
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p *ownedVLESSProxy) PacketConn(ctx context.Context, address netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("VLESS 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
type singleConnectionProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
connection net.Conn
|
||||
}
|
||||
|
||||
func (p *singleConnectionProxy) Conn(context.Context, netapi.Address) (net.Conn, error) {
|
||||
if p.connection == nil {
|
||||
return nil, errors.New("VLESS 底层连接不可用")
|
||||
}
|
||||
connection := p.connection
|
||||
p.connection = nil
|
||||
return connection, nil
|
||||
}
|
||||
|
||||
func (p *singleConnectionProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("VLESS 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
type tlsProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config Config
|
||||
dialer netapi.Proxy
|
||||
}
|
||||
|
||||
func (p *tlsProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
connection, err := p.dialer.Conn(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConnection := tls.Client(connection, p.tlsConfig())
|
||||
handshakeCtx, cancel := newTunnelHandshakeContext(ctx)
|
||||
defer cancel()
|
||||
if err := tlsConnection.HandshakeContext(handshakeCtx); err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("隧道 TLS 握手: %w", err)
|
||||
}
|
||||
return tlsConnection, nil
|
||||
}
|
||||
|
||||
func (p *tlsProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("TLS 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
func (p *tlsProxy) tlsConfig() *tls.Config {
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS12, ServerName: p.config.ServerName,
|
||||
InsecureSkipVerify: p.config.Insecure, NextProtos: append([]string(nil), p.config.ALPN...),
|
||||
}
|
||||
}
|
||||
|
||||
type websocketProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config Config
|
||||
dialer netapi.Proxy
|
||||
}
|
||||
|
||||
func (p *websocketProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
scheme := "ws"
|
||||
if p.config.TLS {
|
||||
scheme = "wss"
|
||||
}
|
||||
path, rawQuery, _ := strings.Cut(p.config.WebSocketPath, "?")
|
||||
endpoint := (&url.URL{Scheme: scheme, Host: p.config.WebSocketHost, Path: path, RawQuery: rawQuery}).String()
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: func(dialCtx context.Context, _, _ string) (net.Conn, error) {
|
||||
return p.dialer.Conn(dialCtx, address)
|
||||
},
|
||||
ForceAttemptHTTP2: false,
|
||||
TLSClientConfig: websocketTLSConfig(p.config),
|
||||
}
|
||||
handshakeCtx, cancel := newTunnelHandshakeContext(ctx)
|
||||
defer cancel()
|
||||
connection, _, err := websocket.Dial(handshakeCtx, endpoint, &websocket.DialOptions{
|
||||
HTTPClient: &http.Client{Transport: transport},
|
||||
Host: p.config.WebSocketHost,
|
||||
})
|
||||
if err != nil {
|
||||
transport.CloseIdleConnections()
|
||||
return nil, fmt.Errorf("隧道 WebSocket 握手: %w", err)
|
||||
}
|
||||
return websocket.NetConn(context.Background(), connection, websocket.MessageBinary), nil
|
||||
}
|
||||
|
||||
func (p *websocketProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("WebSocket 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
type serverDialer struct {
|
||||
netapi.EmptyDispatch
|
||||
address string
|
||||
}
|
||||
|
||||
func (d *serverDialer) Conn(ctx context.Context, _ netapi.Address) (net.Conn, error) {
|
||||
return newServerNetDialer().DialContext(ctx, "tcp", d.address)
|
||||
}
|
||||
|
||||
func newServerNetDialer() *net.Dialer {
|
||||
return &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
}
|
||||
|
||||
func newTunnelHandshakeContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, tunnelHandshakeTimeout)
|
||||
}
|
||||
|
||||
func websocketTLSConfig(config Config) *tls.Config {
|
||||
tlsConfig := (&tlsProxy{config: config}).tlsConfig()
|
||||
tlsConfig.NextProtos = []string{"http/1.1"}
|
||||
return tlsConfig
|
||||
}
|
||||
|
||||
func validateWebSocketHost(host string) error {
|
||||
parsed, err := url.Parse("http://" + strings.TrimSpace(host))
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return errors.New("WebSocket host 无效")
|
||||
}
|
||||
if parsed.Port() != "" {
|
||||
if _, err := canonicalServer(parsed.Hostname(), parsed.Port()); err != nil {
|
||||
return errors.New("WebSocket host 无效")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *serverDialer) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("当前隧道代理不支持 UDP")
|
||||
}
|
||||
|
||||
func canonicalServer(host, port string) (string, error) {
|
||||
host = strings.TrimSpace(strings.Trim(host, "[]"))
|
||||
if host == "" {
|
||||
return "", errors.New("隧道代理服务器不能为空")
|
||||
}
|
||||
parsedPort, err := strconv.ParseUint(strings.TrimSpace(port), 10, 16)
|
||||
if err != nil || parsedPort == 0 {
|
||||
return "", errors.New("隧道代理端口无效")
|
||||
}
|
||||
return net.JoinHostPort(host, strconv.FormatUint(parsedPort, 10)), nil
|
||||
}
|
||||
|
||||
func decodeBase64String(value string) (string, error) {
|
||||
decoded, err := decodeBase64Bytes(value)
|
||||
return string(decoded), err
|
||||
}
|
||||
|
||||
func decodeBase64Bytes(value string) ([]byte, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
for _, encoding := range []*base64.Encoding{base64.RawStdEncoding, base64.StdEncoding, base64.RawURLEncoding, base64.URLEncoding} {
|
||||
if decoded, err := encoding.DecodeString(value); err == nil {
|
||||
return decoded, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid base64")
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func splitList(value string) []string {
|
||||
var result []string
|
||||
for item := range strings.SplitSeq(value, ",") {
|
||||
if item = strings.TrimSpace(item); item != "" {
|
||||
result = append(result, item)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func queryBool(query url.Values, names ...string) (bool, error) {
|
||||
for _, name := range names {
|
||||
if raw, ok := query[name]; ok && len(raw) != 0 {
|
||||
return parseBool(raw[0], name)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func jsonBool(value map[string]any, name string) (bool, error) {
|
||||
raw, ok := value[name]
|
||||
if !ok || raw == nil {
|
||||
return false, nil
|
||||
}
|
||||
switch typed := raw.(type) {
|
||||
case bool:
|
||||
return typed, nil
|
||||
case string:
|
||||
return parseBool(typed, name)
|
||||
case float64:
|
||||
return parseBool(strconv.FormatFloat(typed, 'f', -1, 64), name)
|
||||
default:
|
||||
return false, fmt.Errorf("%s 必须是布尔值", name)
|
||||
}
|
||||
}
|
||||
|
||||
func parseBool(value, name string) (bool, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "1", "true", "yes":
|
||||
return true, nil
|
||||
case "", "0", "false", "no":
|
||||
return false, nil
|
||||
default:
|
||||
return false, fmt.Errorf("%s 必须是布尔值", name)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonString(value map[string]any, name string) string {
|
||||
raw, ok := value[name]
|
||||
if !ok || raw == nil {
|
||||
return ""
|
||||
}
|
||||
switch typed := raw.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(typed)
|
||||
case float64:
|
||||
return strconv.FormatFloat(typed, 'f', -1, 64)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package tunnelproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
const testUUID = "123e4567-e89b-12d3-a456-426614174000"
|
||||
|
||||
func TestNormalizeStripsRemarksAndBuildsDialers(t *testing.T) {
|
||||
vmessJSON := fmt.Sprintf(`{"v":"2","ps":"node one","add":"proxy.example","port":"443","id":%q,"aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`, testUUID)
|
||||
vmessURL := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(vmessJSON))
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
}{
|
||||
{name: "trojan", raw: "trojan://secret@proxy.example:443?security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"},
|
||||
{name: "vless", raw: "vless://" + testUUID + "@proxy.example:443?encryption=none&security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"},
|
||||
{name: "shadowsocks", raw: "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388#one"},
|
||||
{name: "vmess", raw: vmessURL},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
normalized, err := Normalize(test.raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(normalized, "#") || strings.Contains(normalized, "node one") {
|
||||
t.Fatalf("remark leaked into normalized URL: %q", normalized)
|
||||
}
|
||||
if _, err := NewDialer(normalized); err != nil {
|
||||
t.Fatalf("construct dialer: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) {
|
||||
base := "trojan://secret@proxy.example:443?security=tls&sni=edge.example"
|
||||
one, err := Normalize(base + "#one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, err := Normalize(base + "#two")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if one != two {
|
||||
t.Fatalf("remark changed identity: %q != %q", one, two)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeEquivalentShareLinksHaveOneIdentity(t *testing.T) {
|
||||
trojanOne, err := Normalize("trojan://secret@proxy.example:443?type=websocket&security=tls&sni=edge.example&host=edge.example&path=ws")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
trojanTwo, err := Normalize("trojan://secret@proxy.example:443?network=ws&peer=edge.example&host=edge.example&path=%2Fws")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if trojanOne != trojanTwo {
|
||||
t.Fatalf("equivalent Trojan links have different identities: %q != %q", trojanOne, trojanTwo)
|
||||
}
|
||||
|
||||
vmessOne := vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "ws", "tls": "tls",
|
||||
"sni": "edge.example", "host": "edge.example", "path": "ws",
|
||||
})
|
||||
vmessTwo := vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "ws", "tls": "tls",
|
||||
"sni": "edge.example", "host": "edge.example", "path": "/ws",
|
||||
})
|
||||
normalizedOne, err := Normalize(vmessOne)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
normalizedTwo, err := Normalize(vmessTwo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if normalizedOne != normalizedTwo {
|
||||
t.Fatalf("equivalent VMess links have different identities: %q != %q", normalizedOne, normalizedTwo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
if err := server.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tracked := &closeTrackingConn{Conn: client}
|
||||
config := &protocol.Vless{}
|
||||
config.SetUuid(testUUID)
|
||||
proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := proxy.Conn(context.Background(), netapi.ParseDomainPort("tcp", "target.example", 443)); err == nil {
|
||||
t.Fatal("VLESS initial write unexpectedly succeeded")
|
||||
}
|
||||
if !tracked.closed {
|
||||
t.Fatal("failed VLESS connection was not closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTunnelHandshakeContextHasIndependentDeadline(t *testing.T) {
|
||||
ctx, cancel := newTunnelHandshakeContext(context.Background())
|
||||
defer cancel()
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
t.Fatal("tunnel handshake context has no deadline")
|
||||
}
|
||||
remaining := time.Until(deadline)
|
||||
if remaining <= 0 || remaining > tunnelHandshakeTimeout {
|
||||
t.Fatalf("tunnel handshake deadline remaining = %v", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeSupportsLegacyShadowsocks(t *testing.T) {
|
||||
raw := "ss://" + base64.RawStdEncoding.EncodeToString([]byte("chacha20-ietf-poly1305:secret@proxy.example:8388")) + "#legacy"
|
||||
normalized, err := Normalize(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(normalized, "ss://") || strings.Contains(normalized, "#") {
|
||||
t.Fatalf("normalized legacy URL = %q", normalized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"hysteria2://secret@proxy.example:443",
|
||||
"tuic://user:secret@proxy.example:443",
|
||||
"vless://not-a-uuid@proxy.example:443?encryption=none",
|
||||
"vless://" + testUUID + "@proxy.example:443?encryption=none&flow=xtls-rprx-vision",
|
||||
"trojan://secret@proxy.example:443?type=grpc",
|
||||
"trojan://secret@proxy.example:443/unexpected",
|
||||
"ss://" + base64.RawURLEncoding.EncodeToString([]byte("rc4-md5:secret")) + "@proxy.example:8388",
|
||||
"ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388/unexpected",
|
||||
"vmess://not-base64",
|
||||
} {
|
||||
if _, err := Normalize(raw); err == nil {
|
||||
t.Fatalf("invalid tunnel accepted: %q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketTransportCarriesBinaryStream(t *testing.T) {
|
||||
handlerResult := make(chan error, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Host != "edge.example" || request.URL.Path != "/ws" {
|
||||
handlerResult <- fmt.Errorf("request host=%q path=%q", request.Host, request.URL.Path)
|
||||
return
|
||||
}
|
||||
connection, err := websocket.Accept(writer, request, nil)
|
||||
if err != nil {
|
||||
handlerResult <- err
|
||||
return
|
||||
}
|
||||
stream := websocket.NetConn(context.Background(), connection, websocket.MessageBinary)
|
||||
defer stream.Close()
|
||||
_, err = io.CopyN(stream, stream, 4)
|
||||
handlerResult <- err
|
||||
}))
|
||||
defer server.Close()
|
||||
serverAddress := strings.TrimPrefix(server.URL, "http://")
|
||||
proxy := &websocketProxy{
|
||||
config: Config{Server: serverAddress, WebSocketHost: "edge.example", WebSocketPath: "/ws"},
|
||||
dialer: &serverDialer{address: serverAddress},
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
connection, err := proxy.Conn(ctx, netapi.ParseDomainPort("tcp", "target.example", 443))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer connection.Close()
|
||||
if _, err := connection.Write([]byte("pong")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := make([]byte, 4)
|
||||
if _, err := io.ReadFull(connection, response); err != nil || string(response) != "pong" {
|
||||
t.Fatalf("response=%q err=%v", response, err)
|
||||
}
|
||||
if err := <-handlerResult; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type closeTrackingConn struct {
|
||||
net.Conn
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *closeTrackingConn) Close() error {
|
||||
c.closed = true
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
func vmessTestURL(t *testing.T, config map[string]any) string {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return "vmess://" + base64.RawStdEncoding.EncodeToString(payload)
|
||||
}
|
||||
@@ -16,4 +16,94 @@ type AuditRepository interface {
|
||||
ListCursor(ctx context.Context, query AuditCursorQuery) ([]audit.Record, bool, error)
|
||||
Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error)
|
||||
SumTokensByAccountsSince(ctx context.Context, accountIDs []uint64, since time.Time) (map[uint64]int64, error)
|
||||
SummarizeDegrade(ctx context.Context, query DegradeSummaryQuery) (DegradeSummaryResult, error)
|
||||
}
|
||||
|
||||
type DegradeSummaryQuery struct {
|
||||
Start time.Time
|
||||
End time.Time
|
||||
SoftTPS float64
|
||||
HardTPS float64
|
||||
MinGenerationMS int64
|
||||
MinOutputTokens int64
|
||||
FailClosed bool
|
||||
AccountSearch string
|
||||
AccountStatus string
|
||||
AccountClass string
|
||||
MinHits int
|
||||
AccountOffset int
|
||||
AccountLimit int
|
||||
Buckets []DegradeBucketRange
|
||||
RecentLimit int
|
||||
}
|
||||
|
||||
type DegradeBucketRange struct {
|
||||
Start time.Time
|
||||
End time.Time
|
||||
}
|
||||
|
||||
type DegradeSummaryResult struct {
|
||||
Totals DegradeTotals
|
||||
Accounts []DegradeAccount
|
||||
AccountTotal int64
|
||||
AccountOffset int
|
||||
Nodes []DegradeNode
|
||||
Buckets []DegradeBucket
|
||||
Events []DegradeEvent
|
||||
}
|
||||
|
||||
type DegradeTotals struct {
|
||||
Hits int64
|
||||
Accounts int64
|
||||
StillEnabled int64
|
||||
Disabled int64
|
||||
Deleted int64
|
||||
Hard int64
|
||||
Soft int64
|
||||
Burst int64
|
||||
MaxTPS float64
|
||||
}
|
||||
|
||||
type DegradeAccount struct {
|
||||
ID uint64
|
||||
Name string
|
||||
Email string
|
||||
Hits int64
|
||||
MaxTPS float64
|
||||
Burst int64
|
||||
Soft int64
|
||||
Hard int64
|
||||
Last time.Time
|
||||
Enabled bool
|
||||
Found bool
|
||||
BuildBotFlagSource int
|
||||
Nodes []string
|
||||
}
|
||||
|
||||
type DegradeNode struct {
|
||||
Name string
|
||||
Hits int64
|
||||
Accounts int64
|
||||
MaxTPS float64
|
||||
}
|
||||
|
||||
type DegradeBucket struct {
|
||||
Index int
|
||||
Count int64
|
||||
Severe int64
|
||||
}
|
||||
|
||||
// DegradeEvent is a classified streaming-success audit.
|
||||
type DegradeEvent struct {
|
||||
ID uint64
|
||||
RequestID string
|
||||
AccountID *uint64
|
||||
AccountName string
|
||||
EgressNodeID *uint64
|
||||
EgressNodeName string
|
||||
OutputTokens int64
|
||||
TPS float64
|
||||
Class string
|
||||
CreatedAt time.Time
|
||||
Model string
|
||||
}
|
||||
@@ -29,6 +29,7 @@ func NewQualityGuardHandler(service *auditapp.Service, clientKeyID uint64) *Hand
|
||||
func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.GET("/request-audits", h.list)
|
||||
router.GET("/request-audits/summary", h.summary)
|
||||
router.GET("/request-audits/degrade-accounts", h.degradeAccounts)
|
||||
router.GET("/request-audits/:id", h.get)
|
||||
}
|
||||
|
||||
@@ -333,6 +334,133 @@ func (h *Handler) summary(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) degradeAccounts(c *gin.Context) {
|
||||
softTPS, _ := strconv.ParseFloat(c.Query("softTPS"), 64)
|
||||
hardTPS, _ := strconv.ParseFloat(c.Query("hardTPS"), 64)
|
||||
minGenMS, _ := strconv.ParseInt(c.Query("minGenMs"), 10, 64)
|
||||
failClosed, _ := strconv.ParseBool(c.Query("failClosed"))
|
||||
minHits, _ := strconv.Atoi(c.Query("minHits"))
|
||||
page, _ := strconv.Atoi(c.Query("page"))
|
||||
pageSize, _ := strconv.Atoi(c.Query("pageSize"))
|
||||
result, err := h.service.DegradeSummary(
|
||||
c.Request.Context(), c.DefaultQuery("window", "24h"),
|
||||
auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS, MinGenMS: minGenMS, FailClosed: failClosed},
|
||||
auditapp.DegradeAccountFilter{
|
||||
Search: c.Query("search"), Status: c.Query("status"), Class: c.Query("class"), MinHits: minHits,
|
||||
Page: page, PageSize: pageSize,
|
||||
},
|
||||
)
|
||||
if errors.Is(err, auditapp.ErrInvalidPeriod) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidAuditPeriod", "window 仅支持 1h、6h、24h、7d")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "auditDegradeFailed", "读取降智账号失败")
|
||||
return
|
||||
}
|
||||
accounts := make([]degradeAccountResponse, 0, len(result.Accounts))
|
||||
for _, account := range result.Accounts {
|
||||
accounts = append(accounts, degradeAccountResponse{
|
||||
ID: strconv.FormatUint(account.ID, 10), Name: account.Name, Email: account.Email, Hits: account.Hits,
|
||||
MaxTPS: account.MaxTPS, Classes: account.Classes, Nodes: account.Nodes, Last: account.Last,
|
||||
Enabled: account.Enabled, Found: account.Found, BFS: account.BFS,
|
||||
})
|
||||
}
|
||||
events := make([]degradeEventResponse, 0, len(result.Events))
|
||||
for _, event := range result.Events {
|
||||
item := degradeEventResponse{
|
||||
ID: strconv.FormatUint(event.ID, 10), RequestID: event.RequestID, AccountName: event.AccountName,
|
||||
NodeName: event.NodeName, OutputTokens: event.OutputTokens, TPS: event.TPS, Class: event.Class,
|
||||
CreatedAt: event.CreatedAt, Model: event.Model,
|
||||
}
|
||||
if event.AccountID != nil {
|
||||
id := strconv.FormatUint(*event.AccountID, 10)
|
||||
item.AccountID = &id
|
||||
}
|
||||
events = append(events, item)
|
||||
}
|
||||
response.Success(c, http.StatusOK, degradeSummaryResponse{
|
||||
Window: result.Window, GeneratedAt: result.GeneratedAt,
|
||||
Thresholds: degradeThresholdsResponse{SoftTPS: result.Thresholds.SoftTPS, HardTPS: result.Thresholds.HardTPS, MinGenMS: result.Thresholds.MinGenMS, MinOut: result.Thresholds.MinOut},
|
||||
Totals: degradeTotalsResponse{
|
||||
Hits: result.Totals.Hits, Accounts: result.Totals.Accounts, StillEnabled: result.Totals.StillEnabled,
|
||||
Disabled: result.Totals.Disabled, Deleted: result.Totals.Deleted, Hard: result.Totals.Hard,
|
||||
Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS,
|
||||
},
|
||||
Series: result.Series, Nodes: result.Nodes, Accounts: accounts,
|
||||
AccountPage: degradeAccountPageResponse{
|
||||
Page: result.AccountPage.Page, PageSize: result.AccountPage.PageSize,
|
||||
Total: result.AccountPage.Total, HasMore: result.AccountPage.HasMore,
|
||||
},
|
||||
Events: events,
|
||||
})
|
||||
}
|
||||
|
||||
type degradeSummaryResponse struct {
|
||||
Window string `json:"window"`
|
||||
GeneratedAt time.Time `json:"generatedAt"`
|
||||
Thresholds degradeThresholdsResponse `json:"thresholds"`
|
||||
Totals degradeTotalsResponse `json:"totals"`
|
||||
Series []auditapp.DegradeBucket `json:"series"`
|
||||
Nodes []auditapp.DegradeNode `json:"nodes"`
|
||||
Accounts []degradeAccountResponse `json:"accounts"`
|
||||
AccountPage degradeAccountPageResponse `json:"accountPage"`
|
||||
Events []degradeEventResponse `json:"events"`
|
||||
}
|
||||
|
||||
type degradeAccountPageResponse struct {
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
type degradeThresholdsResponse struct {
|
||||
SoftTPS float64 `json:"softTPS"`
|
||||
HardTPS float64 `json:"hardTPS"`
|
||||
MinGenMS int64 `json:"minGenMs"`
|
||||
MinOut int64 `json:"minOutputTokens"`
|
||||
}
|
||||
|
||||
type degradeTotalsResponse struct {
|
||||
Hits int64 `json:"hits"`
|
||||
Accounts int64 `json:"accounts"`
|
||||
StillEnabled int64 `json:"stillEnabled"`
|
||||
Disabled int64 `json:"disabled"`
|
||||
Deleted int64 `json:"deleted"`
|
||||
Hard int64 `json:"hard"`
|
||||
Soft int64 `json:"soft"`
|
||||
Burst int64 `json:"burst"`
|
||||
MaxTPS float64 `json:"maxTPS"`
|
||||
}
|
||||
|
||||
type degradeAccountResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Hits int64 `json:"hits"`
|
||||
MaxTPS float64 `json:"maxTPS"`
|
||||
Classes map[string]int64 `json:"classes"`
|
||||
Nodes []string `json:"nodes"`
|
||||
Last time.Time `json:"last"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Found bool `json:"found"`
|
||||
BFS int `json:"bfs"`
|
||||
}
|
||||
|
||||
type degradeEventResponse struct {
|
||||
ID string `json:"id"`
|
||||
RequestID string `json:"requestId"`
|
||||
AccountID *string `json:"accountId,omitempty"`
|
||||
AccountName string `json:"accountName"`
|
||||
NodeName string `json:"nodeName"`
|
||||
OutputTokens int64 `json:"outputTokens"`
|
||||
TPS float64 `json:"tps"`
|
||||
Class string `json:"class"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
func newListFilter(c *gin.Context) auditapp.ListFilter {
|
||||
return auditapp.ListFilter{
|
||||
Model: c.Query("model"), Status: c.Query("status"), Mode: c.Query("mode"),
|
||||
|
||||
@@ -163,3 +163,42 @@ func TestAuditResponseExplainsBillingWithoutChangingStoredTotal(t *testing.T) {
|
||||
t.Fatalf("historical billing = %#v", historical.Billing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDegradeAccountsListsHardHitsAndRejectsUnknownWindow(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-handler.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewAuditRepository(database)
|
||||
now := time.Now().UTC()
|
||||
first := int64(100)
|
||||
accountID := uint64(11)
|
||||
if err := repo.Create(ctx, auditdomain.Record{
|
||||
RequestID: "degrade-hard", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, AccountName: "noisy",
|
||||
EgressNodeName: "edge-1", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Minute),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := gin.New()
|
||||
NewHandler(auditapp.NewService(repo, slog.Default(), 8, 4, time.Second)).Register(router.Group("/api/admin/v1"))
|
||||
|
||||
ok := httptest.NewRecorder()
|
||||
router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000&failClosed=false&page=1&pageSize=20", nil))
|
||||
if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) ||
|
||||
!strings.Contains(ok.Body.String(), `"found":false`) || !strings.Contains(ok.Body.String(), `"deleted":1`) ||
|
||||
!strings.Contains(ok.Body.String(), `"accountPage":{"page":1,"pageSize":20,"total":1,"hasMore":false}`) {
|
||||
t.Fatalf("status=%d body=%s", ok.Code, ok.Body.String())
|
||||
}
|
||||
|
||||
bad := httptest.NewRecorder()
|
||||
router.ServeHTTP(bad, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=3h", nil))
|
||||
if bad.Code != http.StatusBadRequest || !strings.Contains(bad.Body.String(), "invalidAuditPeriod") {
|
||||
t.Fatalf("bad window status=%d body=%s", bad.Code, bad.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,8 @@ type qualityGuardConfig struct {
|
||||
QuarantineSeconds int `json:"quarantine_seconds"`
|
||||
MinHealthyNodes int `json:"min_healthy_nodes"`
|
||||
MaxOutputTokens int `json:"max_output_tokens"`
|
||||
FailClosed bool `json:"fail_closed"`
|
||||
MinGenerationMS int `json:"min_generation_ms"`
|
||||
Prompt string `json:"prompt"`
|
||||
Expected string `json:"expected"`
|
||||
}
|
||||
@@ -194,6 +196,7 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) {
|
||||
"hard_tps": state.Guard.HardTPS, "consecutive_soft": state.Guard.ConsecutiveSoft,
|
||||
"consecutive_errors": state.Guard.ConsecutiveErrors, "quarantine_seconds": state.Guard.QuarantineSeconds,
|
||||
"min_healthy_nodes": state.Guard.MinHealthyNodes, "max_output_tokens": state.Guard.MaxOutputTokens,
|
||||
"fail_closed": state.Guard.FailClosed, "min_generation_ms": state.Guard.MinGenerationMS,
|
||||
},
|
||||
"nodes": state.Nodes, "protectedNodeIds": state.ProtectedNodeIDs, "recentEvents": state.RecentEvents,
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
|
||||
func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) {
|
||||
path := t.TempDir() + "/state.json"
|
||||
state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}`
|
||||
state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"fail_closed":true,"min_generation_ms":1234,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}`
|
||||
if err := os.WriteFile(path, []byte(state), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -25,7 +25,7 @@ func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) {
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
context.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil)
|
||||
NewHandler(nil, path).qualityGuardStatus(context)
|
||||
if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) {
|
||||
if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) || !strings.Contains(recorder.Body.String(), `"fail_closed":true`) || !strings.Contains(recorder.Body.String(), `"min_generation_ms":1234`) {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "must-not-leak") || strings.Contains(recorder.Body.String(), "private-probe-prompt") || strings.Contains(recorder.Body.String(), "private-marker") || strings.Contains(recorder.Body.String(), "client_key_id") || !strings.Contains(recorder.Body.String(), `"recentEvents":[]`) {
|
||||
|
||||
@@ -87,6 +87,7 @@ type grokModelCapability struct {
|
||||
// Codex catalogs never diverge from the levels each model actually supports.
|
||||
var grokCapabilities = map[string]grokModelCapability{
|
||||
"grok-4.5": {500000, "xAI Grok 4.5 frontier model with reasoning and vision.", true},
|
||||
"grok-4.6": {500000, "xAI Grok 4.6 frontier model with reasoning and vision.", true},
|
||||
"grok-4.3": {1000000, "xAI Grok 4.3 high-capacity reasoning model.", true},
|
||||
"grok-build-0.1": {256000, "xAI Grok Build 0.1 coding model.", false},
|
||||
"grok-4.20-0309-reasoning": {2000000, "xAI Grok 4.20 reasoning model.", true},
|
||||
|
||||
@@ -44,6 +44,7 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) {
|
||||
now := time.Unix(100, 0).UTC()
|
||||
base := newModelListItems([]modeldomain.Route{
|
||||
{PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now},
|
||||
{PublicID: "Build/grok-4.6", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now},
|
||||
{PublicID: "Console/grok-4.3", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, CreatedAt: now},
|
||||
{PublicID: "Console/grok-4.20-0309-reasoning", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, CreatedAt: now},
|
||||
{PublicID: "Build/grok-build-0.1", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now},
|
||||
@@ -53,7 +54,7 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) {
|
||||
for _, item := range expanded {
|
||||
ids[item.ID] = true
|
||||
}
|
||||
for _, want := range []string{"grok-4.5", "grok-4.5-low", "grok-4.5-medium", "grok-4.5-high", "grok-4.3-none", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", "grok-build-0.1"} {
|
||||
for _, want := range []string{"grok-4.5", "grok-4.5-low", "grok-4.5-medium", "grok-4.5-high", "grok-4.6", "grok-4.6-low", "grok-4.6-medium", "grok-4.6-high", "grok-4.6-xhigh", "grok-4.3-none", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", "grok-build-0.1"} {
|
||||
if !ids[want] {
|
||||
t.Fatalf("missing model %q in %#v", want, expanded)
|
||||
}
|
||||
@@ -68,6 +69,24 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendReasoningModelAliasesIncludesConsoleGrok46XHigh(t *testing.T) {
|
||||
expanded := appendReasoningModelAliases([]modelListItem{{
|
||||
ID: "grok-4.6", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses,
|
||||
}})
|
||||
ids := make(map[string]bool, len(expanded))
|
||||
for _, item := range expanded {
|
||||
ids[item.ID] = true
|
||||
}
|
||||
for _, want := range []string{"grok-4.6-low", "grok-4.6-medium", "grok-4.6-high", "grok-4.6-xhigh"} {
|
||||
if !ids[want] {
|
||||
t.Fatalf("missing Console alias %q in %#v", want, expanded)
|
||||
}
|
||||
}
|
||||
if ids["grok-4.6-max"] {
|
||||
t.Fatalf("client compatibility value max must not be advertised as a model alias: %#v", expanded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCodexModelCatalogIncludesRequiredProtocolFields(t *testing.T) {
|
||||
now := time.Unix(100, 0).UTC()
|
||||
items := newModelListItems([]modeldomain.Route{
|
||||
@@ -109,6 +128,42 @@ func TestNewCodexModelCatalogIncludesRequiredProtocolFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexCatalogUsesGrok46MetadataForBaseAndXHighAlias(t *testing.T) {
|
||||
items := []modelListItem{
|
||||
{ID: "grok-4.6", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses},
|
||||
{ID: "grok-4.6-xhigh", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses},
|
||||
}
|
||||
models := newCodexModelCatalog(items).Models
|
||||
if len(models) != 2 {
|
||||
t.Fatalf("model count = %d, want 2", len(models))
|
||||
}
|
||||
|
||||
base := models[0]
|
||||
if base.ContextWindow != 500000 || base.MaxContextWindow != 500000 {
|
||||
t.Fatalf("grok-4.6 context window = %d/%d, want 500000/500000", base.ContextWindow, base.MaxContextWindow)
|
||||
}
|
||||
if base.Description != "xAI Grok 4.6 frontier model with reasoning and vision." {
|
||||
t.Fatalf("grok-4.6 description = %q", base.Description)
|
||||
}
|
||||
if len(base.InputModalities) != 2 || base.InputModalities[0] != "text" || base.InputModalities[1] != "image" {
|
||||
t.Fatalf("grok-4.6 input modalities = %#v, want text/image", base.InputModalities)
|
||||
}
|
||||
if base.DefaultReasoningLevel != "medium" || len(base.SupportedReasoningLevels) != 4 || base.SupportedReasoningLevels[3].Effort != "xhigh" {
|
||||
t.Fatalf("grok-4.6 reasoning metadata = default %q, levels %#v", base.DefaultReasoningLevel, base.SupportedReasoningLevels)
|
||||
}
|
||||
if !base.SupportsReasoningSummaryParameter || !base.SupportsReasoningSummaries {
|
||||
t.Fatalf("grok-4.6 reasoning support missing: %#v", base)
|
||||
}
|
||||
|
||||
alias := models[1]
|
||||
if alias.ContextWindow != base.ContextWindow || alias.MaxContextWindow != base.MaxContextWindow || alias.Description != base.Description {
|
||||
t.Fatalf("grok-4.6-xhigh did not inherit base metadata: %#v", alias)
|
||||
}
|
||||
if len(alias.InputModalities) != 2 || alias.DefaultReasoningLevel != "xhigh" || len(alias.SupportedReasoningLevels) != 1 || alias.SupportedReasoningLevels[0].Effort != "xhigh" {
|
||||
t.Fatalf("grok-4.6-xhigh metadata = %#v", alias)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexCatalogMarksConsoleGrok420AsFixedReasoning(t *testing.T) {
|
||||
entry := newCodexModelCatalog([]modelListItem{{
|
||||
ID: "grok-4.20-0309-reasoning", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses,
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
modelapp "github.com/chenyme/grok2api/backend/internal/application/model"
|
||||
@@ -18,6 +21,11 @@ import (
|
||||
|
||||
type Handler struct{ service *modelapp.Service }
|
||||
|
||||
const (
|
||||
modelSyncHeartbeatInterval = 15 * time.Second
|
||||
modelSyncWriteTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
func NewHandler(service *modelapp.Service) *Handler { return &Handler{service: service} }
|
||||
|
||||
func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
@@ -234,12 +242,94 @@ func (h *Handler) batchDelete(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *Handler) sync(c *gin.Context) {
|
||||
count, err := h.service.Sync(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadGateway, "modelSyncFailed", "同步上游模型失败")
|
||||
c.Header("Content-Type", "text/event-stream; charset=utf-8")
|
||||
c.Header("Cache-Control", "no-cache, no-transform")
|
||||
c.Header("X-Accel-Buffering", "no")
|
||||
if err := writeModelSyncComment(c, "connected"); err != nil {
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"synced": count})
|
||||
|
||||
type syncResult struct {
|
||||
synced int
|
||||
err error
|
||||
}
|
||||
result := make(chan syncResult, 1)
|
||||
ctx, cancel := context.WithCancel(c.Request.Context())
|
||||
defer cancel()
|
||||
var completed atomic.Int64
|
||||
var total atomic.Int64
|
||||
go func() {
|
||||
synced, err := h.service.SyncObserved(ctx, func(current, maximum int) {
|
||||
completed.Store(int64(current))
|
||||
total.Store(int64(maximum))
|
||||
})
|
||||
result <- syncResult{synced: synced, err: err}
|
||||
}()
|
||||
|
||||
heartbeat := time.NewTicker(modelSyncHeartbeatInterval)
|
||||
defer heartbeat.Stop()
|
||||
progressTicker := time.NewTicker(250 * time.Millisecond)
|
||||
defer progressTicker.Stop()
|
||||
lastCompleted, lastTotal := -1, -1
|
||||
for {
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
case value := <-result:
|
||||
if value.err != nil {
|
||||
_ = writeModelSyncEvent(c, "error", gin.H{"code": "modelSyncFailed", "message": "同步模型能力失败"})
|
||||
return
|
||||
}
|
||||
_ = writeModelSyncEvent(c, "complete", gin.H{"synced": value.synced})
|
||||
return
|
||||
case <-heartbeat.C:
|
||||
if err := writeModelSyncComment(c, "heartbeat"); err != nil {
|
||||
return
|
||||
}
|
||||
case <-progressTicker.C:
|
||||
current, maximum := int(completed.Load()), int(total.Load())
|
||||
if maximum > 0 && (current != lastCompleted || maximum != lastTotal) {
|
||||
if err := writeModelSyncEvent(c, "progress", gin.H{"completed": current, "total": maximum}); err != nil {
|
||||
return
|
||||
}
|
||||
lastCompleted, lastTotal = current, maximum
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeModelSyncEvent(c *gin.Context, event string, value any) error {
|
||||
payload, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setModelSyncWriteDeadline(c.Writer); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event, payload); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Writer.Flush()
|
||||
return c.Request.Context().Err()
|
||||
}
|
||||
|
||||
func writeModelSyncComment(c *gin.Context, comment string) error {
|
||||
if err := setModelSyncWriteDeadline(c.Writer); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(c.Writer, ": %s\n\n", comment); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Writer.Flush()
|
||||
return c.Request.Context().Err()
|
||||
}
|
||||
|
||||
func setModelSyncWriteDeadline(writer http.ResponseWriter) error {
|
||||
err := http.NewResponseController(writer).SetWriteDeadline(time.Now().Add(modelSyncWriteTimeout))
|
||||
if errors.Is(err, http.ErrNotSupported) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Handler) update(c *gin.Context) {
|
||||
|
||||
@@ -1,13 +1,38 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
modelapp "github.com/chenyme/grok2api/backend/internal/application/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestSyncStreamsTerminalFailureInsteadOfAcknowledgingSuccess(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
context.Request = httptest.NewRequest(http.MethodPost, "/api/admin/v1/models/sync", nil)
|
||||
|
||||
handler := NewHandler(modelapp.NewService(nil, nil, nil, nil))
|
||||
handler.sync(context)
|
||||
|
||||
if contentType := recorder.Header().Get("Content-Type"); !strings.HasPrefix(contentType, "text/event-stream") {
|
||||
t.Fatalf("content type = %q", contentType)
|
||||
}
|
||||
body := recorder.Body.String()
|
||||
if !strings.Contains(body, ": connected\n\n") || !strings.Contains(body, "event: error\ndata: {\"code\":\"modelSyncFailed\"") {
|
||||
t.Fatalf("unexpected stream body: %q", body)
|
||||
}
|
||||
if strings.Contains(body, "event: complete") || strings.Contains(body, "\"synced\":0") {
|
||||
t.Fatalf("failure was acknowledged as success: %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewModelResponseSeparatesPublicAndUpstreamNames(t *testing.T) {
|
||||
response := newModelResponse(modeldomain.Route{
|
||||
ID: 1, PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5",
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ services:
|
||||
# - NET_ADMIN
|
||||
|
||||
# ================================ FLARESOLVERR ================================
|
||||
# 在管理端将 Clearance 模式设为 FlareSolverr,并使用 http://flaresolverr:8191。
|
||||
# 在管理端将 Clearance 模式设为 FlareSolverr 或按需刷新,并使用 http://flaresolverr:8191。
|
||||
# 启动命令:docker compose --profile flaresolverr up -d
|
||||
# Podman:podman compose --profile flaresolverr up -d
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ModelRouteDTO, ModelRouteGroupDTO } from "@/entities/model/types";
|
||||
import { apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { ApiError, apiEventStream, apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { createObjectDecoder, createPaginatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder";
|
||||
import { i18n } from "@/shared/i18n";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
export type ListModelsInput = {
|
||||
@@ -76,8 +77,48 @@ export function listModelGroups(input: ListModelsInput): Promise<PaginatedDTO<Mo
|
||||
return apiRequest(`/api/admin/v1/models/groups?${query}`, {}, decodeModelGroupPage);
|
||||
}
|
||||
|
||||
export function syncModels(): Promise<{ synced: number }> {
|
||||
return apiRequest("/api/admin/v1/models/sync", { method: "POST" }, decodeCountResult<{ synced: number }>("synced"));
|
||||
type ModelSyncEventDTO = {
|
||||
synced?: number;
|
||||
completed?: number;
|
||||
total?: number;
|
||||
code?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const decodeModelSyncEvent = createObjectDecoder<ModelSyncEventDTO>("model sync event", {
|
||||
synced: isOptional(isNumber),
|
||||
completed: isOptional(isNumber),
|
||||
total: isOptional(isNumber),
|
||||
code: isOptional(isString),
|
||||
message: isOptional(isString),
|
||||
});
|
||||
|
||||
export type ModelSyncProgressDTO = { completed: number; total: number };
|
||||
|
||||
export async function syncModels(onProgress?: (progress: ModelSyncProgressDTO) => void): Promise<{ synced: number }> {
|
||||
let result: { synced: number } | undefined;
|
||||
await apiEventStream("/api/admin/v1/models/sync", {
|
||||
method: "POST",
|
||||
headers: { Accept: "text/event-stream" },
|
||||
}, decodeModelSyncEvent, ({ event, data }) => {
|
||||
if (event === "progress" && typeof data.completed === "number" && typeof data.total === "number" && data.total > 0) {
|
||||
onProgress?.({ completed: Math.min(Math.max(0, data.completed), data.total), total: data.total });
|
||||
return;
|
||||
}
|
||||
if (event === "complete" && typeof data.synced === "number") {
|
||||
result = { synced: data.synced };
|
||||
return;
|
||||
}
|
||||
if (event === "error") {
|
||||
const code = data.code ?? "modelSyncFailed";
|
||||
const message = i18n.exists(`apiErrors.${code}`) ? i18n.t(`apiErrors.${code}`) : (data.message ?? i18n.t("apiErrors.requestFailed"));
|
||||
throw new ApiError(502, code, message);
|
||||
}
|
||||
});
|
||||
if (!result) {
|
||||
throw new ApiError(502, "invalidResponse", i18n.t("apiErrors.invalidResponse"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export type ModelAccountOptionDTO = { id: string; name: string };
|
||||
|
||||
@@ -34,6 +34,8 @@ import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime } from "@/shared/lib/format";
|
||||
import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort";
|
||||
|
||||
const modelSyncToastID = "model-sync-progress";
|
||||
|
||||
export function ModelsPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -135,14 +137,21 @@ export function ModelsPage() {
|
||||
});
|
||||
|
||||
const syncMutation = useMutation({
|
||||
mutationFn: syncModels,
|
||||
mutationFn: () => syncModels((progress) => {
|
||||
toast.loading(t("models.syncingProgress", progress), { id: modelSyncToastID });
|
||||
}),
|
||||
onMutate: () => {
|
||||
toast.loading(t("models.syncing"), { id: modelSyncToastID });
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
setSelected(new Set());
|
||||
setPage(1);
|
||||
void queryClient.invalidateQueries({ queryKey: ["models"] });
|
||||
toast.success(t("models.synced", { count: result.synced }));
|
||||
toast.success(t("models.synced", { count: result.synced }), { id: modelSyncToastID });
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : t("errors.generic"), { id: modelSyncToastID });
|
||||
},
|
||||
onError: showError,
|
||||
});
|
||||
|
||||
function showError(error: unknown): void {
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { updateAccountsEnabled } from "@/features/accounts/accounts-api";
|
||||
import { getDegradeAccounts, type DegradeAccountDTO, type DegradeClass, type DegradeSummaryDTO, type DegradeWindow } from "@/features/quality-guard/quality-guard-api";
|
||||
import { EmptyState, ErrorState } from "@/shared/components/data-state";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatCompactDateTime } from "@/shared/lib/format";
|
||||
|
||||
const MUTE_TOAST_ID = "quality-guard-degrade-mute";
|
||||
|
||||
export function DegradeAccountsPanel({ softTPS, hardTPS, failClosed, minGenMs }: { softTPS?: number; hardTPS?: number; failClosed?: boolean; minGenMs?: number }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [period, setPeriod] = useState<DegradeWindow>("24h");
|
||||
const [search, setSearch] = useState("");
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const [status, setStatus] = useState<"all" | "enabled" | "disabled" | "deleted">("all");
|
||||
const [cls, setCls] = useState<"all" | DegradeClass>("all");
|
||||
const [hitsMin, setHitsMin] = useState(1);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(50);
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set());
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS, failClosed, minGenMs, debouncedSearch, status, cls, hitsMin, page, pageSize],
|
||||
queryFn: () => getDegradeAccounts({
|
||||
window: period, softTPS, hardTPS, failClosed, minGenMs, search: debouncedSearch || undefined,
|
||||
status: status === "all" ? undefined : status, class: cls === "all" ? undefined : cls,
|
||||
minHits: hitsMin, page, pageSize,
|
||||
}),
|
||||
refetchInterval: 15_000,
|
||||
});
|
||||
|
||||
const data = query.data;
|
||||
const rows = useMemo(() => data?.accounts ?? [], [data?.accounts]);
|
||||
const selectable = useMemo(() => rows.filter((account) => account.found && account.enabled), [rows]);
|
||||
const selectedRows = selectable.filter((account) => selected.has(account.id));
|
||||
const allSelected = selectable.length > 0 && selectedRows.length === selectable.length;
|
||||
|
||||
const muteMutation = useMutation({
|
||||
mutationFn: (ids: string[]) => updateAccountsEnabled(ids, false, "grok_build"),
|
||||
onMutate: () => toast.loading(t("qualityGuard.degrade.muting"), { id: MUTE_TOAST_ID }),
|
||||
onSuccess: (_, ids) => {
|
||||
setSelected(new Set());
|
||||
void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["accounts"] });
|
||||
toast.success(t("qualityGuard.degrade.muted", { count: ids.length }), { id: MUTE_TOAST_ID });
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }),
|
||||
});
|
||||
const busy = muteMutation.isPending;
|
||||
|
||||
const toggleAll = (checked: boolean) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
selectable.forEach((account) => {
|
||||
if (checked) next.add(account.id);
|
||||
else next.delete(account.id);
|
||||
});
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
if (query.isError && !data) return <ErrorState message={query.error.message} onRetry={() => void query.refetch()} />;
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<section className="grid overflow-hidden rounded-lg bg-card sm:grid-cols-2 xl:grid-cols-4" aria-label={t("qualityGuard.degrade.overview")}>
|
||||
<Metric icon={AlertTriangle} label={t("qualityGuard.degrade.hits")} value={String(data.totals.hits)} detail={t("qualityGuard.degrade.hitsHelp", { burst: data.totals.burst, soft: data.totals.soft, hard: data.totals.hard })} tone={data.totals.hits ? "bad" : "good"} />
|
||||
<Metric icon={Users} label={t("qualityGuard.degrade.accounts")} value={String(data.totals.accounts)} detail={t("qualityGuard.degrade.accountsHelp", { deleted: data.totals.deleted })} />
|
||||
<Metric icon={PowerOff} label={t("qualityGuard.degrade.stillEnabled")} value={String(data.totals.stillEnabled)} detail={t("qualityGuard.degrade.stillEnabledHelp")} tone={data.totals.stillEnabled ? "bad" : "good"} />
|
||||
<Metric icon={Gauge} label={t("qualityGuard.degrade.maxTPS")} value={Math.round(data.totals.maxTPS).toString()} detail={t("qualityGuard.degrade.maxTPSHelp")} tone={data.totals.maxTPS >= data.thresholds.hardTPS ? "bad" : undefined} />
|
||||
</section>
|
||||
|
||||
<div className="grid items-stretch gap-3 xl:grid-cols-[minmax(0,1.4fr)_minmax(260px,0.8fr)]">
|
||||
<SeriesChart series={data.series} empty={t("qualityGuard.degrade.noHits")} title={t("qualityGuard.degrade.series")} />
|
||||
<NodeList nodes={data.nodes} empty={t("qualityGuard.degrade.noNodes")} title={t("qualityGuard.degrade.nodes")} />
|
||||
</div>
|
||||
|
||||
<section className="overflow-hidden rounded-lg bg-card">
|
||||
<div className="flex flex-col gap-3 border-b px-4 py-4 sm:flex-row sm:items-start sm:justify-between sm:px-5">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("qualityGuard.degrade.accountsTitle")}</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{hitsMin > 1
|
||||
? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accountPage.total, min: hitsMin })
|
||||
: t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accountPage.total })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input className="h-8 w-44 pl-8" value={search} onChange={(event) => { setSearch(event.target.value); setPage(1); setSelected(new Set()); }} placeholder={t("qualityGuard.degrade.search")} />
|
||||
</div>
|
||||
<FilterSelect value={period} onChange={(value) => { setSelected(new Set()); setPage(1); setPeriod(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} />
|
||||
<FilterSelect value={status} onChange={(value) => { setStatus(value as "all" | "enabled" | "disabled" | "deleted"); setPage(1); setSelected(new Set()); }} items={[["all", t("qualityGuard.degrade.statusAll")], ["enabled", t("qualityGuard.degrade.statusOn")], ["disabled", t("qualityGuard.degrade.statusOff")], ["deleted", t("qualityGuard.degrade.statusDeleted")]]} />
|
||||
<FilterSelect value={cls} onChange={(value) => { setCls(value as "all" | DegradeClass); setPage(1); setSelected(new Set()); }} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} />
|
||||
<FilterSelect value={String(hitsMin)} onChange={(value) => { setHitsMin(Number(value)); setPage(1); setSelected(new Set()); }} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} />
|
||||
<Button type="button" variant="secondary" size="sm" className="bg-destructive/10 text-destructive hover:bg-destructive/15 hover:text-destructive" disabled={selectedRows.length === 0 || busy} onClick={() => {
|
||||
if (!window.confirm(t("qualityGuard.degrade.muteConfirm", { count: selectedRows.length }))) return;
|
||||
muteMutation.mutate(selectedRows.map((account) => account.id));
|
||||
}}>
|
||||
<PowerOff />{selectedRows.length ? t("qualityGuard.degrade.muteSelectedCount", { count: selectedRows.length }) : t("qualityGuard.degrade.muteSelected")}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" size="icon" className="size-8" onClick={() => void query.refetch()} disabled={query.isFetching} aria-label={t("common.refresh")}>
|
||||
<RefreshCw className={cn("size-4", query.isFetching && "animate-spin")} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<Table className="min-w-[920px]">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-10 px-3"><Checkbox checked={allSelected ? true : selectedRows.length > 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /></TableHead>
|
||||
<TableHead>{t("qualityGuard.degrade.account")}</TableHead>
|
||||
<TableHead>{t("qualityGuard.degrade.status")}</TableHead>
|
||||
<TableHead className="text-right">{t("qualityGuard.degrade.hitCount")}</TableHead>
|
||||
<TableHead className="text-right">{t("qualityGuard.outputTPS")}</TableHead>
|
||||
<TableHead>{t("qualityGuard.degrade.class")}</TableHead>
|
||||
<TableHead>{t("qualityGuard.node")}</TableHead>
|
||||
<TableHead>{t("qualityGuard.lastObserved")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.length === 0 ? (
|
||||
<TableRow><TableCell colSpan={8}><EmptyState message={t("qualityGuard.degrade.noAccounts")} /></TableCell></TableRow>
|
||||
) : rows.map((account) => {
|
||||
const canMute = account.found && account.enabled;
|
||||
return (
|
||||
<TableRow key={account.id} className={canMute ? "cursor-pointer" : undefined} onClick={() => {
|
||||
if (!canMute) return;
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(account.id)) next.delete(account.id);
|
||||
else next.add(account.id);
|
||||
return next;
|
||||
});
|
||||
}}>
|
||||
<TableCell className="px-3" onClick={(event) => event.stopPropagation()}>
|
||||
<label className="flex size-8 cursor-pointer items-center justify-center">
|
||||
<Checkbox disabled={!canMute} checked={selected.has(account.id)} onCheckedChange={(checked) => setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
if (checked === true) next.add(account.id);
|
||||
else next.delete(account.id);
|
||||
return next;
|
||||
})} />
|
||||
</label>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="font-mono text-xs text-muted-foreground">#{account.id}</div>
|
||||
<div className="text-sm">{account.email || account.name || "-"}</div>
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap">
|
||||
{!account.found
|
||||
? <Badge variant="outline" className="whitespace-nowrap text-muted-foreground">{t("qualityGuard.degrade.deletedStatus")}</Badge>
|
||||
: account.enabled
|
||||
? <Badge variant="outline" className="whitespace-nowrap text-destructive">{t("qualityGuard.degrade.scheduling")}</Badge>
|
||||
: <Badge variant="outline" className="whitespace-nowrap text-emerald-600 dark:text-emerald-400">{t("qualityGuard.degrade.disabledStatus")}</Badge>}
|
||||
{account.bfs ? <Badge variant="outline" className="ml-1 whitespace-nowrap text-muted-foreground">bfs {account.bfs}</Badge> : null}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-mono tabular-nums">{account.hits}</TableCell>
|
||||
<TableCell className={cn("text-right font-mono tabular-nums", account.maxTPS >= data.thresholds.hardTPS ? "text-destructive" : account.maxTPS >= data.thresholds.softTPS ? "text-amber-600 dark:text-amber-400" : "")}>{account.maxTPS}</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">{classSummary(account.classes)}</TableCell>
|
||||
<TableCell className="text-xs">{account.nodes.join(" · ") || "-"}</TableCell>
|
||||
<TableCell className="font-mono text-xs">{account.last ? formatCompactDateTime(account.last, i18n.language) : "-"}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{data.accountPage.total > 0 ? (
|
||||
<div className="border-t px-4 py-3 sm:px-5">
|
||||
<Pagination
|
||||
page={data.accountPage.page}
|
||||
pageSize={data.accountPage.pageSize}
|
||||
total={data.accountPage.total}
|
||||
pageSizeOptions={[20, 50, 100]}
|
||||
onPageChange={(value) => { setPage(value); setSelected(new Set()); }}
|
||||
onPageSizeChange={(value) => { setPageSize(value); setPage(1); setSelected(new Set()); }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="overflow-hidden rounded-lg bg-card">
|
||||
<div className="border-b px-4 py-4 sm:px-5">
|
||||
<h2 className="text-sm font-medium">{t("qualityGuard.degrade.events")}</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t("qualityGuard.degrade.eventsHelp")}</p>
|
||||
</div>
|
||||
<div className="max-h-72 overflow-auto">
|
||||
{data.events.length === 0 ? <EmptyState message={t("qualityGuard.degrade.noEvents")} /> : data.events.map((event) => (
|
||||
<div key={event.id} className="grid grid-cols-[7.5rem_minmax(0,1fr)_auto] gap-3 border-b px-4 py-2 last:border-b-0 sm:px-5">
|
||||
<div className="font-mono text-[11px] text-muted-foreground">{formatCompactDateTime(event.createdAt, i18n.language)}</div>
|
||||
<div className="truncate text-xs">#{event.accountId ?? "-"} {event.accountName} · {event.nodeName} · out {event.outputTokens} · {event.requestId}</div>
|
||||
<div className="flex items-center gap-2">{classBadge(event.class)}<span className="font-mono text-xs tabular-nums">{event.tps}</span></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function classSummary(classes: DegradeAccountDTO["classes"]) {
|
||||
return [
|
||||
classes.buffered_burst ? `burst ${classes.buffered_burst}` : "",
|
||||
classes.soft_tps ? `soft ${classes.soft_tps}` : "",
|
||||
classes.hard_tps ? `hard ${classes.hard_tps}` : "",
|
||||
].filter(Boolean).join(" · ") || "-";
|
||||
}
|
||||
|
||||
function classBadge(cls: DegradeClass) {
|
||||
if (cls === "hard_tps") return <Badge variant="outline" className="text-destructive">hard</Badge>;
|
||||
if (cls === "buffered_burst") return <Badge variant="outline" className="text-amber-600 dark:text-amber-400">burst</Badge>;
|
||||
return <Badge variant="outline" className="text-muted-foreground">soft</Badge>;
|
||||
}
|
||||
|
||||
function FilterSelect({ value, onChange, items }: { value: string; onChange: (value: string) => void; items: string[][] }) {
|
||||
return (
|
||||
<Select value={value} onValueChange={onChange}>
|
||||
<SelectTrigger className="h-8 w-auto min-w-28"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{items.map(([itemValue, label]) => <SelectItem key={itemValue} value={itemValue}>{label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
function Metric({ icon: Icon, label, value, detail, tone }: { icon: typeof AlertTriangle; label: string; value: string; detail: string; tone?: "good" | "bad" }) {
|
||||
return (
|
||||
<div className="flex min-h-24 items-center gap-3 border-b p-4 last:border-b-0 sm:[&:nth-child(odd)]:border-r xl:border-b-0 xl:border-r xl:last:border-r-0">
|
||||
<span className={cn("flex size-9 shrink-0 items-center justify-center rounded-md bg-secondary text-muted-foreground", tone === "good" && "text-emerald-600 dark:text-emerald-400", tone === "bad" && "text-destructive")}><Icon className="size-4" /></span>
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="mt-1 truncate text-lg font-medium tabular-nums">{value}</p>
|
||||
<p className="mt-1 truncate text-[11px] text-muted-foreground">{detail}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeriesChart({ series, empty, title }: { series: DegradeSummaryDTO["series"]; empty: string; title: string }) {
|
||||
const max = Math.max(1, ...series.map((item) => item.count));
|
||||
const labelStep = series.length > 12 ? Math.ceil(series.length / 8) : 1;
|
||||
return (
|
||||
<section className="flex h-full min-h-64 flex-col overflow-hidden rounded-lg bg-card">
|
||||
<div className="shrink-0 border-b px-4 py-4 sm:px-5"><h2 className="text-sm font-medium">{title}</h2></div>
|
||||
<div className="flex min-h-0 flex-1 items-stretch gap-1 px-4 pb-3 pt-2 sm:px-5">
|
||||
{series.length === 0 ? <p className="self-center text-xs text-muted-foreground">{empty}</p> : series.map((item, index) => {
|
||||
const height = item.count <= 0 ? 0 : Math.max(6, Math.round((item.count / max) * 100));
|
||||
const showLabel = index % labelStep === 0 || index === series.length - 1;
|
||||
return (
|
||||
<div key={`${item.label}-${index}`} className="flex min-w-0 flex-1 flex-col" title={`${item.label}: ${item.count}`}>
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<div
|
||||
className={cn("absolute inset-x-0 bottom-0 rounded-t-sm", item.severe > 0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500")}
|
||||
style={{ height: `${height}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1 h-4 text-center text-[10px] tabular-nums text-muted-foreground">
|
||||
{showLabel ? shortSeriesLabel(item.label) : ""}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function shortSeriesLabel(label: string) {
|
||||
const hour = label.match(/(\d{1,2})(?::\d{2})?$/);
|
||||
return hour ? hour[1].padStart(2, "0") : label;
|
||||
}
|
||||
|
||||
function NodeList({ nodes, empty, title }: { nodes: DegradeSummaryDTO["nodes"]; empty: string; title: string }) {
|
||||
const max = Math.max(1, ...nodes.map((node) => node.hits));
|
||||
return (
|
||||
<section className="flex h-full min-h-64 flex-col overflow-hidden rounded-lg bg-card">
|
||||
<div className="shrink-0 border-b px-4 py-4 sm:px-5"><h2 className="text-sm font-medium">{title}</h2></div>
|
||||
<div className="min-h-0 flex-1 space-y-2 overflow-auto p-4 sm:p-5">
|
||||
{nodes.length === 0 ? <p className="text-xs text-muted-foreground">{empty}</p> : nodes.map((node) => (
|
||||
<div key={node.name} className="grid grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-3 text-xs">
|
||||
<div>
|
||||
<div>{node.name}</div>
|
||||
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-muted"><i className="block h-full bg-amber-500" style={{ width: `${Math.round(node.hits / max * 100)}%` }} /></div>
|
||||
</div>
|
||||
<span className="font-mono">{node.hits} / {node.accounts}</span>
|
||||
<span className="font-mono">{node.maxTPS}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { apiRequest } from "@/shared/api/client";
|
||||
import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder";
|
||||
import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isObject, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder";
|
||||
|
||||
export type QualityGuardPolicy = {
|
||||
mode: "active" | "passive" | "hybrid";
|
||||
@@ -76,6 +76,8 @@ export type QualityGuardStatus = {
|
||||
quarantine_seconds: number;
|
||||
min_healthy_nodes: number;
|
||||
max_output_tokens: number;
|
||||
fail_closed: boolean;
|
||||
min_generation_ms: number;
|
||||
};
|
||||
nodes?: Record<string, QualityGuardNodeState>;
|
||||
protectedNodeIds?: string[];
|
||||
@@ -110,6 +112,7 @@ const configValidator = hasShape({
|
||||
node_ids: isArrayOf(isString), active_interval_seconds: isNumber, passive_poll_seconds: isNumber,
|
||||
soft_tps: isNumber, hard_tps: isNumber, consecutive_soft: isNumber, consecutive_errors: isNumber,
|
||||
quarantine_seconds: isNumber, min_healthy_nodes: isNumber, max_output_tokens: isNumber,
|
||||
fail_closed: isBoolean, min_generation_ms: isNumber,
|
||||
});
|
||||
const detectionStatsValidator = hasShape({
|
||||
total: isNumber, healthy: isNumber, soft: isNumber, hard: isNumber,
|
||||
@@ -151,3 +154,91 @@ export function runQualityTest(nodeId: string, status: QualityGuardStatus): Prom
|
||||
export function updateQualityGuardPolicy(policy: QualityGuardPolicy): Promise<{ saved: boolean }> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard/config", { method: "PUT", body: policy }, createObjectDecoder("quality guard config update", { saved: isBoolean }));
|
||||
}
|
||||
|
||||
export type DegradeWindow = "1h" | "6h" | "24h" | "7d";
|
||||
export type DegradeClass = "buffered_burst" | "soft_tps" | "hard_tps";
|
||||
|
||||
export type DegradeAccountDTO = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
hits: number;
|
||||
maxTPS: number;
|
||||
classes: Partial<Record<DegradeClass, number>>;
|
||||
nodes: string[];
|
||||
last: string;
|
||||
enabled: boolean;
|
||||
found: boolean;
|
||||
bfs: number;
|
||||
};
|
||||
|
||||
export type DegradeEventDTO = {
|
||||
id: string;
|
||||
requestId: string;
|
||||
accountId?: string;
|
||||
accountName: string;
|
||||
nodeName: string;
|
||||
outputTokens: number;
|
||||
tps: number;
|
||||
class: DegradeClass;
|
||||
createdAt: string;
|
||||
model: string;
|
||||
};
|
||||
|
||||
export type DegradeSummaryDTO = {
|
||||
window: DegradeWindow;
|
||||
generatedAt: string;
|
||||
thresholds: { softTPS: number; hardTPS: number; minGenMs: number; minOutputTokens: number };
|
||||
totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; deleted: number; hard: number; soft: number; burst: number; maxTPS: number };
|
||||
series: { label: string; count: number; severe: number }[];
|
||||
nodes: { name: string; hits: number; accounts: number; maxTPS: number }[];
|
||||
accounts: DegradeAccountDTO[];
|
||||
accountPage: { page: number; pageSize: number; total: number; hasMore: boolean };
|
||||
events: DegradeEventDTO[];
|
||||
};
|
||||
|
||||
const degradeClassValidator = isOneOf("buffered_burst", "soft_tps", "hard_tps");
|
||||
|
||||
const decodeDegradeSummary = createObjectDecoder<DegradeSummaryDTO>("degrade accounts", {
|
||||
window: isOneOf("1h", "6h", "24h", "7d"),
|
||||
generatedAt: isString,
|
||||
thresholds: hasShape({ softTPS: isNumber, hardTPS: isNumber, minGenMs: isNumber, minOutputTokens: isNumber }),
|
||||
totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, deleted: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }),
|
||||
series: isArrayOf(hasShape({ label: isString, count: isNumber, severe: isNumber })),
|
||||
nodes: isArrayOf(hasShape({ name: isString, hits: isNumber, accounts: isNumber, maxTPS: isNumber })),
|
||||
accounts: isArrayOf(hasShape({
|
||||
id: isString, name: isString, email: isString, hits: isNumber, maxTPS: isNumber,
|
||||
classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, found: isBoolean, bfs: isNumber,
|
||||
})),
|
||||
accountPage: hasShape({ page: isNumber, pageSize: isNumber, total: isNumber, hasMore: isBoolean }),
|
||||
events: isArrayOf(hasShape({
|
||||
id: isString, requestId: isString, accountId: isOptional(isString), accountName: isString,
|
||||
nodeName: isString, outputTokens: isNumber, tps: isNumber, class: degradeClassValidator,
|
||||
createdAt: isString, model: isString,
|
||||
})),
|
||||
});
|
||||
|
||||
export function getDegradeAccounts(input: {
|
||||
window: DegradeWindow;
|
||||
softTPS?: number;
|
||||
hardTPS?: number;
|
||||
failClosed?: boolean;
|
||||
minGenMs?: number;
|
||||
search?: string;
|
||||
status?: "enabled" | "disabled" | "deleted";
|
||||
class?: DegradeClass;
|
||||
minHits?: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}): Promise<DegradeSummaryDTO> {
|
||||
const query = new URLSearchParams({ window: input.window, page: String(input.page), pageSize: String(input.pageSize) });
|
||||
if (input.softTPS) query.set("softTPS", String(input.softTPS));
|
||||
if (input.hardTPS) query.set("hardTPS", String(input.hardTPS));
|
||||
if (input.failClosed !== undefined) query.set("failClosed", String(input.failClosed));
|
||||
if (input.minGenMs) query.set("minGenMs", String(input.minGenMs));
|
||||
if (input.search) query.set("search", input.search);
|
||||
if (input.status) query.set("status", input.status);
|
||||
if (input.class) query.set("class", input.class);
|
||||
if (input.minHits && input.minHits > 1) query.set("minHits", String(input.minHits));
|
||||
return apiRequest(`/api/admin/v1/request-audits/degrade-accounts?${query}`, {}, decodeDegradeSummary);
|
||||
}
|
||||
@@ -18,6 +18,8 @@ import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { DegradeAccountsPanel } from "@/features/quality-guard/degrade-accounts-panel";
|
||||
import { getQualityGuardStatus, runQualityTest, updateQualityGuardPolicy, type QualityGuardEvent, type QualityGuardNodeState, type QualityGuardPolicy, type QualityGuardStatistics, type QualityGuardStatus, type QualityTestResult } from "@/features/quality-guard/quality-guard-api";
|
||||
import { createEgressNode, deleteEgressNodes, listAllEgressNodes, updateEgressNode, updateEgressNodesEnabled, type EgressNodeDTO, type EgressNodeInput } from "@/features/settings/settings-api";
|
||||
import { ErrorState } from "@/shared/components/data-state";
|
||||
@@ -159,6 +161,20 @@ export function QualityGuardPage() {
|
||||
)}
|
||||
/>
|
||||
|
||||
<Tabs defaultValue="nodes">
|
||||
<TabsList>
|
||||
<TabsTrigger value="nodes">{t("qualityGuard.nodesTab")}</TabsTrigger>
|
||||
<TabsTrigger value="accounts">{t("qualityGuard.degrade.tab")}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="accounts" className="mt-6">
|
||||
<DegradeAccountsPanel
|
||||
softTPS={status?.config?.soft_tps}
|
||||
hardTPS={status?.config?.hard_tps}
|
||||
failClosed={status?.config?.fail_closed}
|
||||
minGenMs={status?.config?.min_generation_ms}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="nodes" className="mt-6 space-y-6">
|
||||
{!status?.available ? <UnavailableState /> : (
|
||||
<>
|
||||
<section className="grid overflow-hidden rounded-lg bg-card sm:grid-cols-2 xl:grid-cols-4" aria-label={t("qualityGuard.overview")}>
|
||||
@@ -224,6 +240,8 @@ export function QualityGuardPage() {
|
||||
</AlertDialog>
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import { Table, TableActionCell, TableActionHead, TableBody, TableCell, TableHea
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { EgressAutomation, EgressSources } from "@/features/settings/egress-operations";
|
||||
import { cleanupUnhealthyEgressNodes, createEgressNode, deleteEgressNode, deleteEgressNodes, importEgressText, listEgressNodes, previewUnhealthyEgressNodes, refreshEgressClearance, testEgressNode, updateEgressNode, updateEgressNodesEnabled, type EgressIPProbeDTO, type EgressNodeDTO, type EgressNodeInput, type EgressScope } from "@/features/settings/settings-api";
|
||||
import { cleanupUnhealthyEgressNodes, createEgressNode, deleteEgressNode, deleteEgressNodes, importEgressText, listEgressNodes, previewUnhealthyEgressNodes, refreshEgressClearance, testEgressNode, updateEgressNode, updateEgressNodesEnabled, type ClearanceMode, type EgressIPProbeDTO, type EgressNodeDTO, type EgressNodeInput, type EgressScope } from "@/features/settings/settings-api";
|
||||
import { ErrorState, TableLoadingRow } from "@/shared/components/data-state";
|
||||
import { DataTableShell } from "@/shared/components/data-table-shell";
|
||||
import { DataTableFilters } from "@/shared/components/data-table-filters";
|
||||
@@ -34,7 +34,7 @@ const emptyInput: EgressNodeInput = { name: "", scope: "grok_build", enabled: tr
|
||||
type ImportForm = { name: string; scope: EgressScope; accountCapacity: number; content: string };
|
||||
const emptyImport: ImportForm = { name: "", scope: "grok_build", accountCapacity: 0, content: "" };
|
||||
|
||||
export function EgressNodes({ title, clearanceMode }: { title: string; clearanceMode: "manual" | "flaresolverr" }) {
|
||||
export function EgressNodes({ title, clearanceMode }: { title: string; clearanceMode: ClearanceMode }) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState<EgressNodeDTO | null | undefined>(undefined);
|
||||
@@ -302,7 +302,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => openEdit(node)}><Pencil />{t("common.edit")}</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
{clearanceMode === "flaresolverr" && !node.accountBoundProxy && (node.scope === "grok_web" || node.scope === "grok_web_asset" || node.scope === "grok_console") ? <DropdownMenuItem disabled={refreshClearance.isPending} onClick={() => refreshClearance.mutate(node.id)}><RefreshCw />{t("settings.egress.refreshClearance")}</DropdownMenuItem> : null}
|
||||
{clearanceMode !== "manual" && !node.accountBoundProxy && (node.scope === "grok_web" || node.scope === "grok_web_asset" || node.scope === "grok_console") ? <DropdownMenuItem disabled={refreshClearance.isPending} onClick={() => refreshClearance.mutate(node.id)}><RefreshCw />{t("settings.egress.refreshClearance")}</DropdownMenuItem> : null}
|
||||
<DropdownMenuItem disabled={testNode.isPending || !node.proxyConfigured} onClick={() => testNode.mutate(node.id)}><RefreshCw />{t("settings.egress.test")}</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => remove.mutate(node.id)}><Trash2 />{t("common.delete")}</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
@@ -401,7 +401,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance
|
||||
<div className="flex h-10 items-center justify-between gap-4 rounded-md bg-muted/45 px-3">
|
||||
<span className="text-xs font-medium">{t("settings.egress.clearance")}</span>
|
||||
<Badge variant="secondary" className="shrink-0 text-[10px]">
|
||||
{clearanceMode === "flaresolverr" ? t("settings.web.clearanceFlareSolverr") : t("settings.web.clearanceManual")}
|
||||
{clearanceMode === "flaresolverr" ? t("settings.web.clearanceFlareSolverr") : clearanceMode === "on_demand" ? t("settings.web.clearanceOnDemand") : t("settings.web.clearanceManual")}
|
||||
</Badge>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -485,12 +485,15 @@ function ErrorTooltip({ message }: { message: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ClearanceBadge({ node, clearanceMode }: { node: EgressNodeDTO; clearanceMode: "manual" | "flaresolverr" }) {
|
||||
function ClearanceBadge({ node, clearanceMode }: { node: EgressNodeDTO; clearanceMode: ClearanceMode }) {
|
||||
const { t } = useTranslation();
|
||||
if (node.scope === "grok_build") return <span className="text-xs text-muted-foreground">—</span>;
|
||||
if (clearanceMode === "flaresolverr") {
|
||||
return <Badge variant="secondary" className="text-[10px]">{node.accountBoundProxy ? `${t("settings.web.clearanceFlareSolverr")} · Resin` : t("settings.web.clearanceFlareSolverr")}</Badge>;
|
||||
}
|
||||
if (clearanceMode === "on_demand") {
|
||||
return <Badge variant="secondary" className="text-[10px]">{node.accountBoundProxy ? `${t("settings.web.clearanceOnDemand")} · Resin` : t("settings.web.clearanceOnDemand")}</Badge>;
|
||||
}
|
||||
return <Badge variant={node.cookieConfigured ? "secondary" : "outline"} className={cn("text-[10px]", !node.cookieConfigured && "text-muted-foreground")}>{node.cookieConfigured ? t("settings.egress.configured") : t("settings.egress.none")}</Badge>;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ export type SettingsConfigDTO = {
|
||||
providerWeb: {
|
||||
baseURL: string; quotaTimeout: string; chatTimeout: string; streamIdleTimeout: string; imageTimeout: string; videoTimeout: string;
|
||||
statsigMode: "manual" | "url"; statsigManualValue?: string; statsigManualConfigured: boolean; statsigSignerURL: string;
|
||||
clearanceMode: "manual" | "flaresolverr"; flareSolverrURL: string; clearanceTimeout: string; clearanceRefresh: string;
|
||||
clearanceMode: ClearanceMode; flareSolverrURL: string; clearanceTimeout: string; clearanceRefresh: string;
|
||||
mediaConcurrency: number; allowNSFW: boolean;
|
||||
recoveryBackoffBase: string; recoveryBackoffMax: string;
|
||||
};
|
||||
@@ -37,6 +37,8 @@ export type SettingsConfigDTO = {
|
||||
};
|
||||
};
|
||||
|
||||
export type ClearanceMode = "manual" | "flaresolverr" | "on_demand";
|
||||
|
||||
export type EgressNodeDTO = {
|
||||
id: string; name: string; scope: EgressScope; enabled: boolean;
|
||||
proxyConfigured: boolean; userAgent: string; cookieConfigured: boolean;
|
||||
@@ -104,7 +106,7 @@ const settingsConfigValidator = hasShape({
|
||||
providerWeb: hasShape({
|
||||
baseURL: isString, quotaTimeout: isString, chatTimeout: isString, streamIdleTimeout: isOptional(isString), imageTimeout: isString, videoTimeout: isString,
|
||||
statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean,
|
||||
statsigSignerURL: isString, clearanceMode: isOneOf("manual", "flaresolverr"), flareSolverrURL: isString,
|
||||
statsigSignerURL: isString, clearanceMode: isOneOf("manual", "flaresolverr", "on_demand"), flareSolverrURL: isString,
|
||||
clearanceTimeout: isString, clearanceRefresh: isString, mediaConcurrency: isNumber, allowNSFW: isBoolean, recoveryBackoffBase: isString, recoveryBackoffMax: isString,
|
||||
}),
|
||||
providerConsole: hasShape({ baseURL: isString, chatTimeout: isString, streamIdleTimeout: isOptional(isString) }),
|
||||
|
||||
@@ -83,7 +83,7 @@ export const settingsSchema = z.object({
|
||||
statsigManualValue: z.string().trim().max(4096),
|
||||
statsigManualConfigured: z.boolean(),
|
||||
statsigSignerURL: z.string().trim().max(2048),
|
||||
clearanceMode: z.enum(["manual", "flaresolverr"]),
|
||||
clearanceMode: z.enum(["manual", "flaresolverr", "on_demand"]),
|
||||
flareSolverrURL: z.string().trim().max(2048),
|
||||
clearanceTimeout: durationSchema.refine((value) => durationSeconds(value) >= 10 && durationSeconds(value) <= 300),
|
||||
clearanceRefresh: durationSchema.refine((value) => durationSeconds(value) >= 60 && durationSeconds(value) <= 86_400),
|
||||
@@ -108,7 +108,7 @@ export const settingsSchema = z.object({
|
||||
context.addIssue({ code: "custom", path: ["statsigSignerURL"], message: "invalid" });
|
||||
}
|
||||
}
|
||||
if (value.clearanceMode === "flaresolverr" && !validHTTPURL(value.flareSolverrURL)) {
|
||||
if (value.clearanceMode !== "manual" && !validHTTPURL(value.flareSolverrURL)) {
|
||||
context.addIssue({ code: "custom", path: ["flareSolverrURL"], message: "invalid" });
|
||||
}
|
||||
}),
|
||||
@@ -351,21 +351,45 @@ function validHTTPURL(value: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates HTTP and SOCKS proxy URLs. Empty is allowed for write-only form fields. */
|
||||
/** Performs fast client-side proxy validation; the backend remains authoritative. */
|
||||
function validProxyURL(value: string): boolean {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return true;
|
||||
if (trimmed.length > 2048 || [...trimmed].some((char) => {
|
||||
if (trimmed.length > 8192 || [...trimmed].some((char) => {
|
||||
const code = char.charCodeAt(0);
|
||||
return code <= 0x1f || code === 0x7f;
|
||||
})) return false;
|
||||
if ((trimmed.match(/\{account\}/g) ?? []).length > 1) return false;
|
||||
const scheme = trimmed.slice(0, trimmed.indexOf(":")).toLowerCase();
|
||||
if (["trojan", "vless", "ss", "vmess"].includes(scheme) && trimmed.includes("{account}")) return false;
|
||||
if (scheme === "vmess") return validVMessURL(trimmed);
|
||||
if (scheme === "ss") return validShadowsocksURL(trimmed);
|
||||
try {
|
||||
const parseValue = trimmed.replaceAll("{account}", "grok2api_account_placeholder");
|
||||
const parsed = new URL(parseValue);
|
||||
if (!parsed.host || !parsed.hostname) return false;
|
||||
const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
|
||||
if (!["http", "https", "socks4", "socks4a", "socks5", "socks5h"].includes(scheme)) return false;
|
||||
const parsedScheme = parsed.protocol.replace(/:$/, "").toLowerCase();
|
||||
if (["trojan", "vless"].includes(parsedScheme)) {
|
||||
if (!parsed.username || parsed.password || !parsed.port) return false;
|
||||
const transport = (parsed.searchParams.get("type") ?? parsed.searchParams.get("network") ?? "tcp").toLowerCase();
|
||||
if (!["tcp", "none", "ws", "websocket"].includes(transport)) return false;
|
||||
const security = (parsed.searchParams.get("security") ?? "").toLowerCase();
|
||||
if (!["", "none", "tls"].includes(security)) return false;
|
||||
if (parsed.searchParams.get("flow")) return false;
|
||||
if (parsedScheme === "vless" && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(parsed.username)) return false;
|
||||
if (parsedScheme === "vless" && !["", "none"].includes((parsed.searchParams.get("encryption") ?? "").toLowerCase())) return false;
|
||||
if (!["", "none"].includes((parsed.searchParams.get("headerType") ?? "").toLowerCase())) return false;
|
||||
if (!validTunnelBoolean(parsed.searchParams, ["allowInsecure", "insecure", "skip-cert-verify"])) return false;
|
||||
if (parsed.pathname !== "" && parsed.pathname !== "/") return false;
|
||||
const webSocket = transport === "ws" || transport === "websocket";
|
||||
if (!webSocket && (parsed.searchParams.has("host") || parsed.searchParams.has("path"))) return false;
|
||||
if (webSocket) {
|
||||
const host = parsed.searchParams.get("host") ?? parsed.searchParams.get("sni") ?? parsed.searchParams.get("peer") ?? parsed.hostname;
|
||||
if (!validWebSocketHost(host)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!["http", "https", "socks4", "socks4a", "socks5", "socks5h"].includes(parsedScheme)) return false;
|
||||
if (parsed.search || parsed.hash || (parsed.pathname !== "" && parsed.pathname !== "/")) return false;
|
||||
if (trimmed.includes("{account}")) {
|
||||
if (!parsed.username.includes("grok2api_account_placeholder")) return false;
|
||||
@@ -376,6 +400,100 @@ function validProxyURL(value: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function validShadowsocksURL(value: string): boolean {
|
||||
try {
|
||||
let payload = value.slice("ss://".length).split("#", 1)[0];
|
||||
const queryIndex = payload.indexOf("?");
|
||||
if (queryIndex >= 0) {
|
||||
if ([...new URLSearchParams(payload.slice(queryIndex + 1)).keys()].length !== 0) return false;
|
||||
payload = payload.slice(0, queryIndex);
|
||||
}
|
||||
let credentials: string;
|
||||
let server: string;
|
||||
const separator = payload.lastIndexOf("@");
|
||||
if (separator >= 0) {
|
||||
credentials = decodeURIComponent(payload.slice(0, separator));
|
||||
if (!credentials.includes(":")) credentials = decodeBase64Text(credentials);
|
||||
server = payload.slice(separator + 1);
|
||||
} else {
|
||||
const decoded = decodeBase64Text(payload);
|
||||
const legacySeparator = decoded.lastIndexOf("@");
|
||||
if (legacySeparator < 0) return false;
|
||||
credentials = decoded.slice(0, legacySeparator);
|
||||
server = decoded.slice(legacySeparator + 1);
|
||||
}
|
||||
const credentialSeparator = credentials.indexOf(":");
|
||||
if (credentialSeparator <= 0 || credentialSeparator === credentials.length - 1) return false;
|
||||
const method = credentials.slice(0, credentialSeparator).trim().toLowerCase();
|
||||
if (!["aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305"].includes(method)) return false;
|
||||
const parsed = new URL(`ss://${server}`);
|
||||
return parsed.username === "" && parsed.password === "" && parsed.hostname !== "" && parsed.port !== ""
|
||||
&& (parsed.pathname === "" || parsed.pathname === "/") && parsed.search === "" && parsed.hash === "";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeBase64Text(value: string): string {
|
||||
let payload = value.replaceAll("-", "+").replaceAll("_", "/");
|
||||
payload += "=".repeat((4 - (payload.length % 4)) % 4);
|
||||
const bytes = Uint8Array.from(atob(payload), (character) => character.charCodeAt(0));
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
function validTunnelBoolean(query: URLSearchParams, names: string[]): boolean {
|
||||
for (const name of names) {
|
||||
if (!query.has(name)) continue;
|
||||
return ["", "0", "1", "false", "true", "no", "yes"].includes((query.get(name) ?? "").trim().toLowerCase());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function validWebSocketHost(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(`http://${value.trim()}`);
|
||||
return parsed.hostname !== "" && parsed.username === "" && parsed.password === ""
|
||||
&& (parsed.pathname === "" || parsed.pathname === "/") && parsed.search === "" && parsed.hash === "";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validVMessURL(value: string): boolean {
|
||||
try {
|
||||
let payload = value.slice("vmess://".length).split("#", 1)[0].replaceAll("-", "+").replaceAll("_", "/");
|
||||
payload += "=".repeat((4 - (payload.length % 4)) % 4);
|
||||
const bytes = Uint8Array.from(atob(payload), (character) => character.charCodeAt(0));
|
||||
const config = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;
|
||||
const id = String(config.id ?? "");
|
||||
const port = Number(config.port);
|
||||
const network = String(config.net ?? "tcp").toLowerCase();
|
||||
const tls = String(config.tls ?? "").toLowerCase();
|
||||
const cipher = String(config.scy ?? config.security ?? "auto").toLowerCase();
|
||||
const headerType = String(config.type ?? "").toLowerCase();
|
||||
const alterID = Number(config.aid ?? 0);
|
||||
const webSocket = network === "ws" || network === "websocket";
|
||||
const host = String(config.host ?? config.sni ?? config.add ?? "");
|
||||
return typeof config.add === "string" && config.add.trim() !== "" && Number.isInteger(port) && port > 0 && port <= 65535
|
||||
&& /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)
|
||||
&& Number.isInteger(alterID) && alterID >= 0 && alterID <= 65535
|
||||
&& ["tcp", "ws", "websocket"].includes(network) && ["", "none", "tls"].includes(tls)
|
||||
&& ["auto", "aes-128-gcm", "chacha20-poly1305", "none"].includes(cipher)
|
||||
&& ["", "none"].includes(headerType)
|
||||
&& validJSONTunnelBoolean(config.allowInsecure)
|
||||
&& (webSocket ? validWebSocketHost(host) : String(config.path ?? "") === "" && String(config.host ?? "") === "");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validJSONTunnelBoolean(value: unknown): boolean {
|
||||
if (value == null || typeof value === "boolean") return true;
|
||||
if (typeof value === "number") return value === 0 || value === 1;
|
||||
if (typeof value === "string") return ["", "0", "1", "false", "true", "no", "yes"].includes(value.trim().toLowerCase());
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Subscription fetch proxies must never use per-account lease placeholders. */
|
||||
export function validSubscriptionProxyURL(value: string): boolean {
|
||||
return !value.includes("{account}") && validProxyURL(value);
|
||||
|
||||
@@ -191,17 +191,18 @@ export function SettingsPage() {
|
||||
<SettingsField controlId="egress-clearance-mode" className="sm:col-span-2" label={t("settings.web.clearanceMode")} description={t("settings.web.clearanceModeHelp")} error={form.formState.errors.providerWeb?.clearanceMode?.message}>
|
||||
<Controller control={form.control} name="providerWeb.clearanceMode" render={({ field }) => (
|
||||
<Tabs value={field.value} onValueChange={field.onChange}>
|
||||
<TabsList id="egress-clearance-mode" className="grid w-full grid-cols-2 bg-muted/55">
|
||||
<TabsList id="egress-clearance-mode" className="grid w-full grid-cols-3 bg-muted/55">
|
||||
<TabsTrigger value="manual" className="font-normal">{t("settings.web.clearanceManual")}</TabsTrigger>
|
||||
<TabsTrigger value="flaresolverr" className="font-normal">{t("settings.web.clearanceFlareSolverr")}</TabsTrigger>
|
||||
<TabsTrigger value="on_demand" className="font-normal">{t("settings.web.clearanceOnDemand")}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)} />
|
||||
</SettingsField>
|
||||
{draftClearanceMode === "flaresolverr" ? <>
|
||||
{draftClearanceMode !== "manual" ? <>
|
||||
<SettingsField controlId="egress-flaresolverr-url" className="sm:col-span-2" label={t("settings.web.flareSolverrURL")} description={t("settings.web.flareSolverrURLHelp")} error={form.formState.errors.providerWeb?.flareSolverrURL?.message}><Input id="egress-flaresolverr-url" type="url" placeholder="http://flaresolverr:8191" {...form.register("providerWeb.flareSolverrURL")} /></SettingsField>
|
||||
<SettingsField controlId="egress-clearance-timeout" label={t("settings.web.clearanceTimeout")} description={t("settings.web.clearanceTimeoutHelp")} error={form.formState.errors.providerWeb?.clearanceTimeout?.message}><Controller control={form.control} name="providerWeb.clearanceTimeout" render={({ field }) => <DurationInput id="egress-clearance-timeout" value={field.value} onChange={field.onChange} />} /></SettingsField>
|
||||
<SettingsField controlId="egress-clearance-refresh" label={t("settings.web.clearanceRefresh")} description={t("settings.web.clearanceRefreshHelp")} error={form.formState.errors.providerWeb?.clearanceRefresh?.message}><Controller control={form.control} name="providerWeb.clearanceRefresh" render={({ field }) => <DurationInput id="egress-clearance-refresh" value={field.value} onChange={field.onChange} />} /></SettingsField>
|
||||
{draftClearanceMode === "flaresolverr" ? <SettingsField controlId="egress-clearance-refresh" label={t("settings.web.clearanceRefresh")} description={t("settings.web.clearanceRefreshHelp")} error={form.formState.errors.providerWeb?.clearanceRefresh?.message}><Controller control={form.control} name="providerWeb.clearanceRefresh" render={({ field }) => <DurationInput id="egress-clearance-refresh" value={field.value} onChange={field.onChange} />} /></SettingsField> : null}
|
||||
</> : null}
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { cn } from "@/shared/lib/cn";
|
||||
|
||||
const PAGE_SIZE_OPTIONS = [20, 100, 500, 1000, 2000] as const;
|
||||
|
||||
export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; className?: string }) {
|
||||
export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, pageSizeOptions = PAGE_SIZE_OPTIONS, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; pageSizeOptions?: readonly number[]; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
const pages = Math.max(1, Math.ceil(total / pageSize));
|
||||
|
||||
@@ -20,7 +20,7 @@ export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChan
|
||||
<Button variant="ghost" size="icon" className="size-8" disabled={page >= pages} onClick={() => onPageChange(page + 1)} aria-label={t("common.nextPage")}><ChevronRight /></Button>
|
||||
<Button variant="ghost" size="icon" className="size-8" disabled={page >= pages} onClick={() => onPageChange(pages)} aria-label={t("common.lastPage")}><ChevronsRight /></Button>
|
||||
</div>
|
||||
{onPageSizeChange ? <PageSizeSelector pageSize={pageSize} onChange={onPageSizeChange} /> : <span />}
|
||||
{onPageSizeChange ? <PageSizeSelector pageSize={pageSize} options={pageSizeOptions} onChange={onPageSizeChange} /> : <span />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -36,12 +36,12 @@ export function CursorPagination({ page, pageSize, hasMore, disabled = false, on
|
||||
<span className="min-w-20 px-2 text-center text-xs text-muted-foreground">{t("audits.cursorPage", { page })}</span>
|
||||
<Button variant="ghost" size="icon" className="size-8" disabled={disabled || !hasMore} onClick={onNextPage} aria-label={t("common.nextPage")}><ChevronRight /></Button>
|
||||
</div>
|
||||
<PageSizeSelector pageSize={pageSize} disabled={disabled} onChange={onPageSizeChange} />
|
||||
<PageSizeSelector pageSize={pageSize} disabled={disabled} options={PAGE_SIZE_OPTIONS} onChange={onPageSizeChange} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PageSizeSelector({ pageSize, disabled = false, onChange }: { pageSize: number; disabled?: boolean; onChange: (pageSize: number) => void }) {
|
||||
function PageSizeSelector({ pageSize, disabled = false, options, onChange }: { pageSize: number; disabled?: boolean; options: readonly number[]; onChange: (pageSize: number) => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
@@ -49,7 +49,7 @@ function PageSizeSelector({ pageSize, disabled = false, onChange }: { pageSize:
|
||||
<Select value={String(pageSize)} disabled={disabled} onValueChange={(value) => onChange(Number(value))}>
|
||||
<SelectTrigger className="h-8 w-[76px] rounded-md bg-secondary px-3 text-xs shadow-none" aria-label={t("common.perPage")}><SelectValue /></SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
{PAGE_SIZE_OPTIONS.map((value) => <SelectItem key={value} value={String(value)}>{value}</SelectItem>)}
|
||||
{options.map((value) => <SelectItem key={value} value={String(value)}>{value}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span>{t("common.rows")}</span>
|
||||
|
||||
@@ -481,6 +481,22 @@ const resources = {
|
||||
reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度连续超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" },
|
||||
policy: "当前策略", editPolicy: "编辑策略", editPolicyTitle: "编辑质量守护策略", editPolicyDescription: "保存后由守护进程热加载,无需重启服务。", restoreDefaults: "恢复默认值", policySaved: "策略已保存,正在热加载", invalidPolicyValue: "数值超出允许范围", softThresholdMustBeLower: "软阈值必须低于硬阈值", activeIntervalSeconds: "主动检测间隔(秒)", passiveIntervalSeconds: "被动审计间隔(秒)", consecutiveSoft: "软阈值连续次数", consecutiveErrors: "检测错误连续次数", quarantineSeconds: "隔离时长(秒)", softThreshold: "软阈值", hardThreshold: "硬阈值", activeInterval: "主动间隔", passiveInterval: "审计间隔", quarantineDuration: "隔离时长", minimumNodes: "最少保留节点",
|
||||
unavailable: "质量守护尚未连接", unavailableHelp: "在 config.yaml 中启用 qualityGuard,并启动 quality-guard Compose profile 后,这里会显示实时状态。", testing: "正在检测节点质量", testComplete: "检测完成:{{speed}}", testFailed: "质量检测暂不可用,请稍后重试",
|
||||
nodesTab: "节点质量",
|
||||
degrade: {
|
||||
tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点",
|
||||
hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}",
|
||||
accounts: "涉及账号", accountsHelp: "窗口内去重 · 已删除 {{deleted}}", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁",
|
||||
maxTPS: "峰值 TPS", maxTPSHelp: "单次请求最高",
|
||||
accountsTitle: "降智账号", accountsHint: "显示 {{shown}} / {{total}}", accountsHintFiltered: "显示 {{shown}} / {{total}} · 命中≥{{min}}",
|
||||
search: "搜名称 / 邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁用", statusDeleted: "账号已删除",
|
||||
classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中",
|
||||
hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}",
|
||||
windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" },
|
||||
muteSelected: "禁用所选", muteSelectedCount: "禁用所选 ({{count}})", muteConfirm: "确认禁用 {{count}} 个仍在调度的降智账号?", muting: "正在禁用账号", muted: "已禁用 {{count}} 个账号", muteFailed: "禁用失败",
|
||||
scheduling: "调度中", disabledStatus: "已禁用", deletedStatus: "已删除",
|
||||
events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针",
|
||||
noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件",
|
||||
},
|
||||
refreshNodes: "刷新节点", nodeEnabled: "节点已启用", nodeDisabled: "节点已停用", nodesEnabled: "所选节点已启用", nodesDisabled: "所选节点已停用", enableNode: "启用节点 {{name}}", disableNode: "停用节点 {{name}}",
|
||||
nodeEditorDescription: "管理质量守护使用的 Grok Build 出口。代理地址仅写入;编辑时留空会保留现有配置。", nodeCapacityHelp: "最多可绑定的账号数,0 表示不限制。", deleteNodeTitle: "删除代理节点?", deleteNodeDescription: "将永久删除节点“{{name}}”。此操作无法撤销。", deleteNodesTitle: "删除所选 {{count}} 个节点?", deleteNodesDescription: "所选代理节点将被永久删除,此操作无法撤销。",
|
||||
},
|
||||
@@ -732,6 +748,8 @@ const resources = {
|
||||
deleteDescription: "将删除 {{name}} 及其密钥权限关联;如果上游账号仍支持该模型,后续同步会重新创建。",
|
||||
batchDeleteTitle: "删除所选 {{count}} 个模型路由?",
|
||||
batchDeleteDescription: "将同时删除所选路由及其密钥权限关联;上游账号仍支持的模型会在后续同步时重新创建。",
|
||||
syncing: "正在准备同步账号模型能力",
|
||||
syncingProgress: "正在同步账号模型能力 {{completed}} / {{total}}",
|
||||
synced: "已同步 {{count}} 个模型",
|
||||
created: "模型路由已创建",
|
||||
updated: "模型路由已更新",
|
||||
@@ -777,8 +795,8 @@ const resources = {
|
||||
enabledDescription: "控制该密钥是否允许发起 API 请求。",
|
||||
modelAliases: "模型别名",
|
||||
modelAliasesDescription: "仅为当前可用且支持多个推理等级的模型生成后缀别名。",
|
||||
modelAliasesBuildSupport: "Grok Build:grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。",
|
||||
modelAliasesConsoleSupport: "Grok Console:grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。",
|
||||
modelAliasesBuildSupport: "Grok Build:grok-4.6 支持 low / medium / high / xhigh;grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。",
|
||||
modelAliasesConsoleSupport: "Grok Console:grok-4.6 支持 low / medium / high / xhigh;grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。",
|
||||
modelAliasesUnsupported: "Grok Web、图片模型和视频模型不生成推理等级后缀。",
|
||||
modelAliasesOn: "已开启:可发现并调用当前模型支持的推理等级别名。",
|
||||
modelAliasesOff: "已关闭:不生成动态推理别名;既有 Console 兼容别名不受影响。",
|
||||
@@ -941,7 +959,7 @@ const resources = {
|
||||
console: { baseURLHelp: "Grok Console 请求与账号操作使用的基础端点。", chatTimeoutHelp: "Grok Console 聊天请求完成前允许等待的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "仅文本 SSE 连续无上游数据时允许等待的最长时间;不影响媒体和非流式请求。" },
|
||||
batch: { title: "批量任务", importConcurrency: "导入同步并发", importConcurrencyHelp: "批量导入后并行执行账号初始化与信息同步的任务数。", conversionConcurrency: "账号转换并发", conversionConcurrencyHelp: "跨 Provider 转换账号时允许同时处理的任务数。", syncConcurrency: "数据同步并发", syncConcurrencyHelp: "批量同步账号额度、状态与能力时允许同时处理的任务数。", refreshConcurrency: "凭据刷新并发", refreshConcurrencyHelp: "批量刷新账号凭据时允许同时处理的任务数。", randomDelay: "随机延迟上限(ms)", randomDelayHelp: "批量任务启动前增加的随机延迟上限,用于平滑上游请求峰值。" },
|
||||
media: { title: "媒体存储", maxImageSize: "单张图片上限", maxImageSizeHelp: "单个图片文件允许写入本地媒体存储的最大大小。", maxTotalSize: "媒体存储上限", maxTotalSizeHelp: "本地图片与视频文件允许占用的总存储空间。", cleanupThresholdPercent: "自动清理阈值", cleanupThresholdPercentHelp: "存储使用率达到该比例后,系统按时间清理较早的媒体文件。", cleanupInterval: "容量检查间隔", cleanupIntervalHelp: "后台检查媒体存储使用量并触发清理的时间间隔。", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" },
|
||||
egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H\nResin 可在用户名中使用 {account} 绑定账号租约。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP 或 SOCKS 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" },
|
||||
egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" },
|
||||
routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", preferFreeBuild: "Grok Build Free 账号优先", preferFreeBuildHelp: "启用后优先选择已确认可用的 Free 账号,其他路由条件保持不变。", accountIsolatedConnections: "按账号隔离上游连接", accountIsolatedConnectionsHelp: "开启后,不同账号使用各自的上游 TCP/HTTP 连接池,便于外部 L4 或按连接哈希的负载均衡器分散流量;同一账号仍可复用连接。适用于 Build / Web / Console 出站及 Web 转 Build。会增加连接数、TLS 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" },
|
||||
audit: { title: "请求审计", bufferSize: "队列容量", bufferSizeHelp: "审计记录进入持久化前可在内存队列中等待的最大数量。", batchSize: "批量写入数", batchSizeHelp: "每次数据库事务最多写入的审计记录数量。", flushInterval: "刷新间隔", flushIntervalHelp: "队列未达到批量写入数时,强制提交待处理审计记录的间隔。", commitDelay: "提交聚合等待(毫秒)", commitDelayHelp: "需要确认提交的请求进入原子批次前允许等待的最长时间。" },
|
||||
clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", rpmLimitHelp: "新建客户端密钥默认允许的每分钟请求数。", maxConcurrent: "默认并发数", maxConcurrentHelp: "新建客户端密钥默认允许同时执行的请求数。" },
|
||||
@@ -1470,14 +1488,31 @@ const resources = {
|
||||
media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", totalImages: "Total images", totalBytes: "Storage", pageSummary: "Showing {{count}} / {{total}}", openImage: "Open image {{id}}", deleteTitle: "Delete {{count}} selected images?", deleteDescription: "The image files and gallery records will be permanently removed, and existing image links will stop working. This cannot be undone.", deleted: "Deleted {{count}} images" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", statusProgress: "Status / progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", time: "Time", createdShort: "Created", completedShort: "Done", preview: "Preview video", previewTitle: "Video preview", previewUnavailable: "Local video unavailable", deleteTitle: "Delete {{count}} video records?", deleteDescription: "The task records and their local videos will be permanently removed, and existing video links will stop working. This cannot be undone.", deleted: "Deleted {{count}} video records", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } },
|
||||
auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" },
|
||||
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
|
||||
qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone." },
|
||||
qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.",
|
||||
nodesTab: "Node quality",
|
||||
degrade: {
|
||||
tab: "Degraded accounts", overview: "Degraded account overview", series: "Degrade timeline", nodes: "By egress node",
|
||||
hits: "Degrade hits", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}",
|
||||
accounts: "Accounts", accountsHelp: "Unique in this window · {{deleted}} deleted", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be disabled in bulk",
|
||||
maxTPS: "Peak TPS", maxTPSHelp: "Highest single request",
|
||||
accountsTitle: "Degraded accounts", accountsHint: "Showing {{shown}} / {{total}}", accountsHintFiltered: "Showing {{shown}} / {{total}} · hits ≥ {{min}}",
|
||||
search: "Search name / email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Disabled", statusDeleted: "Deleted accounts",
|
||||
classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits",
|
||||
hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}",
|
||||
windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" },
|
||||
muteSelected: "Disable selected", muteSelectedCount: "Disable selected ({{count}})", muteConfirm: "Disable {{count}} still-scheduled degraded accounts?", muting: "Disabling accounts", muted: "Disabled {{count}} accounts", muteFailed: "Failed to disable accounts",
|
||||
scheduling: "Scheduled", disabledStatus: "Disabled", deletedStatus: "Deleted",
|
||||
events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded",
|
||||
noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events",
|
||||
},
|
||||
},
|
||||
accountQuotaReset: { action: "Reset quota", description: "This clears only local waiting-reset and model quota blocks. It does not change upstream Billing or audit history. Accounts that remain exhausted will be marked again by real traffic.", completed: "Reset local quota state for {{reset}} accounts" },
|
||||
accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" },
|
||||
accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" },
|
||||
dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" },
|
||||
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", imagineQuota: "Imagine quota", imagineQuotaRemaining: "{{remaining}} remaining", imagineQuotaExhausted: "Exhausted, cooling down", imagineModeImagePro: "Image", imagineModeImageEdit: "Image edit", imagineModeVideo: "Video", imagineModeVideo720p: "Video 720p", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter:
Line truncated
|
||||
models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
|
||||
models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", syncing: "Preparing account capability sync", syncingProgress: "Syncing account capabilities {{completed}} / {{total}}", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.6 supports low / medium / high / xhigh; grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.6 supports low / medium / high / xhigh; grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
|
||||
audits: {
|
||||
title: "Request audits",
|
||||
description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.",
|
||||
@@ -1920,6 +1955,7 @@ Object.assign(resources.en.translation.models as unknown as Record<string, strin
|
||||
Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Record<string, string>, {
|
||||
description: "节点按 Grok Build、Grok Web、Grok Console、Web 资源和 Console 资源独立管理代理与健康状态。Console 资源节点仅使用代理与 User-Agent,不发送账号或 Cloudflare Cookie。代理地址和 Cookie 仅写入。",
|
||||
dialogDescription: "配置节点作用域、代理地址和浏览器身份;Console 资源节点用于匿名媒体下载,不使用 Clearance Cookie。",
|
||||
proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。",
|
||||
scopeConsoleAsset: "Grok Console(仅资源)",
|
||||
health: "请求健康",
|
||||
healthHelp: "由真实 Grok 请求的成功、连接失败和反爬拒绝累计得出,与连通探测独立。",
|
||||
@@ -1932,6 +1968,7 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor
|
||||
Object.assign(resources.en.translation.settings.egress as unknown as Record<string, string>, {
|
||||
description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, Web assets, and Console assets. Console asset nodes use only the proxy and User-Agent and never send account or Cloudflare cookies. Proxy URLs and cookies are write-only.",
|
||||
dialogDescription: "Configure the node scope, proxy address, and browser identity. Console asset nodes are for anonymous media downloads and do not use clearance cookies.",
|
||||
proxyProtocols: "Supports HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Trojan, VLESS, Shadowsocks, and VMess.\nTunnel protocols support TCP, WebSocket, and TLS; Resin users can put {account} in the username.",
|
||||
scopeConsoleAsset: "Grok Console (assets only)",
|
||||
accounts: "Bound", health: "Request health", healthHelp: "Accumulated from real Grok request successes, transport failures, and anti-bot rejections; independent of the connectivity probe.",
|
||||
addManually: "Form entry",
|
||||
@@ -1949,8 +1986,8 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record<stri
|
||||
imported: "Proxy import completed: {{imported}} imported, {{skipped}} skipped", tested: "Proxy test completed: {{healthy}} healthy, {{unhealthy}} unhealthy", testedPartial: "Connectivity probe partially completed: {{healthy}} healthy, {{unhealthy}} unhealthy, {{failed}} not completed",
|
||||
rebalanced: "Account allocation completed: {{assigned}} assigned, {{rebalanced}} balanced, {{unplaced}} unplaced", automationSaved: "Automation saved",
|
||||
editSource: "Edit subscription", subscriptionURL: "Subscription URL", sourceDialogDescription: "Configure the subscription URL, fetch route, scope, sync interval, and per-node account capacity.",
|
||||
subscriptionProxy: "Fetch through a proxy", subscriptionProxyURL: "Subscription fetch proxy", subscriptionRoute: "Fetch route", subscriptionProxyShort: "Proxy", invalidSubscriptionProxy: "Enter a valid HTTP or SOCKS proxy URL; {account} is not supported here",
|
||||
importDialogDescription: "Supports plain-text or Base64 proxy lists with one HTTP or SOCKS address per line.",
|
||||
subscriptionProxy: "Fetch through a proxy", subscriptionProxyURL: "Subscription fetch proxy", subscriptionRoute: "Fetch route", subscriptionProxyShort: "Proxy", invalidSubscriptionProxy: "Enter a valid HTTP, SOCKS, Trojan, VLESS, SS, or VMess proxy URL; {account} is not supported here",
|
||||
importDialogDescription: "Supports plain-text or Base64 proxy lists with one HTTP, SOCKS, Trojan, VLESS, SS, or VMess address per line.",
|
||||
probeInterval: "Node check interval", probeIntervalHelp: "How often to check whether enabled proxy nodes are available.",
|
||||
assignmentInterval: "Account assignment interval", assignmentIntervalHelp: "When automatic binding or balancing is enabled, controls how often account bindings and available node capacity are checked.",
|
||||
autoAssign: "Automatically bind accounts", autoAssignHelp: "Assign accounts without a proxy binding to available nodes automatically.",
|
||||
@@ -2011,7 +2048,7 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor
|
||||
subscriptionProxyURL: "订阅拉取代理地址",
|
||||
subscriptionRoute: "拉取线路",
|
||||
subscriptionProxyShort: "代理",
|
||||
invalidSubscriptionProxy: "请输入有效的 HTTP 或 SOCKS 代理地址;此处不支持 {account}",
|
||||
invalidSubscriptionProxy: "请输入有效的 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 代理地址;此处不支持 {account}",
|
||||
refreshInterval: "同步间隔(秒)",
|
||||
noSources: "暂无代理订阅",
|
||||
probeInterval: "节点检测间隔",
|
||||
@@ -2130,6 +2167,14 @@ Object.assign(resources.en.translation.settings.routing as unknown as Record<str
|
||||
markBuildChatDeniedAsReauth: "Mark Build Chat denied as reauth",
|
||||
markBuildChatDeniedAsReauthHelp: "Mark accounts that receive a Build Chat permission denial for reauthorization and remove them from routing.",
|
||||
});
|
||||
Object.assign(resources["zh-CN"].translation.settings.web as unknown as Record<string, string>, {
|
||||
clearanceModeHelp: "手动维护 Clearance,使用 FlareSolverr 定期主动刷新,或仅在上游明确拒绝后按需重新求解。",
|
||||
clearanceOnDemand: "按需刷新",
|
||||
});
|
||||
Object.assign(resources.en.translation.settings.web as unknown as Record<string, string>, {
|
||||
clearanceModeHelp: "Maintain Clearance manually, refresh it proactively with FlareSolverr, or solve on demand only after an explicit upstream rejection.",
|
||||
clearanceOnDemand: "On demand",
|
||||
});
|
||||
function readStoredLanguage(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user