mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
Merge branch 'main' into fix/web-console-sync-progress-flicker
This commit is contained in:
16 files changed
+339
-39
No files matched your search
@@ -431,7 +431,7 @@ func (s *Service) ListCursor(ctx context.Context, rawCursor string, pageSize int
|
||||
if filter.Sort.Field == "" && filter.Sort.Direction == "" {
|
||||
filter.Sort = repository.SortQuery{Field: "createdAt", Direction: repository.SortDescending}
|
||||
}
|
||||
if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") || !repository.IsValidSort(filter.Sort, "request", "model", "billing", "tokens", "status", "mode", "duration", "createdAt") {
|
||||
if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx", "other") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") || !repository.IsValidSort(filter.Sort, "request", "model", "billing", "tokens", "status", "mode", "duration", "createdAt") {
|
||||
return CursorResult{}, ErrInvalidFilter
|
||||
}
|
||||
cursor, err := decodeAuditCursor(rawCursor, filter.Sort)
|
||||
@@ -563,7 +563,7 @@ func (s *Service) SummaryFresh(ctx context.Context, search, rawPeriod string, fi
|
||||
}
|
||||
|
||||
func (s *Service) summary(ctx context.Context, search, rawPeriod string, filter ListFilter, useCache bool) (SummaryResult, error) {
|
||||
if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") {
|
||||
if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx", "other") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") {
|
||||
return SummaryResult{}, ErrInvalidFilter
|
||||
}
|
||||
period, start, end, err := s.resolvePeriod(rawPeriod)
|
||||
|
||||
@@ -269,7 +269,7 @@ func (s *Service) executeImage(
|
||||
var once sync.Once
|
||||
finalize := func(_ Usage, _ string, errorCode string) {
|
||||
once.Do(func() {
|
||||
successful := response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == ""
|
||||
successful := auditRequestSucceeded(response.StatusCode, errorCode)
|
||||
lease.completeSelectorObservation(successful)
|
||||
lease.Release()
|
||||
budget := newFinalizationBudget(string(operation), string(route.Provider))
|
||||
|
||||
@@ -1252,7 +1252,9 @@ attemptLoop:
|
||||
var once sync.Once
|
||||
finalize := func(usage Usage, responseID, errorCode string) {
|
||||
once.Do(func() {
|
||||
successful := response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == ""
|
||||
// HTTP 状态码保留线上真实值;流在 2xx 响应头之后失败时由 errorCode
|
||||
// 决定最终结果,避免把协议状态与业务结果混为一谈。
|
||||
successful := auditRequestSucceeded(response.StatusCode, errorCode)
|
||||
lease.completeSelectorObservation(successful)
|
||||
budget := newFinalizationBudget(string(operation), string(route.Provider))
|
||||
if isUpstreamStreamFailure(errorCode) {
|
||||
@@ -1279,7 +1281,7 @@ attemptLoop:
|
||||
record.MediaOutputImages = int64(max(0, response.QuotaUnits))
|
||||
}
|
||||
tokenPricing, tokenPriced := audit.EstimateOfficialCost(pricingModel, usage.InputTokens, usage.CachedInputTokens, usage.OutputTokens, usage.ContextInputTokens)
|
||||
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" && imagePriced {
|
||||
if successful && imagePriced {
|
||||
record.EstimatedCostInUSDTicks = imagePricing.CostInUSDTicks
|
||||
record.PricingModel = imagePricing.Model
|
||||
record.PricingVersion = audit.OfficialPricingAsOf
|
||||
@@ -1298,7 +1300,7 @@ attemptLoop:
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.ErrorCode = errorCode
|
||||
attempts := failureAttempts.snapshot()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 || errorCode != "" || len(attempts) > 0 {
|
||||
if !successful || len(attempts) > 0 {
|
||||
record.Attempts = attempts
|
||||
}
|
||||
record.CreatedAt = now
|
||||
@@ -1412,6 +1414,13 @@ func isUpstreamStreamFailure(errorCode string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// auditRequestSucceeded keeps transport truth (the HTTP status) separate from
|
||||
// the terminal request outcome. A stream that fails after 2xx headers is not a
|
||||
// successful request even though its HTTP status remains 2xx.
|
||||
func auditRequestSucceeded(statusCode int, errorCode string) bool {
|
||||
return statusCode >= 200 && statusCode < 300 && errorCode == ""
|
||||
}
|
||||
|
||||
func isRetryableTransportFailure(providerValue accountdomain.Provider, err error) bool {
|
||||
return providerValue != accountdomain.ProviderBuild || !neterrorpkg.IsResponseHeaderTimeout(err)
|
||||
}
|
||||
|
||||
@@ -3897,3 +3897,26 @@ func testCipher(t *testing.T) *security.Cipher {
|
||||
}
|
||||
return cipher
|
||||
}
|
||||
|
||||
func TestAuditRequestSucceeded(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
statusCode int
|
||||
errorCode string
|
||||
want bool
|
||||
}{
|
||||
{name: "2xx without error succeeds", statusCode: 200, errorCode: "", want: true},
|
||||
{name: "2xx stream interruption fails", statusCode: 200, errorCode: "upstream_stream_interrupted", want: false},
|
||||
{name: "2xx stream incomplete fails", statusCode: 200, errorCode: "upstream_stream_incomplete", want: false},
|
||||
{name: "any 2xx error fails", statusCode: 201, errorCode: "stream_interrupted", want: false},
|
||||
{name: "4xx fails", statusCode: 404, errorCode: "upstream_error", want: false},
|
||||
{name: "5xx fails", statusCode: 502, errorCode: "upstream_server_error", want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := auditRequestSucceeded(tc.statusCode, tc.errorCode); got != tc.want {
|
||||
t.Fatalf("auditRequestSucceeded(%d, %q) = %t, want %t", tc.statusCode, tc.errorCode, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -63,8 +64,14 @@ func (r *AccountRepository) List(ctx context.Context, input repository.AccountLi
|
||||
query = query.Where("provider = ?", input.Filter.Provider)
|
||||
}
|
||||
if search := strings.TrimSpace(input.Page.Search); search != "" {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(name) LIKE ? OR LOWER(email) LIKE ? OR LOWER(user_id) LIKE ? OR LOWER(team_id) LIKE ?", pattern, pattern, pattern, pattern)
|
||||
if id, err := strconv.ParseUint(strings.TrimPrefix(search, "#"), 10, 64); strings.HasPrefix(search, "#") && err == nil && id > 0 {
|
||||
// #ID 是管理端名单使用的内部精确查询形式,走主键索引且不改变
|
||||
// 原有纯数字名称的模糊搜索语义。
|
||||
query = query.Where("provider_accounts.id = ?", id)
|
||||
} else {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(name) LIKE ? OR LOWER(email) LIKE ? OR LOWER(user_id) LIKE ? OR LOWER(team_id) LIKE ?", pattern, pattern, pattern, pattern)
|
||||
}
|
||||
}
|
||||
switch input.Filter.QuotaType {
|
||||
case "free":
|
||||
|
||||
@@ -26,6 +26,8 @@ const (
|
||||
auditInsertBatchSize = 20
|
||||
auditLookupBatchSize = 500
|
||||
attemptInsertBatchSize = 40
|
||||
auditSuccessPredicate = "status_code >= 200 AND status_code < 300 AND (error_code IS NULL OR error_code = '')"
|
||||
auditSuccessAggregate = "COALESCE(SUM(CASE WHEN " + auditSuccessPredicate + " THEN 1 ELSE 0 END), 0)"
|
||||
)
|
||||
|
||||
var errAuditBatchRequiresFallback = errors.New("audit batch requires idempotent fallback")
|
||||
@@ -642,7 +644,6 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS
|
||||
var aggregate struct {
|
||||
Requests int64
|
||||
SuccessfulRequests int64
|
||||
FailedRequests int64
|
||||
InputTokens int64
|
||||
CachedInputTokens int64
|
||||
OutputTokens int64
|
||||
@@ -658,8 +659,7 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS
|
||||
query := applyAuditQuery(r.db.db.WithContext(ctx).Model(&requestAuditModel{}), input.Search, input.Start, input.End, input.Filter)
|
||||
if err := query.Select(`
|
||||
COUNT(*) AS requests,
|
||||
COALESCE(SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END), 0) AS successful_requests,
|
||||
COALESCE(SUM(CASE WHEN status_code < 200 OR status_code >= 300 THEN 1 ELSE 0 END), 0) AS failed_requests,
|
||||
` + auditSuccessAggregate + ` AS successful_requests,
|
||||
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
||||
COALESCE(SUM(cached_input_tokens), 0) AS cached_input_tokens,
|
||||
COALESCE(SUM(output_tokens), 0) AS output_tokens,
|
||||
@@ -674,7 +674,7 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS
|
||||
return audit.Summary{}, err
|
||||
}
|
||||
result := audit.Summary{
|
||||
Requests: aggregate.Requests, SuccessfulRequests: aggregate.SuccessfulRequests, FailedRequests: aggregate.FailedRequests,
|
||||
Requests: aggregate.Requests, SuccessfulRequests: aggregate.SuccessfulRequests, FailedRequests: aggregate.Requests - aggregate.SuccessfulRequests,
|
||||
InputTokens: aggregate.InputTokens, CachedInputTokens: aggregate.CachedInputTokens, OutputTokens: aggregate.OutputTokens,
|
||||
ReasoningTokens: aggregate.ReasoningTokens, TotalTokens: aggregate.TotalTokens, DurationMS: aggregate.DurationMS,
|
||||
EstimatedCostInUSDTicks: aggregate.EstimatedCostInUSDTicks, PricedRequests: aggregate.PricedRequests,
|
||||
@@ -707,11 +707,16 @@ func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter
|
||||
}
|
||||
switch filter.Status {
|
||||
case "success", "2xx":
|
||||
query = query.Where("status_code >= 200 AND status_code < 300")
|
||||
query = query.Where(auditSuccessPredicate)
|
||||
case "clientError", "4xx":
|
||||
query = query.Where("status_code >= 400 AND status_code < 500")
|
||||
case "serverError", "5xx":
|
||||
query = query.Where("status_code >= 500 AND status_code < 600")
|
||||
case "other":
|
||||
// 保留真实 HTTP 状态:2xx 响应头之后的流失败通过 error_code 识别;
|
||||
// 同时覆盖不属于 2xx/4xx/5xx 的状态段。status_code < 100 兼容
|
||||
// 曾运行过早期实现并写入 0 的开发数据库,但新记录仍只允许 100..599。
|
||||
query = query.Where("(status_code >= 200 AND status_code < 300 AND error_code IS NOT NULL AND error_code <> '') OR status_code < 200 OR (status_code >= 300 AND status_code < 400) OR status_code >= 600")
|
||||
}
|
||||
switch filter.Mode {
|
||||
case "stream":
|
||||
|
||||
@@ -489,4 +489,53 @@ func TestAuditRepositorySummaryAppliesRangeAndGroupsPricingTier(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditRepositoryStreamFailureKeepsHTTPStatusAndFiltersAsOther(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "audit-stream-failure.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := NewAuditRepository(database)
|
||||
now := time.Now().UTC()
|
||||
values := []audit.Record{
|
||||
{RequestID: "stream-interrupted", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "public", StatusCode: 200, Streaming: true, ErrorCode: "upstream_stream_interrupted", DurationMS: 616_731, CreatedAt: now.Add(-time.Hour)},
|
||||
{RequestID: "healthy", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "public", StatusCode: 200, Streaming: true, InputTokens: 100, OutputTokens: 50, TotalTokens: 150, DurationMS: 100, CreatedAt: now.Add(-2 * time.Hour)},
|
||||
{RequestID: "server-error", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "public", StatusCode: 500, ErrorCode: "upstream_server_error", DurationMS: 50, CreatedAt: now.Add(-3 * time.Hour)},
|
||||
}
|
||||
if err := repository.CreateBatch(ctx, values); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 真实 HTTP 200 被保留,但带 error_code 的流式记录计入失败。
|
||||
summary, err := repository.Summarize(ctx, repositorypkg.AuditSummaryQuery{Start: now.Add(-24 * time.Hour), End: now})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.Requests != 3 || summary.SuccessfulRequests != 1 || summary.FailedRequests != 2 {
|
||||
t.Fatalf("summary = %#v", summary)
|
||||
}
|
||||
// "其它错误"筛选通过 error_code 命中 2xx 响应头之后的流失败。
|
||||
items, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 50, Filter: repositorypkg.AuditListFilter{Status: "other"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].RequestID != "stream-interrupted" {
|
||||
t.Fatalf("other filter items = %#v", items)
|
||||
}
|
||||
if items[0].StatusCode != 200 {
|
||||
t.Fatalf("stream failure status = %d, want original HTTP 200", items[0].StatusCode)
|
||||
}
|
||||
// "成功"筛选排除带错误码的记录。
|
||||
items, _, err = repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 50, Filter: repositorypkg.AuditListFilter{Status: "success"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].RequestID != "healthy" {
|
||||
t.Fatalf("success filter items = %#v", items)
|
||||
}
|
||||
}
|
||||
|
||||
func uint64Pointer(value uint64) *uint64 { return &value }
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -34,8 +35,13 @@ func (r *ClientKeyRepository) List(ctx context.Context, input repository.ClientK
|
||||
var total int64
|
||||
query := r.db.db.WithContext(ctx).Model(&clientKeyModel{}).Where("internal_kind IS NULL")
|
||||
if search := strings.TrimSpace(input.Page.Search); search != "" {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(name) LIKE ? OR LOWER(prefix) LIKE ?", pattern, pattern)
|
||||
if id, err := strconv.ParseUint(strings.TrimPrefix(search, "#"), 10, 64); strings.HasPrefix(search, "#") && err == nil && id > 0 {
|
||||
// #ID 走主键索引;普通数字仍按名称/前缀搜索,保持现有 API 兼容。
|
||||
query = query.Where("client_keys.id = ?", id)
|
||||
} else {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(name) LIKE ? OR LOWER(prefix) LIKE ?", pattern, pattern)
|
||||
}
|
||||
}
|
||||
switch input.Filter.Status {
|
||||
case "active":
|
||||
|
||||
@@ -19,8 +19,7 @@ func NewDashboardRepository(db *Database) *DashboardRepository { return &Dashboa
|
||||
|
||||
const dashboardUsageAggregateSelect = `
|
||||
COUNT(*) AS requests,
|
||||
COALESCE(SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END), 0) AS successful_requests,
|
||||
COALESCE(SUM(CASE WHEN status_code < 200 OR status_code >= 300 THEN 1 ELSE 0 END), 0) AS failed_requests,
|
||||
` + auditSuccessAggregate + ` AS successful_requests,
|
||||
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
||||
COALESCE(SUM(cached_input_tokens), 0) AS cached_input_tokens,
|
||||
COALESCE(SUM(output_tokens), 0) AS output_tokens,
|
||||
@@ -99,6 +98,7 @@ func (r *DashboardRepository) Snapshot(ctx context.Context, window repository.Da
|
||||
Scan(&result.Usage).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Usage.FailedRequests = result.Usage.Requests - result.Usage.SuccessfulRequests
|
||||
var buckets []struct {
|
||||
BucketIndex int `gorm:"column:bucket_index"`
|
||||
Requests int64
|
||||
@@ -146,7 +146,7 @@ func (r *DashboardRepository) Snapshot(ctx context.Context, window repository.Da
|
||||
Tokens int64
|
||||
}
|
||||
if err := tx.Model(&requestAuditModel{}).
|
||||
Select("provider, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END), 0) AS successful_requests, COALESCE(SUM(total_tokens), 0) AS tokens").
|
||||
Select("provider, COUNT(*) AS requests, "+auditSuccessAggregate+" AS successful_requests, COALESCE(SUM(total_tokens), 0) AS tokens").
|
||||
Where("created_at >= ? AND created_at < ?", start, end).
|
||||
Group("provider").
|
||||
Order("requests DESC, provider ASC").
|
||||
|
||||
@@ -112,6 +112,34 @@ func TestDashboardRepositorySnapshot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardRepositoryCounts2xxWithErrorAsFailure(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "dashboard-stream-failure.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC)
|
||||
audits := []requestAuditModel{
|
||||
{RequestID: "healthy", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", Operation: "responses", UsageSource: "upstream", StatusCode: 200, CreatedAt: now.Add(-2 * time.Minute)},
|
||||
{RequestID: "stream-interrupted", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", Operation: "responses", UsageSource: "upstream", StatusCode: 200, Streaming: true, ErrorCode: "upstream_stream_interrupted", CreatedAt: now.Add(-time.Minute)},
|
||||
}
|
||||
if err := database.db.WithContext(ctx).Create(&audits).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
boundaries := testDashboardBoundaries(now.Add(-time.Hour), time.Hour, 2)
|
||||
snapshot, err := NewDashboardRepository(database).Snapshot(ctx, testDashboardWindow(boundaries), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Usage.Requests != 2 || snapshot.Usage.SuccessfulRequests != 1 || snapshot.Usage.FailedRequests != 1 {
|
||||
t.Fatalf("usage = %#v", snapshot.Usage)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDashboardUsageAggregate(b *testing.B) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(b.TempDir(), "dashboard-benchmark.db"))
|
||||
|
||||
@@ -3,6 +3,7 @@ package relational
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -49,6 +50,7 @@ func TestListFilters(t *testing.T) {
|
||||
}
|
||||
|
||||
accounts := NewAccountRepository(database)
|
||||
assertAccountSearchResult(t, ctx, accounts, "#"+strconv.FormatUint(free.ID, 10), free.ID)
|
||||
assertAccountFilterCount(t, ctx, accounts, repository.AccountListFilter{QuotaType: "free", Now: now}, 1)
|
||||
assertAccountFilterCount(t, ctx, accounts, repository.AccountListFilter{QuotaType: "paid", Now: now}, 1)
|
||||
assertAccountFilterCount(t, ctx, accounts, repository.AccountListFilter{QuotaType: "unknown", Now: now}, 1)
|
||||
@@ -246,6 +248,7 @@ func TestListFilters(t *testing.T) {
|
||||
}
|
||||
assertClientKeySearchCount(t, ctx, keys, "production", 1)
|
||||
assertClientKeySearchCount(t, ctx, keys, "abc123", 1)
|
||||
assertClientKeySearchResult(t, ctx, keys, "#"+strconv.FormatUint(activeKey.ID, 10), activeKey.ID)
|
||||
keyValues, _, err := keys.List(ctx, repository.ClientKeyListQuery{Page: repository.PageQuery{Limit: 20, Sort: repository.SortQuery{Field: "name", Direction: repository.SortDescending}}, Filter: repository.ClientKeyListFilter{Now: now}})
|
||||
if err != nil || len(keyValues) != 3 || keyValues[0].Name != "production" || keyValues[2].Name != "disabled" {
|
||||
t.Fatalf("client key name sort = %#v, err = %v", keyValues, err)
|
||||
@@ -320,6 +323,14 @@ func assertAccountFilterCount(t *testing.T, ctx context.Context, accounts *Accou
|
||||
}
|
||||
}
|
||||
|
||||
func assertAccountSearchResult(t *testing.T, ctx context.Context, accounts *AccountRepository, search string, expectedID uint64) {
|
||||
t.Helper()
|
||||
values, total, err := accounts.List(ctx, repository.AccountListQuery{Page: repository.PageQuery{Limit: 20, Search: search}})
|
||||
if err != nil || total != 1 || len(values) != 1 || values[0].ID != expectedID {
|
||||
t.Fatalf("account search %q values = %#v, total = %d, err = %v", search, values, total, err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertModelSearchCount(t *testing.T, ctx context.Context, models *ModelRepository, search string, expected int64) {
|
||||
t.Helper()
|
||||
_, total, err := models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 20, Search: search}})
|
||||
@@ -336,6 +347,14 @@ func assertClientKeySearchCount(t *testing.T, ctx context.Context, keys *ClientK
|
||||
}
|
||||
}
|
||||
|
||||
func assertClientKeySearchResult(t *testing.T, ctx context.Context, keys *ClientKeyRepository, search string, expectedID uint64) {
|
||||
t.Helper()
|
||||
values, total, err := keys.List(ctx, repository.ClientKeyListQuery{Page: repository.PageQuery{Limit: 20, Search: search}, Filter: repository.ClientKeyListFilter{Now: time.Now().UTC()}})
|
||||
if err != nil || total != 1 || len(values) != 1 || values[0].ID != expectedID {
|
||||
t.Fatalf("client key search %q values = %#v, total = %d, err = %v", search, values, total, err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertAuditSearchResult(t *testing.T, ctx context.Context, audits *AuditRepository, search, expectedRequestID string) {
|
||||
t.Helper()
|
||||
values, _, err := audits.ListCursor(ctx, repository.AuditCursorQuery{Limit: 20, Search: search})
|
||||
|
||||
@@ -222,7 +222,8 @@ type ListAccountsInput = {
|
||||
risk?: string;
|
||||
agreement?: string;
|
||||
association?: string;
|
||||
provider: AccountProvider;
|
||||
// 为空时返回全部 provider 的账号,用于跨 provider 的通用名单(如请求审计筛选)。
|
||||
provider?: AccountProvider;
|
||||
sortBy?: string;
|
||||
sortOrder?: SortOrder;
|
||||
};
|
||||
@@ -241,7 +242,7 @@ export function listAccounts(input: ListAccountsInput): Promise<PaginatedDTO<Acc
|
||||
query.set("sortBy", input.sortBy);
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
query.set("provider", input.provider);
|
||||
if (input.provider) query.set("provider", input.provider);
|
||||
return apiRequest(`/api/admin/v1/accounts?${query}`, {}, decodeAccountPage);
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ export type AuditDTO = {
|
||||
egressNodeName?: string;
|
||||
egressScope?: "grok_build" | "grok_web" | "grok_console" | "grok_web_asset" | "grok_console_asset";
|
||||
egressMode?: "direct" | "proxy";
|
||||
// 0 表示已返回 2xx 响应头但流随后失败(如首字节超时/流式中断),不属于任何 HTTP 状态段。
|
||||
statusCode: number;
|
||||
streaming: boolean;
|
||||
mediaInputImages: number;
|
||||
|
||||
@@ -9,6 +9,8 @@ import { Spinner } from "@/components/ui/spinner";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { listModels } from "@/entities/model/model-api";
|
||||
import { listClientKeys } from "@/features/client-keys/client-keys-api";
|
||||
import { listAccounts } from "@/features/accounts/accounts-api";
|
||||
import { RequestAuditDetailDialog } from "@/features/audits/request-audit-detail-dialog";
|
||||
import { getRequestAudits, getRequestAuditSummary, type AuditBillingBreakdownDTO, type AuditBillingComponentDTO, type AuditDTO, type AuditPeriod } from "@/features/audits/request-audits-api";
|
||||
import { EmptyState, ErrorState, TableLoadingRow } from "@/shared/components/data-state";
|
||||
@@ -27,6 +29,10 @@ import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/tabl
|
||||
|
||||
const AUDIT_PAGE_CACHE_TIME_MS = 60_000;
|
||||
const AUDIT_SUMMARY_CACHE_TIME_MS = 120_000;
|
||||
// 筛选名单始终限制在服务器搜索后的前 50 条,避免大账号池把大量选项累积到浏览器。
|
||||
const AUDIT_FILTER_PAGE_SIZE = 50;
|
||||
// 名单高度约 5 行,超出后内部滚动。
|
||||
const AUDIT_FILTER_MAX_HEIGHT = "max-h-56 overflow-y-auto py-0.5";
|
||||
|
||||
type AuditCursorState = { scope: string; values: string[] };
|
||||
|
||||
@@ -84,6 +90,65 @@ export function RequestAuditsPage() {
|
||||
queryFn: () => listModels({ page: 1, pageSize: 100 }),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
// 密钥/账号筛选名单只在对应三级菜单展开时懒加载,输入后重新按匹配查询。
|
||||
const [keyFilterOptionsOpen, setKeyFilterOptionsOpen] = useState(false);
|
||||
const [accountFilterOptionsOpen, setAccountFilterOptionsOpen] = useState(false);
|
||||
const [keyFilterOptionsSearch, setKeyFilterOptionsSearch] = useState("");
|
||||
const [accountFilterOptionsSearch, setAccountFilterOptionsSearch] = useState("");
|
||||
const debouncedKeyFilterOptionsSearch = useDebouncedValue(keyFilterOptionsSearch);
|
||||
const debouncedAccountFilterOptionsSearch = useDebouncedValue(accountFilterOptionsSearch);
|
||||
const keyFilterOptionsQuery = useQuery({
|
||||
queryKey: ["client-keys", "audit-filter", debouncedKeyFilterOptionsSearch],
|
||||
queryFn: () => listClientKeys({ page: 1, pageSize: AUDIT_FILTER_PAGE_SIZE, search: auditFilterOptionSearch(debouncedKeyFilterOptionsSearch) }),
|
||||
enabled: keyFilterOptionsOpen,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const accountFilterOptionsQuery = useQuery({
|
||||
queryKey: ["accounts", "audit-filter", debouncedAccountFilterOptionsSearch],
|
||||
queryFn: () => listAccounts({ page: 1, pageSize: AUDIT_FILTER_PAGE_SIZE, search: auditFilterOptionSearch(debouncedAccountFilterOptionsSearch) }),
|
||||
enabled: accountFilterOptionsOpen,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const keyFilterOptionsFailed = keyFilterOptionsQuery.isError;
|
||||
const keyFilterOptionsFetching = keyFilterOptionsQuery.isFetching;
|
||||
const accountFilterOptionsFailed = accountFilterOptionsQuery.isError;
|
||||
const accountFilterOptionsFetching = accountFilterOptionsQuery.isFetching;
|
||||
// 账号范围覆盖三种 provider,审计记录可能来自任一 provider 的账号。
|
||||
const keyFilterOptions = keyFilterOptionsQuery.data?.items ?? [];
|
||||
const accountFilterOptions = accountFilterOptionsQuery.data?.items ?? [];
|
||||
const keyFilterGroups = [
|
||||
{
|
||||
id: "keys", label: t("audits.key"),
|
||||
emptyLabel: keyFilterOptionsFailed ? t("audits.filterOptionsLoadFailed") : keyFilterOptionsFetching ? t("common.loading") : t("audits.filterOptionsEmpty"),
|
||||
options: keyFilterOptions.map((key) => ({
|
||||
value: String(key.id),
|
||||
label: key.name || key.prefix,
|
||||
description: `#${key.id} · ${key.prefix}`,
|
||||
})),
|
||||
loading: keyFilterOptionsFetching, hasMore: keyFilterOptionsFailed,
|
||||
actionLabel: t("common.retry"), onAction: () => { void keyFilterOptionsQuery.refetch(); },
|
||||
noteLabel: !keyFilterOptionsFailed && (keyFilterOptionsQuery.data?.total ?? 0) > keyFilterOptions.length ? t("audits.filterOptionsTruncated") : undefined,
|
||||
hideLabel: true,
|
||||
maxHeightClassName: AUDIT_FILTER_MAX_HEIGHT,
|
||||
},
|
||||
];
|
||||
const accountFilterGroups = [
|
||||
{
|
||||
id: "accounts", label: t("audits.account"),
|
||||
emptyLabel: accountFilterOptionsFailed ? t("audits.filterOptionsLoadFailed") : accountFilterOptionsFetching ? t("common.loading") : t("audits.filterOptionsEmpty"),
|
||||
options: accountFilterOptions.map((account) => ({
|
||||
value: String(account.id),
|
||||
label: account.name || account.email || `#${account.id}`,
|
||||
description: `#${account.id}`,
|
||||
badge: providerShortLabel(account.provider),
|
||||
})),
|
||||
loading: accountFilterOptionsFetching, hasMore: accountFilterOptionsFailed,
|
||||
actionLabel: t("common.retry"), onAction: () => { void accountFilterOptionsQuery.refetch(); },
|
||||
noteLabel: !accountFilterOptionsFailed && (accountFilterOptionsQuery.data?.total ?? 0) > accountFilterOptions.length ? t("audits.filterOptionsTruncated") : undefined,
|
||||
hideLabel: true,
|
||||
maxHeightClassName: AUDIT_FILTER_MAX_HEIGHT,
|
||||
},
|
||||
];
|
||||
const result = auditsQuery.data;
|
||||
const nextCursor = result?.nextCursor ?? "";
|
||||
const summary = summaryQuery.data;
|
||||
@@ -162,13 +227,36 @@ export function RequestAuditsPage() {
|
||||
{ value: "2xx", label: `2xx · ${t("audits.statusSuccess")}` },
|
||||
{ value: "4xx", label: `4xx · ${t("audits.statusClientError")}` },
|
||||
{ value: "5xx", label: `5xx · ${t("audits.statusServerError")}` },
|
||||
{ value: "other", label: t("audits.statusOtherError") },
|
||||
] },
|
||||
{ id: "mode", label: t("audits.mode"), value: modeFilter, onChange: setModeFilter, options: [
|
||||
{ value: "stream", label: t("audits.stream") },
|
||||
{ value: "nonStream", label: t("audits.nonStream") },
|
||||
] },
|
||||
{ id: "key", type: "text", label: t("audits.key"), value: keyFilter, placeholder: t("audits.keyFilterPlaceholder"), onChange: setKeyFilter },
|
||||
{ id: "account", type: "text", label: t("audits.account"), value: accountFilter, placeholder: t("audits.accountFilterPlaceholder"), onChange: setAccountFilter },
|
||||
{
|
||||
id: "key", label: t("audits.key"), value: keyFilter,
|
||||
onChange: setKeyFilter, options: [
|
||||
{
|
||||
value: "any", label: t("audits.key"), groups: keyFilterGroups,
|
||||
onGroupsOpenChange: setKeyFilterOptionsOpen,
|
||||
groupSearch: { value: keyFilterOptionsSearch, placeholder: t("audits.keyFilterPlaceholder"), onChange: (value) => {
|
||||
setKeyFilterOptionsSearch(value);
|
||||
} },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "account", label: t("audits.account"), value: accountFilter,
|
||||
onChange: setAccountFilter, options: [
|
||||
{
|
||||
value: "any", label: t("audits.account"), groups: accountFilterGroups,
|
||||
onGroupsOpenChange: setAccountFilterOptionsOpen,
|
||||
groupSearch: { value: accountFilterOptionsSearch, placeholder: t("audits.accountFilterPlaceholder"), onChange: (value) => {
|
||||
setAccountFilterOptionsSearch(value);
|
||||
} },
|
||||
},
|
||||
],
|
||||
},
|
||||
]} />
|
||||
</div>
|
||||
</>
|
||||
@@ -553,9 +641,20 @@ function StatusCode({ statusCode, hasError = false }: { statusCode: number; hasE
|
||||
function AuditStatus({ audit, onOpen }: { audit: AuditDTO; onOpen: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const mode = audit.operation === "compaction" ? t("audits.operations.compaction") : audit.streaming ? t("audits.stream") : t("audits.nonStream");
|
||||
const hasError = Boolean(audit.errorCode);
|
||||
// 保留真实 HTTP 状态,同时明确标识 2xx 响应头之后发生的流式失败。
|
||||
// statusCode 0 仅兼容曾运行过早期实现的开发数据库。
|
||||
const showErrorLabel = hasError && (audit.statusCode === 0 || (audit.statusCode >= 200 && audit.statusCode < 300));
|
||||
const content = (
|
||||
<>
|
||||
<StatusCode statusCode={audit.statusCode} hasError={Boolean(audit.errorCode)} />
|
||||
{showErrorLabel ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs tabular-nums text-amber-700 dark:text-amber-300">
|
||||
<span className="size-1.5 rounded-full bg-amber-500" />
|
||||
{audit.statusCode > 0 ? `${audit.statusCode} · ` : ""}{t("audits.errorLabel")}
|
||||
</span>
|
||||
) : (
|
||||
<StatusCode statusCode={audit.statusCode} hasError={hasError} />
|
||||
)}
|
||||
<span className="block whitespace-nowrap text-[10px] text-muted-foreground">{mode}</span>
|
||||
</>
|
||||
);
|
||||
@@ -591,6 +690,22 @@ function providerLabel(provider: AuditDTO["provider"]): string {
|
||||
}
|
||||
}
|
||||
|
||||
function providerShortLabel(provider: AuditDTO["provider"]): string {
|
||||
switch (provider) {
|
||||
case "grok_build":
|
||||
return "Build";
|
||||
case "grok_web":
|
||||
return "Web";
|
||||
case "grok_console":
|
||||
return "Console";
|
||||
}
|
||||
}
|
||||
|
||||
function auditFilterOptionSearch(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
return /^\d+$/.test(trimmed) ? `#${trimmed}` : trimmed;
|
||||
}
|
||||
|
||||
function formatUSDCost(ticks: number, fractionDigits: number): string {
|
||||
return `$${(ticks / 10_000_000_000).toFixed(fractionDigits)}`;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Check, ListFilter, X } from "lucide-react";
|
||||
import { Check, ListFilter, Search, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -10,12 +10,16 @@ import { Input } from "@/components/ui/input";
|
||||
type DataTableFilterOptionGroup = {
|
||||
id: string;
|
||||
label: string;
|
||||
options: Array<{ value: string; label: string }>;
|
||||
options: Array<{ value: string; label: string; description?: string; badge?: string }>;
|
||||
emptyLabel?: string;
|
||||
loading?: boolean;
|
||||
hasMore?: boolean;
|
||||
actionLabel?: string;
|
||||
onAction?: () => void;
|
||||
noteLabel?: string;
|
||||
hideLabel?: boolean;
|
||||
// 名单内容超出该高度时内部滚动(例如 max-h-40 = 5 行),避免菜单被拉得很长。
|
||||
maxHeightClassName?: string;
|
||||
};
|
||||
|
||||
type DataTableFilterOption = {
|
||||
@@ -123,27 +127,50 @@ export function DataTableFilters({ filters }: { filters: DataTableFilter[] }) {
|
||||
{narrowedLabel ? <span className="ml-auto max-w-16 truncate text-xs text-muted-foreground">{narrowedLabel}</span> : null}
|
||||
{option.value === filter.value ? <Check className="ml-auto" /> : null}
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent className="max-h-72 w-60 overflow-y-auto">
|
||||
<DropdownMenuSubContent sideOffset={6} className="max-h-[min(26rem,calc(100vh-2rem))] w-72 max-w-[calc(100vw-1rem)] overflow-y-auto p-0 shadow-lg shadow-black/5">
|
||||
{option.groupSearch ? (
|
||||
<div className="sticky top-0 z-10 bg-popover p-2" onKeyDown={(event) => event.stopPropagation()}>
|
||||
<Input
|
||||
className="h-8 text-xs"
|
||||
value={option.groupSearch.value}
|
||||
placeholder={option.groupSearch.placeholder}
|
||||
aria-label={option.groupSearch.placeholder}
|
||||
onChange={(event) => option.groupSearch?.onChange(event.target.value)}
|
||||
/>
|
||||
<div className="sticky top-0 z-20 border-b bg-popover/95 px-2 py-1.5 backdrop-blur-sm" onKeyDown={(event) => event.stopPropagation()}>
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground/70" />
|
||||
<Input
|
||||
className="h-8 border-0 bg-transparent pl-7 text-xs shadow-none focus-visible:ring-0"
|
||||
value={option.groupSearch.value}
|
||||
placeholder={option.groupSearch.placeholder}
|
||||
aria-label={option.groupSearch.placeholder}
|
||||
onChange={(event) => option.groupSearch?.onChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<DropdownMenuRadioGroup value={filter.value} onValueChange={filter.onChange}>
|
||||
<DropdownMenuRadioItem value={option.value}>{t("common.all")}</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value={option.value} className="mx-1 my-1 min-h-8 text-xs focus:bg-muted/50">{t("common.all")}</DropdownMenuRadioItem>
|
||||
{option.groups.map((group) => (
|
||||
<div key={group.id}>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuLabel className="text-muted-foreground">{group.label}</DropdownMenuLabel>
|
||||
{group.options.length === 0
|
||||
? <DropdownMenuItem disabled className="text-xs text-muted-foreground">{group.emptyLabel ?? t("common.noData")}</DropdownMenuItem>
|
||||
: group.options.map((entry) => <DropdownMenuRadioItem key={entry.value} value={entry.value}>{entry.label}</DropdownMenuRadioItem>)}
|
||||
{!group.hideLabel ? <DropdownMenuLabel className="px-3 py-1 text-[10px] font-normal text-muted-foreground">{group.label}</DropdownMenuLabel> : null}
|
||||
<div className={group.maxHeightClassName}>
|
||||
{group.options.length === 0
|
||||
? <DropdownMenuItem disabled className="text-xs text-muted-foreground">{group.emptyLabel ?? t("common.noData")}</DropdownMenuItem>
|
||||
: group.options.map((entry) => (
|
||||
<DropdownMenuRadioItem
|
||||
key={entry.value}
|
||||
value={entry.value}
|
||||
className={entry.description || entry.badge ? "mx-1 min-w-0 items-start py-1.5 pr-7 focus:bg-muted/50 data-[state=checked]:bg-muted/30" : "mx-1"}
|
||||
>
|
||||
{entry.description || entry.badge ? (
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13px] font-normal text-foreground">{entry.label}</span>
|
||||
<span className="mt-px flex min-w-0 items-center gap-1 text-[10px] leading-4 text-muted-foreground/80">
|
||||
{entry.description ? <span className="truncate tabular-nums">{entry.description}</span> : null}
|
||||
{entry.description && entry.badge ? <span aria-hidden="true">·</span> : null}
|
||||
{entry.badge ? <span className="shrink-0">{entry.badge}</span> : null}
|
||||
</span>
|
||||
</span>
|
||||
) : entry.label}
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</div>
|
||||
{group.noteLabel ? <div className="border-t px-3 py-1.5 text-[10px] leading-4 text-muted-foreground/80">{group.noteLabel}</div> : null}
|
||||
{group.hasMore && group.onAction ? (
|
||||
<DropdownMenuItem
|
||||
disabled={group.loading}
|
||||
|
||||
@@ -789,6 +789,9 @@ const resources = {
|
||||
model: "模型",
|
||||
account: "账号",
|
||||
accountFilterPlaceholder: "输入账号名称或 ID",
|
||||
filterOptionsEmpty: "暂无匹配项",
|
||||
filterOptionsTruncated: "显示前 50 项 · 输入关键词继续筛选",
|
||||
filterOptionsLoadFailed: "筛选选项加载失败",
|
||||
egress: "出口",
|
||||
egressProxy: "代理",
|
||||
egressDirect: "直连",
|
||||
@@ -800,6 +803,8 @@ const resources = {
|
||||
statusSuccess: "成功",
|
||||
statusClientError: "客户端错误",
|
||||
statusServerError: "服务端错误",
|
||||
statusOtherError: "其它错误",
|
||||
errorLabel: "错误",
|
||||
operations: { responses: "Responses", compaction: "上下文压缩", chat: "Chat", messages: "Messages", image: "图像生成", image_edit: "图像编辑", video: "视频生成" },
|
||||
compactionUsageUnavailable: "上游未返回用量",
|
||||
usageSummary: "用量统计",
|
||||
@@ -1360,6 +1365,9 @@ const resources = {
|
||||
model: "Model",
|
||||
account: "Account",
|
||||
accountFilterPlaceholder: "Enter account name or ID",
|
||||
filterOptionsEmpty: "No matching items",
|
||||
filterOptionsTruncated: "First 50 shown · Type to refine",
|
||||
filterOptionsLoadFailed: "Failed to load filter options",
|
||||
egress: "Egress",
|
||||
egressProxy: "Proxy",
|
||||
egressDirect: "Direct",
|
||||
@@ -1371,6 +1379,8 @@ const resources = {
|
||||
statusSuccess: "Success",
|
||||
statusClientError: "Client error",
|
||||
statusServerError: "Server error",
|
||||
statusOtherError: "Other error",
|
||||
errorLabel: "Error",
|
||||
operations: { responses: "Responses", compaction: "Context compaction", chat: "Chat", messages: "Messages", image: "Image generation", image_edit: "Image edit", video: "Video generation" },
|
||||
compactionUsageUnavailable: "Upstream usage unavailable",
|
||||
usageSummary: "Usage summary",
|
||||
|
||||
Reference in new issue
Block a user