mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge branch 'main' into pr/video-admission-limits
This commit is contained in:
33 files changed
+3206
-157
No files matched your search
@@ -14,7 +14,10 @@ require (
|
||||
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/metacubex/sing v0.5.7
|
||||
github.com/metacubex/sing-vmess v0.2.5
|
||||
github.com/redis/go-redis/v9 v9.21.0
|
||||
github.com/refraction-networking/utls v1.6.7
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
@@ -41,6 +44,7 @@ require (
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudflare/circl v1.3.7 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
@@ -55,6 +59,7 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/gofrs/uuid/v5 v5.3.2 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
||||
|
||||
@@ -36,6 +36,8 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU=
|
||||
github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA=
|
||||
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=
|
||||
@@ -80,6 +82,8 @@ github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/gofrs/uuid/v5 v5.3.2 h1:2jfO8j3XgSwlz/wHqemAEugfnTlikAYHhnqQ8Xh4fE0=
|
||||
github.com/gofrs/uuid/v5 v5.3.2/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -128,6 +132,10 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM=
|
||||
github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w=
|
||||
github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE=
|
||||
github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -154,6 +162,8 @@ github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SA
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E=
|
||||
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM=
|
||||
github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0=
|
||||
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=
|
||||
|
||||
@@ -212,6 +212,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier,
|
||||
TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent,
|
||||
ResponseHeaderTimeout: cfg.Provider.Build.ResponseHeaderTimeout.Value(),
|
||||
StreamIdleTimeout: cfg.Provider.Build.StreamIdleTimeout.Value(),
|
||||
}, cipher)
|
||||
cliAdapter.SetLogger(logger)
|
||||
cliAdapter.SetEgress(egressManager)
|
||||
@@ -387,6 +388,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
ClientVersion: next.Provider.Build.ClientVersion, ClientIdentifier: next.Provider.Build.ClientIdentifier,
|
||||
TokenAuth: next.Provider.Build.TokenAuth, UserAgent: next.Provider.Build.UserAgent,
|
||||
ResponseHeaderTimeout: next.Provider.Build.ResponseHeaderTimeout.Value(),
|
||||
StreamIdleTimeout: next.Provider.Build.StreamIdleTimeout.Value(),
|
||||
})
|
||||
egressManager.UpdateBuildResponseHeaderTimeout(next.Provider.Build.ResponseHeaderTimeout.Value())
|
||||
egressManager.UpdateBuildStreamIdleTimeout(next.Provider.Build.StreamIdleTimeout.Value())
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const (
|
||||
MatchContains = "contains"
|
||||
MatchLastLine = "last_line"
|
||||
MatchRegex = "regex"
|
||||
)
|
||||
|
||||
func NormalizeMatchMode(mode string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||||
case MatchLastLine, "last-line", "lastline":
|
||||
return MatchLastLine
|
||||
case MatchRegex, "regexp":
|
||||
return MatchRegex
|
||||
default:
|
||||
return MatchContains
|
||||
}
|
||||
}
|
||||
|
||||
func lastNonEmptyLine(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := len(lines) - 1; i >= 0; i-- {
|
||||
line := strings.TrimSpace(lines[i])
|
||||
if line != "" {
|
||||
return line
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// MatchExpected reports whether the probe body satisfies the expected marker.
|
||||
// An empty expected string always matches so throughput-only profiles can skip
|
||||
// content checks.
|
||||
func MatchExpected(text, expected, mode string) bool {
|
||||
expected = strings.TrimSpace(expected)
|
||||
if expected == "" {
|
||||
return true
|
||||
}
|
||||
text = strings.TrimRightFunc(text, unicode.IsSpace)
|
||||
switch NormalizeMatchMode(mode) {
|
||||
case MatchLastLine:
|
||||
line := lastNonEmptyLine(text)
|
||||
if line == "" {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(line, expected)
|
||||
case MatchRegex:
|
||||
re, err := regexp.Compile(expected)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return re.MatchString(text)
|
||||
default:
|
||||
return strings.Contains(text, expected)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package egress
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMatchExpectedModes(t *testing.T) {
|
||||
text := "天空是蓝的,因为瑞利散射。\nQUALITY_OK\n"
|
||||
if !MatchExpected(text, "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("last line QUALITY_OK should match")
|
||||
}
|
||||
if MatchExpected("hello\nNOT_OK", "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("wrong last line must not match")
|
||||
}
|
||||
if !MatchExpected("prefix QUALITY_OK suffix", "QUALITY_OK", MatchContains) {
|
||||
t.Fatal("contains should match")
|
||||
}
|
||||
if MatchExpected("done\nstatus=QUALITY_OK", "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("last-line mode must require the complete marker line")
|
||||
}
|
||||
if MatchExpected("done\nNOT_QUALITY_OK", "QUALITY_OK", MatchLastLine) {
|
||||
t.Fatal("last-line mode must not accept a marker substring")
|
||||
}
|
||||
if !MatchExpected("alpha\nbeta QUALITY_OK", `QUALITY_OK$`, MatchRegex) {
|
||||
t.Fatal("regex should match")
|
||||
}
|
||||
if MatchExpected("nope", "[", MatchRegex) {
|
||||
t.Fatal("invalid regex must not match")
|
||||
}
|
||||
if !MatchExpected("anything", "", MatchContains) {
|
||||
t.Fatal("empty expected is always a match")
|
||||
}
|
||||
}
|
||||
@@ -71,3 +71,32 @@ func TestProbeQualityRejectsUnsupportedNodeAndMissingProber(t *testing.T) {
|
||||
t.Fatalf("missing prober error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeQualityScopesThinkingGuardToReasoningBuildModels(t *testing.T) {
|
||||
repository := &qualityProbeRepository{node: domain.Node{
|
||||
ID: 7, Scope: domain.ScopeBuild, Enabled: true, EncryptedProxyURL: "encrypted",
|
||||
}}
|
||||
prober := &qualityProberStub{}
|
||||
service := NewService(repository, nil, "")
|
||||
service.SetQualityProber(prober)
|
||||
|
||||
result, err := service.ProbeQuality(context.Background(), 7, QualityProbeInput{
|
||||
ClientKeyID: 3, Model: "grok-4.5", RequireThinking: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !prober.input.RequireThinking || !result.ThinkingRequired {
|
||||
t.Fatalf("reasoning model probe=%#v result=%#v", prober.input, result)
|
||||
}
|
||||
|
||||
result, err = service.ProbeQuality(context.Background(), 7, QualityProbeInput{
|
||||
ClientKeyID: 3, Model: "grok-composer-2.5-fast", RequireThinking: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prober.input.RequireThinking || result.ThinkingRequired {
|
||||
t.Fatalf("non-reasoning model probe=%#v result=%#v", prober.input, result)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
@@ -41,6 +42,8 @@ type QualityProbeInput struct {
|
||||
Model string
|
||||
Prompt string
|
||||
Expected string
|
||||
MatchMode string
|
||||
RequireThinking bool
|
||||
MaxOutputTokens int
|
||||
}
|
||||
|
||||
@@ -59,6 +62,7 @@ type QualityProbeResult struct {
|
||||
VisibleCharacters int
|
||||
OutputTokensPerSecond float64
|
||||
ExpectedMatched bool
|
||||
ThinkingRequired bool
|
||||
ResponseSHA256 string
|
||||
}
|
||||
|
||||
@@ -128,13 +132,15 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality
|
||||
input.Model = strings.TrimSpace(input.Model)
|
||||
input.Prompt = strings.TrimSpace(input.Prompt)
|
||||
input.Expected = strings.TrimSpace(input.Expected)
|
||||
rawMatchMode := strings.TrimSpace(input.MatchMode)
|
||||
input.MatchMode = NormalizeMatchMode(input.MatchMode)
|
||||
if input.Model == "" {
|
||||
return QualityProbeResult{}, fmt.Errorf("%w: model 必填", ErrInvalidInput)
|
||||
}
|
||||
if input.Prompt == "" {
|
||||
input.Prompt = DefaultQualityProbePrompt
|
||||
}
|
||||
if input.Expected == "" {
|
||||
if input.Expected == "" && rawMatchMode == "" {
|
||||
input.Expected = DefaultQualityProbeExpected
|
||||
}
|
||||
if len(input.Prompt) > MaxQualityProbePromptBytes || len(input.Expected) > MaxQualityProbeExpectedBytes {
|
||||
@@ -162,7 +168,16 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality
|
||||
if prober == nil {
|
||||
return QualityProbeResult{}, ErrQualityProbeUnavailable
|
||||
}
|
||||
return prober.ProbeEgressQuality(ctx, nodeID, input)
|
||||
// A profile may request the thinking guard, but only a known reasoning-capable
|
||||
// Build model can make zero reasoning tokens meaningful. Unknown/custom and
|
||||
// non-reasoning models stay observable without being falsely quarantined.
|
||||
input.RequireThinking = input.RequireThinking && modeldomain.SupportsReasoningForProvider(accountdomain.ProviderBuild, input.Model)
|
||||
result, err := prober.ProbeEgressQuality(ctx, nodeID, input)
|
||||
if err != nil {
|
||||
return QualityProbeResult{}, err
|
||||
}
|
||||
result.ThinkingRequired = input.RequireThinking
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// AccountBindingRepository is intentionally narrow so existing account
|
||||
|
||||
@@ -104,7 +104,7 @@ func fetchProxySubscription(ctx context.Context, value string, viaProxy string)
|
||||
}
|
||||
}
|
||||
request.Header.Set("Accept", "text/plain, text/*;q=0.9, */*;q=0.1")
|
||||
request.Header.Set("User-Agent", "grok2api-egress-subscription/1")
|
||||
request.Header.Set("User-Agent", "Clash.Meta")
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -368,6 +368,9 @@ func parseProxySubscription(value string) ([]subscriptionEntry, int, error) {
|
||||
return entries, decodedSkipped, nil
|
||||
}
|
||||
}
|
||||
if entries, clashSkipped, matched := parseClashSubscription(value); matched && len(entries) > 0 {
|
||||
return entries, clashSkipped, nil
|
||||
}
|
||||
return nil, skipped, errors.New("订阅中没有可用的代理节点")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type clashSubscription struct {
|
||||
Proxies []yaml.Node `yaml:"proxies"`
|
||||
}
|
||||
|
||||
type clashProxy struct {
|
||||
Type string `yaml:"type"`
|
||||
Server string `yaml:"server"`
|
||||
Port clashInteger `yaml:"port"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
Cipher string `yaml:"cipher"`
|
||||
UUID string `yaml:"uuid"`
|
||||
AlterID clashInteger `yaml:"alterId"`
|
||||
Network string `yaml:"network"`
|
||||
TLS bool `yaml:"tls"`
|
||||
ServerName string `yaml:"servername"`
|
||||
SNI string `yaml:"sni"`
|
||||
Flow string `yaml:"flow"`
|
||||
ALPN clashStringList `yaml:"alpn"`
|
||||
SkipCertVerify bool `yaml:"skip-cert-verify"`
|
||||
ClientFingerprint string `yaml:"client-fingerprint"`
|
||||
Plugin string `yaml:"plugin"`
|
||||
WSOptions clashWebSocketOption `yaml:"ws-opts"`
|
||||
RealityOptions clashRealityOptions `yaml:"reality-opts"`
|
||||
}
|
||||
|
||||
type clashWebSocketOption struct {
|
||||
Path string `yaml:"path"`
|
||||
Headers map[string]string `yaml:"headers"`
|
||||
}
|
||||
|
||||
type clashRealityOptions struct {
|
||||
PublicKey string `yaml:"public-key"`
|
||||
ShortID string `yaml:"short-id"`
|
||||
}
|
||||
|
||||
type clashInteger int
|
||||
|
||||
func (value *clashInteger) UnmarshalYAML(node *yaml.Node) error {
|
||||
if node == nil || node.Kind != yaml.ScalarNode {
|
||||
return errors.New("Clash 整数字段格式无效")
|
||||
}
|
||||
parsed, err := strconv.ParseInt(strings.TrimSpace(node.Value), 10, 32)
|
||||
if err != nil {
|
||||
return errors.New("Clash 整数字段格式无效")
|
||||
}
|
||||
*value = clashInteger(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
type clashStringList []string
|
||||
|
||||
func (value *clashStringList) UnmarshalYAML(node *yaml.Node) error {
|
||||
if node == nil {
|
||||
return errors.New("Clash 字符串列表格式无效")
|
||||
}
|
||||
if node.Kind == yaml.AliasNode {
|
||||
if node.Alias == nil {
|
||||
return errors.New("Clash 字符串列表格式无效")
|
||||
}
|
||||
node = node.Alias
|
||||
}
|
||||
var items []string
|
||||
switch node.Kind {
|
||||
case yaml.ScalarNode:
|
||||
items = strings.Split(node.Value, ",")
|
||||
case yaml.SequenceNode:
|
||||
if err := node.Decode(&items); err != nil {
|
||||
return errors.New("Clash 字符串列表格式无效")
|
||||
}
|
||||
default:
|
||||
return errors.New("Clash 字符串列表格式无效")
|
||||
}
|
||||
normalized := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item = strings.TrimSpace(item); item != "" {
|
||||
normalized = append(normalized, item)
|
||||
}
|
||||
}
|
||||
*value = normalized
|
||||
return nil
|
||||
}
|
||||
|
||||
type clashVMessShare struct {
|
||||
Version string `json:"v"`
|
||||
Address string `json:"add"`
|
||||
Port string `json:"port"`
|
||||
UUID string `json:"id"`
|
||||
AlterID string `json:"aid"`
|
||||
Cipher string `json:"scy"`
|
||||
Network string `json:"net"`
|
||||
TLS string `json:"tls,omitempty"`
|
||||
ServerName string `json:"sni,omitempty"`
|
||||
ALPN string `json:"alpn,omitempty"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
AllowInsecure bool `json:"allowInsecure,omitempty"`
|
||||
}
|
||||
|
||||
func parseClashSubscription(value string) ([]subscriptionEntry, int, bool) {
|
||||
var document clashSubscription
|
||||
if err := yaml.Unmarshal([]byte(strings.TrimPrefix(value, "\ufeff")), &document); err != nil || document.Proxies == nil {
|
||||
return nil, 0, false
|
||||
}
|
||||
if len(document.Proxies) > maxSubscriptionEntries {
|
||||
return nil, len(document.Proxies), true
|
||||
}
|
||||
lines := make([]string, 0, len(document.Proxies))
|
||||
skipped := 0
|
||||
for index := range document.Proxies {
|
||||
var proxy clashProxy
|
||||
if err := document.Proxies[index].Decode(&proxy); err != nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
line, err := clashProxyURL(proxy)
|
||||
if err != nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
entries, lineSkipped := parseProxyLines(strings.Join(lines, "\n"))
|
||||
return entries, skipped + lineSkipped, true
|
||||
}
|
||||
|
||||
func clashProxyURL(proxy clashProxy) (string, error) {
|
||||
server, err := clashProxyServer(proxy.Server, int(proxy.Port))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
proxyType := strings.ToLower(strings.TrimSpace(proxy.Type))
|
||||
switch proxyType {
|
||||
case "http":
|
||||
scheme := "http"
|
||||
if proxy.TLS {
|
||||
scheme = "https"
|
||||
}
|
||||
return clashStandardProxyURL(scheme, server, proxy.Username, proxy.Password), nil
|
||||
case "socks5":
|
||||
if proxy.TLS {
|
||||
return "", errors.New("暂不支持 TLS SOCKS5")
|
||||
}
|
||||
return clashStandardProxyURL("socks5", server, proxy.Username, proxy.Password), nil
|
||||
case "ss":
|
||||
if strings.TrimSpace(proxy.Plugin) != "" {
|
||||
return "", errors.New("暂不支持 Shadowsocks plugin")
|
||||
}
|
||||
method := strings.ToLower(strings.TrimSpace(proxy.Cipher))
|
||||
if method == "" || proxy.Password == "" {
|
||||
return "", errors.New("Shadowsocks cipher/password 不能为空")
|
||||
}
|
||||
credential := base64.RawURLEncoding.EncodeToString([]byte(method + ":" + proxy.Password))
|
||||
return "ss://" + credential + "@" + server, nil
|
||||
case "trojan":
|
||||
if proxy.Password == "" {
|
||||
return "", errors.New("Trojan password 不能为空")
|
||||
}
|
||||
query, err := clashTunnelQuery(proxy, "tls")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return (&url.URL{Scheme: "trojan", User: url.User(proxy.Password), Host: server, RawQuery: query.Encode()}).String(), nil
|
||||
case "vless":
|
||||
if proxy.UUID == "" {
|
||||
return "", errors.New("VLESS UUID 不能为空")
|
||||
}
|
||||
security := "none"
|
||||
if proxy.RealityOptions.PublicKey != "" || proxy.RealityOptions.ShortID != "" {
|
||||
security = "reality"
|
||||
} else if proxy.TLS {
|
||||
security = "tls"
|
||||
}
|
||||
query, err := clashTunnelQuery(proxy, security)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
query.Set("encryption", "none")
|
||||
if flow := strings.TrimSpace(proxy.Flow); flow != "" {
|
||||
query.Set("flow", flow)
|
||||
}
|
||||
if security == "reality" {
|
||||
query.Set("pbk", proxy.RealityOptions.PublicKey)
|
||||
query.Set("sid", proxy.RealityOptions.ShortID)
|
||||
query.Set("fp", firstNonEmptySubscription(proxy.ClientFingerprint, "chrome"))
|
||||
}
|
||||
return (&url.URL{Scheme: "vless", User: url.User(proxy.UUID), Host: server, RawQuery: query.Encode()}).String(), nil
|
||||
case "vmess":
|
||||
return clashVMessURL(proxy)
|
||||
default:
|
||||
return "", fmt.Errorf("暂不支持 Clash 代理类型 %q", proxyType)
|
||||
}
|
||||
}
|
||||
|
||||
func clashProxyServer(host string, port int) (string, error) {
|
||||
host = strings.Trim(strings.TrimSpace(host), "[]")
|
||||
if host == "" || port < 1 || port > 65535 {
|
||||
return "", errors.New("Clash 代理服务器地址无效")
|
||||
}
|
||||
return net.JoinHostPort(host, strconv.Itoa(port)), nil
|
||||
}
|
||||
|
||||
func clashStandardProxyURL(scheme, server, username, password string) string {
|
||||
value := &url.URL{Scheme: scheme, Host: server}
|
||||
if username != "" || password != "" {
|
||||
value.User = url.UserPassword(username, password)
|
||||
}
|
||||
return value.String()
|
||||
}
|
||||
|
||||
func clashTunnelQuery(proxy clashProxy, security string) (url.Values, error) {
|
||||
transport := strings.ToLower(strings.TrimSpace(proxy.Network))
|
||||
if transport == "" {
|
||||
transport = "tcp"
|
||||
}
|
||||
if transport == "websocket" {
|
||||
transport = "ws"
|
||||
}
|
||||
query := make(url.Values)
|
||||
query.Set("type", transport)
|
||||
query.Set("security", security)
|
||||
query.Set("sni", firstNonEmptySubscription(proxy.ServerName, proxy.SNI, proxy.Server))
|
||||
if proxy.SkipCertVerify {
|
||||
query.Set("allowInsecure", "1")
|
||||
}
|
||||
if len(proxy.ALPN) != 0 {
|
||||
query.Set("alpn", strings.Join(proxy.ALPN, ","))
|
||||
}
|
||||
if transport == "ws" {
|
||||
query.Set("path", firstNonEmptySubscription(proxy.WSOptions.Path, "/"))
|
||||
query.Set("host", firstNonEmptySubscription(proxy.WSOptions.Headers["Host"], proxy.WSOptions.Headers["host"], proxy.ServerName, proxy.SNI, proxy.Server))
|
||||
}
|
||||
return query, nil
|
||||
}
|
||||
|
||||
func clashVMessURL(proxy clashProxy) (string, error) {
|
||||
if proxy.UUID == "" {
|
||||
return "", errors.New("VMess UUID 不能为空")
|
||||
}
|
||||
network := strings.ToLower(strings.TrimSpace(proxy.Network))
|
||||
if network == "" {
|
||||
network = "tcp"
|
||||
}
|
||||
if network == "websocket" {
|
||||
network = "ws"
|
||||
}
|
||||
share := clashVMessShare{
|
||||
Version: "2", Address: proxy.Server, Port: strconv.Itoa(int(proxy.Port)), UUID: proxy.UUID,
|
||||
AlterID: strconv.Itoa(int(proxy.AlterID)), Cipher: firstNonEmptySubscription(proxy.Cipher, "auto"), Network: network,
|
||||
ServerName: firstNonEmptySubscription(proxy.ServerName, proxy.SNI, proxy.Server), ALPN: strings.Join(proxy.ALPN, ","),
|
||||
AllowInsecure: proxy.SkipCertVerify,
|
||||
}
|
||||
if proxy.TLS {
|
||||
share.TLS = "tls"
|
||||
}
|
||||
if network == "ws" {
|
||||
share.Path = firstNonEmptySubscription(proxy.WSOptions.Path, "/")
|
||||
share.Host = firstNonEmptySubscription(proxy.WSOptions.Headers["Host"], proxy.WSOptions.Headers["host"], proxy.ServerName, proxy.SNI, proxy.Server)
|
||||
}
|
||||
encoded, err := json.Marshal(share)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "vmess://" + base64.RawStdEncoding.EncodeToString(encoded), nil
|
||||
}
|
||||
|
||||
func firstNonEmptySubscription(values ...string) string {
|
||||
for _, value := range values {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
type subscriptionSyncRepositoryStub struct {
|
||||
@@ -100,6 +101,197 @@ func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionAcceptsClashYAML(t *testing.T) {
|
||||
content := `
|
||||
proxies:
|
||||
- name: http
|
||||
type: http
|
||||
server: http.example
|
||||
port: 8080
|
||||
username: user
|
||||
password: pass
|
||||
- name: socks
|
||||
type: socks5
|
||||
server: socks.example
|
||||
port: 1080
|
||||
- name: trojan
|
||||
type: trojan
|
||||
server: trojan.example
|
||||
port: 443
|
||||
password: secret
|
||||
network: ws
|
||||
sni: edge.example
|
||||
ws-opts:
|
||||
path: /ws
|
||||
headers:
|
||||
Host: edge.example
|
||||
- name: reality
|
||||
type: vless
|
||||
server: reality.example
|
||||
port: 443
|
||||
uuid: 123e4567-e89b-12d3-a456-426614174000
|
||||
network: tcp
|
||||
tls: true
|
||||
servername: edge.example
|
||||
flow: xtls-rprx-vision
|
||||
client-fingerprint: chrome
|
||||
alpn: [h2, http/1.1]
|
||||
reality-opts:
|
||||
public-key: SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8
|
||||
short-id: 0123456789abcdef
|
||||
- name: shadowsocks
|
||||
type: ss
|
||||
server: ss.example
|
||||
port: 8388
|
||||
cipher: aes-128-gcm
|
||||
password: secret
|
||||
- name: vmess
|
||||
type: vmess
|
||||
server: vmess.example
|
||||
port: 443
|
||||
uuid: 123e4567-e89b-12d3-a456-426614174000
|
||||
alterId: 0
|
||||
cipher: auto
|
||||
network: ws
|
||||
tls: true
|
||||
servername: edge.example
|
||||
alpn: [h2, http/1.1]
|
||||
ws-opts:
|
||||
path: /vmess
|
||||
headers:
|
||||
Host: edge.example
|
||||
- name: ignored-hysteria
|
||||
type: hysteria2
|
||||
server: hy.example
|
||||
port: 443
|
||||
password: secret
|
||||
- name: ignored-tuic
|
||||
type: tuic
|
||||
server: tuic.example
|
||||
port: 443
|
||||
password: secret
|
||||
proxy-groups:
|
||||
- name: auto
|
||||
type: select
|
||||
proxies: [http, socks]
|
||||
`
|
||||
entries, skipped, err := parseProxySubscription(content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 6 || skipped != 2 {
|
||||
t.Fatalf("Clash entries=%d skipped=%d values=%#v", len(entries), skipped, entries)
|
||||
}
|
||||
var realityConfig tunnelproxy.Config
|
||||
var vmessConfig tunnelproxy.Config
|
||||
for _, entry := range entries {
|
||||
if !strings.HasPrefix(entry.ProxyURL, "vless://") && !strings.HasPrefix(entry.ProxyURL, "vmess://") {
|
||||
continue
|
||||
}
|
||||
config, parseErr := tunnelproxy.Parse(entry.ProxyURL)
|
||||
if parseErr != nil {
|
||||
t.Fatal(parseErr)
|
||||
}
|
||||
switch config.Scheme {
|
||||
case "vless":
|
||||
realityConfig = config
|
||||
case "vmess":
|
||||
vmessConfig = config
|
||||
}
|
||||
}
|
||||
if realityConfig.Security != "reality" || realityConfig.Flow != "xtls-rprx-vision" || realityConfig.RealityPublicKey == "" || realityConfig.RealityShortID != "0123456789abcdef" || strings.Join(realityConfig.ALPN, ",") != "h2,http/1.1" {
|
||||
t.Fatalf("Clash Reality config = %#v", realityConfig)
|
||||
}
|
||||
if strings.Join(vmessConfig.ALPN, ",") != "h2,http/1.1" {
|
||||
t.Fatalf("Clash VMess config = %#v", vmessConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionSkipsMalformedClashEntriesIndividually(t *testing.T) {
|
||||
content := `
|
||||
proxies:
|
||||
- type: http
|
||||
server: valid.example
|
||||
port: "8080"
|
||||
- type: hysteria2
|
||||
server: ignored.example
|
||||
port: invalid
|
||||
`
|
||||
entries, skipped, err := parseProxySubscription(content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 || skipped != 1 || entries[0].ProxyURL != "http://valid.example:8080" {
|
||||
t.Fatalf("entries=%#v skipped=%d", entries, skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchProxySubscriptionUsesClashUserAgent(t *testing.T) {
|
||||
var userAgent string
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
userAgent = request.Header.Get("User-Agent")
|
||||
_, _ = writer.Write([]byte("http://proxy.example:8080\n"))
|
||||
}))
|
||||
defer proxy.Close()
|
||||
|
||||
body, err := fetchProxySubscription(context.Background(), "http://1.1.1.1/subscription", proxy.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if userAgent != "Clash.Meta" || !strings.Contains(string(body), "proxy.example") {
|
||||
t.Fatalf("User-Agent=%q body=%q", userAgent, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClashRealityPreservesSupportedClientFingerprints(t *testing.T) {
|
||||
content := `
|
||||
proxies:
|
||||
- type: vless
|
||||
server: chrome.example
|
||||
port: 443
|
||||
uuid: 123e4567-e89b-12d3-a456-426614174000
|
||||
flow: xtls-rprx-vision
|
||||
client-fingerprint: chrome
|
||||
reality-opts: &reality
|
||||
public-key: SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8
|
||||
short-id: 0123456789abcdef
|
||||
- type: vless
|
||||
server: edge.example
|
||||
port: 443
|
||||
uuid: 123e4567-e89b-12d3-a456-426614174000
|
||||
flow: xtls-rprx-vision
|
||||
client-fingerprint: edge
|
||||
reality-opts: *reality
|
||||
- type: vless
|
||||
server: safari.example
|
||||
port: 443
|
||||
uuid: 123e4567-e89b-12d3-a456-426614174000
|
||||
flow: xtls-rprx-vision
|
||||
client-fingerprint: safari
|
||||
reality-opts: *reality
|
||||
`
|
||||
entries, skipped, err := parseProxySubscription(content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 3 || skipped != 0 {
|
||||
t.Fatalf("entries=%d skipped=%d", len(entries), skipped)
|
||||
}
|
||||
fingerprints := make(map[string]bool)
|
||||
for _, entry := range entries {
|
||||
config, parseErr := tunnelproxy.Parse(entry.ProxyURL)
|
||||
if parseErr != nil {
|
||||
t.Fatal(parseErr)
|
||||
}
|
||||
fingerprints[config.ClientFingerprint] = true
|
||||
}
|
||||
for _, fingerprint := range []string{"chrome", "edge", "safari"} {
|
||||
if !fingerprints[fingerprint] {
|
||||
t.Fatalf("missing client fingerprint %q", fingerprint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
|
||||
@@ -184,7 +184,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e
|
||||
FirstTokenMS: firstTokenMS, DurationMS: durationMS, GenerationMS: generationMS,
|
||||
ChunkCount: chunkCount, OutputTokens: usage.OutputTokens, ReasoningTokens: usage.ReasoningTokens,
|
||||
VisibleTokens: visibleTokens, VisibleCharacters: visibleCharacters, OutputTokensPerSecond: outputTokensPerSecond,
|
||||
ExpectedMatched: strings.Contains(text, input.Expected), ResponseSHA256: hex.EncodeToString(digest[:]),
|
||||
ExpectedMatched: egressapp.MatchExpected(text, input.Expected, input.MatchMode), ResponseSHA256: hex.EncodeToString(digest[:]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ type Config struct {
|
||||
TokenAuth string
|
||||
UserAgent string
|
||||
ResponseHeaderTimeout time.Duration
|
||||
StreamIdleTimeout time.Duration
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -68,6 +69,7 @@ type Adapter struct {
|
||||
|
||||
func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter {
|
||||
cfg.ResponseHeaderTimeout = normalizeBuildResponseHeaderTimeout(cfg.ResponseHeaderTimeout)
|
||||
cfg.StreamIdleTimeout = normalizeBuildStreamIdleTimeout(cfg.StreamIdleTimeout)
|
||||
transport := newBuildDirectTransport(cfg.ResponseHeaderTimeout)
|
||||
httpClient := &http.Client{Transport: transport}
|
||||
// The official CLI uses a persistent machine identity. The gateway does not collect machine fingerprints;
|
||||
@@ -156,6 +158,7 @@ func buildBotFlaggedFromClaims(claims map[string]any) bool {
|
||||
|
||||
func (a *Adapter) UpdateConfig(cfg Config) {
|
||||
cfg.ResponseHeaderTimeout = normalizeBuildResponseHeaderTimeout(cfg.ResponseHeaderTimeout)
|
||||
cfg.StreamIdleTimeout = normalizeBuildStreamIdleTimeout(cfg.StreamIdleTimeout)
|
||||
a.cfgMu.Lock()
|
||||
previousTimeout := a.cfg.ResponseHeaderTimeout
|
||||
a.cfg = cfg
|
||||
@@ -204,6 +207,13 @@ func normalizeBuildResponseHeaderTimeout(value time.Duration) time.Duration {
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeBuildStreamIdleTimeout(value time.Duration) time.Duration {
|
||||
if value <= 0 {
|
||||
return settingsdomain.DefaultBuildStreamIdleTimeout
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (a *Adapter) config() Config {
|
||||
a.cfgMu.RLock()
|
||||
defer a.cfgMu.RUnlock()
|
||||
@@ -364,6 +374,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
}
|
||||
}
|
||||
}
|
||||
if request.Streaming && isHTTPSuccess(resp.StatusCode) && resp.Body != nil {
|
||||
resp.Body = wrapBuildSemanticIdle(resp.Body, a.config().StreamIdleTimeout)
|
||||
}
|
||||
modelCatalogChanged := a.modelCatalogChanged(request.Credential.ID, resp.Header.Get("x-models-etag"))
|
||||
// Capture or clear reasoning replay in the upstream Responses shape before protocol conversion.
|
||||
if a.shouldCaptureReplay(request, resp, replayKey) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
settingsdomain "github.com/chenyme/grok2api/backend/internal/domain/settings"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
|
||||
@@ -60,16 +61,29 @@ func TestResponseRequestForcedEgressOverridesCredentialBinding(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAdapterHotUpdatesDirectResponseHeaderTimeout(t *testing.T) {
|
||||
adapter := NewAdapter(Config{ResponseHeaderTimeout: 2 * time.Minute}, nil)
|
||||
adapter := NewAdapter(Config{ResponseHeaderTimeout: 2 * time.Minute, StreamIdleTimeout: 3 * time.Minute}, nil)
|
||||
before := adapter.base.current.Load()
|
||||
if before.ResponseHeaderTimeout != 2*time.Minute {
|
||||
t.Fatalf("initial timeout = %s", before.ResponseHeaderTimeout)
|
||||
}
|
||||
adapter.UpdateConfig(Config{ResponseHeaderTimeout: 7 * time.Minute})
|
||||
if got := adapter.config().StreamIdleTimeout; got != 3*time.Minute {
|
||||
t.Fatalf("initial stream idle timeout = %s", got)
|
||||
}
|
||||
adapter.UpdateConfig(Config{ResponseHeaderTimeout: 7 * time.Minute, StreamIdleTimeout: 11 * time.Minute})
|
||||
after := adapter.base.current.Load()
|
||||
if after == before || after.ResponseHeaderTimeout != 7*time.Minute {
|
||||
t.Fatalf("updated transport=%p timeout=%s", after, after.ResponseHeaderTimeout)
|
||||
}
|
||||
if got := adapter.config().StreamIdleTimeout; got != 11*time.Minute {
|
||||
t.Fatalf("updated stream idle timeout = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterDefaultsStreamIdleTimeout(t *testing.T) {
|
||||
adapter := NewAdapter(Config{}, nil)
|
||||
if got := adapter.config().StreamIdleTimeout; got != settingsdomain.DefaultBuildStreamIdleTimeout {
|
||||
t.Fatalf("stream idle timeout = %s, want %s", got, settingsdomain.DefaultBuildStreamIdleTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialMetadataMarksNumericBotFlagOneOrTwo(t *testing.T) {
|
||||
|
||||
@@ -134,6 +134,7 @@ func (a *Adapter) forwardGatewayCompactionWithPolicy(
|
||||
return result, nil
|
||||
}
|
||||
|
||||
resp.Body = wrapBuildSemanticIdle(resp.Body, a.config().StreamIdleTimeout)
|
||||
data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxCompatibleResponseBytes+1))
|
||||
_ = resp.Body.Close()
|
||||
if readErr != nil {
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
|
||||
func TestGatewayCompactionLifecycle(t *testing.T) {
|
||||
@@ -107,6 +108,46 @@ func TestGatewayCompactionRetryVetoStopsSameAccountRetries(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayCompactionSemanticIdleIgnoresKeepalives(t *testing.T) {
|
||||
adapter, encrypted := newCompactionTestAdapter(t)
|
||||
cfg := adapter.config()
|
||||
cfg.StreamIdleTimeout = 60 * time.Millisecond
|
||||
adapter.UpdateConfig(cfg)
|
||||
|
||||
writeDone := make(chan struct{})
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
reader, writer := io.Pipe()
|
||||
go func() {
|
||||
defer close(writeDone)
|
||||
defer writer.Close()
|
||||
for {
|
||||
if _, err := io.WriteString(writer, ": keep-alive\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}()
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: reader,
|
||||
Request: request,
|
||||
}, nil
|
||||
})
|
||||
|
||||
request := compactionProviderRequest(encrypted)
|
||||
_, err := adapter.forwardGatewayCompactionWithPolicy(t.Context(), request, "access-token", request.Body, "", 1, 0)
|
||||
if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) {
|
||||
t.Fatalf("compaction error = %v, want ErrUpstreamStreamIdleTimeout", err)
|
||||
}
|
||||
select {
|
||||
case <-writeDone:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("semantic timeout did not close the compaction response body")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayCompactionResponseNormalizesPartialUsage(t *testing.T) {
|
||||
response := map[string]any{
|
||||
"id": "resp_usage",
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
|
||||
var buildGeneratedDeltaEvents = map[string]struct{}{
|
||||
"response.output_text.delta": {},
|
||||
"response.reasoning_summary_text.delta": {},
|
||||
"response.reasoning_text.delta": {},
|
||||
"response.refusal.delta": {},
|
||||
"response.function_call_arguments.delta": {},
|
||||
"response.custom_tool_call_input.delta": {},
|
||||
}
|
||||
|
||||
var buildGeneratedOutputItemTypes = map[string]struct{}{
|
||||
"code_interpreter_call": {},
|
||||
"custom_tool_call": {},
|
||||
"file_search_call": {},
|
||||
"function_call": {},
|
||||
"image_generation_call": {},
|
||||
"mcp_call": {},
|
||||
"mcp_approval_request": {},
|
||||
"mcp_approval_response": {},
|
||||
"mcp_list_tools": {},
|
||||
"message": {},
|
||||
"reasoning": {},
|
||||
"shell_call": {},
|
||||
"web_search_call": {},
|
||||
}
|
||||
|
||||
// semanticIdleReadCloser measures useful generated output rather than raw
|
||||
// transport bytes, so SSE keepalives and Build control events cannot keep a
|
||||
// stalled generation alive indefinitely.
|
||||
type semanticIdleReadCloser struct {
|
||||
inner io.ReadCloser
|
||||
idle time.Duration
|
||||
timer *time.Timer
|
||||
|
||||
mu sync.Mutex
|
||||
detector buildSSEActivityDetector
|
||||
finished bool
|
||||
timedOut bool
|
||||
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func wrapBuildSemanticIdle(body io.ReadCloser, idle time.Duration) io.ReadCloser {
|
||||
if body == nil || idle <= 0 {
|
||||
return body
|
||||
}
|
||||
wrapper := &semanticIdleReadCloser{inner: body, idle: idle}
|
||||
wrapper.timer = time.AfterFunc(idle, wrapper.timeout)
|
||||
return wrapper
|
||||
}
|
||||
|
||||
func (r *semanticIdleReadCloser) timeout() {
|
||||
r.mu.Lock()
|
||||
if r.finished {
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
r.finished = true
|
||||
r.timedOut = true
|
||||
r.mu.Unlock()
|
||||
_ = r.closeInner()
|
||||
}
|
||||
|
||||
func (r *semanticIdleReadCloser) Read(buffer []byte) (int, error) {
|
||||
n, err := r.inner.Read(buffer)
|
||||
|
||||
r.mu.Lock()
|
||||
if n > 0 && !r.finished && r.detector.Observe(buffer[:n]) {
|
||||
// A failed Stop means the deadline has already elapsed and its callback
|
||||
// owns the outcome. Reset only while the prior deadline is still live.
|
||||
if r.timer.Stop() {
|
||||
r.timer.Reset(r.idle)
|
||||
}
|
||||
}
|
||||
if err != nil && !r.finished {
|
||||
r.finished = true
|
||||
r.timer.Stop()
|
||||
}
|
||||
timedOut := r.timedOut
|
||||
r.mu.Unlock()
|
||||
|
||||
if timedOut {
|
||||
return n, neterror.ErrUpstreamStreamIdleTimeout
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *semanticIdleReadCloser) Close() error {
|
||||
r.mu.Lock()
|
||||
if !r.finished {
|
||||
r.finished = true
|
||||
r.timer.Stop()
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return r.closeInner()
|
||||
}
|
||||
|
||||
func (r *semanticIdleReadCloser) closeInner() error {
|
||||
r.closeOnce.Do(func() {
|
||||
r.closeErr = r.inner.Close()
|
||||
})
|
||||
return r.closeErr
|
||||
}
|
||||
|
||||
func (r *semanticIdleReadCloser) TimedOut() bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.timedOut
|
||||
}
|
||||
|
||||
// buildSSEActivityDetector incrementally parses SSE framing without modifying
|
||||
// the bytes returned to downstream response wrappers.
|
||||
type buildSSEActivityDetector struct {
|
||||
pending []byte
|
||||
eventName string
|
||||
data []byte
|
||||
eventBytes int
|
||||
overLimit bool
|
||||
firstLine bool
|
||||
}
|
||||
|
||||
func (d *buildSSEActivityDetector) Observe(chunk []byte) bool {
|
||||
if len(chunk) == 0 {
|
||||
return false
|
||||
}
|
||||
d.pending = append(d.pending, chunk...)
|
||||
active := false
|
||||
for {
|
||||
newline := bytes.IndexByte(d.pending, '\n')
|
||||
if newline < 0 {
|
||||
break
|
||||
}
|
||||
line := d.pending[:newline]
|
||||
d.pending = d.pending[newline+1:]
|
||||
line = bytes.TrimSuffix(line, []byte{'\r'})
|
||||
if !d.firstLine {
|
||||
line = bytes.TrimPrefix(line, []byte("\xef\xbb\xbf"))
|
||||
d.firstLine = true
|
||||
}
|
||||
if len(line) == 0 {
|
||||
active = d.finishEvent() || active
|
||||
continue
|
||||
}
|
||||
d.observeLine(line)
|
||||
}
|
||||
if len(d.pending)+d.eventBytes > maxCompatibleSSEEventBytes {
|
||||
d.pending = nil
|
||||
d.overLimit = true
|
||||
}
|
||||
return active
|
||||
}
|
||||
|
||||
func (d *buildSSEActivityDetector) observeLine(line []byte) {
|
||||
d.eventBytes += len(line)
|
||||
if d.eventBytes > maxCompatibleSSEEventBytes {
|
||||
d.overLimit = true
|
||||
d.eventName = ""
|
||||
d.data = nil
|
||||
return
|
||||
}
|
||||
if d.overLimit || len(line) == 0 || line[0] == ':' {
|
||||
return
|
||||
}
|
||||
field, value, found := bytes.Cut(line, []byte{':'})
|
||||
if found && len(value) > 0 && value[0] == ' ' {
|
||||
value = value[1:]
|
||||
}
|
||||
switch string(field) {
|
||||
case "event":
|
||||
d.eventName = string(value)
|
||||
case "data":
|
||||
if len(d.data) > 0 {
|
||||
d.data = append(d.data, '\n')
|
||||
}
|
||||
d.data = append(d.data, value...)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *buildSSEActivityDetector) finishEvent() bool {
|
||||
active := false
|
||||
if !d.overLimit && len(d.data) > 0 {
|
||||
var payload struct {
|
||||
Type string `json:"type"`
|
||||
Delta string `json:"delta"`
|
||||
Item struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
CallID string `json:"call_id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"item"`
|
||||
}
|
||||
if json.Unmarshal(d.data, &payload) == nil {
|
||||
kind := strings.TrimSpace(payload.Type)
|
||||
if kind == "" {
|
||||
kind = strings.TrimSpace(d.eventName)
|
||||
}
|
||||
if _, generatedDelta := buildGeneratedDeltaEvents[kind]; generatedDelta {
|
||||
active = payload.Delta != ""
|
||||
} else if kind == "response.output_item.added" || kind == "response.output_item.done" {
|
||||
itemType := strings.TrimSpace(payload.Item.Type)
|
||||
_, generatedItem := buildGeneratedOutputItemTypes[itemType]
|
||||
active = generatedItem && (strings.TrimSpace(payload.Item.ID) != "" ||
|
||||
strings.TrimSpace(payload.Item.CallID) != "" || strings.TrimSpace(payload.Item.Name) != "")
|
||||
}
|
||||
}
|
||||
}
|
||||
d.eventName = ""
|
||||
d.data = nil
|
||||
d.eventBytes = 0
|
||||
d.overLimit = false
|
||||
return active
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
|
||||
func TestBuildSemanticIdleIgnoresNonGeneratedEvents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
chunk string
|
||||
}{
|
||||
{name: "keepalive comment", chunk: ": keep-alive\n\n"},
|
||||
{name: "doom loop control", chunk: "event: response.doom_loop_check\ndata: {\"type\":\"response.doom_loop_check\"}\n\n"},
|
||||
{name: "lifecycle event", chunk: "event: response.in_progress\ndata: {\"type\":\"response.in_progress\"}\n\n"},
|
||||
{name: "empty generated delta", chunk: "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
reader, writer := io.Pipe()
|
||||
body := wrapBuildSemanticIdle(reader, 60*time.Millisecond)
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := io.Copy(io.Discard, body)
|
||||
readDone <- err
|
||||
}()
|
||||
writeDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(writeDone)
|
||||
defer writer.Close()
|
||||
for {
|
||||
if _, err := io.WriteString(writer, test.chunk); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-readDone:
|
||||
if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) {
|
||||
t.Fatalf("body read error = %v, want ErrUpstreamStreamIdleTimeout", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("semantic idle timeout did not interrupt the stream")
|
||||
}
|
||||
<-writeDone
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSemanticIdleResetsOnGeneratedDelta(t *testing.T) {
|
||||
reader, writer := io.Pipe()
|
||||
body := wrapBuildSemanticIdle(reader, 300*time.Millisecond)
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := io.Copy(io.Discard, body)
|
||||
readDone <- err
|
||||
}()
|
||||
|
||||
chunk := "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"x\"}\n\n"
|
||||
if _, err := io.WriteString(writer, chunk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(180 * time.Millisecond)
|
||||
if _, err := io.WriteString(writer, chunk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(180 * time.Millisecond)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-readDone:
|
||||
if err != nil {
|
||||
t.Fatalf("body read error = %v, want nil", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("generated deltas did not keep the stream alive")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSemanticIdleResetsOnGeneratedOutputItem(t *testing.T) {
|
||||
reader, writer := io.Pipe()
|
||||
body := wrapBuildSemanticIdle(reader, 300*time.Millisecond)
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := io.Copy(io.Discard, body)
|
||||
readDone <- err
|
||||
}()
|
||||
|
||||
time.Sleep(180 * time.Millisecond)
|
||||
searchStarted := "event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"id\":\"ws_1\",\"type\":\"web_search_call\",\"status\":\"in_progress\",\"action\":{\"type\":\"search\",\"query\":\"current docs\"}}}\n\n"
|
||||
if _, err := io.WriteString(writer, searchStarted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(180 * time.Millisecond)
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-readDone:
|
||||
if err != nil {
|
||||
t.Fatalf("body read error = %v, want nil", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("generated output item did not keep the stream alive")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSSEActivityDetectorRecognizesSplitGeneratedEvents(t *testing.T) {
|
||||
for kind := range buildGeneratedDeltaEvents {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
var detector buildSSEActivityDetector
|
||||
event := fmt.Sprintf("event: %s\r\ndata: {\"type\":%q,\"delta\":\"x\"}\r\n\r\n", kind, kind)
|
||||
active := false
|
||||
for index := range event {
|
||||
active = detector.Observe([]byte(event[index:index+1])) || active
|
||||
}
|
||||
if !active {
|
||||
t.Fatal("split generated event was not recognized")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSSEActivityDetectorRequiresJSONGeneratedEvent(t *testing.T) {
|
||||
var detector buildSSEActivityDetector
|
||||
if detector.Observe([]byte("event: response.output_text.delta\ndata: not-json\n\n")) {
|
||||
t.Fatal("malformed event unexpectedly counted as generated activity")
|
||||
}
|
||||
if detector.Observe([]byte(": keep-alive\n\n")) {
|
||||
t.Fatal("keepalive unexpectedly counted as generated activity")
|
||||
}
|
||||
if detector.Observe([]byte("event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n")) {
|
||||
t.Fatal("empty delta unexpectedly counted as generated activity")
|
||||
}
|
||||
if detector.Observe([]byte("event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\"}}\n\n")) {
|
||||
t.Fatal("unidentified output item unexpectedly counted as generated activity")
|
||||
}
|
||||
if detector.Observe([]byte("event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\",\"status\":\"in_progress\"}}\n\n")) {
|
||||
t.Fatal("anonymous output item unexpectedly counted as generated activity")
|
||||
}
|
||||
if detector.Observe([]byte("event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"id\":\"control_1\",\"type\":\"private_control\"}}\n\n")) {
|
||||
t.Fatal("unknown output item unexpectedly counted as generated activity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSSEActivityDetectorRecognizesGeneratedOutputItems(t *testing.T) {
|
||||
tests := []string{
|
||||
`{"type":"response.output_item.added","item":{"id":"ws_1","type":"web_search_call","status":"in_progress"}}`,
|
||||
`{"type":"response.output_item.added","item":{"id":"reasoning_1","type":"reasoning"}}`,
|
||||
`{"type":"response.output_item.done","item":{"call_id":"call_1","type":"function_call","name":"lookup","status":"completed"}}`,
|
||||
}
|
||||
for _, payload := range tests {
|
||||
var detector buildSSEActivityDetector
|
||||
if !detector.Observe([]byte("data: " + payload + "\n\n")) {
|
||||
t.Fatalf("generated output item was not recognized: %s", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSemanticIdleStopsAfterEOFOrClose(t *testing.T) {
|
||||
t.Run("EOF", func(t *testing.T) {
|
||||
inner := &countingReadCloser{Reader: strings.NewReader("done")}
|
||||
body := wrapBuildSemanticIdle(inner, 20*time.Millisecond).(*semanticIdleReadCloser)
|
||||
if _, err := io.ReadAll(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
if body.TimedOut() {
|
||||
t.Fatal("timer fired after EOF")
|
||||
}
|
||||
if err := body.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := inner.closes.Load(); got != 1 {
|
||||
t.Fatalf("inner Close calls = %d, want 1", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Close", func(t *testing.T) {
|
||||
inner := &countingReadCloser{Reader: strings.NewReader("")}
|
||||
body := wrapBuildSemanticIdle(inner, 20*time.Millisecond).(*semanticIdleReadCloser)
|
||||
if err := body.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := body.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
if body.TimedOut() {
|
||||
t.Fatal("timer fired after Close")
|
||||
}
|
||||
if got := inner.closes.Load(); got != 1 {
|
||||
t.Fatalf("inner Close calls = %d, want 1", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type countingReadCloser struct {
|
||||
io.Reader
|
||||
closes atomic.Int32
|
||||
}
|
||||
|
||||
func (r *countingReadCloser) Close() error {
|
||||
r.closes.Add(1)
|
||||
return nil
|
||||
}
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
const (
|
||||
ssoBuildClientID = "b1a00492-073a-47ea-816f-4c329264a828"
|
||||
ssoBuildScope = "openid profile email offline_access grok-cli:access api:access conversations:read conversations:write"
|
||||
ssoAccountsURL = "https://accounts.x.ai/"
|
||||
ssoDeviceURL = "https://auth.x.ai/oauth2/device/code"
|
||||
ssoVerifyURL = "https://auth.x.ai/oauth2/device/verify"
|
||||
ssoApproveURL = "https://auth.x.ai/oauth2/device/approve"
|
||||
@@ -75,17 +74,6 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) {
|
||||
status, finalURL, _, err := f.do(ctx, http.MethodGet, ssoAccountsURL, nil)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
if status == http.StatusUnauthorized || strings.Contains(finalURL, "sign-in") || strings.Contains(finalURL, "sign-up") {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
if status < 200 || status >= 400 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("校验 Grok Web SSO 失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
|
||||
form := url.Values{"client_id": {ssoBuildClientID}, "scope": {ssoBuildScope}}
|
||||
status, _, body, err := f.do(ctx, http.MethodPost, ssoDeviceURL, form)
|
||||
if err != nil {
|
||||
@@ -95,16 +83,15 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
return provider.CredentialSeed{}, fmt.Errorf("xAI Device Flow 启动失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
var device struct {
|
||||
DeviceCode string `json:"device_code"`
|
||||
UserCode string `json:"user_code"`
|
||||
VerificationURIComplete string `json:"verification_uri_complete"`
|
||||
Interval int `json:"interval"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
DeviceCode string `json:"device_code"`
|
||||
UserCode string `json:"user_code"`
|
||||
Interval int `json:"interval"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &device); err != nil {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("解析 xAI Device Flow: %w", err)
|
||||
}
|
||||
if device.DeviceCode == "" || device.UserCode == "" || !safeXAIURL(device.VerificationURIComplete) {
|
||||
if device.DeviceCode == "" || device.UserCode == "" {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("xAI Device Flow 返回字段不完整")
|
||||
}
|
||||
if device.Interval <= 0 {
|
||||
@@ -114,33 +101,37 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
device.ExpiresIn = 1800
|
||||
}
|
||||
|
||||
status, finalURL, _, err = f.do(ctx, http.MethodGet, device.VerificationURIComplete, nil)
|
||||
// verify/approve 已在 auth.x.ai 完成状态变更。重定向目标只是结果页,
|
||||
// 因此不访问 accounts.x.ai,直接解析首个 3xx Location 的状态路径。
|
||||
status, finalURL, _, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
if status < 200 || status >= 400 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("打开 Device Flow 验证页失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
status, finalURL, _, err = f.do(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}})
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
if status == http.StatusUnauthorized {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
if status < 200 || status >= 400 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
if !strings.Contains(finalURL, "consent") {
|
||||
if redirectState := ssoDeviceRedirectState(finalURL); redirectState != "consent" {
|
||||
if redirectState == "sign-in" {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败")
|
||||
}
|
||||
status, finalURL, _, err = f.do(ctx, http.MethodPost, ssoApproveURL, url.Values{
|
||||
status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoApproveURL, url.Values{
|
||||
"user_code": {device.UserCode}, "action": {"allow"}, "principal_type": {"User"}, "principal_id": {""},
|
||||
})
|
||||
}, false)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
if status < 200 || status >= 400 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败: %w", conversionHTTPError{status: status})
|
||||
}
|
||||
if !strings.Contains(finalURL, "done") {
|
||||
if redirectState := ssoDeviceRedirectState(finalURL); redirectState != "done" {
|
||||
if redirectState == "sign-in" {
|
||||
return provider.CredentialSeed{}, provider.ErrUnauthorized
|
||||
}
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败")
|
||||
}
|
||||
|
||||
@@ -226,6 +217,12 @@ func (f *ssoBuildFlow) pollToken(ctx context.Context, deviceCode string, interva
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url.Values) (int, string, []byte, error) {
|
||||
return f.doWithFollow(ctx, method, endpoint, form, true)
|
||||
}
|
||||
|
||||
// doWithFollow 在 follow=false 时遇到 3xx 直接返回状态码与解析后的 Location 作为 finalURL,
|
||||
// 用于重定向目标域会被 Cloudflare 拦截(accounts.x.ai)的请求。
|
||||
func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string, form url.Values, follow bool) (int, string, []byte, error) {
|
||||
if !safeXAIURL(endpoint) {
|
||||
return 0, "", nil, fmt.Errorf("xAI OAuth URL 不安全")
|
||||
}
|
||||
@@ -277,6 +274,9 @@ func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url
|
||||
if !safeXAIURL(currentURL) {
|
||||
return response.StatusCode, currentURL, data, fmt.Errorf("xAI OAuth 重定向到非受信域名")
|
||||
}
|
||||
if !follow {
|
||||
return response.StatusCode, currentURL, nil, nil
|
||||
}
|
||||
if response.StatusCode == http.StatusSeeOther || ((response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound) && currentMethod != http.MethodGet && currentMethod != http.MethodHead) {
|
||||
currentMethod = http.MethodGet
|
||||
currentForm = nil
|
||||
@@ -300,6 +300,24 @@ func (f *ssoBuildFlow) captureCookies(response *http.Response) {
|
||||
}
|
||||
}
|
||||
|
||||
func ssoDeviceRedirectState(raw string) string {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || !safeXAIURL(raw) {
|
||||
return ""
|
||||
}
|
||||
path := strings.TrimRight(parsed.EscapedPath(), "/")
|
||||
switch path {
|
||||
case "/oauth2/device/consent":
|
||||
return "consent"
|
||||
case "/oauth2/device/done":
|
||||
return "done"
|
||||
case "/sign-in", "/sign-up":
|
||||
return "sign-in"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) cookieHeader() string {
|
||||
keys := make([]string, 0, len(f.cookies))
|
||||
for key := range f.cookies {
|
||||
|
||||
@@ -2,10 +2,15 @@ package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
type scriptedSSOClient struct {
|
||||
@@ -26,7 +31,7 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) {
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("ok"))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "test-agent", cookies: map[string]string{"sso": "secret"}}
|
||||
status, finalURL, body, err := flow.do(context.Background(), http.MethodGet, ssoAccountsURL, nil)
|
||||
status, finalURL, body, err := flow.do(context.Background(), http.MethodGet, ssoDeviceURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -43,11 +48,89 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) {
|
||||
|
||||
unsafe := &scriptedSSOClient{responses: []*http.Response{{StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://example.com/steal"}}, Body: io.NopCloser(strings.NewReader(""))}}}
|
||||
flow = &ssoBuildFlow{client: unsafe, userAgent: "test-agent", cookies: map[string]string{"sso": "secret"}}
|
||||
if _, _, _, err := flow.do(context.Background(), http.MethodGet, ssoAccountsURL, nil); err == nil {
|
||||
if _, _, _, err := flow.do(context.Background(), http.MethodGet, ssoDeviceURL, nil); err == nil {
|
||||
t.Fatal("unsafe redirect was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowMapsDeadSSOToUnauthorized(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/sign-in"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "dead"}}
|
||||
_, err := flow.convert(context.Background(), fakeCredential())
|
||||
if !errors.Is(err, provider.ErrUnauthorized) {
|
||||
t.Fatalf("err = %v, want ErrUnauthorized", err)
|
||||
}
|
||||
if len(client.requests) != 2 {
|
||||
t.Fatalf("requests = %d, want 2 (device, verify)", len(client.requests))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowUsesAuthEndpointsOnly(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/done"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"access_token":"access","refresh_token":"refresh","expires_in":3600}`))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live", "sso-rw": "live"}}
|
||||
seed, err := flow.convert(context.Background(), fakeCredential())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 4 {
|
||||
t.Fatalf("seed=%#v requests=%d", seed, len(client.requests))
|
||||
}
|
||||
for _, request := range client.requests {
|
||||
if request.URL.Hostname() != "auth.x.ai" {
|
||||
t.Fatalf("device flow visited unexpected host %q", request.URL.Hostname())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live"}}
|
||||
status, finalURL, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != http.StatusSeeOther {
|
||||
t.Fatalf("status = %d, want 303", status)
|
||||
}
|
||||
if finalURL != "https://accounts.x.ai/oauth2/device/consent" {
|
||||
t.Fatalf("finalURL = %q", finalURL)
|
||||
}
|
||||
if len(client.requests) != 1 {
|
||||
t.Fatalf("redirect must not be followed, requests = %d", len(client.requests))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"https://accounts.x.ai/oauth2/device/consent": "consent",
|
||||
"https://accounts.x.ai/oauth2/device/done/": "done",
|
||||
"https://accounts.x.ai/sign-in?returnTo=%2Foauth2": "sign-in",
|
||||
"https://accounts.x.ai/other?next=consent": "",
|
||||
"https://accounts.x.ai/oauth2/device/consent-untrusted": "",
|
||||
"https://example.com/oauth2/device/consent": "",
|
||||
}
|
||||
for raw, wanted := range tests {
|
||||
if actual := ssoDeviceRedirectState(raw); actual != wanted {
|
||||
t.Fatalf("ssoDeviceRedirectState(%q)=%q want=%q", raw, actual, wanted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fakeCredential() accountdomain.Credential { return accountdomain.Credential{} }
|
||||
|
||||
func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) {
|
||||
if token := normalizeSSOToken("sso=token-value; x-userid=drop"); token != "token-value" {
|
||||
t.Fatalf("token = %q", token)
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package tunnelproxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdh"
|
||||
"crypto/ed25519"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
utls "github.com/refraction-networking/utls"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
"golang.org/x/crypto/hkdf"
|
||||
)
|
||||
|
||||
// realityProxy follows the Xray Reality client handshake used by yuhaiin, but
|
||||
// keeps the ClientHello selectable so Clash client-fingerprint values are not
|
||||
// silently replaced with Chrome.
|
||||
type realityProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
dialer netapi.Proxy
|
||||
serverName string
|
||||
publicKey *ecdh.PublicKey
|
||||
shortID [8]byte
|
||||
helloID utls.ClientHelloID
|
||||
alpn []string
|
||||
}
|
||||
|
||||
func newRealityProxy(config Config, dialer netapi.Proxy) (netapi.Proxy, error) {
|
||||
publicKeyBytes, err := base64.RawURLEncoding.DecodeString(config.RealityPublicKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 Reality public key: %w", err)
|
||||
}
|
||||
publicKey, err := ecdh.X25519().NewPublicKey(publicKeyBytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("Reality public key 无效")
|
||||
}
|
||||
var shortID [8]byte
|
||||
decodedLength, err := hex.Decode(shortID[:], []byte(config.RealityShortID))
|
||||
if err != nil || decodedLength > len(shortID) {
|
||||
return nil, errors.New("Reality short ID 无效")
|
||||
}
|
||||
helloID, ok := realityClientHelloID(config.ClientFingerprint)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("VLESS Reality 暂不支持客户端指纹 %q", config.ClientFingerprint)
|
||||
}
|
||||
return &realityProxy{
|
||||
dialer: dialer, serverName: config.ServerName, publicKey: publicKey,
|
||||
shortID: shortID, helloID: helloID, alpn: append([]string(nil), config.ALPN...),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func realityClientHelloID(fingerprint string) (utls.ClientHelloID, bool) {
|
||||
switch fingerprint {
|
||||
case "chrome":
|
||||
return utls.HelloChrome_Auto, true
|
||||
case "firefox":
|
||||
return utls.HelloFirefox_Auto, true
|
||||
case "safari":
|
||||
return utls.HelloSafari_Auto, true
|
||||
case "ios":
|
||||
return utls.HelloIOS_Auto, true
|
||||
case "edge":
|
||||
return utls.HelloEdge_Auto, true
|
||||
case "qq":
|
||||
return utls.HelloQQ_Auto, true
|
||||
default:
|
||||
return utls.ClientHelloID{}, false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *realityProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
connection, err := p.dialer.Conn(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handshakeCtx, cancel := newTunnelHandshakeContext(ctx)
|
||||
defer cancel()
|
||||
secure, err := p.handshake(handshakeCtx, connection)
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("Reality 握手: %w", err)
|
||||
}
|
||||
return secure, nil
|
||||
}
|
||||
|
||||
func (p *realityProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("Reality 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
func (p *realityProxy) handshake(ctx context.Context, connection net.Conn) (net.Conn, error) {
|
||||
verifier := &realityVerifier{serverName: p.serverName}
|
||||
secure, err := buildRealityClientHello(connection, p.serverName, p.alpn, p.helloID, verifier.verifyPeerCertificate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hello := secure.HandshakeState.Hello
|
||||
privateKey := secure.HandshakeState.State13.EcdheKey
|
||||
|
||||
hello.SessionId = make([]byte, 32)
|
||||
copy(hello.Raw[39:], hello.SessionId)
|
||||
binary.BigEndian.PutUint64(hello.SessionId, uint64(time.Now().Unix()))
|
||||
hello.SessionId[0] = 1
|
||||
hello.SessionId[1] = 8
|
||||
hello.SessionId[2] = 1
|
||||
copy(hello.SessionId[8:], p.shortID[:])
|
||||
|
||||
peerKey, err := privateKey.ECDH(p.publicKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Reality ECDH: %w", err)
|
||||
}
|
||||
verifier.authKey = peerKey
|
||||
if _, err := hkdf.New(sha256.New, peerKey, hello.Random[:20], []byte("REALITY")).Read(peerKey); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var aead cipher.AEAD
|
||||
if realityPrefersAESGCM(hello.CipherSuites) {
|
||||
block, cipherErr := aes.NewCipher(peerKey)
|
||||
if cipherErr != nil {
|
||||
return nil, cipherErr
|
||||
}
|
||||
aead, err = cipher.NewGCM(block)
|
||||
} else {
|
||||
aead, err = chacha20poly1305.New(peerKey)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
||||
copy(hello.Raw[39:], hello.SessionId)
|
||||
|
||||
if err := secure.HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !verifier.verified {
|
||||
return nil, errors.New("Reality 身份验证失败")
|
||||
}
|
||||
return secure, nil
|
||||
}
|
||||
|
||||
func buildRealityClientHello(connection net.Conn, serverName string, alpn []string, helloID utls.ClientHelloID, verify func([][]byte, [][]*x509.Certificate) error) (*utls.UConn, error) {
|
||||
config := &utls.Config{
|
||||
ServerName: serverName, InsecureSkipVerify: true, SessionTicketsDisabled: true,
|
||||
NextProtos: append([]string(nil), alpn...), VerifyPeerCertificate: verify,
|
||||
}
|
||||
secure := utls.UClient(connection, config, helloID)
|
||||
if err := secure.BuildHandshakeState(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if secure.HandshakeState.Hello == nil || len(secure.HandshakeState.Hello.Raw) < 71 {
|
||||
return nil, errors.New("Reality ClientHello 无效")
|
||||
}
|
||||
if len(alpn) != 0 {
|
||||
patched := false
|
||||
for _, extension := range secure.Extensions {
|
||||
if alpnExtension, ok := extension.(*utls.ALPNExtension); ok {
|
||||
alpnExtension.AlpnProtocols = append([]string(nil), alpn...)
|
||||
patched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !patched {
|
||||
secure.Extensions = append(secure.Extensions, &utls.ALPNExtension{AlpnProtocols: append([]string(nil), alpn...)})
|
||||
}
|
||||
config.NextProtos = append([]string(nil), alpn...)
|
||||
secure.HandshakeState.Hello.AlpnProtocols = append([]string(nil), alpn...)
|
||||
}
|
||||
privateKey := secure.HandshakeState.State13.EcdheKey
|
||||
if privateKey == nil || privateKey.Curve() != ecdh.X25519() {
|
||||
return nil, fmt.Errorf("Reality 客户端指纹 %q 未提供 X25519 TLS 1.3 key share", helloID.Client)
|
||||
}
|
||||
return secure, nil
|
||||
}
|
||||
|
||||
func realityPrefersAESGCM(cipherSuites []uint16) bool {
|
||||
for _, cipherSuite := range cipherSuites {
|
||||
switch cipherSuite {
|
||||
case utls.TLS_AES_128_GCM_SHA256, utls.TLS_AES_256_GCM_SHA384,
|
||||
utls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, utls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
utls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, utls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
|
||||
return true
|
||||
case utls.TLS_CHACHA20_POLY1305_SHA256, utls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
|
||||
utls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type realityVerifier struct {
|
||||
serverName string
|
||||
authKey []byte
|
||||
verified bool
|
||||
}
|
||||
|
||||
func (v *realityVerifier) verifyPeerCertificate(rawCertificates [][]byte, _ [][]*x509.Certificate) error {
|
||||
certificates := make([]*x509.Certificate, 0, len(rawCertificates))
|
||||
for _, rawCertificate := range rawCertificates {
|
||||
certificate, err := x509.ParseCertificate(rawCertificate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
certificates = append(certificates, certificate)
|
||||
}
|
||||
if len(certificates) == 0 {
|
||||
return errors.New("Reality 服务端未返回证书")
|
||||
}
|
||||
if publicKey, ok := certificates[0].PublicKey.(ed25519.PublicKey); ok {
|
||||
digest := hmac.New(sha512.New, v.authKey)
|
||||
_, _ = digest.Write(publicKey)
|
||||
if bytes.Equal(digest.Sum(nil), certificates[0].Signature) {
|
||||
v.verified = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
options := x509.VerifyOptions{
|
||||
DNSName: v.serverName, Intermediates: x509.NewCertPool(), CurrentTime: time.Now(),
|
||||
}
|
||||
for _, certificate := range certificates[1:] {
|
||||
options.Intermediates.AddCert(certificate)
|
||||
}
|
||||
_, err := certificates[0].Verify(options)
|
||||
return err
|
||||
}
|
||||
@@ -16,11 +16,15 @@ import (
|
||||
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless"
|
||||
visionproxy "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vision"
|
||||
yuhaiinvless "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"
|
||||
singvmess "github.com/metacubex/sing-vmess"
|
||||
singvless "github.com/metacubex/sing-vmess/vless"
|
||||
singmetadata "github.com/metacubex/sing/common/metadata"
|
||||
sscore "github.com/shadowsocks/go-shadowsocks2/core"
|
||||
"github.com/shadowsocks/go-shadowsocks2/socks"
|
||||
)
|
||||
@@ -34,9 +38,15 @@ type Config struct {
|
||||
Cipher string
|
||||
Transport string
|
||||
TLS bool
|
||||
Security string
|
||||
Flow string
|
||||
ServerName string
|
||||
Insecure bool
|
||||
ALPN []string
|
||||
RealityPublicKey string
|
||||
RealityShortID string
|
||||
ClientFingerprint string
|
||||
SpiderX string
|
||||
WebSocketHost string
|
||||
WebSocketPath string
|
||||
CanonicalProxyURL string
|
||||
@@ -111,9 +121,7 @@ func parseUserInfoProxy(value string) (Config, error) {
|
||||
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)
|
||||
}
|
||||
flow := strings.ToLower(strings.TrimSpace(query.Get("flow")))
|
||||
if scheme == "vless" {
|
||||
parsedUUID, err := uuid.Parse(credential)
|
||||
if err != nil {
|
||||
@@ -126,16 +134,39 @@ func parseUserInfoProxy(value string) (Config, error) {
|
||||
}
|
||||
security := strings.ToLower(strings.TrimSpace(query.Get("security")))
|
||||
tlsEnabled := scheme == "trojan"
|
||||
securityMode := "none"
|
||||
if tlsEnabled {
|
||||
securityMode = "tls"
|
||||
}
|
||||
switch security {
|
||||
case "", "tls":
|
||||
if security == "tls" {
|
||||
tlsEnabled = true
|
||||
securityMode = "tls"
|
||||
}
|
||||
case "none":
|
||||
tlsEnabled = false
|
||||
securityMode = "none"
|
||||
case "reality":
|
||||
if scheme != "vless" {
|
||||
return Config{}, errors.New("Reality security 当前仅支持 VLESS")
|
||||
}
|
||||
if transport != "tcp" {
|
||||
return Config{}, errors.New("VLESS Reality 当前仅支持 TCP 传输")
|
||||
}
|
||||
tlsEnabled = true
|
||||
securityMode = "reality"
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security)
|
||||
}
|
||||
if flow != "" {
|
||||
if scheme != "vless" || flow != "xtls-rprx-vision" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow)
|
||||
}
|
||||
if transport != "tcp" || (securityMode != "tls" && securityMode != "reality") {
|
||||
return Config{}, errors.New("VLESS Vision 需要 TCP 和 TLS 或 Reality security")
|
||||
}
|
||||
}
|
||||
if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" {
|
||||
return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType)
|
||||
}
|
||||
@@ -144,6 +175,23 @@ func parseUserInfoProxy(value string) (Config, error) {
|
||||
return Config{}, err
|
||||
}
|
||||
serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname())
|
||||
realityPublicKey := firstNonEmpty(query.Get("pbk"), query.Get("public-key"), query.Get("publicKey"))
|
||||
realityShortID := firstNonEmpty(query.Get("sid"), query.Get("short-id"), query.Get("shortId"))
|
||||
fingerprint := strings.ToLower(firstNonEmpty(query.Get("fp"), query.Get("fingerprint"), query.Get("client-fingerprint")))
|
||||
spiderX := firstNonEmpty(query.Get("spx"), query.Get("spider-x"), query.Get("spiderX"))
|
||||
if securityMode == "reality" {
|
||||
if realityPublicKey == "" {
|
||||
return Config{}, errors.New("VLESS Reality public key 不能为空")
|
||||
}
|
||||
if fingerprint == "" {
|
||||
fingerprint = "chrome"
|
||||
}
|
||||
if _, supported := realityClientHelloID(fingerprint); !supported {
|
||||
return Config{}, fmt.Errorf("VLESS Reality 暂不支持客户端指纹 %q", fingerprint)
|
||||
}
|
||||
} else if realityPublicKey != "" || realityShortID != "" || fingerprint != "" || spiderX != "" {
|
||||
return Config{}, errors.New("Reality 参数只能用于 Reality security")
|
||||
}
|
||||
wsHost := firstNonEmpty(query.Get("host"), serverName)
|
||||
if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil {
|
||||
return Config{}, err
|
||||
@@ -159,8 +207,9 @@ func parseUserInfoProxy(value string) (Config, error) {
|
||||
}
|
||||
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,
|
||||
TLS: tlsEnabled, Security: securityMode, Flow: flow, ServerName: serverName, Insecure: insecure,
|
||||
ALPN: splitList(query.Get("alpn")), RealityPublicKey: realityPublicKey, RealityShortID: realityShortID,
|
||||
ClientFingerprint: fingerprint, SpiderX: spiderX, WebSocketHost: wsHost, WebSocketPath: wsPath,
|
||||
}
|
||||
config.CanonicalProxyURL = canonicalUserInfoProxyURL(config)
|
||||
if err := validateConfig(config); err != nil {
|
||||
@@ -172,15 +221,29 @@ func parseUserInfoProxy(value string) (Config, error) {
|
||||
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")
|
||||
security := config.Security
|
||||
if security == "" {
|
||||
security = "none"
|
||||
if config.TLS {
|
||||
security = "tls"
|
||||
}
|
||||
}
|
||||
query.Set("security", security)
|
||||
if config.Scheme == "vless" {
|
||||
query.Set("encryption", "none")
|
||||
}
|
||||
if config.Flow != "" {
|
||||
query.Set("flow", config.Flow)
|
||||
}
|
||||
query.Set("sni", config.ServerName)
|
||||
if security == "reality" {
|
||||
query.Set("pbk", config.RealityPublicKey)
|
||||
query.Set("sid", config.RealityShortID)
|
||||
query.Set("fp", config.ClientFingerprint)
|
||||
if config.SpiderX != "" {
|
||||
query.Set("spx", config.SpiderX)
|
||||
}
|
||||
}
|
||||
if config.Insecure {
|
||||
query.Set("allowInsecure", "1")
|
||||
}
|
||||
@@ -281,6 +344,7 @@ type vmessShare struct {
|
||||
Network string `json:"net"`
|
||||
TLS string `json:"tls,omitempty"`
|
||||
ServerName string `json:"sni,omitempty"`
|
||||
ALPN string `json:"alpn,omitempty"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
AllowInsecure bool `json:"allowInsecure,omitempty"`
|
||||
@@ -336,6 +400,10 @@ func parseVMess(value string) (Config, error) {
|
||||
}
|
||||
tlsEnabled := tlsMode == "tls"
|
||||
serverName := firstNonEmpty(jsonString(raw, "sni"), address)
|
||||
alpn, err := jsonStringList(raw, "alpn")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
host := firstNonEmpty(jsonString(raw, "host"), serverName)
|
||||
if err := validateWebSocketHost(host); transport == "ws" && err != nil {
|
||||
return Config{}, err
|
||||
@@ -355,7 +423,7 @@ func parseVMess(value string) (Config, error) {
|
||||
}
|
||||
share := vmessShare{
|
||||
Version: "2", Address: address, Port: port, UUID: userID, AlterID: strconv.Itoa(alterID), Cipher: cipher,
|
||||
Network: transport, ServerName: serverName, AllowInsecure: insecure,
|
||||
Network: transport, ServerName: serverName, ALPN: strings.Join(alpn, ","), AllowInsecure: insecure,
|
||||
}
|
||||
if transport == "ws" {
|
||||
share.Host = host
|
||||
@@ -370,7 +438,7 @@ func parseVMess(value string) (Config, error) {
|
||||
}
|
||||
config := Config{
|
||||
Scheme: "vmess", Server: server, Credential: userID, AlterID: alterID, Cipher: cipher,
|
||||
Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure,
|
||||
Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, ALPN: alpn,
|
||||
WebSocketHost: host, WebSocketPath: path,
|
||||
CanonicalProxyURL: "vmess://" + base64.RawStdEncoding.EncodeToString(canonicalJSON),
|
||||
}
|
||||
@@ -456,6 +524,12 @@ 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.Security == "reality" {
|
||||
var err error
|
||||
current, err = newRealityProxy(config, current)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建 Reality 客户端: %w", err)
|
||||
}
|
||||
} else if config.TLS {
|
||||
current = &tlsProxy{config: config, dialer: current}
|
||||
}
|
||||
@@ -467,7 +541,7 @@ func buildProxy(config Config) (netapi.Proxy, error) {
|
||||
case "vless":
|
||||
protocolConfig := &protocol.Vless{}
|
||||
protocolConfig.SetUuid(config.Credential)
|
||||
return newOwnedVLESSProxy(protocolConfig, current)
|
||||
return newOwnedVLESSProxy(protocolConfig, current, config.Flow)
|
||||
case "vmess":
|
||||
protocolConfig := &protocol.Vmess{}
|
||||
protocolConfig.SetUuid(config.Credential)
|
||||
@@ -487,13 +561,23 @@ type ownedVLESSProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config *protocol.Vless
|
||||
dialer netapi.Proxy
|
||||
flow string
|
||||
uuid [16]byte
|
||||
}
|
||||
|
||||
func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy) (netapi.Proxy, error) {
|
||||
if _, err := vless.NewClient(config, dialer); err != nil {
|
||||
func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy, flow string) (netapi.Proxy, error) {
|
||||
if _, err := yuhaiinvless.NewClient(config, dialer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ownedVLESSProxy{config: config, dialer: dialer}, nil
|
||||
proxy := &ownedVLESSProxy{config: config, dialer: dialer, flow: flow}
|
||||
if flow == "xtls-rprx-vision" {
|
||||
userID, err := uuid.Parse(config.GetUuid())
|
||||
if err != nil {
|
||||
return nil, errors.New("VLESS Vision UUID 无效")
|
||||
}
|
||||
copy(proxy.uuid[:], userID[:])
|
||||
}
|
||||
return proxy, nil
|
||||
}
|
||||
|
||||
func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
@@ -501,7 +585,20 @@ func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := vless.NewClient(p.config, &singleConnectionProxy{connection: connection})
|
||||
if p.flow == "xtls-rprx-vision" {
|
||||
result, requestErr := newVisionVLESSConn(connection, address, p.uuid, p.flow)
|
||||
if requestErr != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("发送 VLESS Vision 请求: %w", requestErr)
|
||||
}
|
||||
visionConnection, visionErr := visionproxy.NewVisionConn(result, connection, p.uuid)
|
||||
if visionErr != nil {
|
||||
_ = result.Close()
|
||||
return nil, fmt.Errorf("创建 VLESS Vision 连接: %w", visionErr)
|
||||
}
|
||||
return visionConnection, nil
|
||||
}
|
||||
client, err := yuhaiinvless.NewClient(p.config, &singleConnectionProxy{connection: connection})
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, err
|
||||
@@ -514,6 +611,15 @@ func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func newVisionVLESSConn(connection net.Conn, address netapi.Address, userID [16]byte, flow string) (net.Conn, error) {
|
||||
destination := singmetadata.ParseSocksaddrHostPort(address.Hostname(), address.Port())
|
||||
result := singvless.NewConn(connection, userID, singvmess.CommandTCP, destination, flow)
|
||||
if _, err := result.Write(nil); err != nil {
|
||||
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")
|
||||
}
|
||||
@@ -743,3 +849,28 @@ func jsonString(value map[string]any, name string) string {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func jsonStringList(value map[string]any, name string) ([]string, error) {
|
||||
raw, ok := value[name]
|
||||
if !ok || raw == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if text, ok := raw.(string); ok {
|
||||
return splitList(text), nil
|
||||
}
|
||||
items, ok := raw.([]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s 必须是字符串或字符串数组", name)
|
||||
}
|
||||
result := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
text, ok := item.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s 必须是字符串或字符串数组", name)
|
||||
}
|
||||
if text = strings.TrimSpace(text); text != "" {
|
||||
result = append(result, text)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -16,6 +16,9 @@ import (
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/google/uuid"
|
||||
singvless "github.com/metacubex/sing-vmess/vless"
|
||||
utls "github.com/refraction-networking/utls"
|
||||
)
|
||||
|
||||
const testUUID = "123e4567-e89b-12d3-a456-426614174000"
|
||||
@@ -63,6 +66,100 @@ func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRealityVisionBuildsDialer(t *testing.T) {
|
||||
raw := "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&type=tcp&flow=xtls-rprx-vision&fp=chrome&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=0123456789abcdef&spx=%2F"
|
||||
normalized, err := Normalize(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config, err := Parse(normalized)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if config.Security != "reality" || config.Flow != "xtls-rprx-vision" || config.RealityPublicKey == "" || config.RealityShortID != "0123456789abcdef" || config.ClientFingerprint != "chrome" || config.SpiderX != "/" {
|
||||
t.Fatalf("Reality Vision config = %#v", config)
|
||||
}
|
||||
if _, err := NewDialer(normalized); err != nil {
|
||||
t.Fatalf("construct Reality Vision dialer: %v", err)
|
||||
}
|
||||
for _, field := range []string{"security=reality", "flow=xtls-rprx-vision", "fp=chrome", "pbk=", "sid=0123456789abcdef", "spx=%2F"} {
|
||||
if !strings.Contains(normalized, field) {
|
||||
t.Fatalf("normalized Reality URL missing %q: %s", field, normalized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRealitySupportsStandardClientFingerprints(t *testing.T) {
|
||||
for _, fingerprint := range []string{"chrome", "edge", "safari", "firefox", "ios", "qq"} {
|
||||
t.Run(fingerprint, func(t *testing.T) {
|
||||
raw := "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&type=tcp&flow=xtls-rprx-vision&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=0123456789abcdef&fp=" + fingerprint
|
||||
normalized, err := Normalize(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config, err := Parse(normalized)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if config.ClientFingerprint != fingerprint {
|
||||
t.Fatalf("client fingerprint = %q", config.ClientFingerprint)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealityAcceptedFingerprintsProvideX25519AndPreserveALPN(t *testing.T) {
|
||||
wantedALPN := []string{"h2", "http/1.1"}
|
||||
for _, fingerprint := range []string{"chrome", "edge", "safari", "firefox", "ios", "qq"} {
|
||||
t.Run(fingerprint, func(t *testing.T) {
|
||||
helloID, supported := realityClientHelloID(fingerprint)
|
||||
if !supported {
|
||||
t.Fatalf("fingerprint %q unexpectedly unsupported", fingerprint)
|
||||
}
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
secure, err := buildRealityClientHello(client, "edge.example", wantedALPN, helloID, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Join(secure.HandshakeState.Hello.AlpnProtocols, ",") != strings.Join(wantedALPN, ",") {
|
||||
t.Fatalf("ClientHello ALPN = %v", secure.HandshakeState.Hello.AlpnProtocols)
|
||||
}
|
||||
foundALPN := false
|
||||
for _, extension := range secure.Extensions {
|
||||
alpnExtension, ok := extension.(*utls.ALPNExtension)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
foundALPN = true
|
||||
if strings.Join(alpnExtension.AlpnProtocols, ",") != strings.Join(wantedALPN, ",") {
|
||||
t.Fatalf("ALPN extension = %v", alpnExtension.AlpnProtocols)
|
||||
}
|
||||
}
|
||||
if !foundALPN {
|
||||
t.Fatal("ClientHello has no ALPN extension")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealityClientHelloWithoutTLS13KeyShareReturnsError(t *testing.T) {
|
||||
for name, helloID := range map[string]utls.ClientHelloID{
|
||||
"android": utls.HelloAndroid_11_OkHttp,
|
||||
"360": utls.Hello360_Auto,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
if _, err := buildRealityClientHello(client, "edge.example", nil, helloID, nil); err == nil {
|
||||
t.Fatalf("fingerprint %q unexpectedly produced a Reality key share", name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -99,6 +196,38 @@ func TestNormalizeEquivalentShareLinksHaveOneIdentity(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeVMessPreservesALPN(t *testing.T) {
|
||||
stringURL := vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "tcp", "tls": "tls", "sni": "edge.example",
|
||||
"alpn": "h2, http/1.1",
|
||||
})
|
||||
arrayURL := vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "tcp", "tls": "tls", "sni": "edge.example",
|
||||
"alpn": []string{"h2", "http/1.1"},
|
||||
})
|
||||
stringNormalized, err := Normalize(stringURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
arrayNormalized, err := Normalize(arrayURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stringNormalized != arrayNormalized {
|
||||
t.Fatalf("equivalent VMess ALPN forms have different identities: %q != %q", stringNormalized, arrayNormalized)
|
||||
}
|
||||
config, err := Parse(stringNormalized)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wanted := "h2,http/1.1"
|
||||
if strings.Join(config.ALPN, ",") != wanted || strings.Join((&tlsProxy{config: config}).tlsConfig().NextProtos, ",") != wanted {
|
||||
t.Fatalf("VMess ALPN was not preserved in TLS config: %#v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
if err := server.Close(); err != nil {
|
||||
@@ -107,7 +236,7 @@ func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) {
|
||||
tracked := &closeTrackingConn{Conn: client}
|
||||
config := &protocol.Vless{}
|
||||
config.SetUuid(testUUID)
|
||||
proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked})
|
||||
proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -119,6 +248,41 @@ func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisionVLESSRequestIncludesFlowAddon(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer server.Close()
|
||||
|
||||
var userID [16]byte
|
||||
parsedUUID, err := uuid.Parse(testUUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copy(userID[:], parsedUUID[:])
|
||||
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
connection, requestErr := newVisionVLESSConn(client, netapi.ParseDomainPort("tcp", "target.example", 443), userID, "xtls-rprx-vision")
|
||||
if connection != nil {
|
||||
_ = connection.Close()
|
||||
}
|
||||
result <- requestErr
|
||||
}()
|
||||
|
||||
request, err := singvless.ReadRequest(server)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if request.Flow != "xtls-rprx-vision" {
|
||||
t.Fatalf("VLESS flow addon = %q", request.Flow)
|
||||
}
|
||||
if request.Destination.Fqdn != "target.example" || request.Destination.Port != 443 {
|
||||
t.Fatalf("VLESS destination = %v", request.Destination)
|
||||
}
|
||||
if err := <-result; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTunnelHandshakeContextHasIndependentDeadline(t *testing.T) {
|
||||
ctx, cancel := newTunnelHandshakeContext(context.Background())
|
||||
defer cancel()
|
||||
@@ -149,11 +313,19 @@ func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) {
|
||||
"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",
|
||||
"vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=invalid&sid=01",
|
||||
"vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=opera",
|
||||
"vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=android",
|
||||
"vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=360",
|
||||
"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",
|
||||
vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "tcp", "tls": "tls", "alpn": []any{"h2", 1},
|
||||
}),
|
||||
} {
|
||||
if _, err := Normalize(raw); err == nil {
|
||||
t.Fatalf("invalid tunnel accepted: %q", raw)
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
egressapp "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
@@ -26,6 +27,7 @@ type Handler struct {
|
||||
guardStatePath string
|
||||
guardConfigPath string
|
||||
guardProbe egressapp.QualityProbeInput
|
||||
profilesMu sync.Mutex
|
||||
}
|
||||
|
||||
func NewHandler(service *egressapp.Service, guardStatePath ...string) *Handler {
|
||||
@@ -59,6 +61,10 @@ func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.POST("/egress-nodes/:id/quality-test", h.testQuality)
|
||||
router.GET("/egress-quality-guard", h.qualityGuardStatus)
|
||||
router.PUT("/egress-quality-guard/config", h.updateQualityGuardConfig)
|
||||
router.GET("/egress-quality-guard/profiles", h.listQualityGuardProfiles)
|
||||
router.POST("/egress-quality-guard/profiles", h.createQualityGuardProfile)
|
||||
router.PUT("/egress-quality-guard/profiles/:id", h.updateQualityGuardProfile)
|
||||
router.DELETE("/egress-quality-guard/profiles/:id", h.deleteQualityGuardProfile)
|
||||
router.POST("/egress-quality-guard/nodes/:id/test", h.testQualityGuardNode)
|
||||
router.POST("/egress-nodes/:id/accounts", h.assignAccounts)
|
||||
router.DELETE("/egress-nodes/accounts", h.unassignAccounts)
|
||||
@@ -203,6 +209,10 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) {
|
||||
if state.Statistics.StartedAt > 0 {
|
||||
payload["statistics"] = state.Statistics
|
||||
}
|
||||
if profiles, err := loadProbeProfileFile(h.profilesPath()); err == nil {
|
||||
payload["activeProfileId"] = profiles.ActiveProfileID
|
||||
payload["profiles"] = profiles.summaries()
|
||||
}
|
||||
response.Success(c, http.StatusOK, payload)
|
||||
}
|
||||
|
||||
@@ -361,11 +371,24 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" || h.guardProbe.Prompt == "" || h.guardProbe.Expected == "" {
|
||||
if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用")
|
||||
return
|
||||
}
|
||||
value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, h.guardProbe)
|
||||
var request struct {
|
||||
ProfileID string `json:"profileId"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&request)
|
||||
input, err := h.resolveProbeInput(strings.TrimSpace(request.ProfileID))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.Prompt) == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用")
|
||||
return
|
||||
}
|
||||
value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, input)
|
||||
if err != nil {
|
||||
h.writeQualityProbeError(c, err)
|
||||
return
|
||||
@@ -378,7 +401,8 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) {
|
||||
"visibleTokens": value.VisibleTokens, "visibleCharacters": value.VisibleCharacters,
|
||||
"outputTokensPerSecond": value.OutputTokensPerSecond,
|
||||
"visibleTokensPerSecond": value.OutputTokensPerSecond, "expectedMatched": value.ExpectedMatched,
|
||||
"responseSha256": value.ResponseSHA256,
|
||||
"thinkingRequired": value.ThinkingRequired,
|
||||
"responseSha256": value.ResponseSHA256,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -516,7 +540,8 @@ func (h *Handler) testQuality(c *gin.Context) {
|
||||
"visibleTokens": value.VisibleTokens, "visibleCharacters": value.VisibleCharacters,
|
||||
"outputTokensPerSecond": value.OutputTokensPerSecond,
|
||||
"visibleTokensPerSecond": value.OutputTokensPerSecond, "expectedMatched": value.ExpectedMatched,
|
||||
"responseSha256": value.ResponseSHA256,
|
||||
"thinkingRequired": value.ThinkingRequired,
|
||||
"responseSha256": value.ResponseSHA256,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,12 @@ package egress
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -94,6 +96,99 @@ func TestWriteQualityProbeErrorIdentifiesMissingProbeAccount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityGuardProfilesCRUDAndStatusOmitsPrompt(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
statePath := directory + "/state.json"
|
||||
configPath := directory + "/runtime-config.json"
|
||||
if err := os.WriteFile(statePath, []byte(`{"version":1,"guard":{"mode":"hybrid","model":"grok-4.5","node_ids":["8"]},"nodes":{}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := NewHandler(nil, statePath, configPath)
|
||||
|
||||
createRecorder := httptest.NewRecorder()
|
||||
createContext, _ := gin.CreateTestContext(createRecorder)
|
||||
createContext.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(`{"name":"自定义标记","prompt":"只输出 FLAG_OK","expectedText":"FLAG_OK","matchMode":"last_line","requireThinking":true,"active":true}`))
|
||||
createContext.Request.Header.Set("Content-Type", "application/json")
|
||||
handler.createQualityGuardProfile(createContext)
|
||||
if createRecorder.Code != 200 || !strings.Contains(createRecorder.Body.String(), `"FLAG_OK"`) || !strings.Contains(createRecorder.Body.String(), `"require_thinking":true`) {
|
||||
t.Fatalf("create status=%d body=%s", createRecorder.Code, createRecorder.Body.String())
|
||||
}
|
||||
|
||||
statusRecorder := httptest.NewRecorder()
|
||||
statusContext, _ := gin.CreateTestContext(statusRecorder)
|
||||
statusContext.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil)
|
||||
handler.qualityGuardStatus(statusContext)
|
||||
body := statusRecorder.Body.String()
|
||||
if statusRecorder.Code != 200 || !strings.Contains(body, `"activeProfileId":"p-2"`) || !strings.Contains(body, `"has_expected":true`) || !strings.Contains(body, `"require_thinking":true`) {
|
||||
t.Fatalf("status=%d body=%s", statusRecorder.Code, body)
|
||||
}
|
||||
if strings.Contains(body, "只输出 FLAG_OK") || strings.Contains(body, "FLAG_OK") {
|
||||
t.Fatalf("status leaked probe prompt or marker: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityGuardProfileWritesAreSerialized(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
handler := NewHandler(nil, "", directory+"/runtime-config.json")
|
||||
const count = 32
|
||||
var wait sync.WaitGroup
|
||||
errorsFound := make(chan string, count)
|
||||
for index := 0; index < count; index++ {
|
||||
wait.Add(1)
|
||||
go func(index int) {
|
||||
defer wait.Done()
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
body := fmt.Sprintf(`{"name":"profile-%d","prompt":"probe-%d","matchMode":"contains"}`, index, index)
|
||||
context.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(body))
|
||||
context.Request.Header.Set("Content-Type", "application/json")
|
||||
handler.createQualityGuardProfile(context)
|
||||
if recorder.Code != 200 {
|
||||
errorsFound <- recorder.Body.String()
|
||||
}
|
||||
}(index)
|
||||
}
|
||||
wait.Wait()
|
||||
close(errorsFound)
|
||||
for message := range errorsFound {
|
||||
t.Fatalf("concurrent profile create failed: %s", message)
|
||||
}
|
||||
data, err := loadProbeProfileFile(directory + "/profiles.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
custom := 0
|
||||
for _, profile := range data.Profiles {
|
||||
if !profile.BuiltIn {
|
||||
custom++
|
||||
}
|
||||
}
|
||||
if custom != count {
|
||||
t.Fatalf("custom profiles = %d, want %d", custom, count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityGuardReservedProfilesAreCanonicalized(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
path := directory + "/profiles.json"
|
||||
forged := `{"version":1,"active_profile_id":"quality-marker","profiles":{"quality-marker":{"id":"quality-marker","name":"forged","built_in":false,"prompt":"skip checks","expected_text":"","match_mode":"contains","require_thinking":false},"throughput":{"id":"throughput","name":"forged","built_in":false,"prompt":"skip checks","expected_text":"PASS","match_mode":"regex","require_thinking":true}}}`
|
||||
if err := os.WriteFile(path, []byte(forged), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marker := data.Profiles[profileQualityMarker]
|
||||
if !marker.BuiltIn || marker.ExpectedText != "QUALITY_OK" || marker.MatchMode != egressapp.MatchLastLine || !marker.RequireThinking {
|
||||
t.Fatalf("quality marker was not canonicalized: %#v", marker)
|
||||
}
|
||||
throughput := data.Profiles[profileThroughput]
|
||||
if !throughput.BuiltIn || throughput.ExpectedText != "" || throughput.MatchMode != egressapp.MatchContains || throughput.RequireThinking {
|
||||
t.Fatalf("throughput profile was not canonicalized: %#v", throughput)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateQualityGuardConfigWritesPrivateAtomicFile(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
statePath := directory + "/state.json"
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
egressapp "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/shared/response"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
profileThroughput = "throughput"
|
||||
profileQualityMarker = "quality-marker"
|
||||
maxCustomProfiles = 32
|
||||
)
|
||||
|
||||
type probeProfile struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
BuiltIn bool `json:"built_in"`
|
||||
Prompt string `json:"prompt"`
|
||||
ExpectedText string `json:"expected_text,omitempty"`
|
||||
MatchMode string `json:"match_mode"`
|
||||
RequireThinking bool `json:"require_thinking"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
UpdatedAt float64 `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
type probeProfileFile struct {
|
||||
Version int `json:"version"`
|
||||
ActiveProfileID string `json:"active_profile_id"`
|
||||
NextID int `json:"next_id"`
|
||||
Profiles map[string]probeProfile `json:"profiles"`
|
||||
}
|
||||
|
||||
func builtinProbeProfiles() []probeProfile {
|
||||
return []probeProfile{
|
||||
{
|
||||
ID: profileQualityMarker,
|
||||
Name: "预期标记",
|
||||
BuiltIn: true,
|
||||
Prompt: "先用三点总结为什么天空呈蓝色,最后一行只输出 QUALITY_OK。",
|
||||
ExpectedText: "QUALITY_OK",
|
||||
MatchMode: egressapp.MatchLastLine,
|
||||
RequireThinking: true,
|
||||
},
|
||||
{
|
||||
ID: profileThroughput,
|
||||
Name: "吞吐基线",
|
||||
BuiltIn: true,
|
||||
Prompt: "Write a detailed technical explanation of how TCP slow start works, at least 12 sentences, plain text only.",
|
||||
MatchMode: egressapp.MatchContains,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) profilesPath() string {
|
||||
if h.guardConfigPath == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(filepath.Dir(h.guardConfigPath), "profiles.json")
|
||||
}
|
||||
|
||||
func seedProbeProfileFile(data *probeProfileFile) {
|
||||
if data.Profiles == nil {
|
||||
data.Profiles = map[string]probeProfile{}
|
||||
}
|
||||
if data.Version == 0 {
|
||||
data.Version = 1
|
||||
}
|
||||
now := float64(time.Now().Unix())
|
||||
for _, builtin := range builtinProbeProfiles() {
|
||||
existing, ok := data.Profiles[builtin.ID]
|
||||
if !ok {
|
||||
builtin.UpdatedAt = now
|
||||
data.Profiles[builtin.ID] = builtin
|
||||
continue
|
||||
}
|
||||
// Reserved built-in IDs define recovery safety invariants. Never trust
|
||||
// persisted metadata for these IDs, even if an older version or a manual
|
||||
// edit incorrectly cleared built_in.
|
||||
existing.ID = builtin.ID
|
||||
existing.Name = builtin.Name
|
||||
existing.BuiltIn = true
|
||||
existing.Prompt = builtin.Prompt
|
||||
existing.ExpectedText = builtin.ExpectedText
|
||||
existing.MatchMode = builtin.MatchMode
|
||||
existing.RequireThinking = builtin.RequireThinking
|
||||
existing.MaxOutputTokens = builtin.MaxOutputTokens
|
||||
data.Profiles[builtin.ID] = existing
|
||||
}
|
||||
if data.ActiveProfileID == "" {
|
||||
data.ActiveProfileID = profileQualityMarker
|
||||
}
|
||||
if _, ok := data.Profiles[data.ActiveProfileID]; !ok {
|
||||
data.ActiveProfileID = profileQualityMarker
|
||||
}
|
||||
if data.NextID < 1 {
|
||||
data.NextID = 1
|
||||
}
|
||||
}
|
||||
|
||||
func loadProbeProfileFile(path string) (probeProfileFile, error) {
|
||||
data := probeProfileFile{Version: 1, Profiles: map[string]probeProfile{}}
|
||||
if path == "" {
|
||||
seedProbeProfileFile(&data)
|
||||
return data, nil
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
seedProbeProfileFile(&data)
|
||||
return data, nil
|
||||
}
|
||||
return probeProfileFile{}, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &data); err != nil {
|
||||
return probeProfileFile{}, err
|
||||
}
|
||||
seedProbeProfileFile(&data)
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func saveProbeProfileFile(path string, data probeProfileFile) error {
|
||||
if path == "" {
|
||||
return errors.New("profiles path is empty")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".profiles-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
_ = temporary.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := temporary.Write(raw); err != nil {
|
||||
_ = temporary.Close()
|
||||
return err
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporaryPath, path)
|
||||
}
|
||||
|
||||
func (data probeProfileFile) resolve(id string) (probeProfile, bool) {
|
||||
if id == "" {
|
||||
id = data.ActiveProfileID
|
||||
}
|
||||
profile, ok := data.Profiles[id]
|
||||
return profile, ok
|
||||
}
|
||||
|
||||
func (data probeProfileFile) summaries() []map[string]any {
|
||||
out := make([]map[string]any, 0, len(data.Profiles))
|
||||
for _, profile := range data.Profiles {
|
||||
out = append(out, map[string]any{
|
||||
"id": profile.ID,
|
||||
"name": profile.Name,
|
||||
"built_in": profile.BuiltIn,
|
||||
"match_mode": profile.MatchMode,
|
||||
"has_expected": strings.TrimSpace(profile.ExpectedText) != "",
|
||||
"require_thinking": profile.RequireThinking,
|
||||
})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
leftBuiltIn, _ := out[i]["built_in"].(bool)
|
||||
rightBuiltIn, _ := out[j]["built_in"].(bool)
|
||||
if leftBuiltIn != rightBuiltIn {
|
||||
return leftBuiltIn
|
||||
}
|
||||
leftID, _ := out[i]["id"].(string)
|
||||
rightID, _ := out[j]["id"].(string)
|
||||
return leftID < rightID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func validateProbeProfile(profile *probeProfile, creating bool) error {
|
||||
profile.Name = strings.TrimSpace(profile.Name)
|
||||
profile.Prompt = strings.TrimSpace(profile.Prompt)
|
||||
profile.ExpectedText = strings.TrimSpace(profile.ExpectedText)
|
||||
profile.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode)
|
||||
if profile.Name == "" {
|
||||
return errors.New("方案名称不能为空")
|
||||
}
|
||||
if len(profile.Name) > 80 {
|
||||
return errors.New("方案名称不能超过 80 个字符")
|
||||
}
|
||||
if profile.Prompt == "" {
|
||||
return errors.New("探测 Prompt 不能为空")
|
||||
}
|
||||
if len(profile.Prompt) > egressapp.MaxQualityProbePromptBytes {
|
||||
return errors.New("探测 Prompt 过长")
|
||||
}
|
||||
if len(profile.ExpectedText) > egressapp.MaxQualityProbeExpectedBytes {
|
||||
return errors.New("预期标记过长")
|
||||
}
|
||||
if profile.MatchMode == egressapp.MatchRegex && profile.ExpectedText != "" {
|
||||
if _, err := regexp.Compile(profile.ExpectedText); err != nil {
|
||||
return fmt.Errorf("正则预期标记无效")
|
||||
}
|
||||
}
|
||||
if profile.MaxOutputTokens < 0 || profile.MaxOutputTokens > egressapp.MaxQualityProbeOutputTokens {
|
||||
return fmt.Errorf("方案最大输出需在 0 到 %d Token 之间", egressapp.MaxQualityProbeOutputTokens)
|
||||
}
|
||||
if creating && profile.BuiltIn {
|
||||
return errors.New("不能新建内置方案")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyProfile(base egressapp.QualityProbeInput, profile probeProfile) egressapp.QualityProbeInput {
|
||||
base.Prompt = profile.Prompt
|
||||
base.Expected = profile.ExpectedText
|
||||
base.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode)
|
||||
base.RequireThinking = profile.RequireThinking
|
||||
if profile.MaxOutputTokens > 0 {
|
||||
base.MaxOutputTokens = profile.MaxOutputTokens
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func (h *Handler) listQualityGuardProfiles(c *gin.Context) {
|
||||
data, err := loadProbeProfileFile(h.profilesPath())
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
items := make([]probeProfile, 0, len(data.Profiles))
|
||||
for _, profile := range data.Profiles {
|
||||
items = append(items, profile)
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].BuiltIn != items[j].BuiltIn {
|
||||
return items[i].BuiltIn
|
||||
}
|
||||
return items[i].ID < items[j].ID
|
||||
})
|
||||
response.Success(c, http.StatusOK, gin.H{
|
||||
"activeProfileId": data.ActiveProfileID,
|
||||
"items": items,
|
||||
})
|
||||
}
|
||||
|
||||
type probeProfileWriteRequest struct {
|
||||
Name string `json:"name"`
|
||||
Prompt string `json:"prompt"`
|
||||
ExpectedText string `json:"expectedText"`
|
||||
MatchMode string `json:"matchMode"`
|
||||
RequireThinking bool `json:"requireThinking"`
|
||||
MaxOutputTokens int `json:"maxOutputTokens"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
func (h *Handler) createQualityGuardProfile(c *gin.Context) {
|
||||
path := h.profilesPath()
|
||||
if path == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读")
|
||||
return
|
||||
}
|
||||
var request probeProfileWriteRequest
|
||||
if c.ShouldBindJSON(&request) != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效")
|
||||
return
|
||||
}
|
||||
h.profilesMu.Lock()
|
||||
defer h.profilesMu.Unlock()
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
custom := 0
|
||||
for _, profile := range data.Profiles {
|
||||
if !profile.BuiltIn {
|
||||
custom++
|
||||
}
|
||||
}
|
||||
if custom >= maxCustomProfiles {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", fmt.Sprintf("自定义方案最多 %d 个", maxCustomProfiles))
|
||||
return
|
||||
}
|
||||
profile := probeProfile{
|
||||
Name: request.Name, Prompt: request.Prompt, ExpectedText: request.ExpectedText,
|
||||
MatchMode: request.MatchMode, RequireThinking: request.RequireThinking, MaxOutputTokens: request.MaxOutputTokens,
|
||||
}
|
||||
if err := validateProbeProfile(&profile, true); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error())
|
||||
return
|
||||
}
|
||||
data.NextID++
|
||||
profile.ID = fmt.Sprintf("p-%d", data.NextID)
|
||||
profile.UpdatedAt = float64(time.Now().Unix())
|
||||
data.Profiles[profile.ID] = profile
|
||||
if request.Active {
|
||||
data.ActiveProfileID = profile.ID
|
||||
}
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, profile)
|
||||
}
|
||||
|
||||
func (h *Handler) updateQualityGuardProfile(c *gin.Context) {
|
||||
path := h.profilesPath()
|
||||
if path == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
var request probeProfileWriteRequest
|
||||
if c.ShouldBindJSON(&request) != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效")
|
||||
return
|
||||
}
|
||||
h.profilesMu.Lock()
|
||||
defer h.profilesMu.Unlock()
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
existing, ok := data.Profiles[id]
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "notFound", "方案不存在")
|
||||
return
|
||||
}
|
||||
if existing.BuiltIn {
|
||||
if request.Active {
|
||||
data.ActiveProfileID = existing.ID
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, existing)
|
||||
return
|
||||
}
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能修改,请复制后另存")
|
||||
return
|
||||
}
|
||||
existing.Name = request.Name
|
||||
existing.Prompt = request.Prompt
|
||||
existing.ExpectedText = request.ExpectedText
|
||||
existing.MatchMode = request.MatchMode
|
||||
existing.RequireThinking = request.RequireThinking
|
||||
existing.MaxOutputTokens = request.MaxOutputTokens
|
||||
if err := validateProbeProfile(&existing, false); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error())
|
||||
return
|
||||
}
|
||||
existing.UpdatedAt = float64(time.Now().Unix())
|
||||
data.Profiles[id] = existing
|
||||
if request.Active {
|
||||
data.ActiveProfileID = id
|
||||
}
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, existing)
|
||||
}
|
||||
|
||||
func (h *Handler) deleteQualityGuardProfile(c *gin.Context) {
|
||||
path := h.profilesPath()
|
||||
if path == "" {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
h.profilesMu.Lock()
|
||||
defer h.profilesMu.Unlock()
|
||||
data, err := loadProbeProfileFile(path)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用")
|
||||
return
|
||||
}
|
||||
existing, ok := data.Profiles[id]
|
||||
if !ok {
|
||||
response.Error(c, http.StatusNotFound, "notFound", "方案不存在")
|
||||
return
|
||||
}
|
||||
if existing.BuiltIn {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能删除")
|
||||
return
|
||||
}
|
||||
delete(data.Profiles, id)
|
||||
if data.ActiveProfileID == id {
|
||||
data.ActiveProfileID = profileQualityMarker
|
||||
}
|
||||
if err := saveProbeProfileFile(path, data); err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"deleted": true})
|
||||
}
|
||||
|
||||
func (h *Handler) resolveProbeInput(profileID string) (egressapp.QualityProbeInput, error) {
|
||||
input := h.guardProbe
|
||||
data, err := loadProbeProfileFile(h.profilesPath())
|
||||
if err != nil {
|
||||
return input, err
|
||||
}
|
||||
profile, ok := data.resolve(profileID)
|
||||
if !ok {
|
||||
if profileID != "" {
|
||||
return input, fmt.Errorf("方案不存在")
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
return applyProfile(input, profile), nil
|
||||
}
|
||||
@@ -114,6 +114,7 @@ audit:
|
||||
qualityGuard:
|
||||
enabled: false
|
||||
# 主程序会自动创建并复用不可导出的内部探测身份,无需配置 Client Key。
|
||||
# 使用已验证会输出推理 Token 的 Build 模型时,内置恢复探针还会校验 reasoning Token。
|
||||
model: "grok-4.5"
|
||||
mode: hybrid # passive | active | hybrid
|
||||
activeInterval: 30m
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Pencil, Plus, Star, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { createProbeProfile, deleteProbeProfile, listProbeProfiles, updateProbeProfile, type ProbeProfile } from "@/features/quality-guard/quality-guard-api";
|
||||
|
||||
type Draft = {
|
||||
name: string;
|
||||
prompt: string;
|
||||
expectedText: string;
|
||||
matchMode: string;
|
||||
requireThinking: boolean;
|
||||
};
|
||||
|
||||
const emptyDraft = (): Draft => ({ name: "", prompt: "", expectedText: "", matchMode: "last_line", requireThinking: false });
|
||||
|
||||
export function ProbeProfilesPanel() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState<ProbeProfile | null | undefined>(undefined);
|
||||
const [draft, setDraft] = useState<Draft>(emptyDraft());
|
||||
const [deleting, setDeleting] = useState<ProbeProfile | null>(null);
|
||||
const query = useQuery({ queryKey: ["quality-guard-profiles"], queryFn: listProbeProfiles });
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["quality-guard-profiles"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["quality-guard"] });
|
||||
};
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const payload = {
|
||||
name: draft.name.trim(),
|
||||
prompt: draft.prompt.trim(),
|
||||
expectedText: draft.expectedText.trim(),
|
||||
matchMode: draft.matchMode,
|
||||
requireThinking: draft.requireThinking,
|
||||
};
|
||||
if (editing && !editing.built_in) {
|
||||
return updateProbeProfile(editing.id, payload);
|
||||
}
|
||||
return createProbeProfile(payload);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t("qualityGuard.profileSaved"));
|
||||
setEditing(undefined);
|
||||
invalidate();
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")),
|
||||
});
|
||||
const activateMutation = useMutation({
|
||||
mutationFn: (profile: ProbeProfile) => updateProbeProfile(profile.id, {
|
||||
name: profile.name,
|
||||
prompt: profile.prompt,
|
||||
expectedText: profile.expected_text ?? "",
|
||||
matchMode: profile.match_mode,
|
||||
requireThinking: profile.require_thinking,
|
||||
active: true,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
toast.success(t("qualityGuard.profileSaved"));
|
||||
invalidate();
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")),
|
||||
});
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (profile: ProbeProfile) => deleteProbeProfile(profile.id),
|
||||
onSuccess: () => {
|
||||
toast.success(t("qualityGuard.profileDeleted"));
|
||||
setDeleting(null);
|
||||
invalidate();
|
||||
},
|
||||
onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")),
|
||||
});
|
||||
|
||||
const items = query.data?.items ?? [];
|
||||
const activeId = query.data?.activeProfileId;
|
||||
const readonly = Boolean(editing?.built_in);
|
||||
const matchLabel = (mode: string) => {
|
||||
if (mode === "last_line") return t("qualityGuard.profileMatchLastLine");
|
||||
if (mode === "regex") return t("qualityGuard.profileMatchRegex");
|
||||
return t("qualityGuard.profileMatchContains");
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="overflow-hidden rounded-lg bg-card">
|
||||
<div className="flex flex-col gap-2 border-b px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium">{t("qualityGuard.profilesTab")}</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t("qualityGuard.profilesHelp")}</p>
|
||||
</div>
|
||||
<Button type="button" size="sm" onClick={() => { setEditing(null); setDraft(emptyDraft()); }}>
|
||||
<Plus />{t("qualityGuard.profileCreate")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{items.map((profile) => {
|
||||
const active = profile.id === activeId;
|
||||
const marker = profile.expected_text
|
||||
? `${t("qualityGuard.profileExpected")} ${profile.expected_text} · ${matchLabel(profile.match_mode)}`
|
||||
: t("qualityGuard.profileNoExpected");
|
||||
return (
|
||||
<div key={profile.id} className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<strong className="text-sm">{profile.name}</strong>
|
||||
<Badge variant={profile.built_in ? "secondary" : "outline"}>{t(profile.built_in ? "qualityGuard.profileBuiltin" : "qualityGuard.profileCustom")}</Badge>
|
||||
{active ? <Badge>{t("qualityGuard.profileActive")}</Badge> : null}
|
||||
</div>
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">{marker}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{!active ? <Button type="button" variant="secondary" size="sm" disabled={activateMutation.isPending} onClick={() => activateMutation.mutate(profile)}><Star />{t("qualityGuard.profileActivate")}</Button> : null}
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => {
|
||||
setEditing(profile);
|
||||
setDraft({ name: profile.name, prompt: profile.prompt, expectedText: profile.expected_text ?? "", matchMode: profile.match_mode || "contains", requireThinking: profile.require_thinking });
|
||||
}}><Pencil />{t(profile.built_in ? "qualityGuard.profileView" : "qualityGuard.profileEdit")}</Button>
|
||||
{!profile.built_in ? <Button type="button" variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setDeleting(profile)}><Trash2 />{t("common.delete")}</Button> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Dialog open={editing !== undefined} onOpenChange={(open) => { if (!open && !saveMutation.isPending) setEditing(undefined); }}>
|
||||
<DialogContent className="max-h-[calc(100svh-2rem)] overflow-y-auto sm:max-w-[560px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editing ? t(readonly ? "qualityGuard.profileView" : "qualityGuard.profileEdit") : t("qualityGuard.profileCreate")}</DialogTitle>
|
||||
<DialogDescription>{t("qualityGuard.profilesHelp")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form className="space-y-3.5" onSubmit={(event) => { event.preventDefault(); if (!readonly) saveMutation.mutate(); }}>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="probe-profile-name">{t("qualityGuard.profileName")}</Label>
|
||||
<Input id="probe-profile-name" value={draft.name} disabled={readonly} onChange={(event) => setDraft({ ...draft, name: event.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>{t("qualityGuard.profileMatch")}</Label>
|
||||
<Select value={draft.matchMode} disabled={readonly} onValueChange={(matchMode) => setDraft({ ...draft, matchMode })}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="last_line">{t("qualityGuard.profileMatchLastLine")}</SelectItem>
|
||||
<SelectItem value="contains">{t("qualityGuard.profileMatchContains")}</SelectItem>
|
||||
<SelectItem value="regex">{t("qualityGuard.profileMatchRegex")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="probe-profile-expected">{t("qualityGuard.profileExpected")}</Label>
|
||||
<Input id="probe-profile-expected" value={draft.expectedText} disabled={readonly} onChange={(event) => setDraft({ ...draft, expectedText: event.target.value })} />
|
||||
<p className="text-xs text-muted-foreground">{t("qualityGuard.profileExpectedHelp")}</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="probe-profile-prompt">{t("qualityGuard.profilePrompt")}</Label>
|
||||
<Textarea id="probe-profile-prompt" value={draft.prompt} disabled={readonly} onChange={(event) => setDraft({ ...draft, prompt: event.target.value })} />
|
||||
</div>
|
||||
<div className="flex items-start justify-between gap-4 rounded-md border p-3">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="probe-profile-thinking">{t("qualityGuard.profileRequireThinking")}</Label>
|
||||
<p className="text-xs text-muted-foreground">{t("qualityGuard.profileRequireThinkingHelp")}</p>
|
||||
</div>
|
||||
<Switch id="probe-profile-thinking" checked={draft.requireThinking} disabled={readonly} onCheckedChange={(requireThinking) => setDraft({ ...draft, requireThinking })} />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="secondary" size="sm" onClick={() => setEditing(undefined)}>{t("common.cancel")}</Button>
|
||||
{readonly ? null : <Button type="submit" size="sm" disabled={!draft.name.trim() || !draft.prompt.trim() || saveMutation.isPending}>{saveMutation.isPending ? <Spinner /> : null}{t("common.save")}</Button>}
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog open={deleting !== null} onOpenChange={(open) => { if (!open && !deleteMutation.isPending) setDeleting(null); }}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("common.delete")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t("qualityGuard.profileDeleteConfirm", { name: deleting?.name ?? "" })}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>{t("common.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction className="bg-destructive text-white hover:bg-destructive/90" disabled={deleteMutation.isPending || !deleting} onClick={(event) => { event.preventDefault(); if (deleting) deleteMutation.mutate(deleting); }}>
|
||||
{deleteMutation.isPending ? <Spinner /> : null}{t("common.delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -56,6 +56,26 @@ export type QualityGuardStatistics = {
|
||||
actions: { quarantined: number; restored: number; suppressed: number };
|
||||
};
|
||||
|
||||
export type ProbeProfileSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
built_in: boolean;
|
||||
match_mode: string;
|
||||
has_expected: boolean;
|
||||
require_thinking: boolean;
|
||||
};
|
||||
|
||||
export type ProbeProfile = {
|
||||
id: string;
|
||||
name: string;
|
||||
built_in: boolean;
|
||||
prompt: string;
|
||||
expected_text?: string;
|
||||
match_mode: string;
|
||||
require_thinking: boolean;
|
||||
max_output_tokens?: number;
|
||||
};
|
||||
|
||||
export type QualityGuardStatus = {
|
||||
available: boolean;
|
||||
editable?: boolean;
|
||||
@@ -63,6 +83,8 @@ export type QualityGuardStatus = {
|
||||
updatedAt?: number;
|
||||
lastActiveCycleAt?: number;
|
||||
lastPassivePollAt?: number;
|
||||
activeProfileId?: string;
|
||||
profiles?: ProbeProfileSummary[];
|
||||
config?: {
|
||||
mode: "active" | "passive" | "hybrid";
|
||||
model: string;
|
||||
@@ -91,9 +113,12 @@ export type QualityTestResult = {
|
||||
firstTokenMs: number;
|
||||
durationMs: number;
|
||||
outputTokens: number;
|
||||
reasoningTokens: number;
|
||||
visibleTokens: number;
|
||||
outputTokensPerSecond: number;
|
||||
generationMs: number;
|
||||
expectedMatched: boolean;
|
||||
thinkingRequired: boolean;
|
||||
};
|
||||
|
||||
const nodeStateValidator = hasShape({
|
||||
@@ -131,7 +156,12 @@ const decodeStatus = (value: unknown): QualityGuardStatus => {
|
||||
}
|
||||
return createObjectDecoder<QualityGuardStatus>("quality guard", {
|
||||
available: isBoolean, editable: isOptional(isBoolean), startedAt: isNumber, updatedAt: isNumber, lastActiveCycleAt: isNumber,
|
||||
lastPassivePollAt: isNumber, config: configValidator, nodes: isRecordOf(nodeStateValidator),
|
||||
lastPassivePollAt: isNumber, activeProfileId: isOptional(isString),
|
||||
profiles: isOptional(isArrayOf(hasShape({
|
||||
id: isString, name: isString, built_in: isBoolean, match_mode: isString, has_expected: isBoolean,
|
||||
require_thinking: isBoolean,
|
||||
}))),
|
||||
config: configValidator, nodes: isRecordOf(nodeStateValidator),
|
||||
protectedNodeIds: isOptional(isArrayOf(isString)),
|
||||
recentEvents: isArrayOf(eventValidator), statistics: isOptional(statisticsValidator),
|
||||
})(value);
|
||||
@@ -139,16 +169,50 @@ const decodeStatus = (value: unknown): QualityGuardStatus => {
|
||||
|
||||
const decodeQualityTest = createObjectDecoder<QualityTestResult>("quality test", {
|
||||
nodeId: isString, statusCode: isNumber, firstTokenMs: isNumber, durationMs: isNumber,
|
||||
outputTokens: isNumber, visibleTokens: isNumber, outputTokensPerSecond: isNumber, expectedMatched: isBoolean,
|
||||
outputTokens: isNumber, reasoningTokens: isNumber, visibleTokens: isNumber,
|
||||
outputTokensPerSecond: isNumber, generationMs: isNumber, expectedMatched: isBoolean,
|
||||
thinkingRequired: isBoolean,
|
||||
});
|
||||
|
||||
export function getQualityGuardStatus(): Promise<QualityGuardStatus> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard", {}, decodeStatus);
|
||||
}
|
||||
|
||||
export function runQualityTest(nodeId: string, status: QualityGuardStatus): Promise<QualityTestResult> {
|
||||
export function runQualityTest(nodeId: string, status: QualityGuardStatus, profileId?: string): Promise<QualityTestResult> {
|
||||
if (!status.config) throw new Error("Quality guard configuration is unavailable");
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/nodes/${nodeId}/test`, { method: "POST" }, decodeQualityTest);
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/nodes/${nodeId}/test`, {
|
||||
method: "POST",
|
||||
body: profileId ? { profileId } : {},
|
||||
}, decodeQualityTest);
|
||||
}
|
||||
|
||||
const decodeProfile = createObjectDecoder<ProbeProfile>("probe profile", {
|
||||
id: isString, name: isString, built_in: isBoolean, prompt: isString,
|
||||
expected_text: isOptional(isString), match_mode: isString, require_thinking: isBoolean,
|
||||
max_output_tokens: isOptional(isNumber),
|
||||
});
|
||||
|
||||
export function listProbeProfiles(): Promise<{ activeProfileId: string; items: ProbeProfile[] }> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard/profiles", {}, createObjectDecoder("probe profiles", {
|
||||
activeProfileId: isString,
|
||||
items: isArrayOf(hasShape({
|
||||
id: isString, name: isString, built_in: isBoolean, prompt: isString,
|
||||
expected_text: isOptional(isString), match_mode: isString, require_thinking: isBoolean,
|
||||
max_output_tokens: isOptional(isNumber),
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
export function createProbeProfile(input: { name: string; prompt: string; expectedText?: string; matchMode: string; requireThinking?: boolean; active?: boolean }): Promise<ProbeProfile> {
|
||||
return apiRequest("/api/admin/v1/egress-quality-guard/profiles", { method: "POST", body: input }, decodeProfile);
|
||||
}
|
||||
|
||||
export function updateProbeProfile(id: string, input: { name: string; prompt: string; expectedText?: string; matchMode: string; requireThinking?: boolean; active?: boolean }): Promise<ProbeProfile> {
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/profiles/${id}`, { method: "PUT", body: input }, decodeProfile);
|
||||
}
|
||||
|
||||
export function deleteProbeProfile(id: string): Promise<{ deleted: boolean }> {
|
||||
return apiRequest(`/api/admin/v1/egress-quality-guard/profiles/${id}`, { method: "DELETE" }, createObjectDecoder("delete profile", { deleted: isBoolean }));
|
||||
}
|
||||
|
||||
export function updateQualityGuardPolicy(policy: QualityGuardPolicy): Promise<{ saved: boolean }> {
|
||||
|
||||
@@ -20,6 +20,7 @@ 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 { ProbeProfilesPanel } from "@/features/quality-guard/probe-profiles-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";
|
||||
@@ -164,8 +165,12 @@ export function QualityGuardPage() {
|
||||
<Tabs defaultValue="nodes">
|
||||
<TabsList>
|
||||
<TabsTrigger value="nodes">{t("qualityGuard.nodesTab")}</TabsTrigger>
|
||||
<TabsTrigger value="profiles">{t("qualityGuard.profilesTab")}</TabsTrigger>
|
||||
<TabsTrigger value="accounts">{t("qualityGuard.degrade.tab")}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="profiles" className="mt-6">
|
||||
<ProbeProfilesPanel />
|
||||
</TabsContent>
|
||||
<TabsContent value="accounts" className="mt-6">
|
||||
<DegradeAccountsPanel
|
||||
softTPS={status?.config?.soft_tps}
|
||||
@@ -514,10 +519,18 @@ function isFresh(status?: QualityGuardStatus): boolean {
|
||||
function qualityTestState(result: QualityTestResult, status: QualityGuardStatus): QualityGuardNodeState {
|
||||
const softTPS = status.config?.soft_tps ?? 500;
|
||||
const hardTPS = status.config?.hard_tps ?? 1000;
|
||||
const profile = status.profiles?.find((item) => item.id === status.activeProfileId);
|
||||
const hasExpected = profile?.has_expected ?? true;
|
||||
const requireThinking = result.thinkingRequired;
|
||||
const failClosed = status.config?.fail_closed ?? false;
|
||||
const minimumGenerationMS = status.config?.min_generation_ms ?? 0;
|
||||
let classification = "healthy";
|
||||
let reason = "within_threshold";
|
||||
if (!result.expectedMatched) { classification = "soft"; reason = "expected_marker_missing"; }
|
||||
if (hasExpected && !result.expectedMatched) { classification = "hard"; reason = "expected_marker_missing"; }
|
||||
else if (result.outputTokens < 32) { classification = "soft"; reason = "insufficient_output_tokens"; }
|
||||
else if (requireThinking && result.outputTokens >= 64 && result.reasoningTokens <= 0) { classification = "hard"; reason = "missing_thinking"; }
|
||||
else if (failClosed && result.generationMs < minimumGenerationMS && result.outputTokensPerSecond >= softTPS) { classification = "hard"; reason = "buffered_burst"; }
|
||||
else if (failClosed && result.generationMs < minimumGenerationMS) { classification = "soft"; reason = "insufficient_generation_window"; }
|
||||
else if (result.outputTokensPerSecond >= hardTPS) { classification = "hard"; reason = "hard_tps"; }
|
||||
else if (result.outputTokensPerSecond >= softTPS) { classification = "soft"; reason = "soft_tps"; }
|
||||
const now = Date.now() / 1000;
|
||||
|
||||
@@ -473,15 +473,38 @@ const resources = {
|
||||
title: "质量守护", description: "监测 Grok 出口质量并在异常时自动隔离节点。", overview: "质量守护概览",
|
||||
serviceStatus: "守护服务", running: "运行正常", stale: "状态滞后", mode: "检测模式", availableNodes: "已启用节点", quarantinedNodes: "已隔离节点",
|
||||
modes: { active: "主动检测", passive: "被动审计", hybrid: "混合模式" },
|
||||
nodes: "节点质量", nodesHelp: "速度与 grok2api 面板同口径:输出 Token 包含推理 Token。被动异常只触发主动复测。打击计数依次为被动 / 主动 / 错误。", updatedAt: "状态更新于 {{time}}",
|
||||
nodes: "节点质量", nodesHelp: "速度与 grok2api 面板同口径:输出 Token 包含推理 Token。完整用户请求出现速度异常后会立即隔离,并在隔离期结束后使用受控探针复测。", updatedAt: "状态更新于 {{time}}",
|
||||
node: "节点", state: "状态", outputTPS: "面板输出速度", firstToken: "首字延迟", source: "数据来源", strikes: "打击计数", lastObserved: "最近观测", test: "检测",
|
||||
sources: { active: "主动探针", passive: "请求审计" }, quarantined: "已隔离", fixedFallback: "固定回退(受保护)", suspect: "可疑", healthy: "正常", pending: "待观测", probeFailed: "检测失败",
|
||||
events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求" },
|
||||
statistics: "自动检测统计", statisticsSince: "自 {{time}} 开始累计,不含手动检测。", statisticsChecks: "有效检测总数", statisticsChecksHelp: "主动探测与有效被动审计", statisticsActive: "主动探测", statisticsActiveDetail: "正常 {{healthy}},错误 {{errors}}", statisticsPassive: "被动审计", statisticsPassiveDetail: "正常 {{healthy}},来自真实请求", statisticsTokens: "主动探测输出 Token", statisticsTokensHelp: "包含推理 Token,不代表代理流量", statisticsAnomalies: "异常命中", statisticsAnomalyDetail: "软异常 {{soft}},硬异常 {{hard}}", statisticsQuarantines: "执行隔离", statisticsActionDetail: "已恢复 {{restored}},受保护未隔离 {{suppressed}}",
|
||||
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: "最少保留节点",
|
||||
reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", missing_thinking: "输出缺少 thinking", 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: "节点质量",
|
||||
profilesTab: "探针方案",
|
||||
profilesHelp: "主动质量探测用的 Prompt 与预期标记。标记缺失记为硬异常。",
|
||||
profileActive: "当前使用",
|
||||
profileBuiltin: "内置",
|
||||
profileCustom: "自定义",
|
||||
profileCreate: "新建方案",
|
||||
profileEdit: "编辑方案",
|
||||
profileView: "查看方案",
|
||||
profileName: "名称",
|
||||
profilePrompt: "探测 Prompt",
|
||||
profileExpected: "预期标记",
|
||||
profileExpectedHelp: "留空则只看 Token/s;有标记时短回复命中不因虚高 TPS 误杀",
|
||||
profileMatch: "匹配方式",
|
||||
profileMatchContains: "全文包含",
|
||||
profileMatchLastLine: "最后一行",
|
||||
profileMatchRegex: "正则",
|
||||
profileSaved: "方案已保存",
|
||||
profileDeleted: "方案已删除",
|
||||
profileDeleteConfirm: "将删除“{{name}}”。若正在使用会回退到预期标记。",
|
||||
profileActivate: "设为当前",
|
||||
profileNoExpected: "无预期标记",
|
||||
profileRequireThinking: "要求 Thinking",
|
||||
profileRequireThinkingHelp: "仅用于受控探针;输出达到 64 Token 但没有推理 Token 时判为硬异常。",
|
||||
degrade: {
|
||||
tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点",
|
||||
hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}",
|
||||
@@ -986,7 +1009,7 @@ const resources = {
|
||||
},
|
||||
units: { seconds: "秒", minutes: "分", hours: "时", days: "天" },
|
||||
},
|
||||
settingsBuildTransport: { responseHeaderTimeout: "响应头超时", responseHeaderTimeoutHelp: "请求体发送完成后,等待 Grok Build 返回首个响应头的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "流式响应中连续无新数据到达的最长等待时间,超时后主动中断。" },
|
||||
settingsBuildTransport: { responseHeaderTimeout: "响应头超时", responseHeaderTimeoutHelp: "请求体发送完成后,等待 Grok Build 返回首个响应头的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "流式响应中连续无有效生成内容或工具进度的最长等待时间;心跳与内部控制事件不会延长等待,超时后主动中断。" },
|
||||
settingsBuildForbidden: {
|
||||
markInvalid: "按错误码标记失效",
|
||||
markInvalidHelp: "启用后,Grok Build 返回 403 且错误码命中下方规则时,将账号标记为失效并移出调度。",
|
||||
@@ -1489,8 +1512,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. A completed user request with anomalous throughput is isolated immediately, then verified with a controlled probe after the hold.", 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", missing_thinking: "Missing thinking tokens", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Request 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 active 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",
|
||||
profilesTab: "Probe profiles",
|
||||
profilesHelp: "Prompt and expected marker for active quality probes. A missing marker is a hard failure.",
|
||||
profileActive: "In use",
|
||||
profileBuiltin: "Built-in",
|
||||
profileCustom: "Custom",
|
||||
profileCreate: "New profile",
|
||||
profileEdit: "Edit profile",
|
||||
profileView: "View profile",
|
||||
profileName: "Name",
|
||||
profilePrompt: "Probe prompt",
|
||||
profileExpected: "Expected marker",
|
||||
profileMatch: "Match mode",
|
||||
profileMatchContains: "Contains",
|
||||
profileMatchLastLine: "Last line",
|
||||
profileMatchRegex: "Regex",
|
||||
profileSaved: "Profile saved",
|
||||
profileDeleted: "Profile deleted",
|
||||
profileDeleteConfirm: "Delete “{{name}}”. The active profile falls back to the marker recipe.",
|
||||
profileActivate: "Use this",
|
||||
profileNoExpected: "No expected marker",
|
||||
profileRequireThinking: "Require thinking",
|
||||
profileRequireThinkingHelp: "Controlled probes only. A response with at least 64 output tokens and no reasoning tokens is a hard failure.",
|
||||
profileExpectedHelp: "Leave empty to score throughput only.",
|
||||
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}}",
|
||||
@@ -1641,7 +1687,7 @@ const resources = {
|
||||
},
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", sLine truncated
|
||||
|
||||
settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for new data on an open streaming response before aborting. Covers upstream connections that succeed but go silent mid-stream." },
|
||||
settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for useful generated content or tool progress. Keepalives and private control events do not extend the deadline." },
|
||||
settingsBuildForbidden: { markInvalid: "Invalidate matching error codes", markInvalidHelp: "When enabled, a Grok Build 403 with a matching error code marks the account invalid and removes it from scheduling.", codes: "Invalidation error codes", codesHelp: "Enter one code per line. Codes match the complete code or error.code value case-insensitively, up to 32 entries.", codesInvalid: "Enter 1–32 valid codes using letters, numbers, dots, underscores, colons, or hyphens.", codesPlaceholder: "permission-denied" },
|
||||
settingsRoutingSegmented: { enabled: "Enable segmented selection", enabledHelp: "Applies above the threshold, supports session affinity, and falls back to full-pool selection after four saturated windows.", minCandidates: "Account threshold", minCandidatesHelp: "Enables segmented selection when the eligible account pool reaches this size.", windowSize: "Selection window", windowSizeHelp: "Number of candidate accounts inspected in each segmented window." },
|
||||
settingsRoutingAttempts: {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# Egress Quality Guard
|
||||
|
||||
Egress Quality Guard combines passive production-audit monitoring with active
|
||||
Grok Build probes through each fixed egress node. A passive hard-threshold
|
||||
anomaly quarantines the node immediately; a soft anomaly is confirmed by a
|
||||
fixed active probe.
|
||||
Grok Build probes through each fixed egress node. A complete production request
|
||||
at either passive threshold quarantines the node immediately and holds it until
|
||||
the fixed recovery probe is healthy.
|
||||
|
||||
This is a heuristic circuit breaker, not a model-quality oracle. Very high
|
||||
reported throughput can be caused by upstream or intermediary buffering. Start
|
||||
@@ -14,6 +14,7 @@ your own traffic before allowing automatic quarantine.
|
||||
|
||||
- Supports Grok Build streaming requests after egress nodes and request audits are configured in grok2api.
|
||||
- At least one schedulable Grok Build account must be able to serve the probe model. The account does not have to be bound to every managed node.
|
||||
- The built-in thinking guard is enforced only when the backend recognizes the configured Build model as reasoning-capable. Keep the default `grok-4.5` or another verified reasoning model when missing-thinking detection is required; unknown and non-reasoning models retain marker/TPS checks without this signal.
|
||||
- The main service automatically provisions a non-exportable system probe identity. The sidecar reaches only a scoped internal API over the Compose network.
|
||||
- Classification is heuristic evidence. It cannot prove that upstream model capability changed and does not replace application-level regression tests.
|
||||
|
||||
@@ -32,10 +33,9 @@ your own traffic before allowing automatic quarantine.
|
||||
model name.
|
||||
4. The fixed probe checks output tokens, chunk cadence, first-token time,
|
||||
instruction-marker compliance, and panel-equivalent output-token throughput.
|
||||
5. A high-TPS production request at the hard threshold quarantines the node
|
||||
immediately. A soft result triggers a fixed-prompt probe; active hard results
|
||||
quarantine immediately, while active soft results must reach the configured
|
||||
strike count.
|
||||
5. A production request at either passive TPS threshold quarantines the node
|
||||
immediately and starts the hold. Active hard results quarantine immediately;
|
||||
active soft results must reach the configured strike count.
|
||||
6. Quarantined nodes remain available only to administrator probes. Recovery
|
||||
records a generic connectivity probe for diagnosis, then uses the real
|
||||
model-quality probe as the authority before re-enabling the node.
|
||||
@@ -50,9 +50,8 @@ credential, account-block, and quota signals retain their normal transitions.
|
||||
`qualityGuard.mode` accepts:
|
||||
|
||||
- `passive`: inspect ordinary request audits every few seconds. Routine polling
|
||||
adds no model requests. Hard anomalies quarantine immediately; soft anomalies
|
||||
trigger one active confirmation probe. Recovery probes still run for nodes
|
||||
quarantined by the guard.
|
||||
adds no model requests. Soft and hard anomalies quarantine immediately;
|
||||
recovery probes run only after the hold for nodes quarantined by the guard.
|
||||
- `active`: run only fixed per-node probes at the configured interval.
|
||||
- `hybrid`: enable both detectors. This is the recommended default.
|
||||
|
||||
@@ -156,7 +155,7 @@ Default hybrid policy:
|
||||
- inspect ordinary request audits every 5 seconds;
|
||||
- run active per-node probes every 1,800 seconds, with up to 30 seconds of jitter;
|
||||
- quarantine immediately at 1000 visible tokens/second;
|
||||
- require two consecutive observations at 500 tokens/second;
|
||||
- require two consecutive active-probe observations at 500 tokens/second;
|
||||
- require two consecutive probe errors;
|
||||
- quarantine for 300 seconds;
|
||||
- retain at least three enabled proxied Build nodes.
|
||||
@@ -195,7 +194,8 @@ API remains available.
|
||||
- HTTPS/SSE audits cannot provide reliable proxy transfer-byte counts. The UI reports active-probe output Tokens and does not label them as network traffic.
|
||||
- Intermediary buffering can produce unusually high instantaneous Token/s, so thresholds require calibration for each route.
|
||||
- Passive monitoring processes only complete successful streaming requests with enough output to calculate speed. Short and failed requests are ignored.
|
||||
- A real request may legitimately return cached content, an existing file, or a long constant. Immediate quarantine at the passive hard threshold is therefore intentionally aggressive; raise `hard_tps` when false positives are more costly. Soft anomalies still require a fixed-prompt confirmation.
|
||||
- A real request may legitimately return cached content, an existing file, or a long constant. Passive soft and hard anomalies therefore isolate immediately and hold the node until a controlled recovery probe succeeds; raise the thresholds when false positives are more costly.
|
||||
- Missing-thinking detection applies only to controlled probe profiles that explicitly require thinking. Arbitrary user traffic may legitimately use a non-reasoning model or disable reasoning and is never isolated solely because `reasoningTokens` is zero.
|
||||
- The first run establishes an audit baseline. Cumulative statistics also begin when this version first writes state.
|
||||
- Manual quality tests are diagnostic. They are excluded from automatic statistics and do not directly change quarantine state.
|
||||
|
||||
|
||||
@@ -43,6 +43,9 @@ RUNTIME_CONFIG_FIELDS = {
|
||||
BOOTSTRAP_VERSION = 1
|
||||
BOOTSTRAP_FILE = Path("/var/lib/grok2api-quality-guard/bootstrap.json")
|
||||
INTERNAL_API_PREFIX = "/api/internal/v1/quality-guard"
|
||||
QUALITY_MARKER_PROFILE_ID = "quality-marker"
|
||||
THROUGHPUT_PROFILE_ID = "throughput"
|
||||
THINKING_GUARD_MIN_OUTPUT_TOKENS = 64
|
||||
|
||||
|
||||
class GuardDisabled(RuntimeError):
|
||||
@@ -81,6 +84,7 @@ class Config:
|
||||
state_file: Path
|
||||
lock_file: Path
|
||||
runtime_config_file: Path
|
||||
profiles_file: Path = dataclasses.field(default_factory=lambda: Path("/var/lib/grok2api-quality-guard/profiles.json"))
|
||||
|
||||
@classmethod
|
||||
def from_bootstrap(cls, path: Path = BOOTSTRAP_FILE) -> "Config":
|
||||
@@ -132,6 +136,7 @@ class Config:
|
||||
state_file=Path("/var/lib/grok2api-quality-guard/state.json"),
|
||||
lock_file=Path("/var/lib/grok2api-quality-guard/guard.lock"),
|
||||
runtime_config_file=Path("/var/lib/grok2api-quality-guard/runtime-config.json"),
|
||||
profiles_file=Path("/var/lib/grok2api-quality-guard/profiles.json"),
|
||||
)
|
||||
config.validate()
|
||||
return config
|
||||
@@ -302,8 +307,9 @@ class ApiClient:
|
||||
result.add(node_id)
|
||||
return result
|
||||
|
||||
def quality_test(self, node_id: str) -> dict[str, Any]:
|
||||
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/quality-test")
|
||||
def quality_test(self, node_id: str, profile_id: str = "") -> dict[str, Any]:
|
||||
body = {"profileId": profile_id} if profile_id else {}
|
||||
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/quality-test", body or None)
|
||||
|
||||
def connectivity_test(self, node_id: str) -> dict[str, Any]:
|
||||
return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/test")
|
||||
@@ -350,8 +356,13 @@ class ApiClient:
|
||||
return payload
|
||||
|
||||
|
||||
def classify_result(result: dict[str, Any], config: Config) -> tuple[str, str]:
|
||||
if not bool(result.get("expectedMatched")):
|
||||
def classify_result(result: dict[str, Any], config: Config, profile: dict[str, Any] | None = None) -> tuple[str, str]:
|
||||
expected = ""
|
||||
if profile:
|
||||
expected = str(profile.get("expected_text") or profile.get("expected") or "").strip()
|
||||
if expected and not bool(result.get("expectedMatched")):
|
||||
return "hard", "expected_marker_missing"
|
||||
if profile is None and not bool(result.get("expectedMatched")):
|
||||
return "soft", "expected_marker_missing"
|
||||
output_tokens = int(result.get("outputTokens") or result.get("visibleTokens") or 0)
|
||||
speed_value = result.get("outputTokensPerSecond")
|
||||
@@ -362,8 +373,20 @@ def classify_result(result: dict[str, Any], config: Config) -> tuple[str, str]:
|
||||
generation_ms = int(result.get("generationMs") or 0)
|
||||
if generation_ms <= 0:
|
||||
generation_ms = max(0, int(result.get("durationMs") or 0) - int(result.get("firstTokenMs") or 0))
|
||||
# QUALITY_OK is a content marker, not a quality proof. Apply the same
|
||||
# token / window / TPS rules used for user-traffic audits.
|
||||
if output_tokens < 32:
|
||||
return "soft", "insufficient_output_tokens"
|
||||
reasoning_tokens = max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0))
|
||||
if "thinkingRequired" in result:
|
||||
require_thinking = bool(result.get("thinkingRequired"))
|
||||
else:
|
||||
# Rolling-upgrade compatibility with an older main service.
|
||||
require_thinking = bool(profile and profile.get("require_thinking"))
|
||||
if require_thinking and output_tokens >= THINKING_GUARD_MIN_OUTPUT_TOKENS and reasoning_tokens <= 0:
|
||||
return "hard", "missing_thinking"
|
||||
if config.fail_closed and generation_ms < config.min_generation_ms and speed >= config.soft_tps:
|
||||
return "hard", "buffered_burst"
|
||||
if config.fail_closed and generation_ms < config.min_generation_ms:
|
||||
return "soft", "insufficient_generation_window"
|
||||
if speed >= config.hard_tps:
|
||||
@@ -373,6 +396,66 @@ def classify_result(result: dict[str, Any], config: Config) -> tuple[str, str]:
|
||||
return "healthy", "within_threshold"
|
||||
|
||||
|
||||
def builtin_probe_profiles() -> dict[str, dict[str, Any]]:
|
||||
return {
|
||||
QUALITY_MARKER_PROFILE_ID: {
|
||||
"id": QUALITY_MARKER_PROFILE_ID,
|
||||
"built_in": True,
|
||||
"expected_text": "QUALITY_OK",
|
||||
"match_mode": "last_line",
|
||||
"require_thinking": True,
|
||||
},
|
||||
THROUGHPUT_PROFILE_ID: {
|
||||
"id": THROUGHPUT_PROFILE_ID,
|
||||
"built_in": True,
|
||||
"expected_text": "",
|
||||
"match_mode": "contains",
|
||||
"require_thinking": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def load_probe_profiles(path: Path) -> dict[str, Any]:
|
||||
data = {"version": 1, "active_profile_id": QUALITY_MARKER_PROFILE_ID, "profiles": {}}
|
||||
try:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
loaded = json.load(handle)
|
||||
if isinstance(loaded, dict):
|
||||
data.update(loaded)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
profiles = data.get("profiles")
|
||||
if not isinstance(profiles, dict):
|
||||
profiles = {}
|
||||
data["profiles"] = profiles
|
||||
for profile_id, builtin in builtin_probe_profiles().items():
|
||||
current = profiles.get(profile_id)
|
||||
if not isinstance(current, dict):
|
||||
profiles[profile_id] = builtin
|
||||
continue
|
||||
# Reserved built-in IDs are part of the recovery safety boundary.
|
||||
# Canonicalize them even when an older writer or a manual edit cleared
|
||||
# built_in, otherwise a forged quality-marker could bypass recovery.
|
||||
current.update(builtin)
|
||||
active_profile_id = str(data.get("active_profile_id") or QUALITY_MARKER_PROFILE_ID)
|
||||
if active_profile_id not in profiles:
|
||||
data["active_profile_id"] = QUALITY_MARKER_PROFILE_ID
|
||||
return data
|
||||
|
||||
|
||||
def resolve_probe_profile(path: Path, profile_id: str = "") -> tuple[str, dict[str, Any] | None]:
|
||||
data = load_probe_profiles(path)
|
||||
profiles = data.get("profiles") if isinstance(data.get("profiles"), dict) else {}
|
||||
active = str(data.get("active_profile_id") or QUALITY_MARKER_PROFILE_ID)
|
||||
chosen = str(profile_id or active)
|
||||
profile = profiles.get(chosen)
|
||||
if isinstance(profile, dict):
|
||||
return chosen, profile
|
||||
return chosen, None
|
||||
|
||||
|
||||
def classify_audit(value: dict[str, Any], config: Config) -> tuple[str, str, float, int]:
|
||||
if value.get("provider") != "grok_build" or not bool(value.get("streaming")):
|
||||
return "ignored", "not_build_stream", 0.0, 0
|
||||
@@ -416,6 +499,8 @@ def default_node_state() -> dict[str, Any]:
|
||||
"last_rotation_exit_ip": "",
|
||||
"rotation_failures": 0,
|
||||
"last_no_account_log_at": 0.0,
|
||||
"quarantine_source": "",
|
||||
"passive_degrade_repeats": 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -538,6 +623,7 @@ class Guard:
|
||||
"rotatable_node_ids": list(self.config.rotatable_node_ids),
|
||||
"prompt": self.config.prompt,
|
||||
"expected": self.config.expected,
|
||||
"active_profile_id": resolve_probe_profile(self.config.profiles_file)[0],
|
||||
}
|
||||
|
||||
def _save(self) -> None:
|
||||
@@ -600,7 +686,7 @@ class Guard:
|
||||
bool(self.config.rotation_url)
|
||||
and node_id in set(self.config.rotatable_node_ids)
|
||||
and reason in {
|
||||
"hard_tps", "soft_tps", "buffered_burst", "expected_marker_missing",
|
||||
"hard_tps", "soft_tps", "buffered_burst", "missing_thinking", "expected_marker_missing",
|
||||
"insufficient_output_tokens", "insufficient_generation_window", "probe_errors",
|
||||
"recovery_probe_error", "rotation_error",
|
||||
}
|
||||
@@ -610,7 +696,7 @@ class Guard:
|
||||
def _probe_account_unavailable(exc: Exception) -> bool:
|
||||
return isinstance(exc, ApiError) and exc.code == "egressQualityProbeNoAccount"
|
||||
|
||||
def _quarantine(self, nodes: list[dict[str, Any]], node: dict[str, Any], reason: str, now: float) -> None:
|
||||
def _quarantine(self, nodes: list[dict[str, Any]], node: dict[str, Any], reason: str, now: float, recover_now: bool = True) -> None:
|
||||
node_id = str(node["id"])
|
||||
state = self._state_for(node_id)
|
||||
if not self._can_quarantine(nodes, node_id):
|
||||
@@ -618,13 +704,20 @@ class Guard:
|
||||
log_event("quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, minimum_healthy=self.config.min_healthy_nodes)
|
||||
return
|
||||
previous_state = dict(state)
|
||||
source = "passive" if not recover_now else "active"
|
||||
repeats = int(state.get("passive_degrade_repeats", 0))
|
||||
if source == "passive":
|
||||
repeats += 1
|
||||
scale = min(8, 2 ** max(0, repeats - 1)) if source == "passive" else 1
|
||||
state.update({
|
||||
"active_soft_strikes": 0,
|
||||
"passive_soft_strikes": 0,
|
||||
"error_strikes": 0,
|
||||
"quarantined_until": now + self.config.quarantine_seconds,
|
||||
"quarantined_until": now + self.config.quarantine_seconds * scale,
|
||||
"disabled_by_guard": True,
|
||||
"last_reason": reason,
|
||||
"quarantine_source": source,
|
||||
"passive_degrade_repeats": repeats if source == "passive" else int(state.get("passive_degrade_repeats", 0)),
|
||||
})
|
||||
# Persist ownership before changing backend scheduling state. A crash
|
||||
# after the API call can then be reconciled safely on restart.
|
||||
@@ -647,11 +740,37 @@ class Guard:
|
||||
self._bump_statistic("actions", "quarantined")
|
||||
append_state_event(self.state, "node_quarantined", node_id=node_id, node_name=node.get("name"), reason=reason)
|
||||
self._save()
|
||||
log_event("node_quarantined", node_id=node_id, node_name=node.get("name"), reason=reason, quarantine_seconds=self.config.quarantine_seconds)
|
||||
if reason == "buffered_burst":
|
||||
self._recover_quarantined(node, time.time(), rotate=False, rotate_on_failure=True)
|
||||
log_event(
|
||||
"node_quarantined",
|
||||
node_id=node_id,
|
||||
node_name=node.get("name"),
|
||||
reason=reason,
|
||||
quarantine_seconds=self.config.quarantine_seconds,
|
||||
quarantine_hold_seconds=self.config.quarantine_seconds * scale,
|
||||
quarantine_source=source,
|
||||
degrade_repeats=repeats if source == "passive" else 0,
|
||||
recover_now=recover_now,
|
||||
)
|
||||
if recover_now:
|
||||
if reason == "buffered_burst":
|
||||
self._recover_quarantined(node, time.time(), rotate=False, rotate_on_failure=True)
|
||||
elif self._should_rotate(node_id, reason):
|
||||
self._recover_quarantined(node, time.time(), rotate=True)
|
||||
elif self._should_rotate(node_id, reason):
|
||||
self._recover_quarantined(node, time.time(), rotate=True)
|
||||
try:
|
||||
rotation = self.api.rotate_node(node_id, str(node.get("exitIp") or ""))
|
||||
except Exception as exc:
|
||||
state["rotation_failures"] = int(state.get("rotation_failures", 0)) + 1
|
||||
log_event("node_rotation_failed", node_id=node_id, node_name=node.get("name"), error_type=type(exc).__name__, trigger="passive_hold")
|
||||
else:
|
||||
state.update({
|
||||
"last_rotation_at": time.time(),
|
||||
"last_rotation_exit_ip": str(rotation.get("newExitIp") or ""),
|
||||
"rotation_failures": 0,
|
||||
})
|
||||
append_state_event(self.state, "node_rotated", node_id=node_id, node_name=node.get("name"), exit_ip=str(rotation.get("newExitIp") or ""))
|
||||
self._save()
|
||||
log_event("node_rotated", node_id=node_id, node_name=node.get("name"), exit_ip=str(rotation.get("newExitIp") or ""), trigger="passive_hold")
|
||||
|
||||
def _record_probe(self, node: dict[str, Any], result: dict[str, Any], classification: str, reason: str, now: float) -> None:
|
||||
node_id = str(node["id"])
|
||||
@@ -668,6 +787,7 @@ class Guard:
|
||||
"last_classification": classification,
|
||||
"last_output_tps": round(output_tps, 3),
|
||||
"last_output_tokens": output_tokens,
|
||||
"last_reasoning_tokens": max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0)),
|
||||
"last_first_token_ms": int(result.get("firstTokenMs") or 0),
|
||||
"last_duration_ms": int(result.get("durationMs") or 0),
|
||||
})
|
||||
@@ -689,6 +809,7 @@ class Guard:
|
||||
reason=reason,
|
||||
output_tps=round(output_tps, 3),
|
||||
output_tokens=output_tokens,
|
||||
reasoning_tokens=max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0)),
|
||||
first_token_ms=int(result.get("firstTokenMs") or 0),
|
||||
duration_ms=int(result.get("durationMs") or 0),
|
||||
chunk_count=int(result.get("chunkCount") or 0),
|
||||
@@ -701,8 +822,9 @@ class Guard:
|
||||
if state.get("last_reason") == "probe_no_account" and now < float(state.get("quarantined_until", 0.0)):
|
||||
return
|
||||
self._bump_statistic("active", "total")
|
||||
profile_id, profile = resolve_probe_profile(self.config.profiles_file)
|
||||
try:
|
||||
result = self.api.quality_test(node_id)
|
||||
result = self.api.quality_test(node_id, profile_id)
|
||||
except Exception as exc:
|
||||
if self._probe_account_unavailable(exc):
|
||||
self._defer_no_account(state, node, now, "quality_probe_deferred", trigger=trigger)
|
||||
@@ -714,7 +836,7 @@ class Guard:
|
||||
if trigger == "scheduled" and state["error_strikes"] >= self.config.consecutive_errors:
|
||||
self._quarantine(nodes, node, "probe_errors", now)
|
||||
return
|
||||
classification, reason = classify_result(result, self.config)
|
||||
classification, reason = classify_result(result, self.config, profile)
|
||||
self._record_probe(node, result, classification, reason, now)
|
||||
if classification == "hard" or (
|
||||
classification == "soft" and self.config.fail_closed
|
||||
@@ -760,8 +882,9 @@ class Guard:
|
||||
connectivity_status = "error"
|
||||
log_event("recovery_connectivity_probe_failed", node_id=node_id, node_name=node.get("name"), error_type=type(exc).__name__)
|
||||
self._bump_statistic("active", "total")
|
||||
result = self.api.quality_test(node_id)
|
||||
classification, reason = classify_result(result, self.config)
|
||||
profile_id, profile = resolve_probe_profile(self.config.profiles_file, QUALITY_MARKER_PROFILE_ID)
|
||||
result = self.api.quality_test(node_id, profile_id)
|
||||
classification, reason = classify_result(result, self.config, profile)
|
||||
self._record_probe(node, result, classification, reason, now)
|
||||
except Exception as exc:
|
||||
if self._probe_account_unavailable(exc):
|
||||
@@ -779,6 +902,7 @@ class Guard:
|
||||
if rotate_on_failure and self._should_rotate(node_id, reason):
|
||||
self._recover_quarantined(node, time.time(), rotate=True)
|
||||
return
|
||||
after_passive = self._is_passive_quarantine(state)
|
||||
updated = self.api.set_enabled(node_id, True)
|
||||
if updated != 1:
|
||||
log_event("restore_not_applied", node_id=node_id, node_name=node.get("name"), updated=updated)
|
||||
@@ -790,11 +914,29 @@ class Guard:
|
||||
"quarantined_until": 0.0,
|
||||
"disabled_by_guard": False,
|
||||
"last_reason": "",
|
||||
"quarantine_source": "",
|
||||
})
|
||||
node["enabled"] = True
|
||||
self._bump_statistic("actions", "restored")
|
||||
append_state_event(self.state, "node_restored", node_id=node_id, node_name=node.get("name"), reason="quality_probe_healthy")
|
||||
log_event("node_restored", node_id=node_id, node_name=node.get("name"), connectivity_status=connectivity_status)
|
||||
log_event(
|
||||
"node_restored",
|
||||
node_id=node_id,
|
||||
node_name=node.get("name"),
|
||||
connectivity_status=connectivity_status,
|
||||
reason="quality_probe_healthy",
|
||||
after_passive_hold=after_passive,
|
||||
expected_matched=bool(result.get("expectedMatched")),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _is_passive_quarantine(state: dict[str, Any]) -> bool:
|
||||
source = str(state.get("quarantine_source") or "")
|
||||
if source == "passive":
|
||||
return True
|
||||
if source == "active":
|
||||
return False
|
||||
return str(state.get("last_source") or "") == "passive"
|
||||
|
||||
def _probe_quarantined(self, node: dict[str, Any], now: float) -> None:
|
||||
node_id = str(node["id"])
|
||||
@@ -802,11 +944,15 @@ class Guard:
|
||||
if now < float(state.get("quarantined_until", 0.0)):
|
||||
return
|
||||
reason = str(state.get("last_reason") or "")
|
||||
passive = self._is_passive_quarantine(state)
|
||||
# Dual probe: user traffic isolates immediately; after the hold a
|
||||
# QUALITY_OK probe must come back healthy before restore. Passive
|
||||
# isolate already rotated, so only rotate again if the probe fails.
|
||||
self._recover_quarantined(
|
||||
node,
|
||||
now,
|
||||
rotate=self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=reason == "buffered_burst",
|
||||
rotate=(not passive) and self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=passive or reason == "buffered_burst",
|
||||
)
|
||||
|
||||
def _prepare_nodes(self, now: float) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str]]:
|
||||
@@ -860,15 +1006,16 @@ class Guard:
|
||||
updated = self.api.set_enabled(node_id, False)
|
||||
if updated == 1:
|
||||
node["enabled"] = False
|
||||
state["quarantined_until"] = now + self.config.quarantine_seconds
|
||||
log_event("operator_reenable_requires_probe", node_id=node_id, node_name=node.get("name"))
|
||||
reason = str(state.get("last_reason") or "")
|
||||
self._recover_quarantined(
|
||||
node,
|
||||
now,
|
||||
rotate=self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=reason == "buffered_burst",
|
||||
)
|
||||
if now >= float(state.get("quarantined_until", 0.0)):
|
||||
reason = str(state.get("last_reason") or "")
|
||||
passive = self._is_passive_quarantine(state)
|
||||
self._recover_quarantined(
|
||||
node,
|
||||
now,
|
||||
rotate=(not passive) and self._should_rotate(node_id, reason) and reason != "buffered_burst",
|
||||
rotate_on_failure=passive or reason == "buffered_burst",
|
||||
)
|
||||
skip_ids.add(node_id)
|
||||
continue
|
||||
state.update({
|
||||
@@ -964,6 +1111,7 @@ class Guard:
|
||||
})
|
||||
if classification == "healthy":
|
||||
state["passive_soft_strikes"] = 0
|
||||
state["passive_degrade_repeats"] = 0
|
||||
return
|
||||
if classification == "soft":
|
||||
state["passive_soft_strikes"] = int(state.get("passive_soft_strikes", 0)) + 1
|
||||
@@ -991,13 +1139,15 @@ class Guard:
|
||||
duration_ms=int(audit_value.get("durationMs") or 0),
|
||||
strikes=int(state.get("passive_soft_strikes", 0)),
|
||||
)
|
||||
if classification == "hard":
|
||||
self._quarantine(all_nodes, node, reason, now)
|
||||
return
|
||||
if self.config.fail_closed:
|
||||
self._quarantine(all_nodes, node, reason, now)
|
||||
return
|
||||
self._probe_active(all_nodes, node, now, trigger="passive_confirmation")
|
||||
log_event(
|
||||
"passive_immediate_quarantine",
|
||||
node_id=node_id,
|
||||
node_name=node.get("name"),
|
||||
classification=classification,
|
||||
reason=reason,
|
||||
output_tps=round(speed, 3),
|
||||
)
|
||||
self._quarantine(all_nodes, node, reason, now, recover_now=False)
|
||||
|
||||
def run_passive_cycle(self) -> None:
|
||||
now = time.time()
|
||||
|
||||
@@ -3,6 +3,7 @@ import json
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -36,14 +37,22 @@ def config(**overrides):
|
||||
class ClassificationTests(unittest.TestCase):
|
||||
def test_healthy_soft_and_hard_thresholds(self):
|
||||
cfg = config()
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 499}, cfg)[0], "healthy")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 500}, cfg)[0], "soft")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1000}, cfg)[0], "hard")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 499}, cfg)[0], "healthy")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 500}, cfg)[0], "soft")
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1000}, cfg)[0], "hard")
|
||||
|
||||
def test_missing_marker_and_short_response_are_soft_failures(self):
|
||||
cfg = config()
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": False, "outputTokens": 100, "outputTokensPerSecond": 10}, cfg), ("soft", "expected_marker_missing"))
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 12, "outputTokensPerSecond": 10}, cfg), ("soft", "insufficient_output_tokens"))
|
||||
def test_missing_marker_is_hard_and_quality_ok_is_not_a_healthy_shortcut(self):
|
||||
cfg = config(fail_closed=True, min_generation_ms=1000)
|
||||
marker = {"expected_text": "QUALITY_OK", "match_mode": "last_line", "require_thinking": True}
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": False, "outputTokens": 100, "outputTokensPerSecond": 10}, cfg, marker), ("hard", "expected_marker_missing"))
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 12, "outputTokensPerSecond": 8000}, cfg, marker), ("soft", "insufficient_output_tokens"))
|
||||
self.assertEqual(quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 128, "reasoningTokens": 40, "outputTokensPerSecond": 8000, "generationMs": 50,
|
||||
}, cfg, marker), ("hard", "buffered_burst"))
|
||||
self.assertEqual(quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 128, "reasoningTokens": 40, "outputTokensPerSecond": 80, "generationMs": 1500,
|
||||
}, cfg, marker), ("healthy", "within_threshold"))
|
||||
self.assertEqual(quality_guard.classify_result({"expectedMatched": True, "outputTokens": 12, "outputTokensPerSecond": 10}, cfg, {"expected_text": ""}), ("soft", "insufficient_output_tokens"))
|
||||
|
||||
def test_passive_speed_matches_panel_and_includes_reasoning_tokens(self):
|
||||
cfg = config()
|
||||
@@ -55,6 +64,67 @@ class ClassificationTests(unittest.TestCase):
|
||||
self.assertEqual((classification, reason, output), ("hard", "hard_tps", 1050))
|
||||
self.assertEqual(speed, 10500)
|
||||
|
||||
def test_passive_audit_does_not_infer_thinking_requirement(self):
|
||||
cfg = config(fail_closed=True, min_generation_ms=1000)
|
||||
base = {
|
||||
"provider": "grok_build", "streaming": True, "statusCode": 200,
|
||||
"firstTokenMs": 2000, "durationMs": 4000, "outputTokens": 200,
|
||||
}
|
||||
self.assertEqual(quality_guard.classify_audit({**base, "reasoningTokens": 0}, cfg)[:2], ("healthy", "within_threshold"))
|
||||
classification, reason, speed, _ = quality_guard.classify_audit({**base, "reasoningTokens": 80}, cfg)
|
||||
self.assertEqual((classification, reason), ("healthy", "within_threshold"))
|
||||
self.assertAlmostEqual(speed, 100.0)
|
||||
short = {**base, "outputTokens": 50, "reasoningTokens": 0, "durationMs": 2500}
|
||||
self.assertEqual(quality_guard.classify_audit(short, cfg)[:2], ("healthy", "within_threshold"))
|
||||
tiny = {**base, "outputTokens": 20, "reasoningTokens": 0, "durationMs": 2200}
|
||||
self.assertEqual(quality_guard.classify_audit(tiny, cfg)[0], "ignored")
|
||||
|
||||
def test_probe_missing_thinking_is_hard(self):
|
||||
cfg = config()
|
||||
thinking_profile = {"expected_text": "QUALITY_OK", "require_thinking": True}
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 0,
|
||||
}, cfg, thinking_profile),
|
||||
("hard", "missing_thinking"),
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 90,
|
||||
}, cfg, thinking_profile)[0],
|
||||
"healthy",
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500,
|
||||
}, cfg, thinking_profile),
|
||||
("hard", "missing_thinking"),
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 0,
|
||||
}, cfg, {"expected_text": "", "require_thinking": False})[0],
|
||||
"healthy",
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 0, "thinkingRequired": False,
|
||||
}, cfg, thinking_profile)[0],
|
||||
"healthy",
|
||||
)
|
||||
self.assertEqual(
|
||||
quality_guard.classify_result({
|
||||
"expectedMatched": True, "outputTokens": 200, "outputTokensPerSecond": 80,
|
||||
"generationMs": 2500, "reasoningTokens": 0, "thinkingRequired": True,
|
||||
}, cfg, {"expected_text": "", "require_thinking": False}),
|
||||
("hard", "missing_thinking"),
|
||||
)
|
||||
|
||||
def test_passive_ignores_short_and_failed_requests(self):
|
||||
cfg = config()
|
||||
short = {"provider": "grok_build", "streaming": True, "statusCode": 200, "firstTokenMs": 100, "durationMs": 110, "outputTokens": 20, "reasoningTokens": 0}
|
||||
@@ -78,6 +148,46 @@ class StateTests(unittest.TestCase):
|
||||
|
||||
|
||||
class ConfigTests(unittest.TestCase):
|
||||
def test_missing_profile_file_seeds_builtin_recovery_profiles(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
profile_id, profile = quality_guard.resolve_probe_profile(Path(directory) / "missing.json")
|
||||
self.assertEqual(profile_id, quality_guard.QUALITY_MARKER_PROFILE_ID)
|
||||
self.assertEqual(profile.get("expected_text"), "QUALITY_OK")
|
||||
self.assertTrue(profile.get("require_thinking"))
|
||||
|
||||
def test_reserved_profile_ids_are_canonicalized(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "profiles.json"
|
||||
path.write_text(json.dumps({
|
||||
"version": 1,
|
||||
"active_profile_id": "deleted-profile",
|
||||
"profiles": {
|
||||
"quality-marker": {
|
||||
"id": "quality-marker", "built_in": False,
|
||||
"expected_text": "", "match_mode": "contains",
|
||||
"require_thinking": False,
|
||||
},
|
||||
"throughput": {
|
||||
"id": "throughput", "built_in": False,
|
||||
"expected_text": "PASS", "match_mode": "regex",
|
||||
"require_thinking": True,
|
||||
},
|
||||
},
|
||||
}), encoding="utf-8")
|
||||
loaded = quality_guard.load_probe_profiles(path)["profiles"]
|
||||
profile_id, _ = quality_guard.resolve_probe_profile(path)
|
||||
self.assertEqual(profile_id, quality_guard.QUALITY_MARKER_PROFILE_ID)
|
||||
marker = loaded[quality_guard.QUALITY_MARKER_PROFILE_ID]
|
||||
self.assertTrue(marker["built_in"])
|
||||
self.assertEqual(marker["expected_text"], "QUALITY_OK")
|
||||
self.assertEqual(marker["match_mode"], "last_line")
|
||||
self.assertTrue(marker["require_thinking"])
|
||||
throughput = loaded[quality_guard.THROUGHPUT_PROFILE_ID]
|
||||
self.assertTrue(throughput["built_in"])
|
||||
self.assertEqual(throughput["expected_text"], "")
|
||||
self.assertEqual(throughput["match_mode"], "contains")
|
||||
self.assertFalse(throughput["require_thinking"])
|
||||
|
||||
def test_loads_private_bootstrap_without_admin_credentials(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "bootstrap.json"
|
||||
@@ -177,6 +287,7 @@ class FakeApi:
|
||||
self.fixed_fallback_ids = set(fixed_fallback_ids or [])
|
||||
self.enabled_calls = []
|
||||
self.quality_calls = []
|
||||
self.quality_profile_calls = []
|
||||
self.rotation_calls = []
|
||||
|
||||
def list_nodes(self):
|
||||
@@ -185,8 +296,9 @@ class FakeApi:
|
||||
def fixed_fallback_node_ids(self):
|
||||
return set(self.fixed_fallback_ids)
|
||||
|
||||
def quality_test(self, node_id):
|
||||
def quality_test(self, node_id, profile_id=""):
|
||||
self.quality_calls.append(node_id)
|
||||
self.quality_profile_calls.append(profile_id)
|
||||
value = self.results.pop(0)
|
||||
if isinstance(value, Exception):
|
||||
raise value
|
||||
@@ -225,8 +337,8 @@ class GuardTests(unittest.TestCase):
|
||||
lock_file=Path(directory) / "lock",
|
||||
node_ids=("1",),
|
||||
)
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(self.nodes(), [bad, good])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_cycle()
|
||||
@@ -261,7 +373,7 @@ class GuardTests(unittest.TestCase):
|
||||
lock_file=Path(directory) / "lock",
|
||||
node_ids=("1", "2"),
|
||||
)
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(self.nodes(3), [good], fixed_fallback_ids={"1"})
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_active_cycle()
|
||||
@@ -304,7 +416,7 @@ class GuardTests(unittest.TestCase):
|
||||
self.assert_persisted = bool(persisted["nodes"][node_id]["disabled_by_guard"])
|
||||
return super().set_enabled(node_id, enabled)
|
||||
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
api = ObservingApi(self.nodes(3), [bad])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_active_cycle()
|
||||
@@ -326,7 +438,7 @@ class GuardTests(unittest.TestCase):
|
||||
self.enabled_calls.append((node_id, enabled))
|
||||
raise RuntimeError("backend unavailable")
|
||||
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200, "generationMs": 1500}
|
||||
api = FailingApi(self.nodes(3), [bad])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_active_cycle()
|
||||
@@ -361,7 +473,7 @@ class GuardTests(unittest.TestCase):
|
||||
nodes = self.nodes(2)
|
||||
nodes[0]["enabled"] = False
|
||||
nodes[1]["enabled"] = False
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
good = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(nodes, [good])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
state = guard._state_for("2")
|
||||
@@ -379,7 +491,7 @@ class GuardTests(unittest.TestCase):
|
||||
node_ids=("1",),
|
||||
min_healthy_nodes=3,
|
||||
)
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200}
|
||||
bad = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 1200}
|
||||
api = FakeApi(self.nodes(3), [bad])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_cycle()
|
||||
@@ -398,7 +510,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -411,10 +523,10 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("1", False), ("1", True)])
|
||||
self.assertEqual(api.enabled_calls, [("1", False)])
|
||||
self.assertEqual(api.rotation_calls, [("1", "")])
|
||||
self.assertEqual(api.quality_calls, ["1"])
|
||||
self.assertFalse(guard.state["nodes"]["1"]["disabled_by_guard"])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["1"]["disabled_by_guard"])
|
||||
|
||||
def test_fail_closed_requires_consecutive_probe_errors_then_rotates(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -429,7 +541,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -503,7 +615,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -514,9 +626,10 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("1", False), ("1", True)])
|
||||
self.assertEqual(api.rotation_calls, [])
|
||||
self.assertEqual(api.quality_calls, ["1"])
|
||||
self.assertEqual(api.enabled_calls, [("1", False)])
|
||||
self.assertEqual(api.rotation_calls, [("1", "")])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["1"]["disabled_by_guard"])
|
||||
|
||||
def test_fail_closed_keeps_node_isolated_when_rotated_ip_probe_is_ambiguous(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -531,7 +644,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
ambiguous = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 50,
|
||||
}
|
||||
@@ -553,7 +666,7 @@ class GuardTests(unittest.TestCase):
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"outputTokens": 128,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 100,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
@@ -572,7 +685,7 @@ class GuardTests(unittest.TestCase):
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",))
|
||||
nodes = self.nodes()
|
||||
nodes[0]["enabled"] = False
|
||||
api = FakeApi(nodes, [{"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}])
|
||||
api = FakeApi(nodes, [{"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}])
|
||||
api.connectivity_test = lambda _node_id: {"status": "unhealthy"}
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
state = guard._state_for("1")
|
||||
@@ -596,7 +709,7 @@ class GuardTests(unittest.TestCase):
|
||||
def test_passive_hard_signal_quarantines_immediately_and_ignores_guard_key(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive", node_ids=("2",))
|
||||
healthy = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 100}
|
||||
healthy = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}
|
||||
api = FakeApi(self.nodes(), [healthy], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("guard", "1", 1200, quality_probe=True), self.audit("user", "2", 1200)], "hasMore": False, "nextCursor": ""},
|
||||
@@ -611,32 +724,31 @@ class GuardTests(unittest.TestCase):
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_soft_strikes"], 0)
|
||||
self.assertEqual(guard.state["statistics"]["passive"]["total"], 1)
|
||||
self.assertEqual(guard.state["statistics"]["passive"]["hard"], 1)
|
||||
self.assertEqual(guard.state["nodes"]["2"]["quarantine_source"], "passive")
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_active_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False), ("2", True)])
|
||||
self.assertFalse(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
|
||||
def test_passive_soft_signal_still_requires_active_confirmation(self):
|
||||
def test_passive_soft_signal_quarantines_immediately_without_probe(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive")
|
||||
hard = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 1200}
|
||||
api = FakeApi(self.nodes(), [hard], [
|
||||
api = FakeApi(self.nodes(), [], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user", "2", 600)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
|
||||
def test_passive_signals_quarantine_only_after_consecutive_active_soft_confirmations(self):
|
||||
def test_passive_soft_signal_holds_until_quarantine_window(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive")
|
||||
soft = {"expectedMatched": True, "outputTokens": 100, "outputTokensPerSecond": 600}
|
||||
api = FakeApi(self.nodes(), [soft, soft], [
|
||||
api = FakeApi(self.nodes(), [], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user-1", "2", 600)], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user-2", "2", 600)], "hasMore": False, "nextCursor": ""},
|
||||
@@ -644,12 +756,12 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["active_soft_strikes"], 1)
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2", "2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
|
||||
def test_multiple_passive_hard_signals_only_quarantine_once(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
@@ -665,7 +777,131 @@ class GuardTests(unittest.TestCase):
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_soft_strikes"], 0)
|
||||
|
||||
def test_passive_confirmation_errors_do_not_quarantine(self):
|
||||
def test_passive_hold_restores_only_after_healthy_probe(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", mode="passive")
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 80,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
api = FakeApi(self.nodes(), [good], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user", "2", 2500)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_degrade_repeats"], 1)
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False), ("2", True)])
|
||||
self.assertFalse(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["quarantine_source"], "")
|
||||
|
||||
def test_recovery_always_uses_builtin_quality_marker_profile(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
profiles_path = Path(directory) / "profiles.json"
|
||||
profiles_path.write_text(json.dumps({
|
||||
"version": 1,
|
||||
"active_profile_id": "throughput",
|
||||
"profiles": {
|
||||
"throughput": {
|
||||
"id": "throughput", "built_in": True,
|
||||
"expected_text": "", "match_mode": "contains",
|
||||
},
|
||||
},
|
||||
}), encoding="utf-8")
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json",
|
||||
lock_file=Path(directory) / "lock",
|
||||
profiles_file=profiles_path,
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True, "reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 80, "generationMs": 1500,
|
||||
}
|
||||
nodes = self.nodes()
|
||||
nodes[1]["enabled"] = False
|
||||
api = FakeApi(nodes, [good])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard._state_for("2").update({"disabled_by_guard": True, "quarantined_until": 0})
|
||||
guard._recover_quarantined(nodes[1], time.time(), rotate=False)
|
||||
self.assertEqual(api.quality_profile_calls, [quality_guard.QUALITY_MARKER_PROFILE_ID])
|
||||
self.assertEqual(api.enabled_calls, [("2", True)])
|
||||
|
||||
def test_passive_hold_keeps_isolated_when_recovery_probe_is_unhealthy(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json",
|
||||
lock_file=Path(directory) / "lock",
|
||||
mode="passive",
|
||||
fail_closed=True,
|
||||
)
|
||||
bad = {
|
||||
"expectedMatched": True,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 8000,
|
||||
"generationMs": 50,
|
||||
}
|
||||
api = FakeApi(self.nodes(), [bad], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user", "2", 2500)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["last_reason"], "buffered_burst")
|
||||
|
||||
def test_repeat_passive_degrade_lengthens_hold(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json",
|
||||
lock_file=Path(directory) / "lock",
|
||||
mode="passive",
|
||||
quarantine_seconds=30,
|
||||
)
|
||||
good = {
|
||||
"expectedMatched": True,
|
||||
"reasoningTokens": 40, "outputTokens": 128,
|
||||
"outputTokensPerSecond": 80,
|
||||
"generationMs": 1500,
|
||||
}
|
||||
api = FakeApi(self.nodes(), [good], [
|
||||
{"items": [], "hasMore": False, "nextCursor": ""},
|
||||
{"items": [self.audit("user-1", "2", 2500)], "hasMore": False, "nextCursor": ""},
|
||||
])
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
first_hold = guard.state["nodes"]["2"]["quarantined_until"] - time.time()
|
||||
self.assertGreater(first_hold, 20)
|
||||
self.assertLess(first_hold, 40)
|
||||
guard.state["nodes"]["2"]["quarantined_until"] = 0
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.quality_calls, ["2"])
|
||||
self.assertFalse(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
api.audit_pages.append({"items": [self.audit("user-2", "2", 2500)], "hasMore": False, "nextCursor": ""})
|
||||
before = time.time()
|
||||
guard.run_passive_cycle()
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["passive_degrade_repeats"], 2)
|
||||
second_hold = guard.state["nodes"]["2"]["quarantined_until"] - before
|
||||
self.assertGreaterEqual(second_hold, 55)
|
||||
self.assertLess(second_hold, 70)
|
||||
|
||||
def test_passive_user_anomaly_quarantines_without_waiting_for_probe(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
cfg = config(
|
||||
state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock",
|
||||
@@ -678,8 +914,9 @@ class GuardTests(unittest.TestCase):
|
||||
guard = quality_guard.Guard(cfg, api)
|
||||
guard.run_passive_cycle()
|
||||
guard.run_passive_cycle()
|
||||
self.assertEqual(api.enabled_calls, [])
|
||||
self.assertEqual(guard.state["nodes"]["2"]["error_strikes"], 1)
|
||||
self.assertEqual(api.enabled_calls, [("2", False)])
|
||||
self.assertEqual(api.quality_calls, [])
|
||||
self.assertTrue(guard.state["nodes"]["2"]["disabled_by_guard"])
|
||||
|
||||
@staticmethod
|
||||
def audit(audit_id, node_id, output_tps, quality_probe=False):
|
||||
|
||||
Reference in new issue
Block a user