mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
Merge branch 'main' into fix/basic-tier-promotion
This commit is contained in:
44 files changed
+1686
-119
No files matched your search
@@ -128,8 +128,11 @@ Messages 转换层兼容 Claude Code 常见载荷:标准顶层 `system` 与误
|
||||
- `media_input_images`
|
||||
- `media_output_images`
|
||||
- `media_output_seconds`
|
||||
- `egress_mode`(`proxy` 或 `direct`)
|
||||
- `egress_scope`
|
||||
- `egress_node_id` / `egress_node_name`(出口节点快照)
|
||||
|
||||
不保存 prompt、response body、encrypted reasoning 内容或工具参数。
|
||||
不保存 prompt、response body、encrypted reasoning 内容、工具参数、代理 URL、代理认证信息、User-Agent 或 Cookie。
|
||||
|
||||
Grok Web 未提供与公开 API 等价的精确 Token 计量,因此聊天审计标记 `usageSource: estimated`;图片和视频标记 `usageSource: none`,不会伪造 Token,用量费用仅按已配置的官方媒体单价估算。
|
||||
|
||||
@@ -189,7 +192,7 @@ JSON 只接受当前 `accounts` 结构。SSO 不存在自动刷新:上游返
|
||||
- `sso`、`sso-rw` 始终从当前账号的加密 SSO Token 生成。
|
||||
- Clearance 与出口节点绑定;403 或挑战只重建当前节点会话并降低健康分,下一次优先选择更健康节点,不会冷却或移除账号。
|
||||
- User-Agent 必须与获取 Clearance 时一致。当前 TLS 客户端使用其最新 Chrome 146 profile;自定义为 Firefox、Safari 等非 Chromium UA 会造成明显指纹不一致。
|
||||
- 出口节点按 `Grok Build`、`Grok Web`、`Grok Web(仅资源)` 三个作用域独立管理代理、健康度和冷却状态。Grok Build 始终沿用 Provider 的 CLI User-Agent,节点不能覆盖;Grok Web 和 Web 资源节点独立管理浏览器 User-Agent 与 Cloudflare Cookie。Web 资源未配置专用节点时仅回退到 Grok Web 节点。
|
||||
- 出口节点按 `Grok Build`、`Grok Web`、`Grok Console`、`Grok Web(仅资源)` 四个作用域独立管理代理、健康度和冷却状态。Grok Build 始终沿用 Provider 的 CLI User-Agent,节点不能覆盖;Grok Web、Console 和 Web 资源节点独立管理浏览器 User-Agent 与 Cloudflare Cookie。Web 资源未配置专用节点时仅回退到 Grok Web 节点。
|
||||
- 代理地址支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5 与 SOCKS5H,可携带用户名和密码。Cloudflare Cookie 只适用于 Grok Web。
|
||||
- 配置过对应作用域的出口节点后,如果全部节点不可用,服务不会静默退回直连;只有该作用域完全没有配置节点时才使用 direct。Grok Build 未配置节点时保持原有标准 HTTP 直连。
|
||||
- 首版仅支持 `none/manual` Clearance,不接 FlareSolverr。
|
||||
|
||||
@@ -151,7 +151,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
database.Close()
|
||||
return nil, fmt.Errorf("不支持的运行态驱动: %s", cfg.RuntimeStore.Driver)
|
||||
}
|
||||
mediaService := mediaapp.NewService(mediaAssetRepo, localMediaStore, refreshLock, mediaConfig(cfg))
|
||||
mediaService := mediaapp.NewService(mediaAssetRepo, mediaJobRepo, localMediaStore, refreshLock, mediaConfig(cfg))
|
||||
|
||||
egressManager := infraegress.NewManager(egressRepo, cipher)
|
||||
cliAdapter := cliprovider.NewAdapter(cliprovider.Config{BaseURL: cfg.Provider.Build.BaseURL, ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier, TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent}, cipher)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
)
|
||||
|
||||
func applyAuditEgress(record *audit.Record, trace *infraegress.Trace, provider accountdomain.Provider) {
|
||||
selection, ok := trace.Selection(primaryEgressScope(provider))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
record.EgressNodeName = selection.NodeName
|
||||
record.EgressScope = string(selection.Scope)
|
||||
if selection.Proxied {
|
||||
record.EgressMode = audit.EgressModeProxy
|
||||
} else {
|
||||
record.EgressMode = audit.EgressModeDirect
|
||||
}
|
||||
if selection.NodeID != 0 {
|
||||
id := selection.NodeID
|
||||
record.EgressNodeID = &id
|
||||
}
|
||||
}
|
||||
|
||||
func applyMediaJobEgress(job *media.Job, trace *infraegress.Trace, provider accountdomain.Provider) {
|
||||
selection, ok := trace.Selection(primaryEgressScope(provider))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
job.EgressNodeName = selection.NodeName
|
||||
job.EgressScope = string(selection.Scope)
|
||||
job.EgressMode = string(audit.EgressModeDirect)
|
||||
if selection.Proxied {
|
||||
job.EgressMode = string(audit.EgressModeProxy)
|
||||
}
|
||||
if selection.NodeID != 0 {
|
||||
id := selection.NodeID
|
||||
job.EgressNodeID = &id
|
||||
}
|
||||
}
|
||||
|
||||
func primaryEgressScope(provider accountdomain.Provider) egressdomain.Scope {
|
||||
switch provider {
|
||||
case accountdomain.ProviderWeb:
|
||||
return egressdomain.ScopeWeb
|
||||
case accountdomain.ProviderConsole:
|
||||
return egressdomain.ScopeConsole
|
||||
default:
|
||||
return egressdomain.ScopeBuild
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
@@ -258,6 +259,7 @@ func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key
|
||||
}
|
||||
|
||||
func (s *Service) createResponseAt(ctx context.Context, input Input, path string) (*Result, error) {
|
||||
ctx, egressTrace := infraegress.WithTrace(ctx)
|
||||
startedAt := time.Now()
|
||||
eventID := newAuditEventID()
|
||||
operation := input.Operation
|
||||
@@ -311,6 +313,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.ErrorCode = "model_not_allowed"
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if err := s.audits.Create(ctx, record); err != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err)
|
||||
}
|
||||
@@ -571,6 +574,7 @@ attemptLoop:
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.ErrorCode = errorCode
|
||||
record.CreatedAt = now
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if err := s.audits.Create(persistCtx, record); err != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err)
|
||||
}
|
||||
@@ -611,6 +615,7 @@ attemptLoop:
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.ErrorCode = lastFailure.AuditCode()
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if lastFailure.AccountID != 0 {
|
||||
accountID := lastFailure.AccountID
|
||||
record.AccountID = &accountID
|
||||
@@ -631,6 +636,7 @@ attemptLoop:
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.ErrorCode = "upstream_unavailable"
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
if err := s.audits.Create(persistCtx, record); err != nil {
|
||||
@@ -699,8 +705,8 @@ type ImageEditInput struct {
|
||||
}
|
||||
|
||||
func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput) (*Result, error) {
|
||||
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImage, func(adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
return adapter.GenerateImage(ctx, provider.ImageGenerationRequest{
|
||||
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImage, func(executionCtx context.Context, adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{
|
||||
Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count,
|
||||
Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution,
|
||||
ResponseFormat: input.ResponseFormat, Streaming: input.Streaming,
|
||||
@@ -709,15 +715,16 @@ func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput)
|
||||
}
|
||||
|
||||
func (s *Service) EditImage(ctx context.Context, input ImageEditInput) (*Result, error) {
|
||||
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImageEdit, func(adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
return adapter.EditImage(ctx, provider.ImageEditRequest{
|
||||
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImageEdit, func(executionCtx context.Context, adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
|
||||
return adapter.EditImage(executionCtx, provider.ImageEditRequest{
|
||||
Credential: credential, Model: upstream, Prompt: input.Prompt,
|
||||
ImageURLs: input.ImageURLs, Count: input.Count, Resolution: input.Resolution, ResponseFormat: input.ResponseFormat,
|
||||
})
|
||||
}, false, input.Resolution, input.Count, len(input.ImageURLs))
|
||||
}
|
||||
|
||||
func (s *Service) executeImage(ctx context.Context, requestID string, key clientkey.Key, publicModel string, operation audit.Operation, execute func(provider.ImageAdapter, accountdomain.Credential, string) (*provider.Response, error), streaming bool, resolution string, requestedCount, inputImageCount int) (*Result, error) {
|
||||
func (s *Service) executeImage(ctx context.Context, requestID string, key clientkey.Key, publicModel string, operation audit.Operation, execute func(context.Context, provider.ImageAdapter, accountdomain.Credential, string) (*provider.Response, error), streaming bool, resolution string, requestedCount, inputImageCount int) (*Result, error) {
|
||||
ctx, egressTrace := infraegress.WithTrace(ctx)
|
||||
startedAt := time.Now()
|
||||
eventID := newAuditEventID()
|
||||
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
|
||||
@@ -740,6 +747,32 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
auditBase := audit.Record{
|
||||
EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name,
|
||||
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
|
||||
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: streaming,
|
||||
}
|
||||
if operation == audit.OperationImageEdit {
|
||||
auditBase.MediaInputImages = int64(max(0, inputImageCount))
|
||||
}
|
||||
writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) {
|
||||
record := auditBase
|
||||
record.StatusCode = statusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
if credential != nil {
|
||||
accountID := credential.ID
|
||||
record.AccountID = &accountID
|
||||
record.AccountName = credential.Name
|
||||
}
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
if auditErr := s.audits.Create(persistCtx, record); auditErr != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr)
|
||||
}
|
||||
}
|
||||
pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel)
|
||||
var reservation audit.PricingResult
|
||||
var priced bool
|
||||
@@ -774,6 +807,7 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client
|
||||
for attempt := 0; attempt < attempts; attempt++ {
|
||||
lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, "", excluded, false)
|
||||
if err != nil {
|
||||
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", nil)
|
||||
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
|
||||
}
|
||||
excluded[lease.Credential.ID] = true
|
||||
@@ -781,13 +815,15 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client
|
||||
if err != nil {
|
||||
s.logger.Error("image_credential_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", lease.Credential.ID, "error", err)
|
||||
lease.Release()
|
||||
writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &lease.Credential)
|
||||
return nil, err
|
||||
}
|
||||
response, err = execute(adapter, credential, route.UpstreamModel)
|
||||
response, err = execute(ctx, adapter, credential, route.UpstreamModel)
|
||||
if err != nil {
|
||||
s.logger.Error("image_upstream_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", credential.ID, "error", err)
|
||||
s.selector.MarkFailure(ctx, credential, 0, 0)
|
||||
lease.Release()
|
||||
writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential)
|
||||
return nil, err
|
||||
}
|
||||
if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attempt+1 < attempts {
|
||||
@@ -823,22 +859,13 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client
|
||||
lease.Release()
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
record := audit.Record{
|
||||
EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name,
|
||||
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
|
||||
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone,
|
||||
AccountID: &accountID, AccountName: credential.Name, StatusCode: response.StatusCode,
|
||||
Streaming: streaming, ErrorCode: errorCode,
|
||||
DurationMS: time.Since(startedAt).Milliseconds(), CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
switch operation {
|
||||
case audit.OperationImage:
|
||||
record.MediaOutputImages = int64(max(0, requestedCount))
|
||||
case audit.OperationImageEdit:
|
||||
record.MediaInputImages = int64(max(0, inputImageCount))
|
||||
record.MediaOutputImages = int64(max(0, requestedCount))
|
||||
}
|
||||
record := auditBase
|
||||
record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC()
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" {
|
||||
record.MediaOutputImages = int64(max(0, requestedCount))
|
||||
var pricing audit.PricingResult
|
||||
var priced bool
|
||||
switch operation {
|
||||
|
||||
@@ -19,8 +19,10 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
|
||||
@@ -651,6 +653,30 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) {
|
||||
if adapter.EditResolution() != "2k" {
|
||||
t.Fatalf("image edit resolution = %q", adapter.EditResolution())
|
||||
}
|
||||
|
||||
billingBeforeFailure, err := keyRepo.Get(ctx, key.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter.FailWithEgress(infraegress.NewManager(relational.NewEgressRepository(database), testCipher(t)))
|
||||
if _, err := service.GenerateImage(ctx, ImageGenerationInput{
|
||||
RequestID: "req-image-failed", ClientKey: key, PublicModel: "grok-imagine-image-quality",
|
||||
Prompt: "test", Count: 1, Resolution: "1k", ResponseFormat: "url",
|
||||
}); err == nil {
|
||||
t.Fatal("expected image transport failure")
|
||||
}
|
||||
logs, total, err = auditRepo.List(ctx, 0, 10)
|
||||
if err != nil || total != 5 || len(logs) != 5 {
|
||||
t.Fatalf("failure audit logs=%#v total=%d err=%v", logs, total, err)
|
||||
}
|
||||
failureAudit := logs[0]
|
||||
if failureAudit.RequestID != "req-image-failed" || failureAudit.StatusCode != http.StatusBadGateway || failureAudit.ErrorCode != "upstream_unavailable" || failureAudit.MediaOutputImages != 0 || failureAudit.EstimatedCostInUSDTicks != 0 || failureAudit.EgressMode != audit.EgressModeDirect || failureAudit.EgressScope != string(egressdomain.ScopeWeb) || failureAudit.EgressNodeName != "direct" {
|
||||
t.Fatalf("failure audit = %#v", failureAudit)
|
||||
}
|
||||
updatedKey, err := keyRepo.Get(ctx, key.ID)
|
||||
if err != nil || updatedKey.ReservedUsageUSDTicks != 0 || updatedKey.BilledUsageUSDTicks != billingBeforeFailure.BilledUsageUSDTicks {
|
||||
t.Fatalf("failed image billing key = %#v, err = %v", updatedKey, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessfulWebChatRefreshesCurrentModeQuota(t *testing.T) {
|
||||
@@ -844,6 +870,7 @@ type webImageStreamAdapter struct {
|
||||
streaming bool
|
||||
editResolution string
|
||||
synced chan string
|
||||
failureEgress *infraegress.Manager
|
||||
}
|
||||
|
||||
type webChatQuotaAdapter struct {
|
||||
@@ -877,10 +904,19 @@ func (a *webImageStreamAdapter) QuotaMode(model string) string {
|
||||
func (a *webImageStreamAdapter) TierOrder(string) []account.WebTier {
|
||||
return []account.WebTier{account.WebTierSuper, account.WebTierHeavy}
|
||||
}
|
||||
func (a *webImageStreamAdapter) GenerateImage(_ context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) {
|
||||
func (a *webImageStreamAdapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) {
|
||||
a.mu.Lock()
|
||||
a.streaming = request.Streaming
|
||||
failureEgress := a.failureEgress
|
||||
a.mu.Unlock()
|
||||
if failureEgress != nil {
|
||||
lease, err := failureEgress.Acquire(ctx, egressdomain.ScopeWeb, "image-failure")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lease.Release()
|
||||
return nil, errors.New("simulated image transport failure")
|
||||
}
|
||||
body := "event: image_generation.completed\ndata: {}\n\ndata: [DONE]\n\n"
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body)), QuotaUnits: 1}, nil
|
||||
}
|
||||
@@ -909,6 +945,11 @@ func (a *webImageStreamAdapter) EditResolution() string {
|
||||
defer a.mu.Unlock()
|
||||
return a.editResolution
|
||||
}
|
||||
func (a *webImageStreamAdapter) FailWithEgress(manager *infraegress.Manager) {
|
||||
a.mu.Lock()
|
||||
a.failureEgress = manager
|
||||
a.mu.Unlock()
|
||||
}
|
||||
func (a *webImageStreamAdapter) SyncQuota(context.Context, account.Credential) (provider.QuotaSnapshot, error) {
|
||||
return provider.QuotaSnapshot{}, errors.New("unexpected full quota sync")
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/batch"
|
||||
@@ -200,16 +201,7 @@ func (s *Service) processVideoJob(ctx context.Context, id string) {
|
||||
route, err = s.models.GetByPublicID(ctx, job.Model)
|
||||
}
|
||||
if err != nil {
|
||||
now := time.Now().UTC()
|
||||
job.Status = media.StatusFailed
|
||||
job.ErrorCode = "model_not_found"
|
||||
job.ErrorMessage = "模型路由不存在"
|
||||
job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now
|
||||
if err := s.mediaJobs.UpdateMediaJob(ctx, job); err != nil {
|
||||
s.logger.Warn("video_job_terminal_write_failed", "job_id", job.ID, "error", err)
|
||||
} else {
|
||||
s.cancelBillingReservation("video_usage_" + job.ID)
|
||||
}
|
||||
s.failVideoJob(ctx, job, "model_not_found", errors.New("模型路由不存在"))
|
||||
return
|
||||
}
|
||||
s.runVideoJob(ctx, job, route)
|
||||
@@ -243,6 +235,7 @@ func (s *Service) claimVideoJob(ctx context.Context, id string) (media.Job, bool
|
||||
func (s *Service) runVideoJob(parent context.Context, job media.Job, route model.Route) {
|
||||
ctx, cancel := context.WithTimeout(parent, videoJobTimeout)
|
||||
defer cancel()
|
||||
ctx, egressTrace := infraegress.WithTrace(ctx)
|
||||
startedAt := time.Now()
|
||||
job.Progress = max(job.Progress, 1)
|
||||
job.UpdatedAt = time.Now().UTC()
|
||||
@@ -291,18 +284,20 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
_ = s.accounts.MarkReauthRequired(context.Background(), lease.Credential.ID, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider))
|
||||
}
|
||||
s.selector.MarkFailure(context.Background(), lease.Credential, 0, 0)
|
||||
applyMediaJobEgress(&job, egressTrace, route.Provider)
|
||||
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
|
||||
applyMediaJobEgress(&job, egressTrace, route.Provider)
|
||||
job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now
|
||||
if err := s.persistVideoJobWithRetry(parent, job); err != nil {
|
||||
s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", err)
|
||||
return
|
||||
}
|
||||
s.selector.MarkSuccess(context.Background(), lease.Credential)
|
||||
if err := s.recordVideoUsage(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil {
|
||||
if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil {
|
||||
s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", err)
|
||||
}
|
||||
if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode == "weekly" {
|
||||
@@ -311,7 +306,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
}
|
||||
|
||||
func (s *Service) reconcileVideoUsage(ctx context.Context) error {
|
||||
jobs, err := s.mediaJobs.ListUnrecordedCompletedMediaJobs(ctx, 200)
|
||||
jobs, err := s.mediaJobs.ListUnrecordedTerminalMediaJobs(ctx, 200)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -321,28 +316,42 @@ func (s *Service) reconcileVideoUsage(ctx context.Context) error {
|
||||
if job.CompletedAt != nil {
|
||||
durationMS = max(int64(0), job.CompletedAt.Sub(job.CreatedAt).Milliseconds())
|
||||
}
|
||||
if err := s.recordVideoUsage(ctx, job, durationMS); err != nil {
|
||||
if err := s.recordVideoAudit(ctx, job, durationMS); err != nil {
|
||||
result = firstError(result, fmt.Errorf("任务 %s: %w", job.ID, err))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Service) recordVideoUsage(ctx context.Context, job media.Job, durationMS int64) error {
|
||||
func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationMS int64) error {
|
||||
accountID := job.AccountID
|
||||
createdAt := time.Now().UTC()
|
||||
if job.CompletedAt != nil && !job.CompletedAt.IsZero() {
|
||||
createdAt = job.CompletedAt.UTC()
|
||||
}
|
||||
statusCode := http.StatusOK
|
||||
if job.Status == media.StatusFailed {
|
||||
statusCode = http.StatusBadGateway
|
||||
switch job.ErrorCode {
|
||||
case "account_unavailable", "provider_unavailable":
|
||||
statusCode = http.StatusServiceUnavailable
|
||||
case "model_not_found":
|
||||
statusCode = http.StatusNotFound
|
||||
}
|
||||
}
|
||||
record := audit.Record{
|
||||
EventID: "video_usage_" + job.ID, RequestID: job.RequestID, ClientKeyID: job.ClientKeyID, ClientKeyName: job.ClientKeyName,
|
||||
ModelRouteID: job.ModelRouteID, ModelPublicID: job.Model, ModelUpstreamModel: job.UpstreamModel,
|
||||
Provider: job.Provider, Operation: audit.OperationVideo, UsageSource: audit.UsageSourceNone,
|
||||
AccountID: &accountID, AccountName: job.AccountName, StatusCode: http.StatusOK,
|
||||
MediaInputImages: int64(len(decodeVideoInput(job.InputJSON))), MediaOutputSeconds: int64(max(0, job.Seconds)),
|
||||
DurationMS: durationMS, CreatedAt: createdAt,
|
||||
AccountID: &accountID, AccountName: job.AccountName, StatusCode: statusCode, ErrorCode: job.ErrorCode,
|
||||
EgressNodeID: job.EgressNodeID, EgressNodeName: job.EgressNodeName, EgressScope: job.EgressScope, EgressMode: audit.EgressMode(job.EgressMode),
|
||||
MediaInputImages: int64(len(decodeVideoInput(job.InputJSON))),
|
||||
DurationMS: durationMS, CreatedAt: createdAt,
|
||||
}
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok {
|
||||
if job.Status == media.StatusCompleted {
|
||||
record.MediaOutputSeconds = int64(max(0, job.Seconds))
|
||||
}
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok && job.Status == media.StatusCompleted {
|
||||
record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks
|
||||
record.PricingModel = pricing.Model
|
||||
record.PricingVersion = audit.OfficialPricingAsOf
|
||||
@@ -383,6 +392,9 @@ func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string,
|
||||
s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", updateErr)
|
||||
return
|
||||
}
|
||||
if auditErr := s.recordVideoAudit(context.Background(), job, max(int64(0), now.Sub(job.CreatedAt).Milliseconds())); auditErr != nil {
|
||||
s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", auditErr)
|
||||
}
|
||||
s.cancelBillingReservation("video_usage_" + job.ID)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
@@ -38,6 +39,33 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) {
|
||||
completedAt := time.Now().UTC()
|
||||
nodeID := uint64(42)
|
||||
repository := &videoUsageRepository{job: media.Job{
|
||||
ID: "video_failed_recovery", RequestID: "request-failed-recovery",
|
||||
ClientKeyID: 1, ClientKeyName: "client", AccountID: 2, AccountName: "account",
|
||||
Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 3, UpstreamModel: "video",
|
||||
Seconds: 8, Quality: "720p", Status: media.StatusFailed, ErrorCode: "generation_failed", ErrorMessage: "upstream disconnected",
|
||||
EgressNodeID: &nodeID, EgressNodeName: "warp", EgressScope: "grok_web", EgressMode: "proxy",
|
||||
InputJSON: `{}`, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt,
|
||||
}}
|
||||
recorder := &durableVideoAuditRecorder{}
|
||||
service := &Service{mediaJobs: repository, audits: recorder}
|
||||
if err := service.RecoverVideoJobs(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repository.job.UsageRecordedAt == nil || recorder.calls != 1 {
|
||||
t.Fatalf("recordedAt = %v, audit calls = %d", repository.job.UsageRecordedAt, recorder.calls)
|
||||
}
|
||||
if recorder.last.StatusCode != 502 || recorder.last.ErrorCode != "generation_failed" || recorder.last.EgressNodeID == nil || *recorder.last.EgressNodeID != nodeID || recorder.last.EgressNodeName != "warp" || recorder.last.EgressMode != audit.EgressModeProxy {
|
||||
t.Fatalf("audit = %#v", recorder.last)
|
||||
}
|
||||
if recorder.last.EstimatedCostInUSDTicks != 0 || recorder.last.MediaOutputSeconds != 0 {
|
||||
t.Fatalf("failed job was billed: %#v", recorder.last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVideoQueueIsBoundedAndDeduplicated(t *testing.T) {
|
||||
service := &Service{}
|
||||
service.ConfigureMedia(&videoUsageRepository{}, 1)
|
||||
@@ -82,12 +110,20 @@ func (r *videoUsageRepository) GetMediaJob(context.Context, string, uint64) (med
|
||||
|
||||
func (r *videoUsageRepository) UpdateMediaJob(context.Context, media.Job) error { return nil }
|
||||
|
||||
func (r *videoUsageRepository) ListMediaJobs(context.Context, repository.MediaJobListQuery) ([]media.Job, int64, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
func (r *videoUsageRepository) SummarizeMediaJobs(context.Context) (repository.MediaJobStats, error) {
|
||||
return repository.MediaJobStats{}, nil
|
||||
}
|
||||
|
||||
func (r *videoUsageRepository) ListRecoverableMediaJobs(context.Context, int) ([]media.Job, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *videoUsageRepository) ListUnrecordedCompletedMediaJobs(context.Context, int) ([]media.Job, error) {
|
||||
if r.job.UsageRecordedAt != nil {
|
||||
func (r *videoUsageRepository) ListUnrecordedTerminalMediaJobs(context.Context, int) ([]media.Job, error) {
|
||||
if r.job.UsageRecordedAt != nil || (r.job.Status != media.StatusCompleted && r.job.Status != media.StatusFailed) {
|
||||
return nil, nil
|
||||
}
|
||||
return []media.Job{r.job}, nil
|
||||
|
||||
@@ -21,13 +21,16 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAssetNotFound = errors.New("媒体资源不存在")
|
||||
ErrInvalidImage = errors.New("图片内容无效")
|
||||
ErrAssetNotFound = errors.New("媒体资源不存在")
|
||||
ErrInvalidImage = errors.New("图片内容无效")
|
||||
ErrInvalidFilter = errors.New("媒体筛选条件无效")
|
||||
ErrMediaJobsUnavailable = errors.New("视频任务仓储未配置")
|
||||
)
|
||||
|
||||
// Service 负责图片校验、文件落盘和元数据持久化的一致性收口。
|
||||
type Service struct {
|
||||
assets repository.MediaAssetRepository
|
||||
jobs repository.MediaJobRepository
|
||||
objects repository.MediaObjectStorage
|
||||
cleanupLock repository.DistributedLock
|
||||
publicBaseURL string
|
||||
@@ -49,9 +52,22 @@ type Config struct {
|
||||
CleanupInterval time.Duration
|
||||
}
|
||||
|
||||
func NewService(assets repository.MediaAssetRepository, objects repository.MediaObjectStorage, cleanupLock repository.DistributedLock, cfg Config) *Service {
|
||||
type ImageStats struct {
|
||||
TotalImages int64
|
||||
TotalBytes int64
|
||||
}
|
||||
|
||||
type VideoStats struct {
|
||||
TotalJobs int64
|
||||
Completed int64
|
||||
Failed int64
|
||||
InProgress int64
|
||||
Queued int64
|
||||
}
|
||||
|
||||
func NewService(assets repository.MediaAssetRepository, jobs repository.MediaJobRepository, objects repository.MediaObjectStorage, cleanupLock repository.DistributedLock, cfg Config) *Service {
|
||||
return &Service{
|
||||
assets: assets, objects: objects, cleanupLock: cleanupLock,
|
||||
assets: assets, jobs: jobs, objects: objects, cleanupLock: cleanupLock,
|
||||
publicBaseURL: strings.TrimRight(cfg.PublicBaseURL, "/"), maxImageBytes: cfg.MaxImageBytes,
|
||||
maxTotalBytes: cfg.MaxTotalBytes, cleanupAt: cfg.CleanupThresholdPercent, cleanupEvery: cfg.CleanupInterval,
|
||||
cleanupSignal: make(chan struct{}, 1), configChanged: make(chan struct{}, 1),
|
||||
@@ -136,6 +152,72 @@ func (s *Service) OpenImage(ctx context.Context, id string) (mediadomain.Asset,
|
||||
return asset, body, nil
|
||||
}
|
||||
|
||||
// AdminListImages 分页返回图片资源列表。
|
||||
func (s *Service) AdminListImages(ctx context.Context, page, pageSize int, search string) ([]mediadomain.Asset, int64, error) {
|
||||
return s.assets.ListMediaAssets(ctx, repository.MediaAssetListQuery{Page: mediaPageQuery(page, pageSize, search, repository.SortQuery{})})
|
||||
}
|
||||
|
||||
// AdminListVideoJobs 分页返回视频任务列表。
|
||||
func (s *Service) AdminListVideoJobs(ctx context.Context, page, pageSize int, search, status string, sort repository.SortQuery) ([]mediadomain.Job, int64, error) {
|
||||
if s.jobs == nil {
|
||||
return nil, 0, ErrMediaJobsUnavailable
|
||||
}
|
||||
status = strings.TrimSpace(status)
|
||||
if !validMediaStatus(status) || !repository.IsValidSort(sort, "prompt", "model", "status", "progress", "spec", "account", "createdAt", "completedAt") {
|
||||
return nil, 0, ErrInvalidFilter
|
||||
}
|
||||
return s.jobs.ListMediaJobs(ctx, repository.MediaJobListQuery{
|
||||
Page: mediaPageQuery(page, pageSize, search, sort),
|
||||
Filter: repository.MediaJobListFilter{Status: status},
|
||||
})
|
||||
}
|
||||
|
||||
// AdminImageStats 返回图片统计信息。
|
||||
func (s *Service) AdminImageStats(ctx context.Context) (ImageStats, error) {
|
||||
stats, err := s.assets.SummarizeMediaAssets(ctx)
|
||||
if err != nil {
|
||||
return ImageStats{}, err
|
||||
}
|
||||
return ImageStats{TotalImages: stats.TotalImages, TotalBytes: stats.TotalBytes}, nil
|
||||
}
|
||||
|
||||
// AdminVideoStats 返回视频任务统计信息。
|
||||
func (s *Service) AdminVideoStats(ctx context.Context) (VideoStats, error) {
|
||||
if s.jobs == nil {
|
||||
return VideoStats{}, ErrMediaJobsUnavailable
|
||||
}
|
||||
stats, err := s.jobs.SummarizeMediaJobs(ctx)
|
||||
if err != nil {
|
||||
return VideoStats{}, err
|
||||
}
|
||||
return VideoStats{
|
||||
TotalJobs: stats.TotalJobs, Completed: stats.Completed, Failed: stats.Failed,
|
||||
InProgress: stats.InProgress, Queued: stats.Queued,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func mediaPageQuery(page, pageSize int, search string, sort repository.SortQuery) repository.PageQuery {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return repository.PageQuery{Offset: (page - 1) * pageSize, Limit: pageSize, Search: strings.TrimSpace(search), Sort: sort}
|
||||
}
|
||||
|
||||
func validMediaStatus(status string) bool {
|
||||
switch mediadomain.Status(status) {
|
||||
case "", mediadomain.StatusQueued, mediadomain.StatusInProgress, mediadomain.StatusCompleted, mediadomain.StatusFailed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RunCleanup 响应容量阈值并按周期清理最旧媒体资源。
|
||||
func (s *Service) RunCleanup(ctx context.Context, onError func(error)) {
|
||||
cfg := s.runtimeConfig()
|
||||
|
||||
@@ -33,7 +33,7 @@ func TestServicePersistsAndReopensImage(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(relational.NewMediaAssetRepository(database), objects, nil, Config{
|
||||
service := NewService(relational.NewMediaAssetRepository(database), relational.NewMediaJobRepository(database), objects, nil, Config{
|
||||
PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30,
|
||||
CleanupThresholdPercent: 80, CleanupInterval: 10 * time.Minute,
|
||||
})
|
||||
@@ -96,7 +96,7 @@ func TestCleanupDeletesOldestAssetsAtThreshold(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
service := NewService(repository, objects, nil, Config{
|
||||
service := NewService(repository, relational.NewMediaJobRepository(database), objects, nil, Config{
|
||||
PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20,
|
||||
MaxTotalBytes: int64(len(raw) * 2), CleanupThresholdPercent: 50,
|
||||
CleanupInterval: 10 * time.Minute,
|
||||
@@ -146,7 +146,7 @@ func TestCleanupPreservesMetadataWhenLocalObjectIsMissing(t *testing.T) {
|
||||
if err := objects.Delete(ctx, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(repository, objects, nil, Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: int64(len(raw)), CleanupThresholdPercent: 50, CleanupInterval: 10 * time.Minute})
|
||||
service := NewService(repository, relational.NewMediaJobRepository(database), objects, nil, Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: int64(len(raw)), CleanupThresholdPercent: 50, CleanupInterval: 10 * time.Minute})
|
||||
if _, err := service.Cleanup(ctx); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("cleanup error = %v", err)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,13 @@ const (
|
||||
UsageSourceNone UsageSource = "none"
|
||||
)
|
||||
|
||||
type EgressMode string
|
||||
|
||||
const (
|
||||
EgressModeDirect EgressMode = "direct"
|
||||
EgressModeProxy EgressMode = "proxy"
|
||||
)
|
||||
|
||||
// Record 表示不包含提示词和响应正文的推理请求审计记录。
|
||||
type Record struct {
|
||||
ID uint64
|
||||
@@ -36,6 +43,10 @@ type Record struct {
|
||||
UsageSource UsageSource
|
||||
AccountID *uint64
|
||||
AccountName string
|
||||
EgressNodeID *uint64
|
||||
EgressNodeName string
|
||||
EgressScope string
|
||||
EgressMode EgressMode
|
||||
StatusCode int
|
||||
Streaming bool
|
||||
MediaInputImages int64
|
||||
|
||||
@@ -19,6 +19,10 @@ type Job struct {
|
||||
ClientKeyName string
|
||||
AccountID uint64
|
||||
AccountName string
|
||||
EgressNodeID *uint64
|
||||
EgressNodeName string
|
||||
EgressScope string
|
||||
EgressMode string
|
||||
Provider string
|
||||
Model string
|
||||
ModelRouteID uint64
|
||||
|
||||
@@ -24,6 +24,7 @@ const nodeSnapshotTTL = time.Second
|
||||
|
||||
type Lease struct {
|
||||
NodeID uint64
|
||||
NodeName string
|
||||
Scope domain.Scope
|
||||
ProxyURL string
|
||||
UserAgent string
|
||||
@@ -111,6 +112,7 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
return nil, false, fmt.Errorf("当前没有可用的 %s 出口节点", scope)
|
||||
}
|
||||
if !allowDirect {
|
||||
recordSelection(ctx, Selection{NodeName: "direct", Scope: scope})
|
||||
return nil, false, nil
|
||||
}
|
||||
available = []domain.Node{{ID: 0, Name: "direct", Scope: scope, Enabled: true, Health: 1}}
|
||||
@@ -147,8 +149,9 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
m.mu.Lock()
|
||||
m.inflight[selected.ID]++
|
||||
m.mu.Unlock()
|
||||
recordSelection(ctx, Selection{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, Proxied: proxyURL != ""})
|
||||
var once sync.Once
|
||||
return &Lease{NodeID: selected.ID, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, release: func() {
|
||||
return &Lease{NodeID: selected.ID, NodeName: selected.Name, 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]--
|
||||
|
||||
@@ -58,10 +58,39 @@ func TestAcquireIfConfiguredDoesNotChangeBuildDirectTransport(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager := NewManager(egressRepositoryTestStub{}, cipher)
|
||||
lease, configured, err := manager.AcquireIfConfigured(context.Background(), domain.ScopeBuild, "")
|
||||
ctx, trace := WithTrace(context.Background())
|
||||
lease, configured, err := manager.AcquireIfConfigured(ctx, domain.ScopeBuild, "")
|
||||
if err != nil || configured || lease != nil {
|
||||
t.Fatalf("lease=%#v configured=%v err=%v", lease, configured, err)
|
||||
}
|
||||
selection, ok := trace.Selection(domain.ScopeBuild)
|
||||
if !ok || selection.NodeID != 0 || selection.NodeName != "direct" || selection.Proxied {
|
||||
t.Fatalf("direct selection = %#v, ok=%v", selection, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceRecordsConfiguredProxyWithoutCredentials(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encryptedProxy, err := cipher.Encrypt("socks5h://secret:password@127.0.0.1:1080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{{
|
||||
ID: 42, Name: "primary-proxy", Scope: domain.ScopeBuild, Enabled: true, Health: 1, EncryptedProxyURL: encryptedProxy,
|
||||
}}}, cipher)
|
||||
ctx, trace := WithTrace(context.Background())
|
||||
lease, configured, err := manager.AcquireIfConfigured(ctx, domain.ScopeBuild, "")
|
||||
if err != nil || !configured || lease == nil {
|
||||
t.Fatalf("lease=%#v configured=%v err=%v", lease, configured, err)
|
||||
}
|
||||
defer lease.Release()
|
||||
selection, ok := trace.Selection(domain.ScopeBuild)
|
||||
if !ok || selection.NodeID != 42 || selection.NodeName != "primary-proxy" || !selection.Proxied {
|
||||
t.Fatalf("proxy selection = %#v, ok=%v", selection, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredBuildNodeDoesNotOverrideProviderUserAgent(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
)
|
||||
|
||||
// Selection 是一次上游请求实际选择的出口快照。它只包含可安全写入审计的元数据,
|
||||
// 不包含代理 URL、认证信息、User-Agent 或 Cookie。
|
||||
type Selection struct {
|
||||
NodeID uint64
|
||||
NodeName string
|
||||
Scope domain.Scope
|
||||
Proxied bool
|
||||
}
|
||||
|
||||
// Trace 按作用域保留最后一次实际出口选择。相同请求发生出口重试时,审计记录最终尝试;
|
||||
// Web 资源归档使用独立作用域,不会覆盖主要的 Grok Web 推理出口。
|
||||
type Trace struct {
|
||||
mu sync.RWMutex
|
||||
selections map[domain.Scope]Selection
|
||||
}
|
||||
|
||||
type traceContextKey struct{}
|
||||
|
||||
// WithTrace 为一次网关请求创建或复用并发安全的出口选择轨迹。
|
||||
func WithTrace(ctx context.Context) (context.Context, *Trace) {
|
||||
if existing := TraceFromContext(ctx); existing != nil {
|
||||
return ctx, existing
|
||||
}
|
||||
trace := &Trace{selections: make(map[domain.Scope]Selection)}
|
||||
return context.WithValue(ctx, traceContextKey{}, trace), trace
|
||||
}
|
||||
|
||||
// TraceFromContext 返回上下文中的出口轨迹;未配置时返回 nil。
|
||||
func TraceFromContext(ctx context.Context) *Trace {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
trace, _ := ctx.Value(traceContextKey{}).(*Trace)
|
||||
return trace
|
||||
}
|
||||
|
||||
// Selection 返回指定作用域最后一次实际出口选择的安全快照。
|
||||
func (t *Trace) Selection(scope domain.Scope) (Selection, bool) {
|
||||
if t == nil {
|
||||
return Selection{}, false
|
||||
}
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
value, ok := t.selections[scope]
|
||||
return value, ok
|
||||
}
|
||||
|
||||
func recordSelection(ctx context.Context, value Selection) {
|
||||
trace := TraceFromContext(ctx)
|
||||
if trace == nil {
|
||||
return
|
||||
}
|
||||
trace.mu.Lock()
|
||||
trace.selections[value.Scope] = value
|
||||
trace.mu.Unlock()
|
||||
}
|
||||
@@ -89,7 +89,9 @@ func toAuditModel(value audit.Record) requestAuditModel {
|
||||
EventID: truncate(eventID, 64), RequestID: truncate(value.RequestID, 64), ClientKeyID: value.ClientKeyID, ClientKeyName: truncate(value.ClientKeyName, 160),
|
||||
ModelRouteID: value.ModelRouteID, ModelPublicID: truncate(value.ModelPublicID, 255), ModelUpstreamModel: truncate(value.ModelUpstreamModel, 255),
|
||||
Provider: truncate(provider, 32), Operation: string(operation), UsageSource: string(usageSource),
|
||||
AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), StatusCode: value.StatusCode, Streaming: value.Streaming,
|
||||
AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160),
|
||||
EgressNodeID: value.EgressNodeID, EgressNodeName: truncate(value.EgressNodeName, 160), EgressScope: truncate(value.EgressScope, 32), EgressMode: string(value.EgressMode),
|
||||
StatusCode: value.StatusCode, Streaming: value.Streaming,
|
||||
MediaInputImages: nonNegative(value.MediaInputImages), MediaOutputImages: nonNegative(value.MediaOutputImages), MediaOutputSeconds: nonNegative(value.MediaOutputSeconds),
|
||||
InputTokens: nonNegative(value.InputTokens), CachedInputTokens: nonNegative(value.CachedInputTokens), OutputTokens: nonNegative(value.OutputTokens),
|
||||
ReasoningTokens: nonNegative(value.ReasoningTokens), TotalTokens: nonNegative(value.TotalTokens), CostInUSDTicks: nonNegative(value.CostInUSDTicks),
|
||||
@@ -301,7 +303,7 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS
|
||||
func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB {
|
||||
if value := strings.TrimSpace(search); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Where("LOWER(request_id) LIKE ? OR LOWER(model_public_id) LIKE ? OR LOWER(model_upstream_model) LIKE ?", pattern, pattern, pattern)
|
||||
query = query.Where("LOWER(request_id) LIKE ? OR LOWER(model_public_id) LIKE ? OR LOWER(model_upstream_model) LIKE ? OR LOWER(egress_node_name) LIKE ?", pattern, pattern, pattern, pattern)
|
||||
}
|
||||
if !start.IsZero() {
|
||||
query = query.Where("created_at >= ?", start)
|
||||
|
||||
@@ -58,7 +58,7 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) {
|
||||
{RequestID: "cursor-old", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-48 * time.Hour)},
|
||||
{RequestID: "cursor-1", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-3 * time.Minute)},
|
||||
{RequestID: "cursor-2", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-2 * time.Minute)},
|
||||
{RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", AccountName: "primary", StatusCode: 200, CreatedAt: now.Add(-time.Minute)},
|
||||
{RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", AccountName: "primary", EgressNodeID: uint64Pointer(42), EgressNodeName: "proxy-shanghai", EgressScope: "grok_web", EgressMode: audit.EgressModeProxy, StatusCode: 200, CreatedAt: now.Add(-time.Minute)},
|
||||
}
|
||||
if err := repository.CreateBatch(ctx, values); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -71,9 +71,13 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) {
|
||||
if len(first) != 2 || !hasMore || first[0].ID <= first[1].ID {
|
||||
t.Fatalf("first page = %#v, hasMore = %v", first, hasMore)
|
||||
}
|
||||
if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].AccountName != "primary" {
|
||||
if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].AccountName != "primary" || first[0].EgressNodeID == nil || *first[0].EgressNodeID != 42 || first[0].EgressNodeName != "proxy-shanghai" || first[0].EgressMode != audit.EgressModeProxy {
|
||||
t.Fatalf("audit snapshots = %#v", first[0])
|
||||
}
|
||||
matched, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 10, Search: "proxy-shanghai", Sort: sort})
|
||||
if err != nil || len(matched) != 1 || matched[0].RequestID != "cursor-3" {
|
||||
t.Fatalf("egress search = %#v, err = %v", matched, err)
|
||||
}
|
||||
second, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Cursor: &repositorypkg.SortCursor{ID: first[len(first)-1].ID, Value: first[len(first)-1].CreatedAt}, Limit: 2, Sort: sort})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -147,7 +147,9 @@ func toAuditDomain(value requestAuditModel) audit.Record {
|
||||
ID: value.ID, EventID: value.EventID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName,
|
||||
ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel,
|
||||
Provider: value.Provider, Operation: audit.Operation(value.Operation), UsageSource: audit.UsageSource(value.UsageSource),
|
||||
AccountID: value.AccountID, AccountName: value.AccountName, StatusCode: value.StatusCode, Streaming: value.Streaming,
|
||||
AccountID: value.AccountID, AccountName: value.AccountName,
|
||||
EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: audit.EgressMode(value.EgressMode),
|
||||
StatusCode: value.StatusCode, Streaming: value.Streaming,
|
||||
MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds,
|
||||
InputTokens: value.InputTokens, CachedInputTokens: value.CachedInputTokens, OutputTokens: value.OutputTokens,
|
||||
ReasoningTokens: value.ReasoningTokens, TotalTokens: value.TotalTokens, CostInUSDTicks: value.CostInUSDTicks,
|
||||
|
||||
@@ -2,6 +2,7 @@ package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
@@ -37,6 +38,40 @@ func (r *MediaAssetRepository) GetMediaAsset(ctx context.Context, id string) (me
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListMediaAssets 通过字段投影返回符合筛选条件的稳定分页结果。
|
||||
func (r *MediaAssetRepository) ListMediaAssets(ctx context.Context, input repository.MediaAssetListQuery) ([]media.Asset, int64, error) {
|
||||
query := r.db.db.WithContext(ctx).Model(&mediaAssetModel{})
|
||||
if search := strings.TrimSpace(input.Page.Search); search != "" {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(id) LIKE ? OR LOWER(kind) LIKE ? OR LOWER(mime_type) LIKE ? OR LOWER(sha256) LIKE ?", pattern, pattern, pattern, pattern)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var rows []mediaAssetModel
|
||||
if err := query.Select("id", "kind", "mime_type", "size_bytes", "sha256", "created_at").Order("created_at DESC, id DESC").Offset(input.Page.Offset).Limit(input.Page.Limit).Find(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
values := make([]media.Asset, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
values = append(values, media.Asset{
|
||||
ID: row.ID, Kind: row.Kind, StorageKey: row.StorageKey, MIMEType: row.MIMEType,
|
||||
SizeBytes: row.SizeBytes, SHA256: row.SHA256, CreatedAt: row.CreatedAt,
|
||||
})
|
||||
}
|
||||
return values, total, nil
|
||||
}
|
||||
|
||||
// SummarizeMediaAssets 通过单次聚合查询返回图片数量和存储占用。
|
||||
func (r *MediaAssetRepository) SummarizeMediaAssets(ctx context.Context) (repository.MediaAssetStats, error) {
|
||||
var stats repository.MediaAssetStats
|
||||
err := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}).
|
||||
Select("COUNT(*) AS total_images, COALESCE(SUM(size_bytes), 0) AS total_bytes").
|
||||
Scan(&stats).Error
|
||||
return stats, err
|
||||
}
|
||||
|
||||
func (r *MediaAssetRepository) TotalMediaAssetBytes(ctx context.Context) (int64, error) {
|
||||
var total int64
|
||||
err := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}).Select("COALESCE(SUM(size_bytes), 0)").Scan(&total).Error
|
||||
@@ -90,7 +125,7 @@ func (r *MediaJobRepository) UpdateMediaJob(ctx context.Context, value media.Job
|
||||
if value.ClaimToken != "" {
|
||||
query = query.Where("claim_token = ?", value.ClaimToken)
|
||||
}
|
||||
result := query.Select("request_id", "client_key_name", "account_id", "account_name", "provider", "model", "model_route_id", "upstream_model", "prompt", "seconds", "size", "quality", "status", "progress", "input_json", "upstream_url", "content_type", "error_code", "error_message", "lease_until", "claim_token", "updated_at", "completed_at", "usage_recorded_at").Updates(updates)
|
||||
result := query.Select("request_id", "client_key_name", "account_id", "account_name", "egress_node_id", "egress_node_name", "egress_scope", "egress_mode", "provider", "model", "model_route_id", "upstream_model", "prompt", "seconds", "size", "quality", "status", "progress", "input_json", "upstream_url", "content_type", "error_code", "error_message", "lease_until", "claim_token", "updated_at", "completed_at", "usage_recorded_at").Updates(updates)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -100,12 +135,65 @@ func (r *MediaJobRepository) UpdateMediaJob(ctx context.Context, value media.Job
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MediaJobRepository) ListUnrecordedCompletedMediaJobs(ctx context.Context, limit int) ([]media.Job, error) {
|
||||
// ListMediaJobs 通过固定搜索字段和排序白名单返回稳定分页结果。
|
||||
func (r *MediaJobRepository) ListMediaJobs(ctx context.Context, input repository.MediaJobListQuery) ([]media.Job, int64, error) {
|
||||
query := r.db.db.WithContext(ctx).Model(&mediaJobModel{})
|
||||
if input.Filter.Status != "" {
|
||||
query = query.Where("status = ?", input.Filter.Status)
|
||||
}
|
||||
if search := strings.TrimSpace(input.Page.Search); search != "" {
|
||||
pattern := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(id) LIKE ? OR LOWER(prompt) LIKE ? OR LOWER(model) LIKE ? OR LOWER(account_name) LIKE ? OR LOWER(client_key_name) LIKE ?", pattern, pattern, pattern, pattern, pattern)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var rows []mediaJobModel
|
||||
query = applyStableSort(query, input.Page.Sort, map[string]sortSpec{
|
||||
"prompt": {expression: "LOWER(prompt)"},
|
||||
"model": {expression: "LOWER(model)"},
|
||||
"status": {expression: "status"},
|
||||
"progress": {expression: "progress", defaultDirection: repository.SortDescending},
|
||||
"spec": {expression: "LOWER(size) || ' ' || LOWER(quality)"},
|
||||
"account": {expression: "LOWER(account_name)"},
|
||||
"createdAt": {expression: "created_at", defaultDirection: repository.SortDescending},
|
||||
"completedAt": {expression: "completed_at", nullsLast: true, defaultDirection: repository.SortDescending},
|
||||
}, sortSpec{expression: "created_at", defaultDirection: repository.SortDescending}, "id")
|
||||
if err := query.Select(
|
||||
"id", "client_key_name", "account_name", "model", "prompt", "seconds", "size", "quality",
|
||||
"status", "progress", "error_message", "created_at", "completed_at",
|
||||
).Offset(input.Page.Offset).Limit(input.Page.Limit).Find(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
values := make([]media.Job, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
values = append(values, mediaJobToDomain(row))
|
||||
}
|
||||
return values, total, nil
|
||||
}
|
||||
|
||||
// SummarizeMediaJobs 通过单次条件聚合查询统计全部任务状态。
|
||||
func (r *MediaJobRepository) SummarizeMediaJobs(ctx context.Context) (repository.MediaJobStats, error) {
|
||||
var stats repository.MediaJobStats
|
||||
err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Select(`
|
||||
COUNT(*) AS total_jobs,
|
||||
COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS completed,
|
||||
COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS failed,
|
||||
COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS in_progress,
|
||||
COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS queued`,
|
||||
media.StatusCompleted, media.StatusFailed, media.StatusInProgress, media.StatusQueued,
|
||||
).Scan(&stats).Error
|
||||
return stats, err
|
||||
}
|
||||
|
||||
// ListUnrecordedTerminalMediaJobs 返回尚未完成审计写入的成功或失败任务。
|
||||
func (r *MediaJobRepository) ListUnrecordedTerminalMediaJobs(ctx context.Context, limit int) ([]media.Job, error) {
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
var rows []mediaJobModel
|
||||
if err := r.db.db.WithContext(ctx).Where("status = ? AND usage_recorded_at IS NULL", media.StatusCompleted).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil {
|
||||
if err := r.db.db.WithContext(ctx).Where("status IN ? AND usage_recorded_at IS NULL", []media.Status{media.StatusCompleted, media.StatusFailed}).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values := make([]media.Job, 0, len(rows))
|
||||
@@ -116,13 +204,14 @@ func (r *MediaJobRepository) ListUnrecordedCompletedMediaJobs(ctx context.Contex
|
||||
}
|
||||
|
||||
func (r *MediaJobRepository) MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error {
|
||||
result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status = ? AND usage_recorded_at IS NULL", id, media.StatusCompleted).Update("usage_recorded_at", recordedAt)
|
||||
terminalStatuses := []media.Status{media.StatusCompleted, media.StatusFailed}
|
||||
result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NULL", id, terminalStatuses).Update("usage_recorded_at", recordedAt)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
var count int64
|
||||
if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status = ? AND usage_recorded_at IS NOT NULL", id, media.StatusCompleted).Count(&count).Error; err != nil {
|
||||
if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NOT NULL", id, terminalStatuses).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
@@ -169,8 +258,10 @@ func (r *MediaJobRepository) TryClaimMediaJob(ctx context.Context, id string, no
|
||||
func mediaJobFromDomain(value media.Job) *mediaJobModel {
|
||||
return &mediaJobModel{
|
||||
ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName,
|
||||
AccountID: value.AccountID, AccountName: value.AccountName, Provider: value.Provider,
|
||||
Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel,
|
||||
AccountID: value.AccountID, AccountName: value.AccountName,
|
||||
EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: value.EgressMode,
|
||||
Provider: value.Provider,
|
||||
Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel,
|
||||
Prompt: value.Prompt, Seconds: value.Seconds, Size: value.Size, Quality: value.Quality,
|
||||
Status: string(value.Status), Progress: value.Progress, InputJSON: value.InputJSON, UpstreamURL: value.UpstreamURL,
|
||||
ContentType: value.ContentType, ErrorCode: value.ErrorCode, ErrorMessage: value.ErrorMessage,
|
||||
@@ -182,8 +273,10 @@ func mediaJobFromDomain(value media.Job) *mediaJobModel {
|
||||
func mediaJobToDomain(row mediaJobModel) media.Job {
|
||||
return media.Job{
|
||||
ID: row.ID, RequestID: row.RequestID, ClientKeyID: row.ClientKeyID, ClientKeyName: row.ClientKeyName,
|
||||
AccountID: row.AccountID, AccountName: row.AccountName, Provider: row.Provider,
|
||||
Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel,
|
||||
AccountID: row.AccountID, AccountName: row.AccountName,
|
||||
EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, EgressScope: row.EgressScope, EgressMode: row.EgressMode,
|
||||
Provider: row.Provider,
|
||||
Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel,
|
||||
Prompt: row.Prompt, Seconds: row.Seconds, Size: row.Size, Quality: row.Quality,
|
||||
Status: media.Status(row.Status), Progress: row.Progress, InputJSON: row.InputJSON, UpstreamURL: row.UpstreamURL,
|
||||
ContentType: row.ContentType, ErrorCode: row.ErrorCode, ErrorMessage: row.ErrorMessage,
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
func TestMediaJobRepositoryListMediaJobsPaginatesAndFilters(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
|
||||
accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb,
|
||||
AuthType: accountdomain.AuthTypeSSO,
|
||||
WebTier: accountdomain.WebTierBasic,
|
||||
Name: "media-list-account",
|
||||
SourceKey: "media-list-account",
|
||||
EncryptedAccessToken: testEncryptedToken,
|
||||
AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := clientKeyModel{Name: "media-list-key", Prefix: "media-list-key", SecretHash: testSecretHash, EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 60, MaxConcurrent: 4}
|
||||
if err := database.db.WithContext(ctx).Create(&key).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
jobRepo := NewMediaJobRepository(database)
|
||||
now := time.Date(2026, 7, 13, 12, 0, 0, 0, time.UTC)
|
||||
jobs := []mediadomain.Job{
|
||||
testMediaJob("media_job_completed_old", accountValue.ID, key.ID, mediadomain.StatusCompleted, now.Add(-4*time.Hour)),
|
||||
testMediaJob("media_job_queued_mid", accountValue.ID, key.ID, mediadomain.StatusQueued, now.Add(-3*time.Hour)),
|
||||
testMediaJob("media_job_failed_newer", accountValue.ID, key.ID, mediadomain.StatusFailed, now.Add(-2*time.Hour)),
|
||||
testMediaJob("media_job_completed_new", accountValue.ID, key.ID, mediadomain.StatusCompleted, now.Add(-time.Hour)),
|
||||
}
|
||||
jobs[0].Prompt = "A quiet harbor"
|
||||
jobs[1].Prompt = "Northern lights"
|
||||
jobs[2].Prompt = "Desert sunrise"
|
||||
jobs[3].Prompt = "City skyline"
|
||||
for _, job := range jobs {
|
||||
if err := jobRepo.CreateMediaJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
firstPage, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{
|
||||
Page: repository.PageQuery{Offset: 0, Limit: 2},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 4 {
|
||||
t.Fatalf("total = %d", total)
|
||||
}
|
||||
assertMediaJobIDs(t, firstPage, "media_job_completed_new", "media_job_failed_newer")
|
||||
|
||||
secondPage, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{
|
||||
Page: repository.PageQuery{Offset: 2, Limit: 2},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 4 {
|
||||
t.Fatalf("second page total = %d", total)
|
||||
}
|
||||
assertMediaJobIDs(t, secondPage, "media_job_queued_mid", "media_job_completed_old")
|
||||
|
||||
completed, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{
|
||||
Page: repository.PageQuery{Offset: 0, Limit: 10},
|
||||
Filter: repository.MediaJobListFilter{Status: string(mediadomain.StatusCompleted)},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 2 {
|
||||
t.Fatalf("completed total = %d", total)
|
||||
}
|
||||
assertMediaJobIDs(t, completed, "media_job_completed_new", "media_job_completed_old")
|
||||
|
||||
searched, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{
|
||||
Page: repository.PageQuery{Offset: 0, Limit: 1, Search: "northern"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 1 {
|
||||
t.Fatalf("searched total = %d", total)
|
||||
}
|
||||
assertMediaJobIDs(t, searched, "media_job_queued_mid")
|
||||
|
||||
sorted, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{
|
||||
Page: repository.PageQuery{
|
||||
Offset: 0,
|
||||
Limit: 4,
|
||||
Sort: repository.SortQuery{Field: "prompt", Direction: repository.SortAscending},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 4 {
|
||||
t.Fatalf("sorted total = %d", total)
|
||||
}
|
||||
assertMediaJobIDs(t, sorted, "media_job_completed_old", "media_job_completed_new", "media_job_failed_newer", "media_job_queued_mid")
|
||||
|
||||
stats, err := jobRepo.SummarizeMediaJobs(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stats.TotalJobs != 4 || stats.Completed != 2 || stats.Failed != 1 || stats.InProgress != 0 || stats.Queued != 1 {
|
||||
t.Fatalf("stats = %#v", stats)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaAssetRepositoryListMediaAssetsPaginatesAndCounts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
assetRepo := NewMediaAssetRepository(database)
|
||||
|
||||
stats, err := assetRepo.SummarizeMediaAssets(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stats.TotalImages != 0 || stats.TotalBytes != 0 {
|
||||
t.Fatalf("initial stats = %#v", stats)
|
||||
}
|
||||
|
||||
now := time.Date(2026, 7, 13, 12, 0, 0, 0, time.UTC)
|
||||
assets := []mediadomain.Asset{
|
||||
testMediaAsset("media_asset_0001", "media/asset-0001.png", now.Add(-3*time.Hour)),
|
||||
testMediaAsset("media_asset_0002", "media/asset-0002.png", now.Add(-2*time.Hour)),
|
||||
testMediaAsset("media_asset_0003", "media/asset-0003.png", now.Add(-time.Hour)),
|
||||
}
|
||||
for _, asset := range assets {
|
||||
if err := assetRepo.CreateMediaAsset(ctx, asset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
firstPage, total, err := assetRepo.ListMediaAssets(ctx, repository.MediaAssetListQuery{
|
||||
Page: repository.PageQuery{Offset: 0, Limit: 2},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 3 {
|
||||
t.Fatalf("total = %d", total)
|
||||
}
|
||||
assertMediaAssetIDs(t, firstPage, "media_asset_0003", "media_asset_0002")
|
||||
|
||||
secondPage, total, err := assetRepo.ListMediaAssets(ctx, repository.MediaAssetListQuery{
|
||||
Page: repository.PageQuery{Offset: 2, Limit: 2},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 3 {
|
||||
t.Fatalf("second page total = %d", total)
|
||||
}
|
||||
assertMediaAssetIDs(t, secondPage, "media_asset_0001")
|
||||
|
||||
searched, total, err := assetRepo.ListMediaAssets(ctx, repository.MediaAssetListQuery{
|
||||
Page: repository.PageQuery{Offset: 0, Limit: 1, Search: "0001"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 1 {
|
||||
t.Fatalf("searched total = %d", total)
|
||||
}
|
||||
assertMediaAssetIDs(t, searched, "media_asset_0001")
|
||||
|
||||
stats, err = assetRepo.SummarizeMediaAssets(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stats.TotalImages != 3 || stats.TotalBytes != 3*1024 {
|
||||
t.Fatalf("stats = %#v", stats)
|
||||
}
|
||||
}
|
||||
|
||||
func testMediaJob(id string, accountID, clientKeyID uint64, status mediadomain.Status, createdAt time.Time) mediadomain.Job {
|
||||
job := mediadomain.Job{
|
||||
ID: id,
|
||||
RequestID: "request-" + id,
|
||||
ClientKeyID: clientKeyID,
|
||||
ClientKeyName: "media-list-key",
|
||||
AccountID: accountID,
|
||||
AccountName: "media-list-account",
|
||||
Provider: "grok_web",
|
||||
Model: "grok-imagine-video",
|
||||
ModelRouteID: 1,
|
||||
UpstreamModel: "grok-imagine-video-upstream",
|
||||
Prompt: "test prompt",
|
||||
Seconds: 8,
|
||||
Size: "16:9",
|
||||
Quality: "720p",
|
||||
Status: status,
|
||||
InputJSON: `{}`,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: createdAt,
|
||||
}
|
||||
if status == mediadomain.StatusCompleted || status == mediadomain.StatusFailed {
|
||||
job.Progress = 100
|
||||
completedAt := createdAt.Add(time.Minute)
|
||||
job.CompletedAt = &completedAt
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
func testMediaAsset(id, storageKey string, createdAt time.Time) mediadomain.Asset {
|
||||
return mediadomain.Asset{
|
||||
ID: id,
|
||||
Kind: "image",
|
||||
StorageKey: storageKey,
|
||||
MIMEType: "image/png",
|
||||
SizeBytes: 1024,
|
||||
SHA256: strings.Repeat("a", 64),
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
func assertMediaJobIDs(t *testing.T, values []mediadomain.Job, expected ...string) {
|
||||
t.Helper()
|
||||
if len(values) != len(expected) {
|
||||
t.Fatalf("len(values) = %d, expected %d: %#v", len(values), len(expected), values)
|
||||
}
|
||||
for index, id := range expected {
|
||||
if values[index].ID != id {
|
||||
t.Fatalf("values[%d].ID = %q, expected %q; values = %#v", index, values[index].ID, id, values)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertMediaAssetIDs(t *testing.T, values []mediadomain.Asset, expected ...string) {
|
||||
t.Helper()
|
||||
if len(values) != len(expected) {
|
||||
t.Fatalf("len(values) = %d, expected %d: %#v", len(values), len(expected), values)
|
||||
}
|
||||
for index, id := range expected {
|
||||
if values[index].ID != id {
|
||||
t.Fatalf("values[%d].ID = %q, expected %q; values = %#v", index, values[index].ID, id, values)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +260,10 @@ type requestAuditModel struct {
|
||||
UsageSource string `gorm:"size:16;not null;check:chk_request_audits_usage_source,usage_source IN ('upstream','estimated','none')"`
|
||||
AccountID *uint64 `gorm:"check:chk_request_audits_account_id,account_id IS NULL OR account_id > 0"`
|
||||
AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"`
|
||||
EgressNodeID *uint64 `gorm:"check:chk_request_audits_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"`
|
||||
EgressNodeName string `gorm:"size:160;not null;default:'';check:chk_request_audits_egress_node_name,length(egress_node_name) <= 160"`
|
||||
EgressScope string `gorm:"size:32;not null;default:'';check:chk_request_audits_egress_scope,egress_scope IN ('','grok_build','grok_web','grok_console','grok_web_asset')"`
|
||||
EgressMode string `gorm:"size:16;not null;default:'';check:chk_request_audits_egress_mode,egress_mode IN ('','direct','proxy')"`
|
||||
StatusCode int `gorm:"not null;check:chk_request_audits_status_code,status_code BETWEEN 100 AND 599"`
|
||||
Streaming bool `gorm:"not null;default:false"`
|
||||
MediaInputImages int64 `gorm:"not null;default:0"`
|
||||
@@ -315,27 +319,31 @@ type webResponseStateModel struct {
|
||||
func (webResponseStateModel) TableName() string { return "web_response_states" }
|
||||
|
||||
type mediaJobModel struct {
|
||||
ID string `gorm:"size:64;primaryKey;check:chk_media_jobs_id,length(id) BETWEEN 1 AND 64"`
|
||||
RequestID string `gorm:"size:64;not null;check:chk_media_jobs_request_id,length(request_id) BETWEEN 1 AND 64"`
|
||||
ClientKeyID uint64 `gorm:"not null;check:chk_media_jobs_client_key_id,client_key_id > 0"`
|
||||
ClientKeyName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_client_key_name,length(client_key_name) <= 160"`
|
||||
AccountID uint64 `gorm:"not null;check:chk_media_jobs_account_id,account_id > 0"`
|
||||
AccountName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_account_name,length(account_name) <= 160"`
|
||||
Provider string `gorm:"size:32;not null;check:chk_media_jobs_provider,provider IN ('grok_web')"`
|
||||
Model string `gorm:"size:255;not null;check:chk_media_jobs_model,length(trim(model)) BETWEEN 1 AND 255"`
|
||||
ModelRouteID uint64 `gorm:"not null;check:chk_media_jobs_model_route_id,model_route_id > 0"`
|
||||
UpstreamModel string `gorm:"size:255;not null;check:chk_media_jobs_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
|
||||
Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"`
|
||||
Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"`
|
||||
Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"`
|
||||
Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"`
|
||||
Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"`
|
||||
Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"`
|
||||
InputJSON string `gorm:"type:text;not null;default:'{}';check:chk_media_jobs_input_json,length(input_json) <= 1048576"`
|
||||
UpstreamURL string `gorm:"type:text;not null;default:'';check:chk_media_jobs_upstream_url,length(upstream_url) <= 8192"`
|
||||
ContentType string `gorm:"size:128;not null;default:'';check:chk_media_jobs_content_type,length(content_type) <= 128"`
|
||||
ErrorCode string `gorm:"size:100;not null;default:'';check:chk_media_jobs_error_code,length(error_code) <= 100"`
|
||||
ErrorMessage string `gorm:"size:512;not null;default:'';check:chk_media_jobs_error_message,length(error_message) <= 512"`
|
||||
ID string `gorm:"size:64;primaryKey;check:chk_media_jobs_id,length(id) BETWEEN 1 AND 64"`
|
||||
RequestID string `gorm:"size:64;not null;check:chk_media_jobs_request_id,length(request_id) BETWEEN 1 AND 64"`
|
||||
ClientKeyID uint64 `gorm:"not null;check:chk_media_jobs_client_key_id,client_key_id > 0"`
|
||||
ClientKeyName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_client_key_name,length(client_key_name) <= 160"`
|
||||
AccountID uint64 `gorm:"not null;check:chk_media_jobs_account_id,account_id > 0"`
|
||||
AccountName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_account_name,length(account_name) <= 160"`
|
||||
EgressNodeID *uint64 `gorm:"check:chk_media_jobs_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"`
|
||||
EgressNodeName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_egress_node_name,length(egress_node_name) <= 160"`
|
||||
EgressScope string `gorm:"size:32;not null;default:'';check:chk_media_jobs_egress_scope,egress_scope IN ('','grok_web')"`
|
||||
EgressMode string `gorm:"size:16;not null;default:'';check:chk_media_jobs_egress_mode,egress_mode IN ('','direct','proxy')"`
|
||||
Provider string `gorm:"size:32;not null;check:chk_media_jobs_provider,provider IN ('grok_web')"`
|
||||
Model string `gorm:"size:255;not null;check:chk_media_jobs_model,length(trim(model)) BETWEEN 1 AND 255"`
|
||||
ModelRouteID uint64 `gorm:"not null;check:chk_media_jobs_model_route_id,model_route_id > 0"`
|
||||
UpstreamModel string `gorm:"size:255;not null;check:chk_media_jobs_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
|
||||
Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"`
|
||||
Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"`
|
||||
Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"`
|
||||
Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"`
|
||||
Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"`
|
||||
Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"`
|
||||
InputJSON string `gorm:"type:text;not null;default:'{}';check:chk_media_jobs_input_json,length(input_json) <= 1048576"`
|
||||
UpstreamURL string `gorm:"type:text;not null;default:'';check:chk_media_jobs_upstream_url,length(upstream_url) <= 8192"`
|
||||
ContentType string `gorm:"size:128;not null;default:'';check:chk_media_jobs_content_type,length(content_type) <= 128"`
|
||||
ErrorCode string `gorm:"size:100;not null;default:'';check:chk_media_jobs_error_code,length(error_code) <= 100"`
|
||||
ErrorMessage string `gorm:"size:512;not null;default:'';check:chk_media_jobs_error_message,length(error_message) <= 512"`
|
||||
LeaseUntil *time.Time
|
||||
ClaimToken string `gorm:"size:64;not null;default:'';check:chk_media_jobs_claim_token,claim_token = '' OR length(claim_token) BETWEEN 16 AND 64"`
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
|
||||
@@ -68,15 +68,29 @@ func TestWebResponseStateAndMediaJobRoundTrip(t *testing.T) {
|
||||
if err := jobs.UpdateMediaJob(ctx, claimed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unrecorded, err := jobs.ListUnrecordedCompletedMediaJobs(ctx, 10)
|
||||
unrecorded, err := jobs.ListUnrecordedTerminalMediaJobs(ctx, 10)
|
||||
if err != nil || len(unrecorded) != 1 || unrecorded[0].RequestID != job.RequestID || unrecorded[0].ModelRouteID != job.ModelRouteID {
|
||||
t.Fatalf("unrecorded jobs = %#v, err = %v", unrecorded, err)
|
||||
}
|
||||
if err := jobs.MarkMediaJobUsageRecorded(ctx, job.ID, completedAt.Add(time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unrecorded, err = jobs.ListUnrecordedCompletedMediaJobs(ctx, 10)
|
||||
unrecorded, err = jobs.ListUnrecordedTerminalMediaJobs(ctx, 10)
|
||||
if err != nil || len(unrecorded) != 0 {
|
||||
t.Fatalf("recorded jobs = %#v, err = %v", unrecorded, err)
|
||||
}
|
||||
failedAt := completedAt.Add(2 * time.Second)
|
||||
failed := job
|
||||
failed.ID, failed.RequestID, failed.Status, failed.ErrorCode = "video_failed", "request-video-failed", mediadomain.StatusFailed, "generation_failed"
|
||||
failed.Progress, failed.ClaimToken, failed.CompletedAt, failed.UpdatedAt = 50, "", &failedAt, failedAt
|
||||
if err := jobs.CreateMediaJob(ctx, failed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unrecorded, err = jobs.ListUnrecordedTerminalMediaJobs(ctx, 10)
|
||||
if err != nil || len(unrecorded) != 1 || unrecorded[0].ID != failed.ID {
|
||||
t.Fatalf("failed unrecorded jobs = %#v, err = %v", unrecorded, err)
|
||||
}
|
||||
if err := jobs.MarkMediaJobUsageRecorded(ctx, failed.ID, failedAt.Add(time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func normalizeResponseFormat(raw json.RawMessage) (json.RawMessage, error) {
|
||||
if err := json.Unmarshal(format["json_schema"], &schema); err != nil {
|
||||
return nil, fmt.Errorf("解析 response_format.json_schema: %w", err)
|
||||
}
|
||||
result := make(map[string]json.RawMessage, len(schema)+1)
|
||||
result := make(map[string]json.RawMessage, len(schema))
|
||||
result["type"] = mustJSON("json_schema")
|
||||
for key, value := range schema {
|
||||
result[key] = value
|
||||
|
||||
@@ -455,3 +455,23 @@ func TestConvertResponsesStreamEmitsDoneOnlyToolArguments(t *testing.T) {
|
||||
t.Fatalf("tool block closed multiple times: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertResponsesStreamMessagesInputTokens(t *testing.T) {
|
||||
stream := strings.Join([]string{
|
||||
`event: response.created`,
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.5","status":"in_progress"}}`, "",
|
||||
`event: response.output_text.delta`,
|
||||
`data: {"type":"response.output_text.delta","delta":"hello"}`, "",
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.5","status":"completed","usage":{"input_tokens":194,"output_tokens":7}}}`, "", "",
|
||||
}, "\n")
|
||||
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationMessages))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(converted)
|
||||
|
||||
if !strings.Contains(text, `"input_tokens":194`) {
|
||||
t.Fatalf("message_delta should contain input_tokens from response.completed usage:\n%s", text)
|
||||
}
|
||||
}
|
||||
@@ -294,7 +294,7 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions,
|
||||
"model": model, "input": input, "stream": request.Stream,
|
||||
"max_output_tokens": request.MaxTokens, "store": false,
|
||||
}
|
||||
instructions := make([]string, 0, len(inlineInstructions)+1)
|
||||
instructions := make([]string, 0, len(inlineInstructions))
|
||||
if system, err := anthropicSystemText(request.System); err != nil {
|
||||
return nil, ResponseOptions{}, err
|
||||
} else if system != "" {
|
||||
|
||||
@@ -413,7 +413,7 @@ func (c *streamConverter) done(status string) error {
|
||||
}
|
||||
if err := c.writeEvent("message_delta", map[string]any{
|
||||
"type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nullableAnthropicString(c.stopSequence)},
|
||||
"usage": map[string]any{"output_tokens": c.usage.OutputTokens},
|
||||
"usage": map[string]any{"input_tokens": c.usage.InputTokens, "output_tokens": c.usage.OutputTokens},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -8,12 +8,45 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
)
|
||||
|
||||
// MediaAssetListQuery 表示管理端媒体资源列表的查询条件。
|
||||
type MediaAssetListQuery struct {
|
||||
Page PageQuery
|
||||
}
|
||||
|
||||
// MediaJobListFilter 表示视频任务列表允许使用的业务筛选条件。
|
||||
type MediaJobListFilter struct {
|
||||
Status string
|
||||
}
|
||||
|
||||
// MediaJobListQuery 表示管理端视频任务列表的查询条件。
|
||||
type MediaJobListQuery struct {
|
||||
Page PageQuery
|
||||
Filter MediaJobListFilter
|
||||
}
|
||||
|
||||
// MediaAssetStats 表示媒体资源的聚合统计结果。
|
||||
type MediaAssetStats struct {
|
||||
TotalImages int64
|
||||
TotalBytes int64
|
||||
}
|
||||
|
||||
// MediaJobStats 表示各状态视频任务的聚合统计结果。
|
||||
type MediaJobStats struct {
|
||||
TotalJobs int64
|
||||
Completed int64
|
||||
Failed int64
|
||||
InProgress int64
|
||||
Queued int64
|
||||
}
|
||||
|
||||
type MediaJobRepository interface {
|
||||
CreateMediaJob(ctx context.Context, value media.Job) error
|
||||
GetMediaJob(ctx context.Context, id string, clientKeyID uint64) (media.Job, error)
|
||||
UpdateMediaJob(ctx context.Context, value media.Job) error
|
||||
ListMediaJobs(ctx context.Context, query MediaJobListQuery) ([]media.Job, int64, error)
|
||||
SummarizeMediaJobs(ctx context.Context) (MediaJobStats, error)
|
||||
ListRecoverableMediaJobs(ctx context.Context, limit int) ([]media.Job, error)
|
||||
ListUnrecordedCompletedMediaJobs(ctx context.Context, limit int) ([]media.Job, error)
|
||||
ListUnrecordedTerminalMediaJobs(ctx context.Context, limit int) ([]media.Job, error)
|
||||
TryClaimMediaJob(ctx context.Context, id string, now, leaseUntil time.Time, claimToken string) (media.Job, bool, error)
|
||||
MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error
|
||||
}
|
||||
@@ -22,6 +55,8 @@ type MediaJobRepository interface {
|
||||
type MediaAssetRepository interface {
|
||||
CreateMediaAsset(ctx context.Context, value media.Asset) error
|
||||
GetMediaAsset(ctx context.Context, id string) (media.Asset, error)
|
||||
ListMediaAssets(ctx context.Context, query MediaAssetListQuery) ([]media.Asset, int64, error)
|
||||
SummarizeMediaAssets(ctx context.Context) (MediaAssetStats, error)
|
||||
TotalMediaAssetBytes(ctx context.Context) (int64, error)
|
||||
ListOldestMediaAssets(ctx context.Context, limit int) ([]media.Asset, error)
|
||||
DeleteMediaAsset(ctx context.Context, id string) error
|
||||
|
||||
@@ -35,6 +35,10 @@ type auditResponse struct {
|
||||
UsageSource string `json:"usageSource"`
|
||||
AccountID *uint64 `json:"accountId,string,omitempty"`
|
||||
AccountName string `json:"accountName,omitempty"`
|
||||
EgressNodeID *uint64 `json:"egressNodeId,string,omitempty"`
|
||||
EgressNodeName string `json:"egressNodeName,omitempty"`
|
||||
EgressScope string `json:"egressScope,omitempty"`
|
||||
EgressMode string `json:"egressMode,omitempty"`
|
||||
StatusCode int `json:"statusCode"`
|
||||
Streaming bool `json:"streaming"`
|
||||
MediaInputImages int64 `json:"mediaInputImages"`
|
||||
@@ -195,7 +199,9 @@ func newAuditResponse(value auditdomain.Record) auditResponse {
|
||||
ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName,
|
||||
ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel,
|
||||
Provider: value.Provider, Operation: string(value.Operation), UsageSource: string(value.UsageSource),
|
||||
AccountID: value.AccountID, AccountName: value.AccountName, StatusCode: value.StatusCode, Streaming: value.Streaming,
|
||||
AccountID: value.AccountID, AccountName: value.AccountName,
|
||||
EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: string(value.EgressMode),
|
||||
StatusCode: value.StatusCode, Streaming: value.Streaming,
|
||||
MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds,
|
||||
InputTokens: value.InputTokens, CachedInputTokens: value.CachedInputTokens, OutputTokens: value.OutputTokens,
|
||||
ReasoningTokens: value.ReasoningTokens, TotalTokens: value.TotalTokens, CostInUSDTicks: value.CostInUSDTicks,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package media
|
||||
|
||||
type mediaAssetDTO struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
MimeType string `json:"mimeType"`
|
||||
SizeBytes int64 `json:"sizeBytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type imageStatsDTO struct {
|
||||
TotalImages int64 `json:"totalImages"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
}
|
||||
|
||||
type mediaJobDTO struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Prompt string `json:"prompt"`
|
||||
Status string `json:"status"`
|
||||
Progress int `json:"progress"`
|
||||
Seconds int `json:"seconds"`
|
||||
Size string `json:"size"`
|
||||
Quality string `json:"quality"`
|
||||
AccountName string `json:"accountName"`
|
||||
ClientKeyName string `json:"clientKeyName"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
CompletedAt *string `json:"completedAt"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
}
|
||||
|
||||
type videoStatsDTO struct {
|
||||
TotalJobs int64 `json:"totalJobs"`
|
||||
Completed int64 `json:"completed"`
|
||||
Failed int64 `json:"failed"`
|
||||
InProgress int64 `json:"inProgress"`
|
||||
Queued int64 `json:"queued"`
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"strings"
|
||||
|
||||
mediaapp "github.com/chenyme/grok2api/backend/internal/application/media"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
"github.com/chenyme/grok2api/backend/internal/shared/response"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -23,6 +25,14 @@ func (h *Handler) RegisterPublic(router *gin.Engine) {
|
||||
router.HEAD("/v1/media/images/:assetId", h.getImage)
|
||||
}
|
||||
|
||||
// RegisterAdmin 注册管理端媒体列表和统计端点。
|
||||
func (h *Handler) RegisterAdmin(router *gin.RouterGroup) {
|
||||
router.GET("/media/images", h.listImages)
|
||||
router.GET("/media/images/stats", h.imageStats)
|
||||
router.GET("/media/videos", h.listVideos)
|
||||
router.GET("/media/videos/stats", h.videoStats)
|
||||
}
|
||||
|
||||
func (h *Handler) getImage(c *gin.Context) {
|
||||
asset, body, err := h.service.OpenImage(c.Request.Context(), c.Param("assetId"))
|
||||
if errors.Is(err, mediaapp.ErrAssetNotFound) {
|
||||
@@ -52,3 +62,86 @@ func (h *Handler) getImage(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
_, _ = io.Copy(c.Writer, body)
|
||||
}
|
||||
|
||||
func (h *Handler) listImages(c *gin.Context) {
|
||||
page, pageSize := parsePagination(c)
|
||||
assets, total, err := h.service.AdminListImages(c.Request.Context(), page, pageSize, c.Query("search"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "mediaListImagesFailed", "读取图片列表失败")
|
||||
return
|
||||
}
|
||||
items := make([]mediaAssetDTO, 0, len(assets))
|
||||
for _, a := range assets {
|
||||
items = append(items, mediaAssetDTO{
|
||||
ID: a.ID, Kind: a.Kind, MimeType: a.MIMEType, SizeBytes: a.SizeBytes,
|
||||
SHA256: a.SHA256, CreatedAt: a.CreatedAt.Format("2006-01-02T15:04:05Z"),
|
||||
URL: h.service.PublicImageURL(a.ID),
|
||||
})
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"items": items, "page": page, "pageSize": pageSize, "total": total})
|
||||
}
|
||||
|
||||
func (h *Handler) imageStats(c *gin.Context) {
|
||||
stats, err := h.service.AdminImageStats(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "mediaImageStatsFailed", "读取图片统计失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, imageStatsDTO{TotalImages: stats.TotalImages, TotalBytes: stats.TotalBytes})
|
||||
}
|
||||
|
||||
func (h *Handler) listVideos(c *gin.Context) {
|
||||
page, pageSize := parsePagination(c)
|
||||
jobs, total, err := h.service.AdminListVideoJobs(c.Request.Context(), page, pageSize, c.Query("search"), c.Query("status"), repository.SortQuery{Field: c.Query("sortBy"), Direction: repository.SortDirection(c.Query("sortOrder"))})
|
||||
if errors.Is(err, mediaapp.ErrInvalidFilter) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidFilter", err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "mediaListVideosFailed", "读取视频任务列表失败")
|
||||
return
|
||||
}
|
||||
items := make([]mediaJobDTO, 0, len(jobs))
|
||||
for _, j := range jobs {
|
||||
var completedAt *string
|
||||
if j.CompletedAt != nil {
|
||||
formatted := j.CompletedAt.Format("2006-01-02T15:04:05Z")
|
||||
completedAt = &formatted
|
||||
}
|
||||
items = append(items, mediaJobDTO{
|
||||
ID: j.ID, Model: j.Model, Prompt: j.Prompt, Status: string(j.Status),
|
||||
Progress: j.Progress, Seconds: j.Seconds, Size: j.Size, Quality: j.Quality,
|
||||
AccountName: j.AccountName, ClientKeyName: j.ClientKeyName,
|
||||
CreatedAt: j.CreatedAt.Format("2006-01-02T15:04:05Z"),
|
||||
CompletedAt: completedAt, ErrorMessage: j.ErrorMessage,
|
||||
})
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"items": items, "page": page, "pageSize": pageSize, "total": total})
|
||||
}
|
||||
|
||||
func (h *Handler) videoStats(c *gin.Context) {
|
||||
stats, err := h.service.AdminVideoStats(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "mediaVideoStatsFailed", "读取视频统计失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, videoStatsDTO{
|
||||
TotalJobs: stats.TotalJobs, Completed: stats.Completed, Failed: stats.Failed,
|
||||
InProgress: stats.InProgress, Queued: stats.Queued,
|
||||
})
|
||||
}
|
||||
|
||||
func parsePagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
@@ -30,7 +30,7 @@ func TestPublicImageSupportsGetHeadAndETag(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := mediaapp.NewService(relational.NewMediaAssetRepository(database), objects, nil, mediaapp.Config{
|
||||
service := mediaapp.NewService(relational.NewMediaAssetRepository(database), relational.NewMediaJobRepository(database), objects, nil, mediaapp.Config{
|
||||
PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30,
|
||||
CleanupThresholdPercent: 80, CleanupInterval: 10 * time.Minute,
|
||||
})
|
||||
@@ -61,3 +61,37 @@ func TestPublicImageSupportsGetHeadAndETag(t *testing.T) {
|
||||
t.Fatalf("conditional GET status=%d size=%d", notModified.Code, notModified.Body.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminVideoListRejectsInvalidFilters(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-admin-http.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := mediaapp.NewService(
|
||||
relational.NewMediaAssetRepository(database),
|
||||
relational.NewMediaJobRepository(database),
|
||||
nil,
|
||||
nil,
|
||||
mediaapp.Config{},
|
||||
)
|
||||
router := gin.New()
|
||||
NewHandler(service).RegisterAdmin(router.Group("/api/admin/v1"))
|
||||
|
||||
for _, path := range []string{
|
||||
"/api/admin/v1/media/videos?status=unknown",
|
||||
"/api/admin/v1/media/videos?sortBy=input_json&sortOrder=asc",
|
||||
"/api/admin/v1/media/videos?sortBy=createdAt&sortOrder=sideways",
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("GET %s status = %d, body = %s", path, recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,8 @@ func New(deps Dependencies) *gin.Engine {
|
||||
if deps.SwaggerEnabled {
|
||||
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
}
|
||||
mediahttp.NewHandler(deps.Media).RegisterPublic(router)
|
||||
mediaHandler := mediahttp.NewHandler(deps.Media)
|
||||
mediaHandler.RegisterPublic(router)
|
||||
|
||||
adminRoot := router.Group("/api/admin/v1")
|
||||
authHandler := adminauthhttp.NewHandler(deps.AdminAuth, deps.SecureCookies)
|
||||
@@ -139,6 +140,7 @@ func New(deps Dependencies) *gin.Engine {
|
||||
clientkeyhttp.NewHandler(deps.ClientKeys).Register(adminProtected)
|
||||
audithttp.NewHandler(deps.Audits).Register(adminProtected)
|
||||
dashboardhttp.NewHandler(deps.Dashboard).Register(adminProtected)
|
||||
mediaHandler.RegisterAdmin(adminProtected)
|
||||
settingshttp.NewHandler(deps.Settings).Register(adminProtected)
|
||||
egresshttp.NewHandler(deps.Egress).Register(adminProtected)
|
||||
systemhttp.NewHandler(deps.PublicAPIBaseURL).Register(adminProtected)
|
||||
|
||||
@@ -24,6 +24,8 @@ const navigation = [
|
||||
{ href: "/accounts", label: "nav.accounts", icon: Users },
|
||||
{ href: "/client-keys", label: "nav.clientKeys", icon: KeyRound },
|
||||
{ href: "/models", label: "nav.models", icon: Box },
|
||||
{ href: "/gallery", label: "nav.gallery", icon: Image },
|
||||
{ href: "/video-gallery", label: "nav.videoGallery", icon: Video },
|
||||
{ href: "/request-audits", label: "nav.audits", icon: Eye },
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ const RequestAuditsPage = lazyNamed(() => import("@/features/audits/request-audi
|
||||
const ClientKeysPage = lazyNamed(() => import("@/features/client-keys/client-keys-page"), "ClientKeysPage");
|
||||
const DashboardPage = lazyNamed(() => import("@/features/dashboard/dashboard-page"), "DashboardPage");
|
||||
const ApiDocsPage = lazyNamed(() => import("@/features/docs/api-docs-page"), "ApiDocsPage");
|
||||
const GalleryPage = lazyNamed(() => import("@/features/media/gallery-page"), "GalleryPage");
|
||||
const VideoGalleryPage = lazyNamed(() => import("@/features/media/video-gallery-page"), "VideoGalleryPage");
|
||||
const ModelsPage = lazyNamed(() => import("@/features/models/models-page"), "ModelsPage");
|
||||
const SettingsPage = lazyNamed(() => import("@/features/settings/settings-page"), "SettingsPage");
|
||||
|
||||
@@ -43,6 +45,14 @@ export function DeferredRequestAuditsPage() {
|
||||
return <DeferredPage page={RequestAuditsPage} />;
|
||||
}
|
||||
|
||||
export function DeferredGalleryPage() {
|
||||
return <DeferredPage page={GalleryPage} />;
|
||||
}
|
||||
|
||||
export function DeferredVideoGalleryPage() {
|
||||
return <DeferredPage page={VideoGalleryPage} />;
|
||||
}
|
||||
|
||||
export function DeferredApiDocsPage() {
|
||||
return <DeferredPage page={ApiDocsPage} />;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Navigate, createBrowserRouter } from "react-router-dom";
|
||||
|
||||
import { AnonymousBoundary, AuthBoundary } from "@/app/auth-boundary";
|
||||
import { DeferredAccountsPage, DeferredApiDocsPage, DeferredAppShell, DeferredClientKeysPage, DeferredDashboardPage, DeferredModelsPage, DeferredRequestAuditsPage, DeferredSettingsPage } from "@/app/deferred-pages";
|
||||
import { DeferredAccountsPage, DeferredApiDocsPage, DeferredAppShell, DeferredClientKeysPage, DeferredDashboardPage, DeferredGalleryPage, DeferredModelsPage, DeferredRequestAuditsPage, DeferredSettingsPage, DeferredVideoGalleryPage } from "@/app/deferred-pages";
|
||||
import { LoginPage } from "@/features/auth/login-page";
|
||||
|
||||
export const router = createBrowserRouter([
|
||||
@@ -20,6 +20,8 @@ export const router = createBrowserRouter([
|
||||
{ path: "/accounts", element: <DeferredAccountsPage /> },
|
||||
{ path: "/models", element: <DeferredModelsPage /> },
|
||||
{ path: "/client-keys", element: <DeferredClientKeysPage /> },
|
||||
{ path: "/gallery", element: <DeferredGalleryPage /> },
|
||||
{ path: "/video-gallery", element: <DeferredVideoGalleryPage /> },
|
||||
{ path: "/request-audits", element: <DeferredRequestAuditsPage /> },
|
||||
{ path: "/docs", element: <Navigate to="/docs/chat/completions" replace /> },
|
||||
{ path: "/docs/:category/:endpoint", element: <DeferredApiDocsPage /> },
|
||||
|
||||
@@ -18,6 +18,10 @@ export type AuditDTO = {
|
||||
usageSource: "upstream" | "estimated" | "none";
|
||||
accountId?: string;
|
||||
accountName?: string;
|
||||
egressNodeId?: string;
|
||||
egressNodeName?: string;
|
||||
egressScope?: "grok_build" | "grok_web" | "grok_console" | "grok_web_asset";
|
||||
egressMode?: "direct" | "proxy";
|
||||
statusCode: number;
|
||||
streaming: boolean;
|
||||
mediaInputImages: number;
|
||||
@@ -79,7 +83,10 @@ 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", "grok_console"),
|
||||
operation: isOneOf("responses", "chat", "messages", "image", "image_edit", "video"), usageSource: isOneOf("upstream", "estimated", "none"),
|
||||
accountId: isOptional(isString), accountName: isOptional(isString), statusCode: isNumber, streaming: isBoolean,
|
||||
accountId: isOptional(isString), accountName: isOptional(isString),
|
||||
egressNodeId: isOptional(isString), egressNodeName: isOptional(isString),
|
||||
egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset")), egressMode: isOptional(isOneOf("direct", "proxy")),
|
||||
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),
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Table, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table";
|
||||
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 { getRequestAudits, getRequestAuditSummary, type AuditDTO, type AuditPeriod } from "@/features/audits/request-audits-api";
|
||||
@@ -153,21 +153,23 @@ export function RequestAuditsPage() {
|
||||
{auditsQuery.isError ? <ErrorState message={auditsQuery.error.message} onRetry={() => void auditsQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState /> : null}
|
||||
{auditsQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="min-w-[1160px] table-fixed text-xs">
|
||||
<Table className="min-w-[1280px] table-fixed text-xs">
|
||||
<colgroup>
|
||||
<col className="w-[14%]" />
|
||||
<col className="w-[14%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[26%]" />
|
||||
<col className="w-[8%]" />
|
||||
<col className="w-[12%]" />
|
||||
<col className="w-[13%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[9%]" />
|
||||
<col className="w-[24%]" />
|
||||
<col className="w-[7%]" />
|
||||
<col className="w-[11%]" />
|
||||
<col className="w-[9%]" />
|
||||
<col className="w-[7%]" />
|
||||
<col className="w-[9%]" />
|
||||
</colgroup>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<SortableTableHead field="request" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("audits.request")}</SortableTableHead>
|
||||
<SortableTableHead field="model" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("audits.model")}</SortableTableHead>
|
||||
<TableHead>{t("audits.egress")}</TableHead>
|
||||
<SortableTableHead field="billing" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" onSort={changeSort}>{t("audits.billing")}</SortableTableHead>
|
||||
<SortableTableHead field="tokens" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" onSort={changeSort}>{t("audits.tokens")}</SortableTableHead>
|
||||
<SortableTableHead field="status" sortBy={sort.field} sortOrder={sort.order} align="center" onSort={changeSort}>{t("audits.status")}</SortableTableHead>
|
||||
@@ -177,7 +179,7 @@ export function RequestAuditsPage() {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{auditsQuery.isPending ? <TableLoadingRow colSpan={8} /> : result?.items.map((audit) => (
|
||||
{auditsQuery.isPending ? <TableLoadingRow colSpan={9} /> : result?.items.map((audit) => (
|
||||
<TableRow key={audit.id}>
|
||||
<TableCell className="py-3">
|
||||
<span className="block truncate text-xs" title={audit.requestId}>{audit.requestId}</span>
|
||||
@@ -190,6 +192,7 @@ export function RequestAuditsPage() {
|
||||
clientKey={audit.clientKeyName || `#${audit.clientKeyId}`}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="py-3"><EgressValue audit={audit} /></TableCell>
|
||||
<TableCell className="py-3"><BillingValue audit={audit} /></TableCell>
|
||||
<TableCell className="py-3"><UsageDetails audit={audit} locale={i18n.language} /></TableCell>
|
||||
<TableCell className="py-3 text-center"><AuditStatus statusCode={audit.statusCode} errorCode={audit.errorCode} /></TableCell>
|
||||
@@ -206,6 +209,32 @@ export function RequestAuditsPage() {
|
||||
);
|
||||
}
|
||||
|
||||
function EgressValue({ audit }: { audit: AuditDTO }) {
|
||||
const { t } = useTranslation();
|
||||
if (!audit.egressMode) {
|
||||
return <span className="text-muted-foreground">-</span>;
|
||||
}
|
||||
const proxied = audit.egressMode === "proxy";
|
||||
const node = audit.egressNodeName || (proxied ? t("audits.egressUnknown") : t("audits.egressDirect"));
|
||||
const details = [audit.egressScope, audit.egressNodeId ? `#${audit.egressNodeId}` : ""].filter(Boolean).join(" · ");
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="block min-w-0 max-w-full cursor-help text-left" aria-label={`${proxied ? t("audits.egressProxy") : t("audits.egressDirect")}: ${node}`}>
|
||||
<Badge variant="outline" className={cn("max-w-full font-normal", proxied ? "border-emerald-500/35 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground")}>
|
||||
<span className="truncate">{proxied ? t("audits.egressProxy") : t("audits.egressDirect")}</span>
|
||||
</Badge>
|
||||
<span className="mt-1 block truncate text-[10px] text-muted-foreground">{node}</span>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-72" side="top" align="start">
|
||||
<div>{node}</div>
|
||||
{details ? <div className="mt-1 text-primary-foreground/65">{details}</div> : null}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function BillingValue({ audit }: { audit: AuditDTO }) {
|
||||
const { t } = useTranslation();
|
||||
const upstreamReported = audit.costInUsdTicks > 0;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Database, Image as ImageIcon, RefreshCw, Search, type LucideIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { getImageStats, listImages } from "@/features/media/media-api";
|
||||
import type { MediaAssetDTO } from "@/features/media/types";
|
||||
import { EmptyState, ErrorState, LoadingState } from "@/shared/components/data-state";
|
||||
import { PageHeader } from "@/shared/components/page-header";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { formatDateTime, formatNumber } from "@/shared/lib/format";
|
||||
|
||||
export function GalleryPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [search, setSearch] = useState("");
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const normalizedSearch = debouncedSearch.trim();
|
||||
|
||||
const imagesQuery = useQuery({
|
||||
queryKey: ["media", "images", page, pageSize, normalizedSearch],
|
||||
queryFn: () => listImages({ page, pageSize, search: normalizedSearch || undefined }),
|
||||
});
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ["media", "images", "stats"],
|
||||
queryFn: getImageStats,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
const result = imagesQuery.data;
|
||||
const refreshing = imagesQuery.isFetching || statsQuery.isFetching;
|
||||
|
||||
function refreshAll(): void {
|
||||
void imagesQuery.refetch();
|
||||
void statsQuery.refetch();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={t("media.images.title")}
|
||||
description={t("media.images.description")}
|
||||
actions={(
|
||||
<Button variant="secondary" size="sm" onClick={refreshAll} disabled={refreshing}>
|
||||
<RefreshCw className={refreshing ? "animate-spin" : undefined} />
|
||||
{t("common.refresh")}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
|
||||
<section className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<MediaMetric icon={ImageIcon} loading={statsQuery.isPending} label={t("media.images.totalImages")} value={formatNumber(statsQuery.data?.totalImages ?? 0, i18n.language, 0)} detail={t("media.images.totalImagesDetail")} />
|
||||
<MediaMetric icon={Database} loading={statsQuery.isPending} label={t("media.images.totalBytes")} value={formatBytes(statsQuery.data?.totalBytes ?? 0, i18n.language)} detail={t("media.images.totalBytesDetail")} />
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex min-h-12 flex-wrap items-center justify-between gap-3 py-2">
|
||||
<div className="relative w-full sm:w-80">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-8 pl-9 text-xs"
|
||||
value={search}
|
||||
onChange={(event) => { setSearch(event.target.value); setPage(1); }}
|
||||
placeholder={t("media.images.search")}
|
||||
aria-label={t("media.images.search")}
|
||||
/>
|
||||
</div>
|
||||
{result ? <span className="text-xs text-muted-foreground">{t("media.images.pageSummary", { count: result.items.length, total: result.total })}</span> : null}
|
||||
</div>
|
||||
|
||||
{imagesQuery.isError ? <ErrorState message={imagesQuery.error.message} onRetry={() => void imagesQuery.refetch()} /> : null}
|
||||
{imagesQuery.isPending ? <LoadingState /> : null}
|
||||
{!imagesQuery.isPending && result && result.items.length === 0 ? <EmptyState message={t(normalizedSearch ? "media.images.noMatches" : "media.images.empty")} /> : null}
|
||||
|
||||
{!imagesQuery.isPending && result && result.items.length > 0 ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{result.items.map((image) => <ImageCard key={image.id} image={image} locale={i18n.language} />)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{result && result.total > 0 ? (
|
||||
<Pagination
|
||||
page={result.page}
|
||||
pageSize={result.pageSize}
|
||||
total={result.total}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(value) => { setPageSize(value); setPage(1); }}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageCard({ image, locale }: { image: MediaAssetDTO; locale: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<a href={image.url} target="_blank" rel="noreferrer" className="group overflow-hidden rounded-lg bg-card transition-colors hover:bg-secondary/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40">
|
||||
<div className="aspect-square overflow-hidden bg-muted">
|
||||
<img src={image.url} alt={image.id} loading="lazy" className="size-full object-cover transition-transform duration-200 group-hover:scale-[1.02]" />
|
||||
</div>
|
||||
<div className="space-y-2 p-3 text-xs">
|
||||
<div className="flex min-w-0 items-center justify-between gap-2">
|
||||
<span className="min-w-0 flex-1 truncate font-medium" title={image.id}>{image.id}</span>
|
||||
<span className="shrink-0 text-muted-foreground">{formatBytes(image.sizeBytes, locale)}</span>
|
||||
</div>
|
||||
<div className="flex min-w-0 items-center justify-between gap-2 text-[11px] text-muted-foreground">
|
||||
<span className="min-w-0 truncate" title={image.mimeType}>{image.mimeType || image.kind}</span>
|
||||
<span className="shrink-0 whitespace-nowrap">{formatDateTime(image.createdAt, locale)}</span>
|
||||
</div>
|
||||
<div className="truncate font-mono text-[10px] text-muted-foreground/75" title={image.sha256}>{t("media.images.sha256")}: {image.sha256}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function MediaMetric({ icon: Icon, label, value, detail, loading }: { icon: LucideIcon; label: string; value: string; detail: string; loading: boolean }) {
|
||||
return (
|
||||
<div className="min-h-28 rounded-lg bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<Icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="mt-3 flex min-h-7 items-center text-xl font-medium tabular-nums">{loading ? <Spinner /> : value}</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{detail}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatBytes(value: number, locale: string): string {
|
||||
if (!Number.isFinite(value) || value <= 0) return "0 B";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
let size = value;
|
||||
let unitIndex = 0;
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
return `${new Intl.NumberFormat(locale, { maximumFractionDigits: unitIndex === 0 || size >= 10 ? 0 : 1 }).format(size)} ${units[unitIndex]}`;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { MediaAssetDTO, ImageStatsDTO, MediaJobDTO, VideoStatsDTO } from "@/features/media/types";
|
||||
import { apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import {
|
||||
createObjectDecoder,
|
||||
createPaginatedDecoder,
|
||||
hasShape,
|
||||
isNumber,
|
||||
isString,
|
||||
isOneOf,
|
||||
} from "@/shared/api/decoder";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
export type ListImagesInput = {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
search?: string;
|
||||
};
|
||||
|
||||
export type ListVideosInput = {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
status?: MediaJobDTO["status"] | "";
|
||||
search?: string;
|
||||
sortBy?: string;
|
||||
sortOrder?: SortOrder;
|
||||
};
|
||||
|
||||
const mediaAssetShape = {
|
||||
id: isString,
|
||||
kind: isString,
|
||||
mimeType: isString,
|
||||
sizeBytes: isNumber,
|
||||
sha256: isString,
|
||||
createdAt: isString,
|
||||
url: isString,
|
||||
};
|
||||
|
||||
const mediaJobShape = {
|
||||
id: isString,
|
||||
model: isString,
|
||||
prompt: isString,
|
||||
status: isOneOf("queued", "in_progress", "completed", "failed"),
|
||||
progress: isNumber,
|
||||
seconds: isNumber,
|
||||
size: isString,
|
||||
quality: isString,
|
||||
accountName: isString,
|
||||
clientKeyName: isString,
|
||||
createdAt: isString,
|
||||
completedAt: (value: unknown) => value === null || isString(value),
|
||||
errorMessage: isString,
|
||||
};
|
||||
|
||||
const decodeImageStats = createObjectDecoder<ImageStatsDTO>("image stats", {
|
||||
totalImages: isNumber,
|
||||
totalBytes: isNumber,
|
||||
});
|
||||
const decodeVideoStats = createObjectDecoder<VideoStatsDTO>("video stats", {
|
||||
totalJobs: isNumber,
|
||||
completed: isNumber,
|
||||
failed: isNumber,
|
||||
inProgress: isNumber,
|
||||
queued: isNumber,
|
||||
});
|
||||
|
||||
export function listImages(input: ListImagesInput): Promise<PaginatedDTO<MediaAssetDTO>> {
|
||||
const query = new URLSearchParams({ page: String(input.page), pageSize: String(input.pageSize) });
|
||||
if (input.search) query.set("search", input.search);
|
||||
return apiRequest(`/api/admin/v1/media/images?${query}`, {}, createPaginatedDecoder(hasShape(mediaAssetShape)));
|
||||
}
|
||||
|
||||
export function getImageStats(): Promise<ImageStatsDTO> {
|
||||
return apiRequest("/api/admin/v1/media/images/stats", {}, decodeImageStats);
|
||||
}
|
||||
|
||||
export function listVideos(input: ListVideosInput): Promise<PaginatedDTO<MediaJobDTO>> {
|
||||
const query = new URLSearchParams({ page: String(input.page), pageSize: String(input.pageSize) });
|
||||
if (input.status) query.set("status", input.status);
|
||||
if (input.search) query.set("search", input.search);
|
||||
if (input.sortBy && input.sortOrder) {
|
||||
query.set("sortBy", input.sortBy);
|
||||
query.set("sortOrder", input.sortOrder);
|
||||
}
|
||||
return apiRequest(`/api/admin/v1/media/videos?${query}`, {}, createPaginatedDecoder(hasShape(mediaJobShape)));
|
||||
}
|
||||
|
||||
export function getVideoStats(): Promise<VideoStatsDTO> {
|
||||
return apiRequest("/api/admin/v1/media/videos/stats", {}, decodeVideoStats);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export type MediaAssetDTO = {
|
||||
id: string;
|
||||
kind: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
sha256: string;
|
||||
createdAt: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type MediaJobDTO = {
|
||||
id: string;
|
||||
model: string;
|
||||
prompt: string;
|
||||
status: "queued" | "in_progress" | "completed" | "failed";
|
||||
progress: number;
|
||||
seconds: number;
|
||||
size: string;
|
||||
quality: string;
|
||||
accountName: string;
|
||||
clientKeyName: string;
|
||||
createdAt: string;
|
||||
completedAt: string | null;
|
||||
errorMessage: string;
|
||||
};
|
||||
|
||||
export type ImageStatsDTO = { totalImages: number; totalBytes: number };
|
||||
export type VideoStatsDTO = { totalJobs: number; completed: number; failed: number; inProgress: number; queued: number };
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { AlertCircle, CheckCircle2, Clock, ListVideo, Loader2, RefreshCw, Search, type LucideIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Table, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { getVideoStats, listVideos } from "@/features/media/media-api";
|
||||
import type { MediaJobDTO } from "@/features/media/types";
|
||||
import { EmptyState, ErrorState, TableLoadingRow } from "@/shared/components/data-state";
|
||||
import { DataTableShell } from "@/shared/components/data-table-shell";
|
||||
import { PageHeader } from "@/shared/components/page-header";
|
||||
import { Pagination } from "@/shared/components/pagination";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime, formatNumber } from "@/shared/lib/format";
|
||||
import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort";
|
||||
|
||||
type VideoStatusFilter = MediaJobDTO["status"] | "";
|
||||
|
||||
const statusOptions: VideoStatusFilter[] = ["", "queued", "in_progress", "completed", "failed"];
|
||||
|
||||
export function VideoGalleryPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [search, setSearch] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState<VideoStatusFilter>("");
|
||||
const [sort, setSort] = useState<TableSort>({ field: "createdAt", order: "desc" });
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const normalizedSearch = debouncedSearch.trim();
|
||||
|
||||
const videosQuery = useQuery({
|
||||
queryKey: ["media", "videos", page, pageSize, statusFilter, normalizedSearch, sort.field, sort.order],
|
||||
queryFn: () => listVideos({ page, pageSize, status: statusFilter, search: normalizedSearch || undefined, sortBy: sort.field, sortOrder: sort.order }),
|
||||
});
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ["media", "videos", "stats"],
|
||||
queryFn: getVideoStats,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
|
||||
const result = videosQuery.data;
|
||||
const refreshing = videosQuery.isFetching || statsQuery.isFetching;
|
||||
|
||||
function refreshAll(): void {
|
||||
void videosQuery.refetch();
|
||||
void statsQuery.refetch();
|
||||
}
|
||||
|
||||
function changeSort(field: string, initialOrder: SortOrder): void {
|
||||
setSort((current) => nextTableSort(current, field, initialOrder));
|
||||
setPage(1);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={t("media.videos.title")}
|
||||
description={t("media.videos.description")}
|
||||
actions={(
|
||||
<Button variant="secondary" size="sm" onClick={refreshAll} disabled={refreshing}>
|
||||
<RefreshCw className={refreshing ? "animate-spin" : undefined} />
|
||||
{t("common.refresh")}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
|
||||
<section className="grid gap-2 sm:grid-cols-2 xl:grid-cols-5">
|
||||
<VideoMetric icon={ListVideo} loading={statsQuery.isPending} label={t("media.videos.totalJobs")} value={formatNumber(statsQuery.data?.totalJobs ?? 0, i18n.language, 0)} />
|
||||
<VideoMetric icon={Clock} loading={statsQuery.isPending} label={t("media.videos.queued")} value={formatNumber(statsQuery.data?.queued ?? 0, i18n.language, 0)} />
|
||||
<VideoMetric icon={Loader2} loading={statsQuery.isPending} label={t("media.videos.inProgress")} value={formatNumber(statsQuery.data?.inProgress ?? 0, i18n.language, 0)} />
|
||||
<VideoMetric icon={CheckCircle2} loading={statsQuery.isPending} label={t("media.videos.completed")} value={formatNumber(statsQuery.data?.completed ?? 0, i18n.language, 0)} />
|
||||
<VideoMetric icon={AlertCircle} loading={statsQuery.isPending} label={t("media.videos.failed")} value={formatNumber(statsQuery.data?.failed ?? 0, i18n.language, 0)} />
|
||||
</section>
|
||||
|
||||
<DataTableShell
|
||||
toolbar={(
|
||||
<>
|
||||
<div className="flex w-full flex-wrap items-center gap-2 sm:w-auto">
|
||||
<div className="relative min-w-0 flex-1 sm:w-72 sm:flex-none">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-8 pl-9 text-xs"
|
||||
value={search}
|
||||
onChange={(event) => { setSearch(event.target.value); setPage(1); }}
|
||||
placeholder={t("media.videos.search")}
|
||||
aria-label={t("media.videos.search")}
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter || "all"} onValueChange={(value) => { setStatusFilter(value === "all" ? "" : value as VideoStatusFilter); setPage(1); }}>
|
||||
<SelectTrigger className="w-36" aria-label={t("media.videos.statusFilter")}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent align="start">
|
||||
{statusOptions.map((status) => (
|
||||
<SelectItem key={status || "all"} value={status || "all"}>{status ? t(`media.videoStatus.${status}`) : t("common.all")}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{result ? <span className="text-xs text-muted-foreground">{t("media.videos.pageSummary", { count: result.items.length, total: result.total })}</span> : null}
|
||||
</>
|
||||
)}
|
||||
footer={result && result.total > 0 ? (
|
||||
<Pagination
|
||||
page={result.page}
|
||||
pageSize={result.pageSize}
|
||||
total={result.total}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(value) => { setPageSize(value); setPage(1); }}
|
||||
/>
|
||||
) : undefined}
|
||||
>
|
||||
{videosQuery.isError ? <ErrorState message={videosQuery.error.message} onRetry={() => void videosQuery.refetch()} /> : null}
|
||||
{result && result.items.length === 0 ? <EmptyState message={t("media.videos.empty")} /> : null}
|
||||
{videosQuery.isPending || (result && result.items.length > 0) ? (
|
||||
<Table className="min-w-[1180px] table-fixed text-xs">
|
||||
<colgroup>
|
||||
<col className="w-[25%]" />
|
||||
<col className="w-[13%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[9%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[12%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[11%]" />
|
||||
</colgroup>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<SortableTableHead field="prompt" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("media.videos.prompt")}</SortableTableHead>
|
||||
<SortableTableHead field="model" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("media.videos.model")}</SortableTableHead>
|
||||
<SortableTableHead field="status" sortBy={sort.field} sortOrder={sort.order} align="center" onSort={changeSort}>{t("media.videos.status")}</SortableTableHead>
|
||||
<SortableTableHead field="progress" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" align="center" onSort={changeSort}>{t("media.videos.progress")}</SortableTableHead>
|
||||
<SortableTableHead field="spec" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("media.videos.spec")}</SortableTableHead>
|
||||
<SortableTableHead field="account" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("media.videos.owner")}</SortableTableHead>
|
||||
<SortableTableHead field="createdAt" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" onSort={changeSort}>{t("media.videos.createdAt")}</SortableTableHead>
|
||||
<SortableTableHead field="completedAt" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" onSort={changeSort}>{t("media.videos.completedAt")}</SortableTableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{videosQuery.isPending ? <TableLoadingRow colSpan={8} /> : result?.items.map((job) => (
|
||||
<TableRow key={job.id}>
|
||||
<TableCell className="min-w-0 py-3">
|
||||
<div className="min-w-0">
|
||||
<span className="block truncate text-xs font-medium" title={job.prompt}>{job.prompt || "-"}</span>
|
||||
<span className="mt-0.5 block truncate font-mono text-[10px] text-muted-foreground" title={job.id}>{job.id}</span>
|
||||
{job.errorMessage ? <span className="mt-1 block truncate text-[11px] text-destructive" title={job.errorMessage}>{job.errorMessage}</span> : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="min-w-0 py-3"><span className="block truncate" title={job.model}>{job.model || "-"}</span></TableCell>
|
||||
<TableCell className="py-3 text-center"><VideoStatusBadge status={job.status} /></TableCell>
|
||||
<TableCell className="py-3 text-center"><ProgressValue value={job.progress} locale={i18n.language} /></TableCell>
|
||||
<TableCell className="py-3">
|
||||
<div className="space-y-0.5 text-xs">
|
||||
<span className="block truncate" title={formatSpec(job)}>{formatSpec(job)}</span>
|
||||
<span className="block text-[11px] text-muted-foreground">{t("media.videos.seconds", { count: job.seconds })}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="min-w-0 py-3">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<span className="block truncate" title={job.accountName}>{job.accountName || "-"}</span>
|
||||
<span className="block truncate text-[11px] text-muted-foreground" title={job.clientKeyName}>{job.clientKeyName || "-"}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap py-3 text-xs text-muted-foreground">{formatDateTime(job.createdAt, i18n.language)}</TableCell>
|
||||
<TableCell className="whitespace-nowrap py-3 text-xs text-muted-foreground">{formatDateTime(job.completedAt, i18n.language)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : null}
|
||||
</DataTableShell>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VideoMetric({ icon: Icon, label, value, loading }: { icon: LucideIcon; label: string; value: string; loading: boolean }) {
|
||||
return (
|
||||
<div className="min-h-24 rounded-lg bg-card p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<Icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="mt-3 flex min-h-7 items-center text-xl font-medium tabular-nums">{loading ? <Spinner /> : value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VideoStatusBadge({ status }: { status: MediaJobDTO["status"] }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Badge variant="secondary" className={cn("whitespace-nowrap", statusClassName(status))}>
|
||||
{t(`media.videoStatus.${status}`)}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function ProgressValue({ value, locale }: { value: number; locale: string }) {
|
||||
const normalized = Math.max(0, Math.min(100, value));
|
||||
return (
|
||||
<div className="mx-auto flex w-20 flex-col items-center gap-1">
|
||||
<span className="text-xs tabular-nums">{formatNumber(normalized, locale, 0)}%</span>
|
||||
<span className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
|
||||
<span className="block h-full rounded-full bg-primary" style={{ width: `${normalized}%` }} />
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function statusClassName(status: MediaJobDTO["status"]): string {
|
||||
switch (status) {
|
||||
case "completed":
|
||||
return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
|
||||
case "failed":
|
||||
return "bg-red-500/10 text-red-700 dark:text-red-300";
|
||||
case "in_progress":
|
||||
return "bg-sky-500/10 text-sky-700 dark:text-sky-300";
|
||||
case "queued":
|
||||
return "bg-amber-500/10 text-amber-700 dark:text-amber-300";
|
||||
}
|
||||
}
|
||||
|
||||
function formatSpec(job: MediaJobDTO): string {
|
||||
return [job.size, job.quality].filter(Boolean).join(" · ") || "-";
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { Table, TableActionCell, TableActionHead, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { createEgressNode, deleteEgressNode, listEgressNodes, updateEgressNode, type EgressNodeDTO, type EgressNodeInput, type EgressScope } from "@/features/settings/settings-api";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { ErrorState } from "@/shared/components/data-state";
|
||||
import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort";
|
||||
|
||||
const emptyInput: EgressNodeInput = { name: "", scope: "grok_build", enabled: true, proxyURL: "", userAgent: "", cloudflareCookies: "" };
|
||||
@@ -84,7 +85,7 @@ export function EgressNodes() {
|
||||
<p className="text-xs text-muted-foreground">{t("console.egressDescription")}</p>
|
||||
<Button type="button" size="sm" variant="secondary" onClick={openCreate}><Plus />{t("settings.egress.add")}</Button>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
{query.isError ? <ErrorState message={query.error.message} onRetry={() => void query.refetch()} /> : <div className="overflow-hidden rounded-md border">
|
||||
<Table>
|
||||
<TableHeader><TableRow><SortableTableHead field="name" sortBy={sort.field} sortOrder={sort.order} onSort={changeSort}>{t("settings.egress.name")}</SortableTableHead><SortableTableHead field="scope" sortBy={sort.field} sortOrder={sort.order} align="center" onSort={changeSort}>{t("settings.egress.scope")}</SortableTableHead><SortableTableHead field="proxy" sortBy={sort.field} sortOrder={sort.order} align="center" onSort={changeSort}>{t("settings.egress.proxy")}</SortableTableHead><SortableTableHead field="clearance" sortBy={sort.field} sortOrder={sort.order} align="center" onSort={changeSort}>{t("settings.egress.clearance")}</SortableTableHead><SortableTableHead field="health" sortBy={sort.field} sortOrder={sort.order} initialOrder="desc" align="center" onSort={changeSort}>{t("settings.egress.health")}</SortableTableHead><TableActionHead /></TableRow></TableHeader>
|
||||
<TableBody>
|
||||
@@ -104,7 +105,7 @@ export function EgressNodes() {
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
<Dialog open={editing !== undefined} onOpenChange={(open) => { if (!open) setEditing(undefined); }}>
|
||||
<DialogContent>
|
||||
|
||||
@@ -64,18 +64,18 @@ const decodeSettingsSnapshot = createObjectDecoder<SettingsSnapshotDTO>("setting
|
||||
restartRequired: isArrayOf(isString),
|
||||
});
|
||||
const egressNodeValidator = hasShape({
|
||||
id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_web_asset"), enabled: isBoolean,
|
||||
id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "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,
|
||||
id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "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 }),
|
||||
defaultUserAgents: hasShape({ grok_build: isString, grok_web: isString, grok_console: isString, grok_web_asset: isString }),
|
||||
});
|
||||
|
||||
export function getSettings(): Promise<SettingsSnapshotDTO> {
|
||||
|
||||
@@ -40,7 +40,7 @@ export function ErrorState({ message, onRetry }: { message: string; onRetry: ()
|
||||
<div className="flex min-h-44 flex-col items-center justify-center gap-3 text-center">
|
||||
<AlertCircle className="size-7 text-destructive" />
|
||||
<p className="max-w-md text-sm text-muted-foreground">{message}</p>
|
||||
<Button variant="secondary" size="sm" onClick={onRetry}>{t("common.retry")}</Button>
|
||||
<Button type="button" variant="secondary" size="sm" onClick={onRetry}>{t("common.retry")}</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -87,10 +87,55 @@ const resources = {
|
||||
accounts: "账号",
|
||||
models: "模型",
|
||||
clientKeys: "密钥",
|
||||
gallery: "图库",
|
||||
videoGallery: "视频库",
|
||||
audits: "请求审计",
|
||||
docs: "文档",
|
||||
settings: "设置",
|
||||
},
|
||||
media: {
|
||||
images: {
|
||||
title: "图库",
|
||||
description: "浏览已生成的图片资源",
|
||||
search: "搜索 ID、类型或哈希",
|
||||
empty: "暂无图片",
|
||||
noMatches: "未找到匹配的图片",
|
||||
sha256: "SHA256",
|
||||
totalImages: "图片总数",
|
||||
totalImagesDetail: "已归档的图片数量",
|
||||
totalBytes: "占用空间",
|
||||
totalBytesDetail: "所有图片文件总大小",
|
||||
pageSummary: "显示 {{count}} / {{total}} 张",
|
||||
},
|
||||
videos: {
|
||||
title: "视频库",
|
||||
description: "查看视频生成任务记录",
|
||||
search: "搜索提示词或 ID",
|
||||
empty: "暂无视频任务",
|
||||
statusFilter: "状态筛选",
|
||||
totalJobs: "任务总数",
|
||||
queued: "排队中",
|
||||
inProgress: "进行中",
|
||||
completed: "已完成",
|
||||
failed: "失败",
|
||||
prompt: "提示词",
|
||||
model: "模型",
|
||||
status: "状态",
|
||||
progress: "进度",
|
||||
spec: "规格",
|
||||
owner: "归属",
|
||||
createdAt: "创建时间",
|
||||
completedAt: "完成时间",
|
||||
seconds: "{{count}} 秒",
|
||||
pageSummary: "显示 {{count}} / {{total}} 条",
|
||||
},
|
||||
videoStatus: {
|
||||
queued: "排队中",
|
||||
in_progress: "进行中",
|
||||
completed: "已完成",
|
||||
failed: "失败",
|
||||
},
|
||||
},
|
||||
auth: {
|
||||
title: "管理员登录",
|
||||
productTitle: "轻量 API 网关",
|
||||
@@ -397,7 +442,7 @@ const resources = {
|
||||
audits: {
|
||||
title: "请求审计",
|
||||
description: "仅记录路由、状态、耗时和用量明细,不保存请求或响应正文。",
|
||||
search: "搜索请求 ID 或模型",
|
||||
search: "搜索请求 ID、模型或出口节点",
|
||||
request: "请求 ID",
|
||||
route: "路由",
|
||||
status: "状态",
|
||||
@@ -414,6 +459,10 @@ const resources = {
|
||||
model: "模型",
|
||||
account: "账号",
|
||||
accountFilterPlaceholder: "输入账号名称或 ID",
|
||||
egress: "出口",
|
||||
egressProxy: "代理",
|
||||
egressDirect: "直连",
|
||||
egressUnknown: "未命名节点",
|
||||
owningAccount: "所属账号",
|
||||
owningKey: "所属密钥",
|
||||
routeDetails: "查看路由详情",
|
||||
@@ -706,15 +755,16 @@ const resources = {
|
||||
expiryUnknown: "Credential expiry is unknown",
|
||||
},
|
||||
common: { actions: "Actions", cancel: "Cancel", close: "Close", copy: "Copy", copied: "Copied", copyFailed: "Copy failed", create: "Create", delete: "Delete", disabled: "Disabled", disable: "Disable", edit: "Edit", enabled: "Enabled", enable: "Enable", loading: "Loading", importingProgress: "Importing, completed {{completed}} / {{total}}", syncingProgress: "Syncing initial data, completed {{completed}} / {{total}}", noData: "No data", pageOf: "Page {{page}}/{{pages}}", perPage: "Per page", rows: "rows", firstPage: "First page", lastPage: "Last page", previousPage: "Previous page", nextPage: "Next page", selectedCount: "{{count}} selected", selectPage: "Select this page", selectItem: "Select {{name}}", refresh: "Refresh", retry: "Retry", filter: "Filters", all: "All", clearFilters: "Clear filters", save: "Save", reset: "Reset", sortAscending: "Sort {{column}} ascending", sortDescending: "Sort {{column}} descending" },
|
||||
nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", audits: "Request audits", docs: "Documentation", settings: "Settings" },
|
||||
nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", docs: "Documentation", settings: "Settings" },
|
||||
media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", sha256: "SHA256", totalImages: "Total images", totalImagesDetail: "Archived image count", totalBytes: "Storage", totalBytesDetail: "Total size of all image files", pageSummary: "Showing {{count}} / {{total}}" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } },
|
||||
auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" },
|
||||
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
|
||||
dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", resourcesTitle: "Resource status", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 models", model: "Model", share: "Call share", noTopModels: "No model calls in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" },
|
||||
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "The selected {{count}} accounts will use SSO to complete Device OAuth automatically. Linked accounts are skipped and conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}Line truncated
|
||||
models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "When enabled, only selected accounts are routed and treated as manually confirmed to support the model. Otherwise model sync decides automatically.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
|
||||
audits: { title: "Request audits", description: "Stores routing, status, latency, and usage details only. Request and response bodies are never saved.", search: "Search request ID or model", request: "Request ID", route: "Route", status: "Status", mode: "Mode", tokens: "Details", billing: "Billing", duration: "Duration", createdAt: "Time", stream: "Streaming", nonStream: "Non-streaming", cursorPage: "Page {{page}}", key: "Key", keyFilterPlaceholder: "Enter key name or ID", model: "Model", account: "Account", accountFilterPlaceholder: "Enter account name or ID", owningAccount: "Account", owningKey: "Client key", routeDetails: "View routing details", statusSuccess: "Success", statusClientError: "Client error", statusServerError: "Server error", usageSummary: "Usage summary", totalRequests: "Total requests", requestBreakdown: "{{success}} succeeded · {{failed}} failed", totalTokens: "Total tokens", tokenEfficiency: "Cache hit rate {{cacheRate}}%", tokenBreakdown: "Input {{input}} · Output {{output}} · Cached {{cached}} · Reasoning {{reasoning}}", successRate: "Success rate", averageDuration: "Average duration {{duration}}", estimatedCost: "Estimated cost", pricingCoverage: "{{priced}} priced · {{unpriced}} unpriced", pricingDescription: "Calculated using the latest official xAI model prices. Models without a listed price are excluded.", total: "Total", input: "Input", output: "Output", mediaInput: "Media Input", imageCount: "{{count}} images", secondsCount: "{{count}} sec", cached: "Cached", reasoning: "Reasoning", costUsd: "Cost ${{value}}", sources: "Sources {{count}}", serverTools: "Server tools called {{count}} times" },
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit" }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, or Web assets. Build inherits the Provider User-Agent; Web nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } },
|
||||
audits: { title: "Request audits", description: "Stores routing, status, latency, and usage details only. Request and response bodies are never saved.", search: "Search request ID, model, or egress node", request: "Request ID", route: "Route", status: "Status", mode: "Mode", tokens: "Details", billing: "Billing", duration: "Duration", createdAt: "Time", stream: "Streaming", nonStream: "Non-streaming", cursorPage: "Page {{page}}", key: "Key", keyFilterPlaceholder: "Enter key name or ID", model: "Model", account: "Account", accountFilterPlaceholder: "Enter account name or ID", egress: "Egress", egressProxy: "Proxy", egressDirect: "Direct", egressUnknown: "Unnamed node", owningAccount: "Account", owningKey: "Client key", routeDetails: "View routing details", statusSuccess: "Success", statusClientError: "Client error", statusServerError: "Server error", usageSummary: "Usage summary", totalRequests: "Total requests", requestBreakdown: "{{success}} succeeded · {{failed}} failed", totalTokens: "Total tokens", tokenEfficiency: "Cache hit rate {{cacheRate}}%", tokenBreakdown: "Input {{input}} · Output {{output}} · Cached {{cached}} · Reasoning {{reasoning}}", successRate: "Success rate", averageDuration: "Average duration {{duration}}", estimatedCost: "Estimated cost", pricingCoverage: "{{priced}} priced · {{unpriced}} unpriced", pricingDescription: "Calculated using the latest official xAI model prices. Models without a listed price are excluded.", total: "Total", input: "Input", output: "Output", mediaInput: "Media Input", imageCount: "{{count}} images", secondsCount: "{{count}} sec", cached: "Cached", reasoning: "Reasoning", costUsd: "Cost ${{value}}", sources: "Sources {{count}}", serverTools: "Server tools called {{count}} times" },
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit" }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } },
|
||||
docs: {
|
||||
title: "API documentation",
|
||||
description: "OpenAI Responses compatibility, account routing, and conversation-state behavior for this gateway.",
|
||||
|
||||
Reference in new issue
Block a user