mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
fix: separate Grok Build and Web proxy transports
This commit is contained in:
1 parent
d626a26db4
commit
9244306352
40 files changed
+1254
-417
No files matched your search
@@ -26,6 +26,7 @@ Thumbs.db
|
||||
|
||||
# Go
|
||||
/.gocache/
|
||||
/.gocache-*/
|
||||
/backend/grok2api
|
||||
/backend/coverage.out
|
||||
*.coverprofile
|
||||
|
||||
@@ -166,7 +166,7 @@ JSON 只接受当前 `accounts` 结构。SSO 不存在自动刷新:上游返
|
||||
|
||||
## Cloudflare And Egress
|
||||
|
||||
- HTTP 使用 Chrome TLS/HTTP2 指纹;Imagine 使用同一代理、User-Agent 和 Cookie Bundle 的 WebSocket 客户端。
|
||||
- Grok Build 使用标准 Go HTTP/TLS 传输并保持 CLI User-Agent;通过代理时仍沿用该传输,不切换成浏览器指纹。Grok Web HTTP 使用 Chrome TLS/HTTP2 指纹;Imagine 使用同一代理、User-Agent 和 Cookie Bundle 的 WebSocket 客户端。
|
||||
- 每次上游 HTTP 请求生成独立 UUID v4 `x-xai-request-id`,并携带与浏览器同源 fetch 一致的最小稳定请求头;不伪造 Client Hints、Sentry、trace 数据或手工 HTTP/2 头顺序。
|
||||
- 设置页支持两种 `x-statsig-id` 来源:手动模式直接使用管理员写入的固定值,不自动失效、刷新或替换;URL 模式会先使用同一账号、出口节点、User-Agent 与 Cookie 访问 `https://grok.com/index`,读取 `grok-site-verification` meta,再把请求 method、path 和 metaContent 发送到配置的签名服务。默认签名 URL 是 `https://grok.wodf.de/sign`。URL 签名按 method/path 缓存;Code 7 会立即强制刷新并替换旧值,刷新失败时保留上一个真实签名,绝不发送随机占位签名。
|
||||
- URL 模式按 `method + path` 在当前实例内共享一份签名,跨账号复用并缓存 1 小时;不同路径不会混用。并发刷新使用 singleflight 合并,缓存最多保存 4096 个路径,过期项会及时清理。签名服务不会收到 SSO、Cloudflare Cookie、提示词或响应正文。公网签名服务必须使用无凭据、查询参数或片段的 HTTPS:443 地址;Docker 单标签服务名、localhost、`.local/.internal` 和私有地址可使用 HTTP/HTTPS 与自定义端口,例如 `http://grok-signer-go:8788/sign`。签名请求不跟随重定向。手动值仅写入,管理接口只返回是否已配置。
|
||||
|
||||
+1
-1
@@ -3,6 +3,7 @@ module github.com/chenyme/grok2api/backend
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/bdandy/go-socks4 v1.2.3
|
||||
github.com/bogdanfinn/fhttp v0.6.8
|
||||
github.com/bogdanfinn/tls-client v1.15.1
|
||||
github.com/bogdanfinn/websocket v1.5.5-barnius
|
||||
@@ -28,7 +29,6 @@ require (
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/bdandy/go-errors v1.2.2 // indirect
|
||||
github.com/bdandy/go-socks4 v1.2.3 // indirect
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect
|
||||
github.com/bogdanfinn/utls v1.7.7-barnius // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
|
||||
@@ -3,7 +3,6 @@ package app
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -26,18 +25,18 @@ const (
|
||||
)
|
||||
|
||||
type startupReport struct {
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
CompletedAt *time.Time `json:"completedAt,omitempty"`
|
||||
Credentials accountapp.CredentialStartupReport `json:"credentials"`
|
||||
CooldownsRestored int `json:"cooldownsRestored"`
|
||||
QuotaRecoveriesRestored int `json:"quotaRecoveriesRestored"`
|
||||
DueWebQuotasQueued int `json:"dueWebQuotasQueued"`
|
||||
StatsigKeysWarmed int `json:"statsigKeysWarmed"`
|
||||
StaleWebQuotasFound int `json:"staleWebQuotasFound"`
|
||||
StaleWebQuotasSynced int `json:"staleWebQuotasSynced"`
|
||||
StaleModelCatalogsFound int `json:"staleModelCatalogsFound"`
|
||||
StaleModelCatalogsSynced int `json:"staleModelCatalogsSynced"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
StartedAt time.Time
|
||||
CompletedAt *time.Time
|
||||
Credentials accountapp.CredentialStartupReport
|
||||
CooldownsRestored int
|
||||
QuotaRecoveriesRestored int
|
||||
DueWebQuotasQueued int
|
||||
StatsigKeysWarmed int
|
||||
StaleWebQuotasFound int
|
||||
StaleWebQuotasSynced int
|
||||
StaleModelCatalogsFound int
|
||||
StaleModelCatalogsSynced int
|
||||
ErrorCount int
|
||||
}
|
||||
|
||||
type startupState struct {
|
||||
@@ -79,18 +78,12 @@ func (s *startupState) updateReport(update func(*startupReport)) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *startupState) recordError(component string, err error) {
|
||||
func (s *startupState) recordError(err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
message := strings.TrimSpace(component + ": " + err.Error())
|
||||
if len(message) > 300 {
|
||||
message = message[:300]
|
||||
}
|
||||
s.updateReport(func(report *startupReport) {
|
||||
if len(report.Errors) < 20 {
|
||||
report.Errors = append(report.Errors, message)
|
||||
}
|
||||
report.ErrorCount++
|
||||
})
|
||||
}
|
||||
|
||||
@@ -107,9 +100,7 @@ func (s *startupState) setStatsig(state, detail string, warmed int) {
|
||||
func (s *startupState) snapshot() (string, time.Time, startupReport, httpserver.ReadinessComponent) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
report := s.report
|
||||
report.Errors = append([]string(nil), report.Errors...)
|
||||
return s.phase, s.updatedAt, report, s.statsig
|
||||
return s.phase, s.updatedAt, s.report, s.statsig
|
||||
}
|
||||
|
||||
func (s *startupState) acceptsTraffic() bool {
|
||||
@@ -128,7 +119,7 @@ func readinessSnapshot(
|
||||
) httpserver.ReadinessSnapshot {
|
||||
phase, updatedAt, report, statsig := state.snapshot()
|
||||
snapshot := httpserver.ReadinessSnapshot{
|
||||
Ready: false, State: phase, UpdatedAt: updatedAt, Startup: report,
|
||||
Ready: false, State: phase, UpdatedAt: updatedAt, Startup: newReadinessStartupReport(report),
|
||||
Components: map[string]httpserver.ReadinessComponent{
|
||||
"runtime_store": {State: "unknown"},
|
||||
"grok_build": {State: "unknown"},
|
||||
@@ -228,6 +219,29 @@ func readinessSnapshot(
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// newReadinessStartupReport 只公开稳定统计,不把启动错误原文暴露到无鉴权就绪端点。
|
||||
func newReadinessStartupReport(report startupReport) *httpserver.ReadinessStartupReport {
|
||||
return &httpserver.ReadinessStartupReport{
|
||||
StartedAt: report.StartedAt,
|
||||
CompletedAt: report.CompletedAt,
|
||||
Credentials: httpserver.ReadinessCredentialReport{
|
||||
SchedulesBackfilled: report.Credentials.SchedulesBackfilled,
|
||||
CriticalFound: report.Credentials.CriticalFound,
|
||||
Refreshed: report.Credentials.Refreshed,
|
||||
Failed: report.Credentials.Failed,
|
||||
},
|
||||
CooldownsRestored: report.CooldownsRestored,
|
||||
QuotaRecoveriesRestored: report.QuotaRecoveriesRestored,
|
||||
DueWebQuotasQueued: report.DueWebQuotasQueued,
|
||||
StatsigKeysWarmed: report.StatsigKeysWarmed,
|
||||
StaleWebQuotasFound: report.StaleWebQuotasFound,
|
||||
StaleWebQuotasSynced: report.StaleWebQuotasSynced,
|
||||
StaleModelCatalogsFound: report.StaleModelCatalogsFound,
|
||||
StaleModelCatalogsSynced: report.StaleModelCatalogsSynced,
|
||||
ErrorCount: report.ErrorCount,
|
||||
}
|
||||
}
|
||||
|
||||
func startupCandidateUsable(candidate accountdomain.RoutingCandidate, now time.Time) bool {
|
||||
credential := candidate.Credential
|
||||
if credential.EncryptedAccessToken == "" || credential.AuthStatus != accountdomain.AuthStatusActive {
|
||||
@@ -261,20 +275,20 @@ func (a *Application) reconcileStartup(ctx context.Context) {
|
||||
|
||||
if _, err := a.clientKeys.CleanupExpiredBilling(recoveryCtx, 1000); err != nil {
|
||||
a.logger.Warn("billing_reservation_cleanup_failed", "error", err)
|
||||
a.startup.recordError("billing_cleanup", err)
|
||||
a.startup.recordError(err)
|
||||
}
|
||||
if err := a.gateway.RecoverVideoJobs(recoveryCtx); err != nil {
|
||||
a.logger.Warn("video_job_recovery_failed", "error", err)
|
||||
a.startup.recordError("video_recovery", err)
|
||||
a.startup.recordError(err)
|
||||
}
|
||||
if _, err := a.accountRepo.PruneExpiredModelQuotaBlocks(recoveryCtx, time.Now().UTC(), 1000); err != nil {
|
||||
a.logger.Warn("model_cooldown_cleanup_failed", "error", err)
|
||||
a.startup.recordError("model_cooldown_cleanup", err)
|
||||
a.startup.recordError(err)
|
||||
}
|
||||
for _, providerValue := range []accountdomain.Provider{accountdomain.ProviderBuild, accountdomain.ProviderWeb} {
|
||||
values, err := a.accountRepo.ListEnabled(recoveryCtx, providerValue)
|
||||
if err != nil {
|
||||
a.startup.recordError("cooldown_restore", err)
|
||||
a.startup.recordError(err)
|
||||
continue
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
@@ -290,7 +304,7 @@ func (a *Application) reconcileStartup(ctx context.Context) {
|
||||
a.startup.updateReport(func(startup *startupReport) { startup.Credentials = report })
|
||||
if err != nil && ctx.Err() == nil {
|
||||
a.logger.Warn("credential_startup_recovery_incomplete", "error", err, "found", report.CriticalFound, "refreshed", report.Refreshed, "failed", report.Failed)
|
||||
a.startup.recordError("credential_recovery", err)
|
||||
a.startup.recordError(err)
|
||||
}
|
||||
a.startup.setPhase("running")
|
||||
a.logger.Info("startup_reconciliation_completed", "credentials_backfilled", report.SchedulesBackfilled, "critical_found", report.CriticalFound, "credentials_refreshed", report.Refreshed, "credentials_failed", report.Failed)
|
||||
@@ -330,7 +344,7 @@ func (a *Application) queueDueWebQuotaRefresh(ctx context.Context) {
|
||||
windows, err := a.accounts.ListDueWebQuotaWindows(ctx, time.Now().UTC(), 1000)
|
||||
if err != nil {
|
||||
a.logger.Warn("web_quota_startup_catchup_failed", "error", err)
|
||||
a.startup.recordError("web_quota_catchup", err)
|
||||
a.startup.recordError(err)
|
||||
return
|
||||
}
|
||||
for _, window := range windows {
|
||||
|
||||
@@ -2,7 +2,10 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -12,6 +15,19 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
func TestReadinessStartupReportDoesNotExposeInternalErrors(t *testing.T) {
|
||||
state := newStartupState(0)
|
||||
state.recordError(errors.New("postgres://private-host/internal"))
|
||||
_, _, report, _ := state.snapshot()
|
||||
payload, err := json.Marshal(newReadinessStartupReport(report))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(payload), "private-host") || !strings.Contains(string(payload), `"errorCount":1`) {
|
||||
t.Fatalf("public readiness leaked internal error: %s", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessKeepsBuildReadyWhenWebIsUnavailable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "readiness.db"))
|
||||
|
||||
@@ -9,11 +9,12 @@ import (
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
)
|
||||
|
||||
// CredentialStartupReport 汇总启动阶段的凭据调度与恢复结果。
|
||||
type CredentialStartupReport struct {
|
||||
SchedulesBackfilled int `json:"schedulesBackfilled"`
|
||||
CriticalFound int `json:"criticalFound"`
|
||||
Refreshed int `json:"refreshed"`
|
||||
Failed int `json:"failed"`
|
||||
SchedulesBackfilled int
|
||||
CriticalFound int
|
||||
Refreshed int
|
||||
Failed int
|
||||
}
|
||||
|
||||
// ReconcileCredentialSchedules 为升级前账号补齐持久化调度,不解密凭据,也不访问上游。
|
||||
|
||||
@@ -356,7 +356,7 @@ func (s *Service) summary(ctx context.Context, search, rawPeriod string, filter
|
||||
return s.loadSummary(ctx, search, filter, period, start, end)
|
||||
}
|
||||
cacheKey := fmt.Sprintf("%s\x00%s\x00%s\x00%s\x00%s\x00%s\x00%s", period, search, filter.Model, filter.Status, filter.Mode, filter.Key, filter.Account)
|
||||
return s.summaryCache.Load(cacheKey, end, func() (SummaryResult, error) {
|
||||
return s.summaryCache.Load(ctx, cacheKey, end, func() (SummaryResult, error) {
|
||||
return s.loadSummary(ctx, search, filter, period, start, end)
|
||||
})
|
||||
}
|
||||
@@ -502,7 +502,12 @@ func (s *Service) persistBatch(records []auditdomain.Record) {
|
||||
return
|
||||
}
|
||||
if attempt < auditWriteAttempts {
|
||||
time.Sleep(time.Duration(attempt) * 100 * time.Millisecond)
|
||||
timer := time.NewTimer(time.Duration(attempt) * 100 * time.Millisecond)
|
||||
select {
|
||||
case <-s.stop:
|
||||
timer.Stop()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
dropped := s.dropped.Add(uint64(len(records)))
|
||||
|
||||
@@ -106,7 +106,7 @@ func (s *Service) get(ctx context.Context, rawPeriod, rawTimezone string, useCac
|
||||
return s.load(ctx, period, bucketCount, bucketDays, location, rawNow)
|
||||
}
|
||||
cacheKey := string(period) + "\x00" + location.String()
|
||||
return s.cache.Load(cacheKey, rawNow, func() (Result, error) {
|
||||
return s.cache.Load(ctx, cacheKey, rawNow, func() (Result, error) {
|
||||
return s.load(ctx, period, bucketCount, bucketDays, location, rawNow)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -245,16 +245,16 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.UpstreamModel, "", true)
|
||||
if err != nil {
|
||||
if parent.Err() != nil {
|
||||
s.deferVideoJob(job)
|
||||
s.deferVideoJob(parent, job)
|
||||
return
|
||||
}
|
||||
s.failVideoJob(job, "account_unavailable", err)
|
||||
s.failVideoJob(parent, job, "account_unavailable", err)
|
||||
return
|
||||
}
|
||||
defer lease.Release()
|
||||
adapter, ok := s.providers.Videos(route.Provider)
|
||||
if !ok {
|
||||
s.failVideoJob(job, "provider_unavailable", ErrNoAvailableAccount)
|
||||
s.failVideoJob(parent, job, "provider_unavailable", ErrNoAvailableAccount)
|
||||
return
|
||||
}
|
||||
lastProgress := job.Progress
|
||||
@@ -277,20 +277,20 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
})
|
||||
if err != nil {
|
||||
if parent.Err() != nil {
|
||||
s.deferVideoJob(job)
|
||||
s.deferVideoJob(parent, job)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, provider.ErrUnauthorized) {
|
||||
_ = s.accounts.MarkReauthRequired(context.Background(), lease.Credential.ID, "Grok Web SSO credential rejected")
|
||||
}
|
||||
s.selector.MarkFailure(context.Background(), lease.Credential, 0, 0)
|
||||
s.failVideoJob(job, "generation_failed", err)
|
||||
s.failVideoJob(parent, job, "generation_failed", err)
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
job.Status, job.Progress, job.UpstreamURL, job.ContentType = media.StatusCompleted, 100, result.URL, result.ContentType
|
||||
job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now
|
||||
if err := s.persistVideoJobWithRetry(job); err != nil {
|
||||
if err := s.persistVideoJobWithRetry(parent, job); err != nil {
|
||||
s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", err)
|
||||
return
|
||||
}
|
||||
@@ -365,21 +365,21 @@ func decodeVideoInput(value string) []string {
|
||||
return input["image_urls"]
|
||||
}
|
||||
|
||||
func (s *Service) failVideoJob(job media.Job, code string, err error) {
|
||||
func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, err error) {
|
||||
now := time.Now().UTC()
|
||||
job.Status, job.ErrorCode, job.ErrorMessage = media.StatusFailed, code, err.Error()
|
||||
if len(job.ErrorMessage) > 512 {
|
||||
job.ErrorMessage = job.ErrorMessage[:512]
|
||||
}
|
||||
job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now
|
||||
if updateErr := s.persistVideoJobWithRetry(job); updateErr != nil {
|
||||
if updateErr := s.persistVideoJobWithRetry(ctx, job); updateErr != nil {
|
||||
s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", updateErr)
|
||||
return
|
||||
}
|
||||
s.cancelBillingReservation("video_usage_" + job.ID)
|
||||
}
|
||||
|
||||
func (s *Service) deferVideoJob(job media.Job) {
|
||||
func (s *Service) deferVideoJob(ctx context.Context, job media.Job) {
|
||||
now := time.Now().UTC()
|
||||
leaseUntil := now.Add(5 * time.Minute)
|
||||
job.Status = media.StatusInProgress
|
||||
@@ -387,22 +387,29 @@ func (s *Service) deferVideoJob(job media.Job) {
|
||||
job.UpdatedAt = now
|
||||
job.ErrorCode = ""
|
||||
job.ErrorMessage = ""
|
||||
if err := s.persistVideoJobWithRetry(job); err != nil {
|
||||
if err := s.persistVideoJobWithRetry(ctx, job); err != nil {
|
||||
s.logger.Error("video_job_defer_write_failed", "job_id", job.ID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) persistVideoJobWithRetry(job media.Job) error {
|
||||
// persistVideoJobWithRetry 至少执行一次收尾写入;后续退避可被工作进程关闭信号取消。
|
||||
func (s *Service) persistVideoJobWithRetry(ctx context.Context, job media.Job) error {
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
lastErr = s.mediaJobs.UpdateMediaJob(ctx, job)
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
|
||||
lastErr = s.mediaJobs.UpdateMediaJob(writeCtx, job)
|
||||
cancel()
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
if attempt < 3 {
|
||||
time.Sleep(time.Duration(attempt) * 100 * time.Millisecond)
|
||||
timer := time.NewTimer(time.Duration(attempt) * 100 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return errors.Join(lastErr, ctx.Err())
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
|
||||
@@ -330,7 +330,9 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config,
|
||||
next.Provider.Build.BaseURL = strings.TrimSpace(input.ProviderBuild.BaseURL)
|
||||
next.Provider.Build.ClientVersion = strings.TrimSpace(input.ProviderBuild.ClientVersion)
|
||||
next.Provider.Build.ClientIdentifier = strings.TrimSpace(input.ProviderBuild.ClientIdentifier)
|
||||
next.Provider.Build.TokenAuth = strings.TrimSpace(input.ProviderBuild.TokenAuth)
|
||||
if tokenAuth := strings.TrimSpace(input.ProviderBuild.TokenAuth); tokenAuth != "" {
|
||||
next.Provider.Build.TokenAuth = tokenAuth
|
||||
}
|
||||
next.Provider.Build.UserAgent = strings.TrimSpace(input.ProviderBuild.UserAgent)
|
||||
next.Provider.Web.BaseURL = strings.TrimSpace(input.ProviderWeb.BaseURL)
|
||||
next.Provider.Web.StatsigMode = strings.TrimSpace(input.ProviderWeb.StatsigMode)
|
||||
|
||||
@@ -120,8 +120,8 @@ type QuotaWindow struct {
|
||||
|
||||
// QuotaBreakdown 保存上游周额度中的产品枚举及其使用百分比。
|
||||
type QuotaBreakdown struct {
|
||||
ProductCode int `json:"productCode"`
|
||||
UsagePercent float64 `json:"usagePercent"`
|
||||
ProductCode int
|
||||
UsagePercent float64
|
||||
}
|
||||
|
||||
const (
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/bdandy/go-socks4"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
// newBuildClient keeps Grok Build on the standard Go HTTP/TLS stack used by
|
||||
// the official CLI-facing transport. Browser TLS impersonation is reserved for
|
||||
// Grok Web, where the browser fingerprint and User-Agent belong together.
|
||||
func newBuildClient(proxyURL string) (*http.Client, error) {
|
||||
direct := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: direct.DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 256,
|
||||
MaxIdleConnsPerHost: 128,
|
||||
MaxConnsPerHost: 256,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ResponseHeaderTimeout: 30 * time.Second,
|
||||
ExpectContinueTimeout: time.Second,
|
||||
}
|
||||
if strings.TrimSpace(proxyURL) != "" {
|
||||
parsed, err := url.Parse(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 Grok Build 出口代理: %w", err)
|
||||
}
|
||||
switch strings.ToLower(parsed.Scheme) {
|
||||
case "http", "https":
|
||||
transport.Proxy = http.ProxyURL(parsed)
|
||||
case "socks4", "socks4a", "socks5", "socks5h":
|
||||
dialer, err := xproxy.FromURL(parsed, direct)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建 Grok Build SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialContext(dialer)
|
||||
default:
|
||||
return nil, fmt.Errorf("Grok Build 不支持代理协议 %q", parsed.Scheme)
|
||||
}
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func dialContext(dialer xproxy.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
||||
if contextual, ok := dialer.(xproxy.ContextDialer); ok {
|
||||
return contextual.DialContext
|
||||
}
|
||||
type result struct {
|
||||
connection net.Conn
|
||||
err error
|
||||
}
|
||||
return func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
completed := make(chan result, 1)
|
||||
go func() {
|
||||
connection, err := dialer.Dial(network, address)
|
||||
completed <- result{connection: connection, err: err}
|
||||
}()
|
||||
select {
|
||||
case value := <-completed:
|
||||
return value.connection, value.err
|
||||
case <-ctx.Done():
|
||||
go func() {
|
||||
value := <-completed
|
||||
if value.connection != nil {
|
||||
_ = value.connection.Close()
|
||||
}
|
||||
}()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewBuildClientUsesStandardTransportForEveryProxyFamily(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
proxyURL string
|
||||
httpProxy bool
|
||||
}{
|
||||
{name: "direct"},
|
||||
{name: "http", proxyURL: "http://user:password@127.0.0.1:8080", httpProxy: true},
|
||||
{name: "https", proxyURL: "https://proxy.example:8443", httpProxy: true},
|
||||
{name: "socks4", proxyURL: "socks4://127.0.0.1:1080"},
|
||||
{name: "socks4a", proxyURL: "socks4a://proxy.example:1080"},
|
||||
{name: "socks5", proxyURL: "socks5://127.0.0.1:1080"},
|
||||
{name: "socks5h warp", proxyURL: "socks5h://warp:1080"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
client, err := newBuildClient(test.proxyURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport, ok := client.Transport.(*http.Transport)
|
||||
if !ok {
|
||||
t.Fatalf("transport = %T, want *http.Transport", client.Transport)
|
||||
}
|
||||
if transport.ForceAttemptHTTP2 != true || transport.DialContext == nil {
|
||||
t.Fatalf("standard transport not fully configured: %#v", transport)
|
||||
}
|
||||
if (transport.Proxy != nil) != test.httpProxy {
|
||||
t.Fatalf("http proxy callback configured=%v, want %v", transport.Proxy != nil, test.httpProxy)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewBuildClientRejectsUnsupportedProxyScheme(t *testing.T) {
|
||||
if _, err := newBuildClient("ftp://proxy.example:21"); err == nil {
|
||||
t.Fatal("unsupported proxy scheme was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildClientRoutesThroughSOCKS5HWithRemoteDNS(t *testing.T) {
|
||||
target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Header.Get("User-Agent") != "grok-shell/0.2.99 (linux; x86_64)" {
|
||||
t.Errorf("User-Agent = %q", request.Header.Get("User-Agent"))
|
||||
}
|
||||
writer.Header().Set("Connection", "close")
|
||||
_, _ = io.WriteString(writer, "ok")
|
||||
}))
|
||||
defer target.Close()
|
||||
upstreamAddress := strings.TrimPrefix(target.URL, "http://")
|
||||
_, upstreamPort, err := net.SplitHostPort(upstreamAddress)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
requestedHost := make(chan string, 1)
|
||||
proxyDone := make(chan error, 1)
|
||||
go func() { proxyDone <- serveSOCKS5TunnelOnce(listener, upstreamAddress, requestedHost) }()
|
||||
|
||||
client, err := newBuildClient("socks5h://" + listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodGet, "http://cli-chat-proxy.grok.test:"+upstreamPort+"/v1/models", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Close = true
|
||||
request.Header.Set("User-Agent", "grok-shell/0.2.99 (linux; x86_64)")
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := io.ReadAll(response.Body)
|
||||
_ = response.Body.Close()
|
||||
if err != nil || string(body) != "ok" {
|
||||
t.Fatalf("body=%q err=%v", body, err)
|
||||
}
|
||||
select {
|
||||
case host := <-requestedHost:
|
||||
if host != "cli-chat-proxy.grok.test" {
|
||||
t.Fatalf("SOCKS target host = %q", host)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("SOCKS proxy did not receive a target hostname")
|
||||
}
|
||||
select {
|
||||
case err := <-proxyDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("SOCKS proxy did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
func serveSOCKS5TunnelOnce(listener net.Listener, upstreamAddress string, requestedHost chan<- string) error {
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer connection.Close()
|
||||
_ = connection.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
var greeting [2]byte
|
||||
if _, err := io.ReadFull(connection, greeting[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if greeting[0] != 5 {
|
||||
return fmt.Errorf("SOCKS version = %d", greeting[0])
|
||||
}
|
||||
methods := make([]byte, int(greeting[1]))
|
||||
if _, err := io.ReadFull(connection, methods); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := connection.Write([]byte{5, 0}); err != nil {
|
||||
return err
|
||||
}
|
||||
var header [4]byte
|
||||
if _, err := io.ReadFull(connection, header[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if header[0] != 5 || header[1] != 1 {
|
||||
return fmt.Errorf("SOCKS request header = %v", header)
|
||||
}
|
||||
host, err := readSOCKS5Host(connection, header[3])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var port [2]byte
|
||||
if _, err := io.ReadFull(connection, port[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = binary.BigEndian.Uint16(port[:])
|
||||
requestedHost <- host
|
||||
|
||||
upstream, err := net.DialTimeout("tcp", upstreamAddress, 2*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer upstream.Close()
|
||||
_ = upstream.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := connection.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 0}); err != nil {
|
||||
return err
|
||||
}
|
||||
copyDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, copyErr := io.Copy(upstream, connection)
|
||||
copyDone <- copyErr
|
||||
}()
|
||||
_, downstreamErr := io.Copy(connection, upstream)
|
||||
upstreamErr := <-copyDone
|
||||
if downstreamErr != nil && !isClosedNetworkError(downstreamErr) {
|
||||
return downstreamErr
|
||||
}
|
||||
if upstreamErr != nil && !isClosedNetworkError(upstreamErr) {
|
||||
return upstreamErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readSOCKS5Host(reader io.Reader, addressType byte) (string, error) {
|
||||
switch addressType {
|
||||
case 1:
|
||||
value := make([]byte, net.IPv4len)
|
||||
_, err := io.ReadFull(reader, value)
|
||||
return net.IP(value).String(), err
|
||||
case 3:
|
||||
var size [1]byte
|
||||
if _, err := io.ReadFull(reader, size[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
value := make([]byte, int(size[0]))
|
||||
_, err := io.ReadFull(reader, value)
|
||||
return string(value), err
|
||||
case 4:
|
||||
value := make([]byte, net.IPv6len)
|
||||
_, err := io.ReadFull(reader, value)
|
||||
return net.IP(value).String(), err
|
||||
default:
|
||||
return "", fmt.Errorf("SOCKS address type = %d", addressType)
|
||||
}
|
||||
}
|
||||
|
||||
func isClosedNetworkError(err error) bool {
|
||||
return err == nil || strings.Contains(strings.ToLower(err.Error()), "closed network connection")
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -23,14 +24,26 @@ const nodeSnapshotTTL = time.Second
|
||||
|
||||
type Lease struct {
|
||||
NodeID uint64
|
||||
Scope domain.Scope
|
||||
ProxyURL string
|
||||
UserAgent string
|
||||
CFCookies string
|
||||
client *browserClient
|
||||
client requestClient
|
||||
browser *browserClient
|
||||
release func()
|
||||
}
|
||||
|
||||
func (l *Lease) Do(request *http.Request) (*http.Response, error) { return l.client.Do(request) }
|
||||
type requestClient interface {
|
||||
Do(*http.Request) (*http.Response, error)
|
||||
CloseIdleConnections()
|
||||
}
|
||||
|
||||
func (l *Lease) Do(request *http.Request) (*http.Response, error) {
|
||||
if l == nil || l.client == nil {
|
||||
return nil, errors.New("出口客户端未初始化")
|
||||
}
|
||||
return l.client.Do(request)
|
||||
}
|
||||
func (l *Lease) Release() {
|
||||
if l != nil && l.release != nil {
|
||||
l.release()
|
||||
@@ -50,7 +63,8 @@ type Manager struct {
|
||||
|
||||
type cachedClient struct {
|
||||
fingerprint string
|
||||
client *browserClient
|
||||
client requestClient
|
||||
browser *browserClient
|
||||
}
|
||||
|
||||
type cachedNodeSnapshot struct {
|
||||
@@ -126,7 +140,7 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
if scope != domain.ScopeBuild && userAgent == "" {
|
||||
userAgent = DefaultUserAgent
|
||||
}
|
||||
client, err := m.clientFor(selected.ID, proxyURL, userAgent, cookies)
|
||||
client, err := m.clientFor(selected.ID, scope, proxyURL, userAgent, cookies)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
@@ -134,7 +148,7 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
m.inflight[selected.ID]++
|
||||
m.mu.Unlock()
|
||||
var once sync.Once
|
||||
return &Lease{NodeID: selected.ID, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client, release: func() {
|
||||
return &Lease{NodeID: selected.ID, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, release: func() {
|
||||
once.Do(func() {
|
||||
m.mu.Lock()
|
||||
m.inflight[selected.ID]--
|
||||
@@ -216,26 +230,49 @@ func (m *Manager) selectNode(nodes []domain.Node, affinity string) domain.Node {
|
||||
return best
|
||||
}
|
||||
|
||||
func (m *Manager) clientFor(id uint64, proxyURL, userAgent, cookies string) (*browserClient, error) {
|
||||
fingerprint := fmt.Sprintf("%x", sha256.Sum256([]byte(proxyURL+"\x00"+userAgent+"\x00"+cookies)))
|
||||
func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent, cookies string) (cachedClient, error) {
|
||||
clientKind := "browser"
|
||||
if scope == domain.ScopeBuild {
|
||||
clientKind = "build"
|
||||
}
|
||||
fingerprint := fmt.Sprintf("%x", sha256.Sum256([]byte(clientKind+"\x00"+proxyURL+"\x00"+userAgent+"\x00"+cookies)))
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if cached, ok := m.clients[id]; ok && cached.fingerprint == fingerprint {
|
||||
return cached.client, nil
|
||||
return cached, nil
|
||||
}
|
||||
client, err := newBrowserClient(proxyURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
var value cachedClient
|
||||
value.fingerprint = fingerprint
|
||||
if scope == domain.ScopeBuild {
|
||||
client, err := newBuildClient(proxyURL)
|
||||
if err != nil {
|
||||
return cachedClient{}, err
|
||||
}
|
||||
value.client = client
|
||||
} else {
|
||||
client, err := newBrowserClient(proxyURL)
|
||||
if err != nil {
|
||||
return cachedClient{}, err
|
||||
}
|
||||
value.client = client
|
||||
value.browser = client
|
||||
}
|
||||
m.clients[id] = cachedClient{fingerprint: fingerprint, client: client}
|
||||
return client, nil
|
||||
if previous, exists := m.clients[id]; exists && previous.client != nil {
|
||||
previous.client.CloseIdleConnections()
|
||||
}
|
||||
m.clients[id] = value
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Feedback(ctx context.Context, nodeID uint64, status int, transportErr error) {
|
||||
m.FeedbackForScope(ctx, domain.ScopeWeb, nodeID, status, transportErr)
|
||||
}
|
||||
|
||||
func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, nodeID uint64, status int, transportErr error) {
|
||||
if nodeID == 0 {
|
||||
if transportErr != nil || status == http.StatusForbidden || status >= 500 {
|
||||
if transportErr != nil || status >= 500 || (scope != domain.ScopeBuild && status == http.StatusForbidden) {
|
||||
m.mu.Lock()
|
||||
delete(m.clients, 0)
|
||||
m.invalidateClientLocked(0)
|
||||
m.mu.Unlock()
|
||||
}
|
||||
return
|
||||
@@ -253,13 +290,17 @@ func (m *Manager) Feedback(ctx context.Context, nodeID uint64, status int, trans
|
||||
value.LastError = ""
|
||||
case status == http.StatusUnauthorized || status == http.StatusTooManyRequests:
|
||||
return
|
||||
case scope == domain.ScopeBuild && status == http.StatusForbidden:
|
||||
// Build 403 可能是账号权限、额度、Token 或出口策略,响应体由网关层
|
||||
// 分类;仅凭状态码不能把标准 CLI 出口误判为 Web anti-bot。
|
||||
return
|
||||
case status == http.StatusForbidden:
|
||||
value.FailureCount++
|
||||
value.Health = max(0.05, value.Health*0.7)
|
||||
value.CooldownUntil = nil
|
||||
value.LastError = "anti-bot rejection"
|
||||
m.mu.Lock()
|
||||
delete(m.clients, nodeID)
|
||||
m.invalidateClientLocked(nodeID)
|
||||
m.mu.Unlock()
|
||||
default:
|
||||
value.FailureCount++
|
||||
@@ -273,7 +314,7 @@ func (m *Manager) Feedback(ctx context.Context, nodeID uint64, status int, trans
|
||||
value.LastError = fmt.Sprintf("upstream status %d", status)
|
||||
}
|
||||
m.mu.Lock()
|
||||
delete(m.clients, nodeID)
|
||||
m.invalidateClientLocked(nodeID)
|
||||
m.mu.Unlock()
|
||||
}
|
||||
if _, err := m.repository.UpdateEgressNode(ctx, value); err == nil {
|
||||
@@ -281,6 +322,13 @@ func (m *Manager) Feedback(ctx context.Context, nodeID uint64, status int, trans
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) invalidateClientLocked(nodeID uint64) {
|
||||
if cached, exists := m.clients[nodeID]; exists && cached.client != nil {
|
||||
cached.client.CloseIdleConnections()
|
||||
}
|
||||
delete(m.clients, nodeID)
|
||||
}
|
||||
|
||||
func BuildSSOCookie(token, cloudflareCookies string) string {
|
||||
token = strings.TrimSpace(token)
|
||||
if strings.HasPrefix(strings.ToLower(token), "sso=") {
|
||||
|
||||
@@ -69,8 +69,12 @@ func TestConfiguredBuildNodeDoesNotOverrideProviderUserAgent(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encryptedProxy, err := cipher.Encrypt("socks5h://warp:1080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{{
|
||||
ID: 1, Name: "build", Scope: domain.ScopeBuild, Enabled: true, Health: 1, UserAgent: "legacy-build-agent",
|
||||
ID: 1, Name: "build", Scope: domain.ScopeBuild, Enabled: true, Health: 1, UserAgent: "legacy-build-agent", EncryptedProxyURL: encryptedProxy,
|
||||
}}}, cipher)
|
||||
lease, configured, err := manager.AcquireIfConfigured(context.Background(), domain.ScopeBuild, "")
|
||||
if err != nil {
|
||||
@@ -83,6 +87,72 @@ func TestConfiguredBuildNodeDoesNotOverrideProviderUserAgent(t *testing.T) {
|
||||
if lease.UserAgent != "" {
|
||||
t.Fatalf("build lease userAgent = %q", lease.UserAgent)
|
||||
}
|
||||
if _, ok := lease.client.(*http.Client); !ok || lease.browser != nil || lease.Scope != domain.ScopeBuild {
|
||||
t.Fatalf("build lease client=%T browser=%p scope=%q", lease.client, lease.browser, lease.Scope)
|
||||
}
|
||||
if _, _, err := lease.DialWebSocket(context.Background(), "wss://example.com", nil, time.Second); err == nil {
|
||||
t.Fatal("build lease unexpectedly exposed browser WebSocket")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredWebNodeKeepsChromeBrowserTransport(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{{
|
||||
ID: 1, Name: "web", Scope: domain.ScopeWeb, Enabled: true, Health: 1,
|
||||
}}}, cipher)
|
||||
lease, err := manager.Acquire(context.Background(), domain.ScopeWeb, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if _, ok := lease.client.(*browserClient); !ok || lease.browser == nil || lease.Scope != domain.ScopeWeb {
|
||||
t.Fatalf("web lease client=%T browser=%p scope=%q", lease.client, lease.browser, lease.Scope)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildForbiddenDoesNotPoisonEgressNode(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := &mutableEgressRepository{node: domain.Node{ID: 1, Name: "build", Scope: domain.ScopeBuild, Enabled: true, Health: 1}}
|
||||
manager := NewManager(repository, cipher)
|
||||
lease, _, err := manager.AcquireIfConfigured(context.Background(), domain.ScopeBuild, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease.Release()
|
||||
manager.FeedbackForScope(context.Background(), domain.ScopeBuild, 1, http.StatusForbidden, nil)
|
||||
if repository.updates != 0 || repository.node.Health != 1 || repository.node.LastError != "" {
|
||||
t.Fatalf("build 403 poisoned node: updates=%d node=%#v", repository.updates, repository.node)
|
||||
}
|
||||
if _, exists := manager.clients[1]; !exists {
|
||||
t.Fatal("build client was invalidated by an ambiguous 403")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebForbiddenStillRebuildsBrowserSession(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := &mutableEgressRepository{node: domain.Node{ID: 1, Name: "web", Scope: domain.ScopeWeb, Enabled: true, Health: 1}}
|
||||
manager := NewManager(repository, cipher)
|
||||
lease, err := manager.Acquire(context.Background(), domain.ScopeWeb, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease.Release()
|
||||
manager.Feedback(context.Background(), 1, http.StatusForbidden, nil)
|
||||
if repository.updates != 1 || repository.node.Health >= 1 || repository.node.LastError != "anti-bot rejection" {
|
||||
t.Fatalf("web 403 feedback = updates=%d node=%#v", repository.updates, repository.node)
|
||||
}
|
||||
if _, exists := manager.clients[1]; exists {
|
||||
t.Fatal("web browser session was not invalidated after 403")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebAssetFallsBackToWeb(t *testing.T) {
|
||||
@@ -93,6 +163,11 @@ func TestWebAssetFallsBackToWeb(t *testing.T) {
|
||||
manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{
|
||||
{ID: 2, Name: "web", Scope: domain.ScopeWeb, Enabled: true, Health: 1},
|
||||
}}, cipher)
|
||||
webLease, err := manager.Acquire(context.Background(), domain.ScopeWeb, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer webLease.Release()
|
||||
lease, err := manager.Acquire(context.Background(), domain.ScopeWebAsset, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -101,6 +176,9 @@ func TestWebAssetFallsBackToWeb(t *testing.T) {
|
||||
if lease.NodeID != 2 {
|
||||
t.Fatalf("node = %d, want web fallback node 2", lease.NodeID)
|
||||
}
|
||||
if lease.client != webLease.client {
|
||||
t.Fatal("Web Asset fallback did not reuse the matching Web browser session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressNodeSnapshotAvoidsRepeatedRepositoryReads(t *testing.T) {
|
||||
@@ -125,6 +203,44 @@ type countingEgressRepository struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
type mutableEgressRepository struct {
|
||||
node domain.Node
|
||||
updates int
|
||||
}
|
||||
|
||||
func (r *mutableEgressRepository) ListEgressNodes(_ context.Context, scope domain.Scope, _ repository.SortQuery) ([]domain.Node, error) {
|
||||
if scope != "" && r.node.Scope != scope {
|
||||
return nil, nil
|
||||
}
|
||||
return []domain.Node{r.node}, nil
|
||||
}
|
||||
|
||||
func (r *mutableEgressRepository) GetEgressNode(_ context.Context, id uint64) (domain.Node, error) {
|
||||
if r.node.ID != id {
|
||||
return domain.Node{}, errors.New("not found")
|
||||
}
|
||||
return r.node, nil
|
||||
}
|
||||
|
||||
func (r *mutableEgressRepository) CreateEgressNode(_ context.Context, value domain.Node) (domain.Node, error) {
|
||||
r.node = value
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *mutableEgressRepository) UpdateEgressNode(_ context.Context, value domain.Node) (domain.Node, error) {
|
||||
r.node = value
|
||||
r.updates++
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *mutableEgressRepository) DeleteEgressNode(_ context.Context, id uint64) error {
|
||||
if r.node.ID != id {
|
||||
return errors.New("not found")
|
||||
}
|
||||
r.node = domain.Node{}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *countingEgressRepository) ListEgressNodes(ctx context.Context, scope domain.Scope, sort repository.SortQuery) ([]domain.Node, error) {
|
||||
r.calls++
|
||||
return r.egressRepositoryTestStub.ListEgressNodes(ctx, scope, sort)
|
||||
|
||||
@@ -2,6 +2,7 @@ package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -15,10 +16,13 @@ import (
|
||||
type browserClient struct{ inner tlsclient.HttpClient }
|
||||
|
||||
func (l *Lease) DialWebSocket(ctx context.Context, endpoint string, headers fhttp.Header, handshakeTimeout time.Duration) (*websocket.Conn, *fhttp.Response, error) {
|
||||
if l == nil || l.browser == nil {
|
||||
return nil, nil, errors.New("当前出口客户端不支持浏览器 WebSocket")
|
||||
}
|
||||
dialer := &websocket.Dialer{
|
||||
HandshakeTimeout: handshakeTimeout,
|
||||
NetDialTLSContext: l.client.inner.GetTLSDialer(),
|
||||
NetDialContext: l.client.inner.GetDialer().DialContext,
|
||||
NetDialTLSContext: l.browser.inner.GetTLSDialer(),
|
||||
NetDialContext: l.browser.inner.GetDialer().DialContext,
|
||||
}
|
||||
return dialer.DialContext(ctx, endpoint, headers)
|
||||
}
|
||||
@@ -56,6 +60,12 @@ func (c *browserClient) Do(request *http.Request) (*http.Response, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *browserClient) CloseIdleConnections() {
|
||||
if c != nil && c.inner != nil {
|
||||
c.inner.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func toFHTTPRequest(request *http.Request) (*fhttp.Request, error) {
|
||||
var body io.Reader
|
||||
if request.Body != nil {
|
||||
|
||||
@@ -17,6 +17,11 @@ type AccountRepository struct{ db *Database }
|
||||
|
||||
func NewAccountRepository(db *Database) *AccountRepository { return &AccountRepository{db: db} }
|
||||
|
||||
type quotaBreakdownJSON struct {
|
||||
ProductCode int `json:"productCode"`
|
||||
UsagePercent float64 `json:"usagePercent"`
|
||||
}
|
||||
|
||||
const (
|
||||
accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0 OR billing.credit_usage_percent > 0))`
|
||||
accountFreeSignalPredicate = `(LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.is_unified_billing_user = TRUE OR billing.usage_period_type <> '' OR billing.top_up_method <> '' OR billing.billing_period_start <> '' OR (billing.history_json <> '' AND billing.history_json <> '[]' AND billing.history_json <> 'null'))))`
|
||||
@@ -830,7 +835,11 @@ func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint
|
||||
}
|
||||
}
|
||||
for _, value := range values {
|
||||
breakdownJSON, err := json.Marshal(value.Breakdown)
|
||||
serializedBreakdown := make([]quotaBreakdownJSON, 0, len(value.Breakdown))
|
||||
for _, item := range value.Breakdown {
|
||||
serializedBreakdown = append(serializedBreakdown, quotaBreakdownJSON{ProductCode: item.ProductCode, UsagePercent: item.UsagePercent})
|
||||
}
|
||||
breakdownJSON, err := json.Marshal(serializedBreakdown)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -928,8 +937,12 @@ func (r *AccountRepository) ListStaleWebQuotaAccountIDs(ctx context.Context, bef
|
||||
}
|
||||
|
||||
func toQuotaWindowDomain(row quotaWindowModel) account.QuotaWindow {
|
||||
var breakdown []account.QuotaBreakdown
|
||||
_ = json.Unmarshal([]byte(row.BreakdownJSON), &breakdown)
|
||||
var serializedBreakdown []quotaBreakdownJSON
|
||||
_ = json.Unmarshal([]byte(row.BreakdownJSON), &serializedBreakdown)
|
||||
breakdown := make([]account.QuotaBreakdown, 0, len(serializedBreakdown))
|
||||
for _, item := range serializedBreakdown {
|
||||
breakdown = append(breakdown, account.QuotaBreakdown{ProductCode: item.ProductCode, UsagePercent: item.UsagePercent})
|
||||
}
|
||||
return account.QuotaWindow{
|
||||
AccountID: row.AccountID, Mode: row.Mode, Remaining: row.Remaining, Total: row.Total,
|
||||
UsagePercent: row.UsagePercent, Breakdown: breakdown, WindowSeconds: row.WindowSeconds,
|
||||
|
||||
@@ -27,11 +27,11 @@ func (t *egressTransport) RoundTrip(request *http.Request) (*http.Response, erro
|
||||
}
|
||||
response, err := lease.Do(request)
|
||||
if err != nil {
|
||||
t.manager.Feedback(context.WithoutCancel(request.Context()), lease.NodeID, 0, err)
|
||||
t.manager.FeedbackForScope(context.WithoutCancel(request.Context()), domainegress.ScopeBuild, lease.NodeID, 0, err)
|
||||
lease.Release()
|
||||
return nil, err
|
||||
}
|
||||
t.manager.Feedback(context.WithoutCancel(request.Context()), lease.NodeID, response.StatusCode, nil)
|
||||
t.manager.FeedbackForScope(context.WithoutCancel(request.Context()), domainegress.ScopeBuild, lease.NodeID, response.StatusCode, nil)
|
||||
if response.Body == nil {
|
||||
lease.Release()
|
||||
return response, nil
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package resultcache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -53,16 +54,21 @@ func (c *Cache[K, V]) Get(key K, now time.Time) (V, bool) {
|
||||
return value.value, true
|
||||
}
|
||||
|
||||
// Load 合并同一键的并发加载,避免缓存过期瞬间重复执行昂贵查询。
|
||||
func (c *Cache[K, V]) Load(key K, now time.Time, loader func() (V, error)) (V, error) {
|
||||
// Load 合并同一键的并发加载;等待者可独立取消,不受首个请求生命周期拖累。
|
||||
func (c *Cache[K, V]) Load(ctx context.Context, key K, now time.Time, loader func() (V, error)) (V, error) {
|
||||
if value, ok := c.Get(key, now); ok {
|
||||
return value, nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
if pending, ok := c.loads[key]; ok {
|
||||
c.mu.Unlock()
|
||||
<-pending.done
|
||||
return pending.value, pending.err
|
||||
select {
|
||||
case <-pending.done:
|
||||
return pending.value, pending.err
|
||||
case <-ctx.Done():
|
||||
var zero V
|
||||
return zero, ctx.Err()
|
||||
}
|
||||
}
|
||||
pending := &flight[V]{done: make(chan struct{})}
|
||||
c.loads[key] = pending
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package resultcache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -37,7 +39,7 @@ func TestCacheCoalescesConcurrentLoads(t *testing.T) {
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
value, err := cache.Load("shared", now, func() (int, error) {
|
||||
value, err := cache.Load(context.Background(), "shared", now, func() (int, error) {
|
||||
calls.Add(1)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
return 42, nil
|
||||
@@ -54,3 +56,31 @@ func TestCacheCoalescesConcurrentLoads(t *testing.T) {
|
||||
t.Fatalf("calls = %d, results = %#v", calls.Load(), results)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheWaiterHonorsCancellation(t *testing.T) {
|
||||
cache := New[string, int](2, time.Minute)
|
||||
loaderStarted := make(chan struct{})
|
||||
releaseLoader := make(chan struct{})
|
||||
loaderDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(loaderDone)
|
||||
_, _ = cache.Load(context.Background(), "shared", time.Now(), func() (int, error) {
|
||||
close(loaderStarted)
|
||||
<-releaseLoader
|
||||
return 42, nil
|
||||
})
|
||||
}()
|
||||
<-loaderStarted
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := cache.Load(ctx, "shared", time.Now(), func() (int, error) {
|
||||
t.Fatal("canceled waiter unexpectedly became the loader")
|
||||
return 0, nil
|
||||
}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("load error = %v, want context canceled", err)
|
||||
}
|
||||
|
||||
close(releaseLoader)
|
||||
<-loaderDone
|
||||
}
|
||||
@@ -65,12 +65,37 @@ type ReadinessComponent struct {
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// ReadinessCredentialReport 表示可公开的启动凭据恢复统计。
|
||||
type ReadinessCredentialReport struct {
|
||||
SchedulesBackfilled int `json:"schedulesBackfilled"`
|
||||
CriticalFound int `json:"criticalFound"`
|
||||
Refreshed int `json:"refreshed"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
// ReadinessStartupReport 表示可公开的启动恢复统计,不包含内部错误文本。
|
||||
type ReadinessStartupReport struct {
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
CompletedAt *time.Time `json:"completedAt,omitempty"`
|
||||
Credentials ReadinessCredentialReport `json:"credentials"`
|
||||
CooldownsRestored int `json:"cooldownsRestored"`
|
||||
QuotaRecoveriesRestored int `json:"quotaRecoveriesRestored"`
|
||||
DueWebQuotasQueued int `json:"dueWebQuotasQueued"`
|
||||
StatsigKeysWarmed int `json:"statsigKeysWarmed"`
|
||||
StaleWebQuotasFound int `json:"staleWebQuotasFound"`
|
||||
StaleWebQuotasSynced int `json:"staleWebQuotasSynced"`
|
||||
StaleModelCatalogsFound int `json:"staleModelCatalogsFound"`
|
||||
StaleModelCatalogsSynced int `json:"staleModelCatalogsSynced"`
|
||||
ErrorCount int `json:"errorCount"`
|
||||
}
|
||||
|
||||
// ReadinessSnapshot 表示公开就绪端点的稳定响应契约。
|
||||
type ReadinessSnapshot struct {
|
||||
Ready bool `json:"ready"`
|
||||
State string `json:"state"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Components map[string]ReadinessComponent `json:"components,omitempty"`
|
||||
Startup any `json:"startup,omitempty"`
|
||||
Startup *ReadinessStartupReport `json:"startup,omitempty"`
|
||||
}
|
||||
|
||||
// New 创建完整 HTTP 路由并明确区分公共、管理员和客户端鉴权边界。
|
||||
|
||||
@@ -3,6 +3,7 @@ package settings
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
settingsapp "github.com/chenyme/grok2api/backend/internal/application/settings"
|
||||
@@ -37,11 +38,12 @@ type mediaConfigDTO struct {
|
||||
}
|
||||
|
||||
type providerBuildConfigDTO struct {
|
||||
BaseURL string `json:"baseURL"`
|
||||
ClientVersion string `json:"clientVersion"`
|
||||
ClientIdentifier string `json:"clientIdentifier"`
|
||||
TokenAuth string `json:"tokenAuth"`
|
||||
UserAgent string `json:"userAgent"`
|
||||
BaseURL string `json:"baseURL"`
|
||||
ClientVersion string `json:"clientVersion"`
|
||||
ClientIdentifier string `json:"clientIdentifier"`
|
||||
TokenAuth string `json:"tokenAuth"`
|
||||
TokenAuthConfigured bool `json:"tokenAuthConfigured"`
|
||||
UserAgent string `json:"userAgent"`
|
||||
}
|
||||
|
||||
type providerWebConfigDTO struct {
|
||||
@@ -175,7 +177,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse {
|
||||
Config: settingsConfigDTO{
|
||||
ProviderBuild: providerBuildConfigDTO{
|
||||
BaseURL: config.ProviderBuild.BaseURL, ClientVersion: config.ProviderBuild.ClientVersion,
|
||||
ClientIdentifier: config.ProviderBuild.ClientIdentifier, TokenAuth: config.ProviderBuild.TokenAuth,
|
||||
ClientIdentifier: config.ProviderBuild.ClientIdentifier, TokenAuthConfigured: strings.TrimSpace(config.ProviderBuild.TokenAuth) != "",
|
||||
UserAgent: config.ProviderBuild.UserAgent,
|
||||
},
|
||||
ProviderWeb: providerWebConfigDTO{
|
||||
|
||||
@@ -34,6 +34,17 @@ func TestSettingsResponseDoesNotExposeManualStatsigValue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsResponseDoesNotExposeBuildTokenAuth(t *testing.T) {
|
||||
response := newSettingsResponse(settingsapp.Snapshot{Config: settingsapp.EditableConfig{ProviderBuild: settingsapp.ProviderBuildConfig{TokenAuth: "must-not-leak"}}})
|
||||
data, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(data), "must-not-leak") || !strings.Contains(string(data), `"tokenAuthConfigured":true`) {
|
||||
t.Fatalf("settings response leaked or lost Build token status: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsResponseIncludesRecommendedBuildBaseline(t *testing.T) {
|
||||
response := newSettingsResponse(settingsapp.Snapshot{RecommendedProviderBuild: settingsapp.ProviderBuildRecommendation{
|
||||
ClientVersion: "0.2.99", UserAgent: "grok-shell/0.2.99 (linux; x86_64)",
|
||||
|
||||
@@ -32,4 +32,3 @@ services:
|
||||
|
||||
volumes:
|
||||
grok2api-data:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ModelRouteDTO } from "@/entities/model/types";
|
||||
import { apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { createObjectDecoder, createPaginatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
type ListModelsInput = {
|
||||
@@ -12,6 +13,33 @@ type ListModelsInput = {
|
||||
sortOrder?: SortOrder;
|
||||
};
|
||||
|
||||
const modelRouteValidator = hasShape({
|
||||
id: isString,
|
||||
publicId: isString,
|
||||
provider: isOneOf("grok_build", "grok_web"),
|
||||
upstreamModel: isString,
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video"),
|
||||
origin: isOneOf("catalog", "discovered", "manual"),
|
||||
enabled: isBoolean,
|
||||
accountIds: isArrayOf(isString),
|
||||
bindingMode: isBoolean,
|
||||
supportedAccounts: isNumber,
|
||||
syncedAccounts: isNumber,
|
||||
totalAccounts: isNumber,
|
||||
capabilityKnown: isBoolean,
|
||||
available: isBoolean,
|
||||
lastSyncedAt: isOptional(isString),
|
||||
});
|
||||
const decodeModelRoute = createObjectDecoder<ModelRouteDTO>("model route", {
|
||||
id: isString, publicId: isString, provider: isOneOf("grok_build", "grok_web"), upstreamModel: isString,
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video"), origin: isOneOf("catalog", "discovered", "manual"),
|
||||
enabled: isBoolean, accountIds: isArrayOf(isString), bindingMode: isBoolean, supportedAccounts: isNumber,
|
||||
syncedAccounts: isNumber, totalAccounts: isNumber, capabilityKnown: isBoolean, available: isBoolean, lastSyncedAt: isOptional(isString),
|
||||
});
|
||||
const decodeModelPage = createPaginatedDecoder<ModelRouteDTO>(modelRouteValidator);
|
||||
const modelAccountValidator = hasShape({ id: isString, name: isString });
|
||||
const decodeModelAccounts = createObjectDecoder<{ items: ModelAccountOptionDTO[] }>("model accounts", { items: isArrayOf(modelAccountValidator) });
|
||||
|
||||
export function listModels(input: ListModelsInput): Promise<PaginatedDTO<ModelRouteDTO>> {
|
||||
const query = new URLSearchParams({ page: String(input.page), pageSize: String(input.pageSize) });
|
||||
if (input.search) query.set("search", input.search);
|
||||
@@ -21,11 +49,11 @@ export function listModels(input: ListModelsInput): Promise<PaginatedDTO<ModelRo
|
||||
query.set("sortBy", input.sortBy);
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
return apiRequest<PaginatedDTO<ModelRouteDTO>>(`/api/admin/v1/models?${query}`);
|
||||
return apiRequest(`/api/admin/v1/models?${query}`, {}, decodeModelPage);
|
||||
}
|
||||
|
||||
export function syncModels(): Promise<{ synced: number }> {
|
||||
return apiRequest<{ synced: number }>("/api/admin/v1/models/sync", { method: "POST" });
|
||||
return apiRequest("/api/admin/v1/models/sync", { method: "POST" }, decodeCountResult<{ synced: number }>("synced"));
|
||||
}
|
||||
|
||||
export type ModelAccountOptionDTO = { id: string; name: string };
|
||||
@@ -40,25 +68,25 @@ export type CreateModelInput = {
|
||||
};
|
||||
|
||||
export function listModelAccountOptions(provider: "grok_build" | "grok_web"): Promise<{ items: ModelAccountOptionDTO[] }> {
|
||||
return apiRequest<{ items: ModelAccountOptionDTO[] }>(`/api/admin/v1/models/accounts?provider=${provider}`);
|
||||
return apiRequest(`/api/admin/v1/models/accounts?provider=${provider}`, {}, decodeModelAccounts);
|
||||
}
|
||||
|
||||
export function createModel(input: CreateModelInput): Promise<ModelRouteDTO> {
|
||||
return apiRequest<ModelRouteDTO>("/api/admin/v1/models", { method: "POST", body: input });
|
||||
return apiRequest("/api/admin/v1/models", { method: "POST", body: input }, decodeModelRoute);
|
||||
}
|
||||
|
||||
export function updateModel(id: string, input: { publicId: string; enabled: boolean; accountIds: string[] }): Promise<ModelRouteDTO> {
|
||||
return apiRequest<ModelRouteDTO>(`/api/admin/v1/models/${id}`, { method: "PATCH", body: input });
|
||||
return apiRequest(`/api/admin/v1/models/${id}`, { method: "PATCH", body: input }, decodeModelRoute);
|
||||
}
|
||||
|
||||
export function deleteModel(id: string): Promise<{ deleted: boolean }> {
|
||||
return apiRequest<{ deleted: boolean }>(`/api/admin/v1/models/${id}`, { method: "DELETE" });
|
||||
return apiRequest(`/api/admin/v1/models/${id}`, { method: "DELETE" }, decodeBooleanResult<{ deleted: boolean }>("deleted"));
|
||||
}
|
||||
|
||||
export function deleteModels(ids: string[]): Promise<{ deleted: number }> {
|
||||
return apiRequest<{ deleted: number }>("/api/admin/v1/models", { method: "DELETE", body: { ids } });
|
||||
return apiRequest("/api/admin/v1/models", { method: "DELETE", body: { ids } }, decodeCountResult<{ deleted: number }>("deleted"));
|
||||
}
|
||||
|
||||
export function updateModelsEnabled(ids: string[], enabled: boolean): Promise<{ updated: number }> {
|
||||
return apiRequest<{ updated: number }>("/api/admin/v1/models/batch", { method: "PATCH", body: { ids, enabled } });
|
||||
return apiRequest("/api/admin/v1/models/batch", { method: "PATCH", body: { ids, enabled } }, decodeCountResult<{ updated: number }>("updated"));
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { apiRequest } from "@/shared/api/client";
|
||||
import { createObjectDecoder, isString } from "@/shared/api/decoder";
|
||||
|
||||
export type SystemInfoDTO = {
|
||||
publicApiBaseURL: string;
|
||||
};
|
||||
|
||||
const decodeSystemInfo = createObjectDecoder<SystemInfoDTO>("system info", { publicApiBaseURL: isString });
|
||||
|
||||
export function getSystemInfo(): Promise<SystemInfoDTO> {
|
||||
return apiRequest<SystemInfoDTO>("/api/admin/v1/system");
|
||||
return apiRequest("/api/admin/v1/system", {}, decodeSystemInfo);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { Info } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import type { AccountDTO, BillingDTO, QuotaDTO } from "@/features/accounts/accounts-api";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime, formatNumber } from "@/shared/lib/format";
|
||||
|
||||
export function AccountQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: BillingDTO; locale: string }) {
|
||||
const { t } = useTranslation();
|
||||
if (quota.type === "unknown") {
|
||||
return <span className="text-xs text-muted-foreground">{t("accounts.quotaUnknown")}</span>;
|
||||
}
|
||||
if (quota.type !== "free") {
|
||||
return <BuildQuota quota={quota} billing={billing} locale={locale} />;
|
||||
}
|
||||
|
||||
const percent = Math.min(100, Math.max(0, quota.usagePercent));
|
||||
const used = formatNumber(quota.used, locale, 0);
|
||||
const limit = formatNumber(quota.limit, locale, 0);
|
||||
const isEstimated = !quota.limitKnown;
|
||||
const statusDescription = quota.status === "waitingReset" && quota.nextProbeAt
|
||||
? t("accounts.waitingResetUntil", { time: formatDateTime(quota.nextProbeAt, locale) })
|
||||
: quota.status === "probing"
|
||||
? t("accounts.probingQuota")
|
||||
: quota.confirmed
|
||||
? t("accounts.upstreamConfirmed")
|
||||
: null;
|
||||
const usage = quota.limit > 0
|
||||
? isEstimated ? t("accounts.freeEstimatedUsage", { used, limit }) : `${used} / ${limit} tokens`
|
||||
: t("accounts.freeObservedUsage", { used });
|
||||
|
||||
return (
|
||||
<div className="w-full min-w-0 space-y-1.5">
|
||||
<div className="flex items-start justify-between gap-3 text-[11px] font-normal">
|
||||
<div className="inline-flex min-w-0 items-center gap-1 text-muted-foreground">
|
||||
<span>{usage}</span>
|
||||
{isEstimated ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="inline-flex shrink-0 text-muted-foreground transition-colors hover:text-foreground" aria-label={t("accounts.freeEstimatedDescription")}>
|
||||
<Info className="size-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("accounts.freeEstimatedDescription")}</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="shrink-0 text-muted-foreground">{isEstimated ? "≈" : ""}{formatNumber(quota.usagePercent, locale, 1)}%</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${percent}%` }} /></div>
|
||||
{statusDescription ? <div className="text-[11px] text-muted-foreground">{statusDescription}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: BillingDTO; locale: string }) {
|
||||
const { t } = useTranslation();
|
||||
const hasWeekly = billing?.usagePeriodType === "USAGE_PERIOD_TYPE_WEEKLY";
|
||||
const hasMonthly = quota.limit > 0;
|
||||
if (!hasWeekly && !hasMonthly) return <span className="text-xs text-muted-foreground">{t("accounts.paidQuotaUsage")}</span>;
|
||||
|
||||
const weeklyPercent = Math.max(0, Math.min(100, billing?.creditUsagePercent ?? 0));
|
||||
const monthlyPercent = Math.max(0, Math.min(100, quota.usagePercent));
|
||||
const statusDescription = quota.status === "waitingReset" && quota.nextProbeAt
|
||||
? t("accounts.paidWaitingResetUntil", { time: formatDateTime(quota.nextProbeAt, locale) })
|
||||
: quota.status === "probing" ? t("accounts.paidProbingQuota") : null;
|
||||
|
||||
return (
|
||||
<div className="w-full min-w-0 space-y-1.5">
|
||||
<div className={cn("grid w-full min-w-0 divide-x divide-border/70", hasWeekly && hasMonthly ? "grid-cols-2" : "grid-cols-1")}>
|
||||
{hasWeekly ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="min-w-0 px-2 text-left font-normal first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]"><span className="truncate text-muted-foreground">{t("accounts.weeklyQuota")}</span><span className="shrink-0 tabular-nums">{formatNumber(weeklyPercent, locale, 1)}%</span></div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${weeklyPercent}%` }} /></div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.weeklyLimit", { percent: formatNumber(100 - weeklyPercent, locale, 1) })}</div>
|
||||
<div className="text-muted-foreground">{billing?.usagePeriodEnd ? t("accounts.quotaResetAt", { time: formatDateTime(billing.usagePeriodEnd, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{hasMonthly ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="min-w-0 px-2 text-left font-normal first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]"><span className="truncate text-muted-foreground">{t("accounts.monthlyQuota")}</span><span className="shrink-0 tabular-nums">{formatNumber(quota.used, locale, 2)}/{formatNumber(quota.limit, locale, 2)}</span></div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${monthlyPercent}%` }} /></div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.paidQuotaDetails", { remaining: formatNumber(quota.remaining, locale, 2) })}</div>
|
||||
<div className="text-muted-foreground">{billing?.billingPeriodEnd ? t("accounts.quotaResetAt", { time: formatDateTime(billing.billingPeriodEnd, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
{statusDescription ? <div className="text-[11px] text-muted-foreground">{statusDescription}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const visibleWebQuotaModes = ["auto", "fast", "expert", "heavy"] as const;
|
||||
|
||||
export function WebQuota({ windows, locale, tier }: { windows: NonNullable<AccountDTO["quotaWindows"]>; locale: string; tier?: AccountDTO["webTier"] }) {
|
||||
const { t } = useTranslation();
|
||||
if (windows.length === 0) return <span className="text-xs text-muted-foreground">{t("accounts.quotaNotSynced")}</span>;
|
||||
const windowsByMode = new Map(windows.map((window) => [window.mode, window]));
|
||||
const weekly = windowsByMode.get("weekly");
|
||||
if (weekly) return <WeeklyWebQuota window={weekly} locale={locale} t={t} />;
|
||||
|
||||
const fast = windowsByMode.get("fast");
|
||||
if (tier === "basic" && fast) return <WebQuotaMode mode="Fast" window={fast} locale={locale} />;
|
||||
return (
|
||||
<div className="grid w-full min-w-0 grid-cols-4 divide-x divide-border/70">
|
||||
{visibleWebQuotaModes.map((mode) => {
|
||||
const window = windowsByMode.get(mode);
|
||||
if (!window) {
|
||||
return <div key={mode} className="min-w-0 px-2 first:pl-0 last:pr-0"><div className="flex items-center justify-between gap-1 text-[11px]"><span className="truncate capitalize text-muted-foreground">{mode}</span><span className="text-muted-foreground">-</span></div><div className="mt-1.5 h-1.5 rounded-full bg-muted" /></div>;
|
||||
}
|
||||
return <WebQuotaMode key={mode} mode={formatWebQuotaMode(mode)} window={window} locale={locale} compact />;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type WebQuotaWindow = NonNullable<AccountDTO["quotaWindows"]>[number];
|
||||
|
||||
function WeeklyWebQuota({ window, locale, t }: { window: WebQuotaWindow; locale: string; t: TFunction }) {
|
||||
const usedPercent = Math.max(0, Math.min(100, window.usagePercent));
|
||||
const breakdown = (window.breakdown ?? []).filter((item) => item.usagePercent > 0);
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="block w-full min-w-0 text-left">
|
||||
<div className="flex items-center justify-between gap-2 text-[11px]">
|
||||
{breakdown.length > 0 ? <div className="flex min-w-0 items-center gap-2.5 overflow-hidden text-muted-foreground">{breakdown.slice(0, 3).map((item) => <span key={item.productCode} className="flex shrink-0 items-center gap-1"><span className={cn("size-1.5 rounded-full", quotaProductColor(item.productCode))} /><span>{quotaProductLabel(item.productCode, t)}</span><span className="tabular-nums text-foreground">{formatNumber(item.usagePercent, locale, 1)}%</span></span>)}{breakdown.length > 3 ? <span className="shrink-0">+{breakdown.length - 3}</span> : null}</div> : <span className="truncate text-muted-foreground">{t("accounts.weeklyQuota")}</span>}
|
||||
<span className="shrink-0 tabular-nums">{formatNumber(usedPercent, locale, 1)}%</span>
|
||||
</div>
|
||||
<div className="mt-1.5 flex h-1.5 overflow-hidden rounded-full bg-muted">{breakdown.length > 0 ? breakdown.map((item) => <div key={item.productCode} className={cn("h-full shrink-0", quotaProductColor(item.productCode))} style={{ width: `${Math.max(0, Math.min(100, item.usagePercent))}%` }} />) : <div className="h-full bg-primary" style={{ width: `${usedPercent}%` }} />}</div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.webWeeklyQuotaUsage", { remaining: formatNumber(100 - usedPercent, locale, 1) })}</div>
|
||||
<div className="text-muted-foreground">{window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
{breakdown.length > 0 ? <div className="mt-2 grid gap-1 border-t pt-2">{breakdown.map((item) => <div key={item.productCode} className="flex items-center justify-between gap-4"><span className="flex items-center gap-1.5"><span className={cn("size-2 rounded-full", quotaProductColor(item.productCode))} />{quotaProductLabel(item.productCode, t)}</span><span className="tabular-nums">{formatNumber(item.usagePercent, locale, 1)}%</span></div>)}</div> : null}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function WebQuotaMode({ mode, window, locale, compact = false }: { mode: string; window: WebQuotaWindow; locale: string; compact?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const used = Math.max(0, window.total - window.remaining);
|
||||
const percent = window.total > 0 ? Math.max(0, Math.min(100, used / window.total * 100)) : 0;
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className={cn("block w-full min-w-0 text-left", compact && "px-2 first:pl-0 last:pr-0")}>
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]"><span className="truncate text-muted-foreground">{mode}</span><span className="shrink-0 tabular-nums">{formatNumber(used, locale, 0)}/{formatNumber(window.total, locale, 0)}</span></div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${percent}%` }} /></div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent><div>{t("accounts.webModeQuotaRemaining", { mode, remaining: formatNumber(window.remaining, locale, 0) })}</div><div className="text-muted-foreground">{window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}</div></TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function formatWebQuotaMode(mode: string): string {
|
||||
return mode ? mode.charAt(0).toUpperCase() + mode.slice(1) : mode;
|
||||
}
|
||||
|
||||
function quotaProductLabel(code: number, t: TFunction): string {
|
||||
const keys: Record<number, string> = { 0: "thirdParty", 1: "api", 2: "build", 3: "plugins", 4: "chat", 5: "imagine", 6: "voice" };
|
||||
const key = keys[code];
|
||||
return key ? t(`quotaProducts.${key}`) : t("quotaProducts.unknown", { code });
|
||||
}
|
||||
|
||||
function quotaProductColor(code: number): string {
|
||||
const colors: Record<number, string> = { 0: "bg-quota-product-0", 1: "bg-quota-product-1", 2: "bg-quota-product-2", 3: "bg-quota-product-3", 4: "bg-quota-product-4", 5: "bg-quota-product-5", 6: "bg-quota-product-6" };
|
||||
return colors[code] ?? "bg-muted-foreground";
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ApiError, apiDownload, apiEventStream, apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { createObjectDecoder, createPaginatedDecoder, createValidatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder";
|
||||
import { i18n } from "@/shared/i18n";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
@@ -111,6 +112,52 @@ export type DevicePollDTO = {
|
||||
syncFailed?: number;
|
||||
};
|
||||
|
||||
const billingValidator = hasShape({
|
||||
planCode: isOptional(isString), planName: isOptional(isString), monthlyLimit: isNumber, used: isNumber, remaining: isNumber,
|
||||
onDemandCap: isNumber, onDemandUsed: isNumber, prepaidBalance: isNumber, creditUsagePercent: isNumber,
|
||||
isUnifiedBillingUser: isBoolean, topUpMethod: isOptional(isString), usagePeriodType: isOptional(isString),
|
||||
usagePeriodStart: isOptional(isString), usagePeriodEnd: isOptional(isString), billingPeriodStart: isOptional(isString),
|
||||
billingPeriodEnd: isOptional(isString), syncedAt: isString,
|
||||
});
|
||||
const quotaValidator = hasShape({
|
||||
type: isOneOf("free", "paid", "unknown"), source: isOneOf("unknown", "upstreamBilling", "upstreamExhaustion", "responseModel", "billingProfile"),
|
||||
confidence: isOneOf("estimated", "observed", "confirmed", ""), status: isOneOf("active", "waitingReset", "probing"),
|
||||
unit: isOptional(isOneOf("tokens", "credits")), used: isNumber, limit: isNumber, remaining: isNumber, usagePercent: isNumber,
|
||||
limitKnown: isBoolean, windowHours: isOptional(isNumber), observed: isBoolean, confirmed: isBoolean,
|
||||
periodStart: isOptional(isString), periodEnd: isOptional(isString), exhaustedAt: isOptional(isString),
|
||||
nextProbeAt: isOptional(isString), lastConfirmedAt: isOptional(isString),
|
||||
});
|
||||
const quotaBreakdownValidator = hasShape({ productCode: isNumber, usagePercent: isNumber });
|
||||
const quotaWindowValidator = hasShape({
|
||||
mode: isString, remaining: isNumber, total: isNumber, usagePercent: isNumber, breakdown: isOptional(isArrayOf(quotaBreakdownValidator)),
|
||||
windowSeconds: isNumber, resetAt: isOptional(isString), syncedAt: isOptional(isString), source: isOneOf("default", "estimated", "upstream"),
|
||||
});
|
||||
const accountValidator = hasShape({
|
||||
id: isString, provider: isString, authType: isOneOf("oauth", "sso"), webTier: isOptional(isOneOf("auto", "basic", "super", "heavy")),
|
||||
webTierSyncedAt: isOptional(isString), name: isString, email: isOptional(isString), userId: isOptional(isString), teamId: isOptional(isString),
|
||||
enabled: isBoolean, authStatus: isOneOf("active", "reauthRequired"), expiresAt: isOptional(isString), refreshable: isBoolean,
|
||||
refreshDueAt: isOptional(isString), lastRefreshAt: isOptional(isString), refreshFailureCount: isNumber,
|
||||
lastRefreshErrorCode: isOptional(isString), priority: isNumber, maxConcurrent: isNumber, minimumRemaining: isNumber,
|
||||
failureCount: isNumber, cooldownUntil: isOptional(isString), lastError: isOptional(isString), lastUsedAt: isOptional(isString),
|
||||
linkedAccountId: isOptional(isString), linkedAccountName: isOptional(isString), linkedProvider: isOptional(isOneOf("grok_build", "grok_web")),
|
||||
createdAt: isString, billing: isOptional(billingValidator), quota: quotaValidator, quotaWindows: isOptional(isArrayOf(quotaWindowValidator)),
|
||||
});
|
||||
const decodeAccount = createValidatedDecoder<AccountDTO>("account", accountValidator);
|
||||
const decodeAccountPage = createPaginatedDecoder<AccountDTO>(accountValidator);
|
||||
const decodeAccountSummary = createObjectDecoder<AccountSummaryDTO>("account summary", {
|
||||
total: isNumber, available: isNumber, recovering: isNumber, attention: isNumber,
|
||||
providers: isRecordOf(hasShape({ total: isNumber, available: isNumber })),
|
||||
recovery: hasShape({ cooldown: isNumber, waitingReset: isNumber, probing: isNumber }),
|
||||
issues: hasShape({ disabled: isNumber, reauthRequired: isNumber }),
|
||||
});
|
||||
const decodeDeviceSession = createObjectDecoder<DeviceSessionDTO>("device session", {
|
||||
sessionId: isString, userCode: isString, verificationUri: isString, verificationUriComplete: isOptional(isString),
|
||||
intervalSeconds: isNumber, expiresAt: isString,
|
||||
});
|
||||
const decodeDevicePoll = createObjectDecoder<DevicePollDTO>("device poll", {
|
||||
status: isOneOf("pending", "succeeded", "syncFailed"), account: isOptional(accountValidator), synced: isOptional(isNumber), syncFailed: isOptional(isNumber),
|
||||
});
|
||||
|
||||
type ListAccountsInput = {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
@@ -134,27 +181,27 @@ export function listAccounts(input: ListAccountsInput): Promise<PaginatedDTO<Acc
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
query.set("provider", input.provider);
|
||||
return apiRequest<PaginatedDTO<AccountDTO>>(`/api/admin/v1/accounts?${query}`);
|
||||
return apiRequest(`/api/admin/v1/accounts?${query}`, {}, decodeAccountPage);
|
||||
}
|
||||
|
||||
export function getAccountSummary(): Promise<AccountSummaryDTO> {
|
||||
return apiRequest<AccountSummaryDTO>("/api/admin/v1/accounts/summary");
|
||||
return apiRequest("/api/admin/v1/accounts/summary", {}, decodeAccountSummary);
|
||||
}
|
||||
|
||||
export function updateAccount(id: string, input: AccountUpdateInput): Promise<AccountDTO> {
|
||||
return apiRequest<AccountDTO>(`/api/admin/v1/accounts/${id}`, { method: "PATCH", body: input });
|
||||
return apiRequest(`/api/admin/v1/accounts/${id}`, { method: "PATCH", body: input }, decodeAccount);
|
||||
}
|
||||
|
||||
export function deleteAccount(id: string): Promise<{ deleted: boolean }> {
|
||||
return apiRequest<{ deleted: boolean }>(`/api/admin/v1/accounts/${id}`, { method: "DELETE" });
|
||||
return apiRequest(`/api/admin/v1/accounts/${id}`, { method: "DELETE" }, decodeBooleanResult<{ deleted: boolean }>("deleted"));
|
||||
}
|
||||
|
||||
export function refreshAccountBilling(id: string): Promise<AccountDTO> {
|
||||
return apiRequest<AccountDTO>(`/api/admin/v1/accounts/${id}/refresh-billing`, { method: "POST" });
|
||||
return apiRequest(`/api/admin/v1/accounts/${id}/refresh-billing`, { method: "POST" }, decodeAccount);
|
||||
}
|
||||
|
||||
export function refreshAccountToken(id: string): Promise<AccountDTO> {
|
||||
return apiRequest<AccountDTO>(`/api/admin/v1/accounts/${id}/refresh-token`, { method: "POST" });
|
||||
return apiRequest(`/api/admin/v1/accounts/${id}/refresh-token`, { method: "POST" }, decodeAccount);
|
||||
}
|
||||
|
||||
export type AccountBatchResultDTO = { succeeded: number; failed: number };
|
||||
@@ -191,6 +238,13 @@ type AccountTaskStreamPayload = Partial<BuildConversionResultDTO & AccountTaskPr
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const decodeAccountTaskStreamPayload = createObjectDecoder<AccountTaskStreamPayload>("account task event", {
|
||||
created: isOptional(isNumber), linked: isOptional(isNumber), skipped: isOptional(isNumber), failed: isOptional(isNumber),
|
||||
synced: isOptional(isNumber), syncFailed: isOptional(isNumber), completed: isOptional(isNumber), total: isOptional(isNumber),
|
||||
phase: isOptional(isOneOf("importing", "converting", "syncing")), updated: isOptional(isNumber), succeeded: isOptional(isNumber),
|
||||
code: isOptional(isString), message: isOptional(isString),
|
||||
});
|
||||
|
||||
function hasNumericResult(value: AccountTaskStreamPayload, fields: string[]): boolean {
|
||||
return fields.every((field) => {
|
||||
const item = value[field as keyof AccountTaskStreamPayload];
|
||||
@@ -230,12 +284,12 @@ async function runAccountTask<T>(path: string, body: BodyInit | object | undefin
|
||||
}
|
||||
};
|
||||
try {
|
||||
await apiEventStream<AccountTaskStreamPayload>(path, {
|
||||
await apiEventStream(path, {
|
||||
method: "POST",
|
||||
headers: { Accept: "text/event-stream" },
|
||||
body,
|
||||
signal,
|
||||
}, ({ event, data }) => {
|
||||
}, decodeAccountTaskStreamPayload, ({ event, data }) => {
|
||||
if (event === "progress" && typeof data.completed === "number" && typeof data.total === "number") {
|
||||
const phase = data.phase === "importing" || data.phase === "converting" || data.phase === "syncing" ? data.phase : undefined;
|
||||
reportProgress({ completed: data.completed, total: data.total, phase });
|
||||
@@ -290,7 +344,7 @@ export function importWebAccounts(files: readonly File[], onProgress?: (value: A
|
||||
}
|
||||
|
||||
export function refreshAccountQuota(id: string): Promise<AccountDTO> {
|
||||
return apiRequest<AccountDTO>(`/api/admin/v1/accounts/${id}/refresh-quota`, { method: "POST" });
|
||||
return apiRequest(`/api/admin/v1/accounts/${id}/refresh-quota`, { method: "POST" }, decodeAccount);
|
||||
}
|
||||
|
||||
export function exportAccounts(): Promise<Blob> {
|
||||
@@ -298,21 +352,21 @@ export function exportAccounts(): Promise<Blob> {
|
||||
}
|
||||
|
||||
export function updateAccountsEnabled(ids: string[], enabled: boolean, provider: "grok_build" | "grok_web"): Promise<{ updated: number }> {
|
||||
return apiRequest<{ updated: number }>("/api/admin/v1/accounts/batch", { method: "PATCH", body: { ids, enabled, provider } });
|
||||
return apiRequest("/api/admin/v1/accounts/batch", { method: "PATCH", body: { ids, enabled, provider } }, decodeCountResult<{ updated: number }>("updated"));
|
||||
}
|
||||
|
||||
export function refreshAccountsBilling(ids: string[], provider: "grok_build" | "grok_web"): Promise<{ succeeded: number; failed: number }> {
|
||||
return apiRequest<{ succeeded: number; failed: number }>("/api/admin/v1/accounts/batch/refresh-billing", { method: "POST", body: { ids, provider } });
|
||||
return apiRequest("/api/admin/v1/accounts/batch/refresh-billing", { method: "POST", body: { ids, provider } }, createObjectDecoder("account batch", { succeeded: isNumber, failed: isNumber }));
|
||||
}
|
||||
|
||||
export function deleteAccounts(ids: string[], provider: "grok_build" | "grok_web"): Promise<{ deleted: number }> {
|
||||
return apiRequest<{ deleted: number }>("/api/admin/v1/accounts", { method: "DELETE", body: { ids, provider } });
|
||||
return apiRequest("/api/admin/v1/accounts", { method: "DELETE", body: { ids, provider } }, decodeCountResult<{ deleted: number }>("deleted"));
|
||||
}
|
||||
|
||||
export function startDeviceAuthorization(): Promise<DeviceSessionDTO> {
|
||||
return apiRequest<DeviceSessionDTO>("/api/admin/v1/accounts/device/start", { method: "POST" });
|
||||
return apiRequest("/api/admin/v1/accounts/device/start", { method: "POST" }, decodeDeviceSession);
|
||||
}
|
||||
|
||||
export function pollDeviceAuthorization(sessionId: string, signal: AbortSignal): Promise<DevicePollDTO> {
|
||||
return apiRequest<DevicePollDTO>(`/api/admin/v1/accounts/device/${sessionId}/poll`, { method: "POST", signal });
|
||||
return apiRequest(`/api/admin/v1/accounts/device/${sessionId}/poll`, { method: "POST", signal }, decodeDevicePoll);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ArrowRight, CircleCheck, ClipboardPaste, Clock3, Copy, Download, ExternalLink, FileUp, Info, Link2, MoreHorizontal, Pencil, RefreshCw, RotateCw, Search, Trash2, TriangleAlert, Users } from "lucide-react";
|
||||
import { ArrowRight, CircleCheck, ClipboardPaste, Clock3, Copy, Download, ExternalLink, FileUp, Link2, MoreHorizontal, Pencil, RefreshCw, RotateCw, Search, Trash2, TriangleAlert, Users } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { useForm, useWatch } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -55,11 +55,11 @@ import {
|
||||
type AccountDTO,
|
||||
type AccountUpdateInput,
|
||||
type AccountTaskProgressDTO,
|
||||
type BillingDTO,
|
||||
type BuildConversionInput,
|
||||
type DeviceSessionDTO,
|
||||
type QuotaDTO,
|
||||
} from "@/features/accounts/accounts-api";
|
||||
import { AccountQuota, WebQuota } from "@/features/accounts/account-quota";
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return (error instanceof DOMException || error instanceof Error) && error.name === "AbortError";
|
||||
@@ -816,232 +816,6 @@ function AccountMetricPanel({ icon, label, value, detail, loading }: { icon: Rea
|
||||
);
|
||||
}
|
||||
|
||||
function AccountQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: BillingDTO; locale: string }) {
|
||||
const { t } = useTranslation();
|
||||
if (quota.type === "unknown") {
|
||||
return <span className="text-xs text-muted-foreground">{t("accounts.quotaUnknown")}</span>;
|
||||
}
|
||||
|
||||
const isFree = quota.type === "free";
|
||||
if (!isFree) {
|
||||
return <BuildQuota quota={quota} billing={billing} locale={locale} />;
|
||||
}
|
||||
|
||||
const percent = Math.min(100, Math.max(0, quota.usagePercent));
|
||||
const isWaitingReset = quota.status === "waitingReset";
|
||||
const isProbing = quota.status === "probing";
|
||||
const used = formatNumber(quota.used, locale, 0);
|
||||
const limit = formatNumber(quota.limit, locale, 0);
|
||||
const isEstimated = !quota.limitKnown;
|
||||
const statusDescription = isWaitingReset && quota.nextProbeAt
|
||||
? t("accounts.waitingResetUntil", { time: formatDateTime(quota.nextProbeAt, locale) })
|
||||
: isProbing
|
||||
? t("accounts.probingQuota")
|
||||
: quota.confirmed
|
||||
? t("accounts.upstreamConfirmed")
|
||||
: null;
|
||||
const usage = quota.limit > 0
|
||||
? isEstimated
|
||||
? t("accounts.freeEstimatedUsage", { used, limit })
|
||||
: `${used} / ${limit} tokens`
|
||||
: t("accounts.freeObservedUsage", { used });
|
||||
return (
|
||||
<div className="w-full min-w-0 space-y-1.5">
|
||||
<div className="flex items-start justify-between gap-3 text-[11px] font-normal">
|
||||
<div className="inline-flex min-w-0 items-center gap-1 text-muted-foreground">
|
||||
<span>{usage}</span>
|
||||
{isEstimated ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="inline-flex shrink-0 text-muted-foreground transition-colors hover:text-foreground" aria-label={t("accounts.freeEstimatedDescription")}>
|
||||
<Info className="size-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t("accounts.freeEstimatedDescription")}</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="shrink-0 text-muted-foreground">{isEstimated ? "≈" : ""}{formatNumber(quota.usagePercent, locale, 1)}%</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-muted">
|
||||
<div className="h-full bg-emerald-500" style={{ width: `${percent}%` }} />
|
||||
</div>
|
||||
{statusDescription ? <div className="text-[11px] text-muted-foreground">{statusDescription}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: BillingDTO; locale: string }) {
|
||||
const { t } = useTranslation();
|
||||
const hasWeekly = billing?.usagePeriodType === "USAGE_PERIOD_TYPE_WEEKLY";
|
||||
const hasMonthly = quota.limit > 0;
|
||||
if (!hasWeekly && !hasMonthly) {
|
||||
return <span className="text-xs text-muted-foreground">{t("accounts.paidQuotaUsage")}</span>;
|
||||
}
|
||||
|
||||
const weeklyPercent = Math.max(0, Math.min(100, billing?.creditUsagePercent ?? 0));
|
||||
const weeklyRemainingPercent = 100 - weeklyPercent;
|
||||
const monthlyPercent = Math.max(0, Math.min(100, quota.usagePercent));
|
||||
const monthlyUsed = formatNumber(quota.used, locale, 2);
|
||||
const monthlyLimit = formatNumber(quota.limit, locale, 2);
|
||||
const monthlyRemaining = formatNumber(quota.remaining, locale, 2);
|
||||
const statusDescription = quota.status === "waitingReset" && quota.nextProbeAt
|
||||
? t("accounts.paidWaitingResetUntil", { time: formatDateTime(quota.nextProbeAt, locale) })
|
||||
: quota.status === "probing"
|
||||
? t("accounts.paidProbingQuota")
|
||||
: null;
|
||||
return (
|
||||
<div className="w-full min-w-0 space-y-1.5">
|
||||
<div className={cn("grid w-full min-w-0 divide-x divide-border/70", hasWeekly && hasMonthly ? "grid-cols-2" : "grid-cols-1")}>
|
||||
{hasWeekly ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="min-w-0 px-2 text-left font-normal first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]">
|
||||
<span className="truncate text-muted-foreground">{t("accounts.weeklyQuota")}</span>
|
||||
<span className="shrink-0 tabular-nums">{formatNumber(weeklyPercent, locale, 1)}%</span>
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${weeklyPercent}%` }} /></div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.weeklyLimit", { percent: formatNumber(weeklyRemainingPercent, locale, 1) })}</div>
|
||||
<div className="text-muted-foreground">{billing?.usagePeriodEnd ? t("accounts.quotaResetAt", { time: formatDateTime(billing.usagePeriodEnd, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{hasMonthly ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="min-w-0 px-2 text-left font-normal first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]">
|
||||
<span className="truncate text-muted-foreground">{t("accounts.monthlyQuota")}</span>
|
||||
<span className="shrink-0 tabular-nums">{monthlyUsed}/{monthlyLimit}</span>
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${monthlyPercent}%` }} /></div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.paidQuotaDetails", { remaining: monthlyRemaining })}</div>
|
||||
<div className="text-muted-foreground">{billing?.billingPeriodEnd ? t("accounts.quotaResetAt", { time: formatDateTime(billing.billingPeriodEnd, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
{statusDescription ? <div className="text-[11px] text-muted-foreground">{statusDescription}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const visibleWebQuotaModes = ["auto", "fast", "expert", "heavy"] as const;
|
||||
|
||||
function WebQuota({ windows, locale, tier }: { windows: NonNullable<AccountDTO["quotaWindows"]>; locale: string; tier?: AccountDTO["webTier"] }) {
|
||||
const { t } = useTranslation();
|
||||
if (windows.length === 0) return <span className="text-xs text-muted-foreground">{t("accounts.quotaNotSynced")}</span>;
|
||||
const windowsByMode = new Map(windows.map((window) => [window.mode, window]));
|
||||
const weekly = windowsByMode.get("weekly");
|
||||
if (weekly) {
|
||||
const usedPercent = Math.max(0, Math.min(100, weekly.usagePercent));
|
||||
const remainingPercent = 100 - usedPercent;
|
||||
const breakdown = (weekly.breakdown ?? []).filter((item) => item.usagePercent > 0);
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center justify-between gap-2 text-[11px]">
|
||||
{breakdown.length > 0 ? <div className="flex min-w-0 items-center gap-2.5 overflow-hidden text-muted-foreground">
|
||||
{breakdown.slice(0, 3).map((item) => (
|
||||
<span key={item.productCode} className="flex shrink-0 items-center gap-1">
|
||||
<span className={`size-1.5 rounded-full ${quotaProductColor(item.productCode)}`} />
|
||||
<span>{quotaProductLabel(item.productCode, locale)}</span>
|
||||
<span className="tabular-nums text-foreground">{formatNumber(item.usagePercent, locale, 1)}%</span>
|
||||
</span>
|
||||
))}
|
||||
{breakdown.length > 3 ? <span className="shrink-0">+{breakdown.length - 3}</span> : null}
|
||||
</div> : <span className="truncate text-muted-foreground">{t("accounts.weeklyQuota")}</span>}
|
||||
<span className="shrink-0 tabular-nums">{formatNumber(usedPercent, locale, 1)}%</span>
|
||||
</div>
|
||||
<div className="mt-1.5 flex h-1.5 overflow-hidden rounded-full bg-muted">
|
||||
{breakdown.length > 0 ? breakdown.map((item) => (
|
||||
<div key={item.productCode} className={`h-full shrink-0 ${quotaProductColor(item.productCode)}`} style={{ width: `${Math.max(0, Math.min(100, item.usagePercent))}%` }} />
|
||||
)) : <div className="h-full bg-primary" style={{ width: `${usedPercent}%` }} />}
|
||||
</div>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.webWeeklyQuotaUsage", { remaining: formatNumber(remainingPercent, locale, 1) })}</div>
|
||||
<div className="text-muted-foreground">{weekly.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(weekly.resetAt, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
{breakdown.length > 0 ? <div className="mt-2 grid gap-1 border-t pt-2">{breakdown.map((item) => (
|
||||
<div key={item.productCode} className="flex items-center justify-between gap-4">
|
||||
<span className="flex items-center gap-1.5"><span className={`size-2 rounded-full ${quotaProductColor(item.productCode)}`} />{quotaProductLabel(item.productCode, locale)}</span>
|
||||
<span className="tabular-nums">{formatNumber(item.usagePercent, locale, 1)}%</span>
|
||||
</div>
|
||||
))}</div> : null}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
const fast = windowsByMode.get("fast");
|
||||
if (tier === "basic" && fast) {
|
||||
const used = Math.max(0, fast.total - fast.remaining);
|
||||
const percent = fast.total > 0 ? Math.max(0, Math.min(100, used / fast.total * 100)) : 0;
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center justify-between gap-2 text-[11px]">
|
||||
<span className="truncate text-muted-foreground">Fast</span>
|
||||
<span className="shrink-0 tabular-nums">{formatNumber(used, locale, 0)}/{formatNumber(fast.total, locale, 0)}</span>
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${percent}%` }} /></div>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.webModeQuotaRemaining", { mode: "Fast", remaining: formatNumber(fast.remaining, locale, 0) })}</div>
|
||||
<div className="text-muted-foreground">{fast.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(fast.resetAt, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="grid w-full min-w-0 grid-cols-4 divide-x divide-border/70">
|
||||
{visibleWebQuotaModes.map((mode) => {
|
||||
const window = windowsByMode.get(mode);
|
||||
if (!window) {
|
||||
return (
|
||||
<div key={mode} className="min-w-0 px-2 first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]">
|
||||
<span className="truncate capitalize text-muted-foreground">{mode}</span>
|
||||
<span className="text-muted-foreground">-</span>
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 rounded-full bg-muted" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const used = Math.max(0, window.total - window.remaining);
|
||||
const percent = window.total > 0 ? Math.max(0, Math.min(100, used / window.total * 100)) : 0;
|
||||
return (
|
||||
<Tooltip key={mode}>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="min-w-0 px-2 first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]">
|
||||
<span className="truncate capitalize text-muted-foreground">{mode}</span>
|
||||
<span className="shrink-0 tabular-nums">{formatNumber(used, locale, 0)}/{formatNumber(window.total, locale, 0)}</span>
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full bg-primary" style={{ width: `${percent}%` }} /></div>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{t("accounts.webModeQuotaRemaining", { mode: formatWebQuotaMode(mode), remaining: formatNumber(window.remaining, locale, 0) })}</div>
|
||||
<div className="text-muted-foreground">{window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function webTierLabel(tier: AccountDTO["webTier"]) {
|
||||
if (tier === "basic") return "Free";
|
||||
if (tier === "super") return "Super";
|
||||
@@ -1054,38 +828,6 @@ function WebAccountType({ tier }: { tier?: AccountDTO["webTier"] }) {
|
||||
return <AccountTypeText label={label} variant={tier === "basic" ? "free" : "default"} />;
|
||||
}
|
||||
|
||||
function formatWebQuotaMode(mode: string) {
|
||||
return mode ? mode.charAt(0).toUpperCase() + mode.slice(1) : mode;
|
||||
}
|
||||
|
||||
function quotaProductLabel(code: number, locale: string) {
|
||||
const chinese = locale.toLowerCase().startsWith("zh");
|
||||
const labels: Record<number, [string, string]> = {
|
||||
0: ["第三方", "Third Party"],
|
||||
1: ["API", "API"],
|
||||
2: ["Grok Build", "Grok Build"],
|
||||
3: ["Grok Plugins", "Grok Plugins"],
|
||||
4: ["聊天", "Chat"],
|
||||
5: ["Imagine", "Imagine"],
|
||||
6: ["语音", "Voice"],
|
||||
};
|
||||
const label = labels[code];
|
||||
return label ? label[chinese ? 0 : 1] : `${chinese ? "产品" : "Product"} ${code}`;
|
||||
}
|
||||
|
||||
function quotaProductColor(code: number) {
|
||||
const colors: Record<number, string> = {
|
||||
0: "bg-zinc-500",
|
||||
1: "bg-sky-500",
|
||||
2: "bg-emerald-500",
|
||||
3: "bg-amber-500",
|
||||
4: "bg-indigo-400",
|
||||
5: "bg-blue-600",
|
||||
6: "bg-rose-500",
|
||||
};
|
||||
return colors[code] ?? "bg-muted-foreground";
|
||||
}
|
||||
|
||||
function AccountType({ quota }: { quota: QuotaDTO }) {
|
||||
const { t } = useTranslation();
|
||||
if (quota.type === "unknown") {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { apiRequest } from "@/shared/api/client";
|
||||
import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder";
|
||||
import type { PeriodValue } from "@/shared/lib/period";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
@@ -74,6 +75,32 @@ export type AuditSummaryDTO = {
|
||||
};
|
||||
};
|
||||
|
||||
const auditValidator = hasShape({
|
||||
id: isString, requestId: isString, clientKeyId: isString, clientKeyName: isOptional(isString), modelRouteId: isString,
|
||||
modelPublicId: isOptional(isString), modelUpstreamModel: isOptional(isString), provider: isOneOf("grok_build", "grok_web"),
|
||||
operation: isOneOf("responses", "chat", "messages", "image", "image_edit", "video"), usageSource: isOneOf("upstream", "estimated", "none"),
|
||||
accountId: isOptional(isString), accountName: isOptional(isString), statusCode: isNumber, streaming: isBoolean,
|
||||
mediaInputImages: isNumber, mediaOutputImages: isNumber, mediaOutputSeconds: isNumber, inputTokens: isNumber,
|
||||
cachedInputTokens: isNumber, outputTokens: isNumber, reasoningTokens: isNumber, totalTokens: isNumber,
|
||||
costInUsdTicks: isNumber, estimatedCostInUsdTicks: isNumber, pricingModel: isOptional(isString), pricingVersion: isOptional(isString),
|
||||
numSourcesUsed: isNumber, numServerSideToolsUsed: isNumber, contextInputTokens: isNumber, contextOutputTokens: isNumber,
|
||||
durationMs: isNumber, errorCode: isOptional(isString), createdAt: isString,
|
||||
});
|
||||
const decodeAuditPage = createObjectDecoder<AuditCursorPageDTO>("audit page", {
|
||||
items: isArrayOf(auditValidator), pageSize: isNumber, nextCursor: isString, hasMore: isBoolean,
|
||||
});
|
||||
const decodeAuditSummary = createObjectDecoder<AuditSummaryDTO>("audit summary", {
|
||||
period: isOneOf("24h", "7d", "30d", "90d"), generatedAt: isString, range: hasShape({ start: isString, end: isString }),
|
||||
usage: hasShape({
|
||||
requests: isNumber, successfulRequests: isNumber, failedRequests: isNumber, inputTokens: isNumber,
|
||||
cachedInputTokens: isNumber, outputTokens: isNumber, reasoningTokens: isNumber, totalTokens: isNumber,
|
||||
averageDurationMs: isNumber, successRate: isNumber, estimatedCostInUsdTicks: isNumber,
|
||||
}),
|
||||
pricing: hasShape({
|
||||
source: isString, asOf: isString, pricedRequests: isNumber, unpricedRequests: isNumber, pricedTokens: isNumber, unpricedTokens: isNumber,
|
||||
}),
|
||||
});
|
||||
|
||||
type AuditQuery = {
|
||||
cursor?: string;
|
||||
pageSize?: number;
|
||||
@@ -101,7 +128,7 @@ export function getRequestAudits(input: AuditQuery): Promise<AuditCursorPageDTO>
|
||||
query.set("sortBy", input.sortBy);
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
return apiRequest<AuditCursorPageDTO>(`/api/admin/v1/request-audits?${query}`);
|
||||
return apiRequest(`/api/admin/v1/request-audits?${query}`, {}, decodeAuditPage);
|
||||
}
|
||||
|
||||
export function getRequestAuditSummary(input: Omit<AuditQuery, "cursor" | "pageSize">, refresh = false): Promise<AuditSummaryDTO> {
|
||||
@@ -113,5 +140,5 @@ export function getRequestAuditSummary(input: Omit<AuditQuery, "cursor" | "pageS
|
||||
if (input.key) query.set("key", input.key);
|
||||
if (input.account) query.set("account", input.account);
|
||||
if (refresh) query.set("refresh", "1");
|
||||
return apiRequest<AuditSummaryDTO>(`/api/admin/v1/request-audits/summary?${query}`);
|
||||
return apiRequest(`/api/admin/v1/request-audits/summary?${query}`, {}, decodeAuditSummary);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { createObjectDecoder, createPaginatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOptional, isString } from "@/shared/api/decoder";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
export type ClientKeyDTO = {
|
||||
@@ -27,6 +28,20 @@ export type ClientKeyInput = {
|
||||
|
||||
export type CreateKeyResponseDTO = { key: ClientKeyDTO; secret: string };
|
||||
|
||||
const clientKeyValidator = hasShape({
|
||||
id: isString, name: isString, prefix: isString, enabled: isBoolean, expiresAt: isOptional(isString),
|
||||
rpmLimit: isNumber, maxConcurrent: isNumber, billingLimitUsdTicks: isNumber, billedUsageUsdTicks: isNumber,
|
||||
allowedModelIds: isArrayOf(isString), lastUsedAt: isOptional(isString),
|
||||
});
|
||||
const decodeClientKey = createObjectDecoder<ClientKeyDTO>("client key", {
|
||||
id: isString, name: isString, prefix: isString, enabled: isBoolean, expiresAt: isOptional(isString),
|
||||
rpmLimit: isNumber, maxConcurrent: isNumber, billingLimitUsdTicks: isNumber, billedUsageUsdTicks: isNumber,
|
||||
allowedModelIds: isArrayOf(isString), lastUsedAt: isOptional(isString),
|
||||
});
|
||||
const decodeClientKeyPage = createPaginatedDecoder<ClientKeyDTO>(clientKeyValidator);
|
||||
const decodeCreatedClientKey = createObjectDecoder<CreateKeyResponseDTO>("created client key", { key: clientKeyValidator, secret: isString });
|
||||
const decodeSecret = createObjectDecoder<{ secret: string }>("client key secret", { secret: isString });
|
||||
|
||||
type ListClientKeysInput = {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
@@ -46,29 +61,29 @@ export function listClientKeys(input: ListClientKeysInput): Promise<PaginatedDTO
|
||||
query.set("sortBy", input.sortBy);
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
return apiRequest<PaginatedDTO<ClientKeyDTO>>(`/api/admin/v1/client-keys?${query}`);
|
||||
return apiRequest(`/api/admin/v1/client-keys?${query}`, {}, decodeClientKeyPage);
|
||||
}
|
||||
|
||||
export function createClientKey(input: ClientKeyInput): Promise<CreateKeyResponseDTO> {
|
||||
return apiRequest<CreateKeyResponseDTO>("/api/admin/v1/client-keys", { method: "POST", body: input });
|
||||
return apiRequest("/api/admin/v1/client-keys", { method: "POST", body: input }, decodeCreatedClientKey);
|
||||
}
|
||||
|
||||
export function getClientKeySecret(id: string): Promise<{ secret: string }> {
|
||||
return apiRequest<{ secret: string }>(`/api/admin/v1/client-keys/${id}/secret`);
|
||||
return apiRequest(`/api/admin/v1/client-keys/${id}/secret`, {}, decodeSecret);
|
||||
}
|
||||
|
||||
export function updateClientKey(id: string, input: ClientKeyInput): Promise<ClientKeyDTO> {
|
||||
return apiRequest<ClientKeyDTO>(`/api/admin/v1/client-keys/${id}`, { method: "PATCH", body: input });
|
||||
return apiRequest(`/api/admin/v1/client-keys/${id}`, { method: "PATCH", body: input }, decodeClientKey);
|
||||
}
|
||||
|
||||
export function deleteClientKey(id: string): Promise<{ deleted: boolean }> {
|
||||
return apiRequest<{ deleted: boolean }>(`/api/admin/v1/client-keys/${id}`, { method: "DELETE" });
|
||||
return apiRequest(`/api/admin/v1/client-keys/${id}`, { method: "DELETE" }, decodeBooleanResult<{ deleted: boolean }>("deleted"));
|
||||
}
|
||||
|
||||
export function updateClientKeysEnabled(ids: string[], enabled: boolean): Promise<{ updated: number }> {
|
||||
return apiRequest<{ updated: number }>("/api/admin/v1/client-keys/batch", { method: "PATCH", body: { ids, enabled } });
|
||||
return apiRequest("/api/admin/v1/client-keys/batch", { method: "PATCH", body: { ids, enabled } }, decodeCountResult<{ updated: number }>("updated"));
|
||||
}
|
||||
|
||||
export function deleteClientKeys(ids: string[]): Promise<{ deleted: number }> {
|
||||
return apiRequest<{ deleted: number }>("/api/admin/v1/client-keys", { method: "DELETE", body: { ids } });
|
||||
return apiRequest("/api/admin/v1/client-keys", { method: "DELETE", body: { ids } }, decodeCountResult<{ deleted: number }>("deleted"));
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { apiRequest } from "@/shared/api/client";
|
||||
import { createObjectDecoder, hasShape, isArrayOf, isNumber, isOneOf, isString } from "@/shared/api/decoder";
|
||||
import type { PeriodValue } from "@/shared/lib/period";
|
||||
|
||||
export type DashboardPeriod = PeriodValue;
|
||||
@@ -32,8 +33,34 @@ export type DashboardDTO = {
|
||||
topModels: Array<{ model: string; requests: number; inputTokens: number; cachedInputTokens: number; outputTokens: number; reasoningTokens: number; tokens: number; billedCostUsdTicks: number }>;
|
||||
};
|
||||
|
||||
const dashboardSeriesModel = hasShape({ model: isString, tokens: isNumber, billedCostUsdTicks: isNumber });
|
||||
const dashboardSeriesItem = hasShape({
|
||||
start: isString, end: isString, requests: isNumber, inputTokens: isNumber, cachedInputTokens: isNumber,
|
||||
outputTokens: isNumber, reasoningTokens: isNumber, tokens: isNumber, billedCostUsdTicks: isNumber, models: isArrayOf(dashboardSeriesModel),
|
||||
});
|
||||
const dashboardModelItem = hasShape({
|
||||
model: isString, requests: isNumber, inputTokens: isNumber, cachedInputTokens: isNumber,
|
||||
outputTokens: isNumber, reasoningTokens: isNumber, tokens: isNumber, billedCostUsdTicks: isNumber,
|
||||
});
|
||||
const decodeDashboard = createObjectDecoder<DashboardDTO>("dashboard", {
|
||||
period: isOneOf("24h", "7d", "30d", "90d"),
|
||||
generatedAt: isString,
|
||||
range: hasShape({ start: isString, end: isString }),
|
||||
resources: hasShape({
|
||||
activeAccounts: isNumber, totalAccounts: isNumber, enabledModels: isNumber, totalModels: isNumber,
|
||||
activeClientKeys: isNumber, totalClientKeys: isNumber, allTimeRequests: isNumber,
|
||||
}),
|
||||
usage: hasShape({
|
||||
requests: isNumber, successfulRequests: isNumber, failedRequests: isNumber, inputTokens: isNumber,
|
||||
cachedInputTokens: isNumber, outputTokens: isNumber, reasoningTokens: isNumber, tokens: isNumber,
|
||||
billedCostUsdTicks: isNumber, successRate: isNumber,
|
||||
}),
|
||||
series: isArrayOf(dashboardSeriesItem),
|
||||
topModels: isArrayOf(dashboardModelItem),
|
||||
});
|
||||
|
||||
export function getDashboard(period: DashboardPeriod, timezone: string, refresh = false): Promise<DashboardDTO> {
|
||||
const query = new URLSearchParams({ period, timezone });
|
||||
if (refresh) query.set("refresh", "1");
|
||||
return apiRequest<DashboardDTO>(`/api/admin/v1/dashboard?${query.toString()}`);
|
||||
return apiRequest(`/api/admin/v1/dashboard?${query.toString()}`, {}, decodeDashboard);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { apiRequest } from "@/shared/api/client";
|
||||
import { createObjectDecoder, decodeBooleanResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
export type SettingsConfigDTO = {
|
||||
providerBuild: { baseURL: string; clientVersion: string; clientIdentifier: string; tokenAuth: string; userAgent: string };
|
||||
providerBuild: { baseURL: string; clientVersion: string; clientIdentifier: string; tokenAuth: string; tokenAuthConfigured: boolean; userAgent: string };
|
||||
providerWeb: {
|
||||
baseURL: string; quotaTimeout: string; chatTimeout: string; imageTimeout: string; videoTimeout: string;
|
||||
statsigMode: "manual" | "url"; statsigManualValue?: string; statsigManualConfigured: boolean; statsigSignerURL: string;
|
||||
@@ -41,12 +42,47 @@ export type SettingsSnapshotDTO = {
|
||||
restartRequired: string[];
|
||||
};
|
||||
|
||||
const settingsConfigValidator = hasShape({
|
||||
providerBuild: hasShape({ baseURL: isString, clientVersion: isString, clientIdentifier: isString, tokenAuth: isString, tokenAuthConfigured: isBoolean, userAgent: isString }),
|
||||
providerWeb: hasShape({
|
||||
baseURL: isString, quotaTimeout: isString, chatTimeout: isString, imageTimeout: isString, videoTimeout: isString,
|
||||
statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean,
|
||||
statsigSignerURL: isString, mediaConcurrency: isNumber, allowNSFW: isBoolean, recoveryBackoffBase: isString, recoveryBackoffMax: isString,
|
||||
}),
|
||||
batch: hasShape({ importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }),
|
||||
media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }),
|
||||
routing: hasShape({ stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber }),
|
||||
audit: hasShape({ bufferSize: isNumber, batchSize: isNumber, flushInterval: isString }),
|
||||
clientKeyDefaults: hasShape({ rpmLimit: isNumber, maxConcurrent: isNumber }),
|
||||
});
|
||||
const decodeSettingsSnapshot = createObjectDecoder<SettingsSnapshotDTO>("settings", {
|
||||
config: settingsConfigValidator,
|
||||
recommendedProviderBuild: hasShape({ clientVersion: isString, userAgent: isString }),
|
||||
updatedAt: isString,
|
||||
revision: isString,
|
||||
restartRequired: isArrayOf(isString),
|
||||
});
|
||||
const egressNodeValidator = hasShape({
|
||||
id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_web_asset"), enabled: isBoolean,
|
||||
proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, health: isNumber, failureCount: isNumber,
|
||||
cooldownUntil: isOptional(isString), lastError: isOptional(isString),
|
||||
});
|
||||
const decodeEgressNode = createObjectDecoder<EgressNodeDTO>("egress node", {
|
||||
id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_web_asset"), enabled: isBoolean,
|
||||
proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, health: isNumber, failureCount: isNumber,
|
||||
cooldownUntil: isOptional(isString), lastError: isOptional(isString),
|
||||
});
|
||||
const decodeEgressNodeList = createObjectDecoder<EgressNodeListDTO>("egress node list", {
|
||||
items: isArrayOf(egressNodeValidator),
|
||||
defaultUserAgents: hasShape({ grok_build: isString, grok_web: isString, grok_web_asset: isString }),
|
||||
});
|
||||
|
||||
export function getSettings(): Promise<SettingsSnapshotDTO> {
|
||||
return apiRequest<SettingsSnapshotDTO>("/api/admin/v1/settings");
|
||||
return apiRequest("/api/admin/v1/settings", {}, decodeSettingsSnapshot);
|
||||
}
|
||||
|
||||
export function updateSettings(revision: string, config: SettingsConfigDTO): Promise<SettingsSnapshotDTO> {
|
||||
return apiRequest<SettingsSnapshotDTO>("/api/admin/v1/settings", { method: "PUT", body: { revision, config } });
|
||||
return apiRequest("/api/admin/v1/settings", { method: "PUT", body: { revision, config } }, decodeSettingsSnapshot);
|
||||
}
|
||||
|
||||
export function listEgressNodes(input?: { sortBy?: string; sortOrder?: SortOrder }): Promise<EgressNodeListDTO> {
|
||||
@@ -56,17 +92,17 @@ export function listEgressNodes(input?: { sortBy?: string; sortOrder?: SortOrder
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
const suffix = query.size > 0 ? `?${query}` : "";
|
||||
return apiRequest<EgressNodeListDTO>(`/api/admin/v1/egress-nodes${suffix}`);
|
||||
return apiRequest(`/api/admin/v1/egress-nodes${suffix}`, {}, decodeEgressNodeList);
|
||||
}
|
||||
|
||||
export function createEgressNode(input: EgressNodeInput): Promise<EgressNodeDTO> {
|
||||
return apiRequest<EgressNodeDTO>("/api/admin/v1/egress-nodes", { method: "POST", body: input });
|
||||
return apiRequest("/api/admin/v1/egress-nodes", { method: "POST", body: input }, decodeEgressNode);
|
||||
}
|
||||
|
||||
export function updateEgressNode(id: string, input: EgressNodeInput): Promise<EgressNodeDTO> {
|
||||
return apiRequest<EgressNodeDTO>(`/api/admin/v1/egress-nodes/${id}`, { method: "PUT", body: input });
|
||||
return apiRequest(`/api/admin/v1/egress-nodes/${id}`, { method: "PUT", body: input }, decodeEgressNode);
|
||||
}
|
||||
|
||||
export function deleteEgressNode(id: string): Promise<{ deleted: boolean }> {
|
||||
return apiRequest<{ deleted: boolean }>(`/api/admin/v1/egress-nodes/${id}`, { method: "DELETE" });
|
||||
return apiRequest(`/api/admin/v1/egress-nodes/${id}`, { method: "DELETE" }, decodeBooleanResult<{ deleted: boolean }>("deleted"));
|
||||
}
|
||||
@@ -23,8 +23,13 @@ export const settingsSchema = z.object({
|
||||
baseURL: z.url(),
|
||||
clientVersion: z.string().trim().min(1),
|
||||
clientIdentifier: z.string().trim().min(1),
|
||||
tokenAuth: z.string().trim().min(1),
|
||||
tokenAuth: z.string().trim(),
|
||||
tokenAuthConfigured: z.boolean(),
|
||||
userAgent: z.string().trim().min(1),
|
||||
}).superRefine((value, context) => {
|
||||
if (!value.tokenAuthConfigured && value.tokenAuth.length === 0) {
|
||||
context.addIssue({ code: "custom", path: ["tokenAuth"], message: "required" });
|
||||
}
|
||||
}),
|
||||
providerWeb: z.object({
|
||||
baseURL: z.url().refine((value) => value.startsWith("https://")),
|
||||
@@ -80,7 +85,7 @@ export type SettingsForm = z.infer<typeof settingsSchema>;
|
||||
|
||||
export function toSettingsForm(config: SettingsConfigDTO): SettingsForm {
|
||||
return {
|
||||
providerBuild: config.providerBuild,
|
||||
providerBuild: { ...config.providerBuild, tokenAuth: "" },
|
||||
providerWeb: {
|
||||
...config.providerWeb,
|
||||
statsigManualValue: "",
|
||||
|
||||
@@ -89,7 +89,7 @@ export function SettingsPage() {
|
||||
<SettingsField controlId="provider-base-url" className="sm:col-span-2" label={t("settings.provider.baseURL")} error={form.formState.errors.providerBuild?.baseURL?.message}><Input id="provider-base-url" {...form.register("providerBuild.baseURL")} /></SettingsField>
|
||||
<SettingsField controlId="provider-client-version" label={t("settings.provider.clientVersion")} badge={t("settings.provider.recommendedVersion", { version: recommendedBuild?.clientVersion ?? "-" })} error={form.formState.errors.providerBuild?.clientVersion?.message}><Input id="provider-client-version" {...form.register("providerBuild.clientVersion")} /></SettingsField>
|
||||
<SettingsField controlId="provider-client-identifier" label={t("settings.provider.clientIdentifier")} error={form.formState.errors.providerBuild?.clientIdentifier?.message}><Input id="provider-client-identifier" {...form.register("providerBuild.clientIdentifier")} /></SettingsField>
|
||||
<SettingsField controlId="provider-token-auth" label={t("settings.provider.tokenAuth")} error={form.formState.errors.providerBuild?.tokenAuth?.message}><Input id="provider-token-auth" {...form.register("providerBuild.tokenAuth")} /></SettingsField>
|
||||
<SettingsField controlId="provider-token-auth" label={t("settings.provider.tokenAuth")} badge={form.watch("providerBuild.tokenAuthConfigured") ? t("settings.web.statsigConfigured") : undefined} error={form.formState.errors.providerBuild?.tokenAuth?.message}><Input id="provider-token-auth" type="password" autoComplete="off" placeholder={form.watch("providerBuild.tokenAuthConfigured") ? t("settings.web.statsigKeepConfigured") : undefined} {...form.register("providerBuild.tokenAuth")} /></SettingsField>
|
||||
<SettingsField controlId="provider-user-agent" label={t("settings.provider.userAgent")} error={form.formState.errors.providerBuild?.userAgent?.message}><Input id="provider-user-agent" {...form.register("providerBuild.userAgent")} /></SettingsField>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
@@ -30,6 +30,13 @@
|
||||
--sidebar-accent: oklch(0.96 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.14 0 0);
|
||||
--sidebar-border: oklch(0.93 0 0);
|
||||
--quota-product-0: oklch(0.55 0 0);
|
||||
--quota-product-1: oklch(0.68 0.14 235);
|
||||
--quota-product-2: oklch(0.64 0.15 155);
|
||||
--quota-product-3: oklch(0.75 0.15 80);
|
||||
--quota-product-4: oklch(0.68 0.14 285);
|
||||
--quota-product-5: oklch(0.58 0.18 255);
|
||||
--quota-product-6: oklch(0.65 0.19 20);
|
||||
}
|
||||
|
||||
.dark {
|
||||
@@ -58,6 +65,13 @@
|
||||
--sidebar-accent: oklch(0.22 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.96 0 0);
|
||||
--sidebar-border: oklch(0.25 0 0);
|
||||
--quota-product-0: oklch(0.66 0 0);
|
||||
--quota-product-1: oklch(0.74 0.12 235);
|
||||
--quota-product-2: oklch(0.72 0.13 155);
|
||||
--quota-product-3: oklch(0.8 0.13 80);
|
||||
--quota-product-4: oklch(0.74 0.12 285);
|
||||
--quota-product-5: oklch(0.68 0.15 255);
|
||||
--quota-product-6: oklch(0.72 0.16 20);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
@@ -86,6 +100,13 @@
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-quota-product-0: var(--quota-product-0);
|
||||
--color-quota-product-1: var(--quota-product-1);
|
||||
--color-quota-product-2: var(--quota-product-2);
|
||||
--color-quota-product-3: var(--quota-product-3);
|
||||
--color-quota-product-4: var(--quota-product-4);
|
||||
--color-quota-product-5: var(--quota-product-5);
|
||||
--color-quota-product-6: var(--quota-product-6);
|
||||
--radius-sm: calc(var(--radius) - 2px);
|
||||
--radius-md: var(--radius);
|
||||
--radius-lg: calc(var(--radius) + 2px);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createObjectDecoder, hasShape, isString, type ApiDecoder } from "@/shared/api/decoder";
|
||||
import { runtimeConfig } from "@/shared/config/runtime-config";
|
||||
import { i18n } from "@/shared/i18n";
|
||||
|
||||
@@ -43,7 +44,7 @@ function localizedErrorMessage(code: string, fallback: string): string {
|
||||
return i18n.exists(key) ? i18n.t(key) : fallback;
|
||||
}
|
||||
|
||||
async function parseResponse<T>(response: Response): Promise<T> {
|
||||
async function parseResponse<T>(response: Response, decode: ApiDecoder<T>): Promise<T> {
|
||||
const payload: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = readErrorEnvelope(payload);
|
||||
@@ -53,7 +54,11 @@ async function parseResponse<T>(response: Response): Promise<T> {
|
||||
if (!isRecord(payload) || !("data" in payload)) {
|
||||
throw new ApiError(response.status, "invalidResponse", localizedErrorMessage("invalidResponse", "Server returned an invalid response"));
|
||||
}
|
||||
return payload.data as T;
|
||||
try {
|
||||
return decode(payload.data);
|
||||
} catch {
|
||||
throw new ApiError(response.status, "invalidResponse", localizedErrorMessage("invalidResponse", "Server returned an invalid response"));
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
@@ -81,7 +86,7 @@ async function requestRefresh(): Promise<RefreshResult> {
|
||||
invalidateSession();
|
||||
return "invalid";
|
||||
}
|
||||
const tokens = await parseResponse<AuthTokensDTO>(response);
|
||||
const tokens = await parseResponse(response, decodeAuthTokensDTO);
|
||||
setAccessToken(tokens.accessToken);
|
||||
return "refreshed";
|
||||
} catch {
|
||||
@@ -140,21 +145,21 @@ async function sendApiRequest(path: string, options: RequestOptions): Promise<Re
|
||||
});
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
export async function apiRequest<T>(path: string, options: RequestOptions, decode: ApiDecoder<T>): Promise<T> {
|
||||
const { authenticated = true, retryAuth = true } = options;
|
||||
const response = await sendApiRequest(path, options);
|
||||
|
||||
if (response.status === 401 && authenticated && retryAuth) {
|
||||
const refreshResult = await refreshAccessToken();
|
||||
if (refreshResult === "refreshed") {
|
||||
return apiRequest<T>(path, { ...options, retryAuth: false });
|
||||
return apiRequest<T>(path, { ...options, retryAuth: false }, decode);
|
||||
}
|
||||
if (refreshResult === "unavailable") {
|
||||
throw new ApiError(503, "sessionRefreshUnavailable", localizedErrorMessage("sessionRefreshUnavailable", "Unable to refresh the session. Please retry."));
|
||||
}
|
||||
}
|
||||
|
||||
return parseResponse<T>(response);
|
||||
return parseResponse(response, decode);
|
||||
}
|
||||
|
||||
export type ApiStreamEvent<T> = {
|
||||
@@ -163,20 +168,20 @@ export type ApiStreamEvent<T> = {
|
||||
};
|
||||
|
||||
// apiEventStream 使用现有管理员鉴权发起 POST SSE,并正确处理任意分块边界。
|
||||
export async function apiEventStream<T>(path: string, options: RequestOptions, onEvent: (value: ApiStreamEvent<T>) => void): Promise<void> {
|
||||
export async function apiEventStream<T>(path: string, options: RequestOptions, decode: ApiDecoder<T>, onEvent: (value: ApiStreamEvent<T>) => void): Promise<void> {
|
||||
const { authenticated = true, retryAuth = true } = options;
|
||||
const response = await sendApiRequest(path, options);
|
||||
if (response.status === 401 && authenticated && retryAuth) {
|
||||
const refreshResult = await refreshAccessToken();
|
||||
if (refreshResult === "refreshed") {
|
||||
return apiEventStream(path, { ...options, retryAuth: false }, onEvent);
|
||||
return apiEventStream(path, { ...options, retryAuth: false }, decode, onEvent);
|
||||
}
|
||||
if (refreshResult === "unavailable") {
|
||||
throw new ApiError(503, "sessionRefreshUnavailable", localizedErrorMessage("sessionRefreshUnavailable", "Unable to refresh the session. Please retry."));
|
||||
}
|
||||
}
|
||||
if (!response.ok) {
|
||||
await parseResponse<never>(response);
|
||||
await parseResponse(response, decodeNever);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new ApiError(response.status, "invalidResponse", localizedErrorMessage("invalidResponse", "Server returned an invalid response"));
|
||||
@@ -201,7 +206,7 @@ export async function apiEventStream<T>(path: string, options: RequestOptions, o
|
||||
if (data.length === 0) return;
|
||||
let payload: T;
|
||||
try {
|
||||
payload = JSON.parse(data.join("\n")) as T;
|
||||
payload = decode(JSON.parse(data.join("\n")) as unknown);
|
||||
} catch {
|
||||
throw new ApiError(response.status, "invalidResponse", localizedErrorMessage("invalidResponse", "Server returned an invalid response"));
|
||||
}
|
||||
@@ -264,8 +269,8 @@ export async function apiDownload(path: string, retryAuth = true): Promise<Blob>
|
||||
throw new ApiError(503, "sessionRefreshUnavailable", localizedErrorMessage("sessionRefreshUnavailable", "Unable to refresh the session. Please retry."));
|
||||
}
|
||||
}
|
||||
if (!response.ok) {
|
||||
await parseResponse<never>(response);
|
||||
if (!response.ok) {
|
||||
await parseResponse(response, decodeNever);
|
||||
throw new ApiError(response.status, "requestFailed", localizedErrorMessage("requestFailed", "The request failed"));
|
||||
}
|
||||
return response.blob();
|
||||
@@ -287,6 +292,22 @@ export type LoginResponseDTO = {
|
||||
tokens: AuthTokensDTO;
|
||||
};
|
||||
|
||||
const adminValidator = hasShape({ id: isString, username: isString });
|
||||
const authTokensValidator = hasShape({ accessToken: isString, accessTokenExpiresAt: isString, refreshTokenExpiresAt: isString });
|
||||
|
||||
export const decodeAdminDTO = createObjectDecoder<AdminDTO>("admin", { id: isString, username: isString });
|
||||
export const decodeAuthTokensDTO = createObjectDecoder<AuthTokensDTO>("auth tokens", {
|
||||
accessToken: isString,
|
||||
accessTokenExpiresAt: isString,
|
||||
refreshTokenExpiresAt: isString,
|
||||
});
|
||||
export const decodeLoginResponseDTO = createObjectDecoder<LoginResponseDTO>("login", { admin: adminValidator, tokens: authTokensValidator });
|
||||
export const decodeLoggedOut = createObjectDecoder<{ loggedOut: boolean }>("logout", { loggedOut: (value) => typeof value === "boolean" });
|
||||
|
||||
function decodeNever(): never {
|
||||
throw new Error("unexpected successful response");
|
||||
}
|
||||
|
||||
export type PaginatedDTO<T> = {
|
||||
items: T[];
|
||||
page: number;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
export type ApiDecoder<T> = (value: unknown) => T;
|
||||
export type ValueValidator = (value: unknown) => boolean;
|
||||
|
||||
export const isString: ValueValidator = (value) => typeof value === "string";
|
||||
export const isNumber: ValueValidator = (value) => typeof value === "number" && Number.isFinite(value);
|
||||
export const isBoolean: ValueValidator = (value) => typeof value === "boolean";
|
||||
export const isObject: ValueValidator = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
export function isOptional(validator: ValueValidator): ValueValidator {
|
||||
return (value) => value === undefined || validator(value);
|
||||
}
|
||||
|
||||
export function isArrayOf(validator: ValueValidator): ValueValidator {
|
||||
return (value) => Array.isArray(value) && value.every(validator);
|
||||
}
|
||||
|
||||
export function isRecordOf(validator: ValueValidator): ValueValidator {
|
||||
return (value) => {
|
||||
if (!isObject(value)) return false;
|
||||
return Object.values(value as Record<string, unknown>).every(validator);
|
||||
};
|
||||
}
|
||||
|
||||
export function isOneOf<const T extends readonly string[]>(...values: T): ValueValidator {
|
||||
return (value) => typeof value === "string" && values.includes(value);
|
||||
}
|
||||
|
||||
export function hasShape(shape: Readonly<Record<string, ValueValidator>>): ValueValidator {
|
||||
return (value) => {
|
||||
if (!isObject(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return Object.entries(shape).every(([key, validator]) => validator(record[key]));
|
||||
};
|
||||
}
|
||||
|
||||
export function createObjectDecoder<T>(name: string, shape: Readonly<Record<string, ValueValidator>>): ApiDecoder<T> {
|
||||
return createValidatedDecoder(name, hasShape(shape));
|
||||
}
|
||||
|
||||
export function createValidatedDecoder<T>(name: string, validator: ValueValidator): ApiDecoder<T> {
|
||||
return (value) => {
|
||||
if (!validator(value)) throw new Error(`${name} response shape is invalid`);
|
||||
// shape 已逐字段验证;断言只保留在统一外部输入边界。
|
||||
return value as T;
|
||||
};
|
||||
}
|
||||
|
||||
export function decodeBooleanResult<T>(field: string): ApiDecoder<T> {
|
||||
return createObjectDecoder<T>("boolean result", { [field]: isBoolean });
|
||||
}
|
||||
|
||||
export function decodeCountResult<T>(field: string): ApiDecoder<T> {
|
||||
return createObjectDecoder<T>("count result", { [field]: isNumber });
|
||||
}
|
||||
|
||||
export function createPaginatedDecoder<T>(itemValidator: ValueValidator): ApiDecoder<{ items: T[]; page: number; pageSize: number; total: number }> {
|
||||
return createObjectDecoder("paginated result", {
|
||||
items: isArrayOf(itemValidator),
|
||||
page: isNumber,
|
||||
pageSize: isNumber,
|
||||
total: isNumber,
|
||||
});
|
||||
}
|
||||
@@ -3,11 +3,13 @@ import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import {
|
||||
ApiError,
|
||||
apiRequest,
|
||||
decodeAdminDTO,
|
||||
decodeLoggedOut,
|
||||
decodeLoginResponseDTO,
|
||||
refreshAccessToken,
|
||||
setAccessToken,
|
||||
subscribeSessionInvalidated,
|
||||
type AdminDTO,
|
||||
type LoginResponseDTO,
|
||||
} from "@/shared/api/client";
|
||||
import { AuthContext, type AuthStatus } from "@/shared/auth/auth-state";
|
||||
|
||||
@@ -29,7 +31,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
try {
|
||||
const value = await apiRequest<AdminDTO>("/api/admin/v1/me", { retryAuth: false });
|
||||
const value = await apiRequest("/api/admin/v1/me", { retryAuth: false }, decodeAdminDTO);
|
||||
setAdmin(value);
|
||||
setStatus("authenticated");
|
||||
} catch (error) {
|
||||
@@ -56,12 +58,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}, [restoreSession]);
|
||||
|
||||
async function login(username: string, password: string): Promise<void> {
|
||||
const response = await apiRequest<LoginResponseDTO>("/api/admin/v1/auth/login", {
|
||||
const response = await apiRequest("/api/admin/v1/auth/login", {
|
||||
method: "POST",
|
||||
body: { username, password },
|
||||
authenticated: false,
|
||||
retryAuth: false,
|
||||
});
|
||||
}, decodeLoginResponseDTO);
|
||||
setAccessToken(response.tokens.accessToken);
|
||||
setAdmin(response.admin);
|
||||
setStatus("authenticated");
|
||||
@@ -69,12 +71,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
async function logout(): Promise<void> {
|
||||
try {
|
||||
await apiRequest<{ loggedOut: boolean }>("/api/admin/v1/auth/logout", {
|
||||
await apiRequest("/api/admin/v1/auth/logout", {
|
||||
method: "POST",
|
||||
body: {},
|
||||
authenticated: false,
|
||||
retryAuth: false,
|
||||
});
|
||||
}, decodeLoggedOut);
|
||||
} finally {
|
||||
setAccessToken(null);
|
||||
setAdmin(null);
|
||||
@@ -86,7 +88,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
await apiRequest("/api/admin/v1/me/password", {
|
||||
method: "PUT",
|
||||
body: { currentPassword, newPassword },
|
||||
});
|
||||
}, () => undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -265,6 +265,16 @@ const resources = {
|
||||
batchBillingRefreshed: "额度同步完成:成功 {{succeeded}},失败 {{failed}}",
|
||||
batchDeleteTitle: "删除所选 {{count}} 个账号?",
|
||||
},
|
||||
quotaProducts: {
|
||||
thirdParty: "第三方",
|
||||
api: "API",
|
||||
build: "Grok Build",
|
||||
plugins: "Grok Plugins",
|
||||
chat: "聊天",
|
||||
imagine: "Imagine",
|
||||
voice: "语音",
|
||||
unknown: "产品 {{code}}",
|
||||
},
|
||||
models: {
|
||||
title: "模型路由",
|
||||
description: "管理 Grok Build 与 Grok Web 的公开模型名称、能力类型和上游映射。",
|
||||
@@ -785,6 +795,7 @@ const resources = {
|
||||
noteVideoBoundAccount: "Media jobs remain bound to their creating account; status and asset reads never splice across accounts.",
|
||||
},
|
||||
},
|
||||
quotaProducts: { thirdParty: "Third Party", api: "API", build: "Grok Build", plugins: "Grok Plugins", chat: "Chat", imagine: "Imagine", voice: "Voice", unknown: "Product {{code}}" },
|
||||
errors: { generic: "The operation failed. Please try again.", required: "This field is required", minPassword: "Password must contain at least 8 characters", positive: "Enter a value greater than zero" },
|
||||
apiErrors: {
|
||||
accountBatchDeleteFailed: "Failed to delete accounts",
|
||||
|
||||
Reference in new issue
Block a user