diff --git a/README.md b/README.md index 82599dab..fd0d628c 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,8 @@ Grok2API 是一个纯 Go 实现的 Grok API 网关。项目将 Grok Build OAuth - **标准接口**:Responses、Chat Completions、Images、异步 Videos、Anthropic Messages - **多账号调度**:优先级、并发限制、额度门控、会话粘滞、冷却与故障切换 - **账号接入**:Device OAuth、OAuth JSON、SSO JSON、逐行 SSO Token -- **媒体能力**:图片生成、图片编辑、视频生成、图片本地归档与 URL/Base64 返回 +- **媒体能力**:图片生成、图片编辑、视频生成、图片本地归档与 URL/Base64 返回;XAI ZDR 视频可经一次性 PUT 接收落盘 +- **Build XAI 推理回退**:主地址 `cli-chat-proxy.grok.com` 对可回退推理操作明确 HTTP 403 且 `api.x.ai` 成功时,账号级持久标记;后续模型目录 / Responses 创建·Compact / 视频走 XAI(Billing 与 stored GET/DELETE 仍走主地址) - **基础设施**:SQLite/PostgreSQL、Memory/Redis、HTTP 与 SOCKS 代理池 - **安全边界**:AES-256-GCM 凭据加密、客户端密钥哈希、日志脱敏、SSRF 与传输上限 - **管理后台**:Dashboard、账号、模型、客户端密钥、请求审计、接口文档与热加载设置 @@ -209,6 +210,7 @@ Authorization: Bearer g2a_xxx_xxx | `POST` | `/v1/images/generations` | 图片生成 | | `POST` | `/v1/images/edits` | 图片编辑 | | `GET` | `/v1/media/images/{id}` | 公开归档图片 | +| `PUT` | `/v1/media/uploads/{token}` | XAI 视频一次性上传接收(无需客户端 API key;票据即授权) | | `POST` | `/v1/videos/generations` | 创建视频任务 | | `GET` | `/v1/videos/{request_id}` | 查询视频任务 | @@ -269,6 +271,21 @@ socks5h://Default.{account}:RESIN_PROXY_TOKEN@resin:2260 粘性代理只会在请求尚未写入上游且错误明确属于代理连接阶段时,使用同一账号额外重试两次。`401`、`429`、额度耗尽、永久凭据错误、`UPSTREAM_REQUEST_FAILED`,以及可能已经提交的生成请求都不会在出口层自动重放。 +## Build XAI 推理回退与视频上传 + +当 Grok Build 主 API(默认 `https://cli-chat-proxy.grok.com/v1`)对**可回退推理操作**返回明确 HTTP 403,且同一 OAuth token 访问备用地址(默认 `https://api.x.ai/v1`)成功时,系统会幂等持久化账号级 `buildApiFallback`(XAI 推理回退)标记。 + +**可回退并在已标记后直连 XAI**:`GET /models`、`POST /responses`(含 Chat/Messages 兼容)、`POST /responses/compact`、视频创建与轮询。 + +**始终主地址(不探测 XAI)**:`GET /billing` 与 `format=credits`、`GET/DELETE /responses/{id}` 已存储资源、OAuth device/authorization/token refresh、以及其它未知 Build 路径。生产探针显示 XAI 对 stored response 与 Billing 返回 404;将 Billing 改走 XAI 只会把主地址可诊断的 403 变成误导性 404,且无法恢复额度。 + +- **设置**:管理端 Grok Build 的「XAI 备用地址」可编辑;旧运行设置缺字段时默认 `https://api.x.ai/v1`。 +- **账号**:回退标记是内部运行状态,不在账号管理接口或页面暴露手工开关;仅当 Billing 已确认付费、主地址返回 403 且 XAI 请求成功时自动写入。Free/Unknown 即使存在旧标记也始终走主地址;token 刷新、SSO 转换与 upsert 不会误改该状态。 +- **视频 ZDR**:走 XAI 时必须提供可写 `output.upload_url`。服务端签发高熵、限时、一次性 PUT 地址(`PUT /v1/media/uploads/{token}`),上传完成后写入本地 `kind=video` 媒体资产并绑定视频任务。 +- **公开地址**:`frontend.publicApiBaseURL`(或运行设置覆盖)必须是 **xAI 可访问的 HTTPS** 根地址,否则 XAI 视频回退会返回本地配置错误且不标记回退。 +- **上传限制**:默认最大 256 MiB、仅视频 MIME、一次性消费;伪造/过期/重复/超限 PUT 被拒绝且不产生资产。 +- **资格变化**:每次使用回退地址前都会重新校验实时 Billing;账号不再呈现付费信号时立即回到主地址。已创建视频任务记录自己的轮询 base,不受后续资格变化影响。 + ## 生产部署 - 使用 HTTPS,并设置 `auth.secureCookies: true` @@ -277,6 +294,7 @@ socks5h://Default.{account}:RESIN_PROXY_TOKEN@resin:2260 - 本地媒体目录在多实例下必须使用共享卷或实例亲和 - 持久化备份 `config.yaml`、关系型数据库和媒体目录 - 不要将 OAuth、SSO、Cloudflare Cookie 或账号导出文件提交到 Git +- 若使用 Build 视频 XAI 回退,确保公网 HTTPS `publicApiBaseURL` 可被 xAI PUT 访问 - 对外暴露前建议配置反向代理、访问日志和基础网络防护 ## 开发 diff --git a/VERSION b/VERSION index 2c854bca..96506fd2 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v3.0.2 \ No newline at end of file +v3.0.2 diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index 935c8885..f65b2166 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -103,6 +103,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat egressRepo := relational.NewEgressRepository(database) mediaJobRepo := relational.NewMediaJobRepository(database) mediaAssetRepo := relational.NewMediaAssetRepository(database) + mediaUploadTicketRepo := relational.NewMediaUploadTicketRepository(database) loadedConfig, settingsUpdatedAt, settingsRevision, err := settingsapp.LoadPersisted(ctx, cfg, runtimeSettingsRepo) if err != nil { database.Close() @@ -155,11 +156,16 @@ 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, mediaJobRepo, localMediaStore, refreshLock, mediaConfig(cfg)) + mediaService := mediaapp.NewServiceWithTickets(mediaAssetRepo, mediaJobRepo, mediaUploadTicketRepo, 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) + cliAdapter := cliprovider.NewAdapter(cliprovider.Config{ + BaseURL: cfg.Provider.Build.BaseURL, FallbackBaseURL: config.NormalizeBuildFallbackBaseURL(cfg.Provider.Build.FallbackBaseURL), + ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier, + TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent, + }, cipher) cliAdapter.SetEgress(egressManager) + cliAdapter.SetVideoUploadIssuer(mediaService) webAdapter := webprovider.NewAdapter(webProviderConfig(cfg), egressManager, cipher, responseRepo, mediaService) webAdapter.SetLogger(logger) consoleAdapter := consoleprovider.NewAdapter(consoleProviderConfig(cfg), egressManager, cipher) @@ -189,6 +195,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat pool.UpdateJitter(cfg.Batch.RandomDelay.Value()) } accountService := accountapp.NewService(accountRepo, auditRepo, deviceSessions, sticky, providers, cipher, refreshLock) + cliAdapter.SetFallbackMarker(accountService) accountService.SetLogger(logger) accountService.SetQuotaRecoveryQueue(quotaQueue) accountService.SetTaskPools(conversionPool, syncPool, refreshPool) @@ -236,9 +243,11 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat auditService := auditapp.NewService(auditRepo, logger, cfg.Audit.BufferSize, cfg.Audit.BatchSize, cfg.Audit.FlushInterval.Value()) dashboardService := dashboardapp.NewService(dashboardRepo) selector := gateway.NewSelector(accountRepo, concurrency, sticky, providers, cfg.Routing.StickyTTL.Value(), cfg.Routing.CooldownBase.Value(), cfg.Routing.CooldownMax.Value(), cfg.Routing.CapacityWait.Value()) + selector.UpdatePreferFreeBuild(cfg.Routing.PreferFreeBuild) gatewayService := gateway.NewService(modelService, auditService, accountService, clientKeyService, providers, selector, responseRepo, cfg.Routing.MaxAttempts) gatewayService.SetLogger(logger) gatewayService.ConfigureMedia(mediaJobRepo, cfg.Provider.Web.MediaConcurrency) + gatewayService.ConfigureMediaAssets(mediaService) quotaRecoveryService := quotarecoveryapp.NewService(logger, quotaQueue, accountService, cfg.Provider.Web.RecoveryBackoffBase.Value(), cfg.Provider.Web.RecoveryBackoffMax.Value()) quotaRecoveryService.SetBulkPool(syncPool) inferenceConcurrency := httpmiddleware.NewConcurrencyGate(cfg.Server.MaxConcurrentRequests) @@ -263,9 +272,9 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat pool.UpdateJitter(next.Batch.RandomDelay.Value()) } cliAdapter.UpdateConfig(cliprovider.Config{ - BaseURL: next.Provider.Build.BaseURL, ClientVersion: next.Provider.Build.ClientVersion, - ClientIdentifier: next.Provider.Build.ClientIdentifier, TokenAuth: next.Provider.Build.TokenAuth, - UserAgent: next.Provider.Build.UserAgent, + BaseURL: next.Provider.Build.BaseURL, FallbackBaseURL: config.NormalizeBuildFallbackBaseURL(next.Provider.Build.FallbackBaseURL), + ClientVersion: next.Provider.Build.ClientVersion, ClientIdentifier: next.Provider.Build.ClientIdentifier, + TokenAuth: next.Provider.Build.TokenAuth, UserAgent: next.Provider.Build.UserAgent, }) webAdapter.UpdateConfig(webProviderConfig(next)) consoleAdapter.UpdateConfig(consoleProviderConfig(next)) @@ -274,6 +283,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat quotaRecoveryService.UpdateConfig(next.Provider.Web.RecoveryBackoffBase.Value(), next.Provider.Web.RecoveryBackoffMax.Value()) accountSyncService.UpdateConcurrency(next.Batch.ImportConcurrency) selector.UpdateConfig(next.Routing.StickyTTL.Value(), next.Routing.CooldownBase.Value(), next.Routing.CooldownMax.Value(), next.Routing.CapacityWait.Value()) + selector.UpdatePreferFreeBuild(next.Routing.PreferFreeBuild) gatewayService.UpdateMaxAttempts(next.Routing.MaxAttempts) auditService.UpdateConfig(next.Audit.BatchSize, next.Audit.FlushInterval.Value()) clientKeyService.UpdateDefaults(next.ClientKeyDefaults.RPMLimit, next.ClientKeyDefaults.MaxConcurrent) diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 1393d4cc..9f48089c 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -468,7 +468,7 @@ func newQuotaView(billing *accountdomain.Billing, observedTokens int64, recovery ExhaustedAt: recovery.ExhaustedAt, NextProbeAt: recovery.NextProbeAt, LastConfirmedAt: recovery.LastConfirmedAt, } } - if billing != nil && (billing.MonthlyLimit > 0 || billing.OnDemandCap > 0 || billing.OnDemandUsed > 0 || billing.PrepaidBalance > 0 || billing.CreditUsagePercent > 0) { + if billing != nil && billing.IsPaid() { result := QuotaView{Type: QuotaTypePaid, Source: "upstreamBilling", Confidence: "observed", Unit: "credits", UsagePercent: billing.CreditUsagePercent, Status: QuotaStatusActive, PeriodStart: billing.BillingPeriodStart, PeriodEnd: billing.BillingPeriodEnd} if recovery != nil && recovery.Kind == accountdomain.QuotaRecoveryKindPaid { result.Status = QuotaStatusWaitingReset @@ -538,10 +538,7 @@ func newQuotaView(billing *accountdomain.Billing, observedTokens int64, recovery } func isEstimatedFreeBillingProfile(billing *accountdomain.Billing) bool { - if billing == nil { - return false - } - return billing.IsUnifiedBillingUser || billing.UsagePeriodType != "" || billing.TopUpMethod != "" || billing.BillingPeriodStart != "" || len(billing.History) > 0 + return billing != nil && billing.HasFreeProfileSignal() } // StartDeviceLogin 启动短期 Device OAuth,会话只保存在有界运行态存储中。 @@ -1285,6 +1282,21 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie return s.Get(ctx, updated.ID) } +// MarkBuildAPIFallback 幂等写入 Build 账号 XAI 推理回退标记;失败不吞掉,调用方可重试。 +func (s *Service) MarkBuildAPIFallback(ctx context.Context, id uint64, enabled bool) error { + return mapRepositoryError(s.accounts.MarkBuildAPIFallback(ctx, id, enabled)) +} + +// CanUseBuildAPIFallback 仅允许 Billing 已确认付费的 Build 账号访问 XAI 回退地址。 +// 缺失或读取失败的 Billing 按无资格处理,由调用方 fail closed。 +func (s *Service) CanUseBuildAPIFallback(ctx context.Context, id uint64) (bool, error) { + billing, err := s.accounts.GetBilling(ctx, id) + if err != nil { + return false, mapRepositoryError(err) + } + return billing.IsPaid(), nil +} + func (s *Service) Delete(ctx context.Context, id uint64) error { if s.sticky != nil { _ = s.sticky.DeleteByAccount(ctx, id) @@ -1628,8 +1640,7 @@ func (s *Service) ProbePaidQuota(ctx context.Context, value accountdomain.Creden } func (s *Service) reconcilePaidQuotaRecovery(ctx context.Context, credential accountdomain.Credential, billing accountdomain.Billing, afterProbe bool) error { - isPaid := billing.MonthlyLimit > 0 || billing.OnDemandCap > 0 || billing.OnDemandUsed > 0 || billing.PrepaidBalance > 0 || billing.CreditUsagePercent > 0 - if !isPaid || !billing.IsExhausted(credential.MinimumRemaining) { + if !billing.IsPaid() || !billing.IsExhausted(credential.MinimumRemaining) { recovery, err := s.accounts.GetQuotaRecovery(ctx, credential.ID) if errors.Is(err, repository.ErrNotFound) || (err == nil && recovery.Kind != accountdomain.QuotaRecoveryKindPaid) { return nil diff --git a/backend/internal/application/accountsync/service.go b/backend/internal/application/accountsync/service.go index 47d936ba..8e26d437 100644 --- a/backend/internal/application/accountsync/service.go +++ b/backend/internal/application/accountsync/service.go @@ -173,6 +173,7 @@ sendLoop: func (s *Service) syncAccount(ctx context.Context, accountID uint64) error { var syncErr error + billingSnapshotCreated := false view, err := s.accounts.Get(ctx, accountID) if err != nil { return fmt.Errorf("读取账号: %w", err) @@ -209,6 +210,8 @@ func (s *Service) syncAccount(ctx context.Context, accountID uint64) error { if err != nil { s.logger.Warn("account_initial_billing_sync_failed", "account_id", accountID, "error", err) syncErr = errors.Join(syncErr, fmt.Errorf("同步额度: %w", err)) + } else { + billingSnapshotCreated = true } } } @@ -218,7 +221,7 @@ func (s *Service) syncAccount(ctx context.Context, accountID uint64) error { s.logger.Warn("account_initial_model_check_failed", "account_id", accountID, "error", err) return errors.Join(syncErr, fmt.Errorf("检查模型快照: %w", err)) } - if hasModels { + if hasModels && !billingSnapshotCreated { return syncErr } operationCtx, cancel := context.WithTimeout(ctx, operationTimeout) diff --git a/backend/internal/application/accountsync/service_test.go b/backend/internal/application/accountsync/service_test.go index dc94fbc2..80c8975e 100644 --- a/backend/internal/application/accountsync/service_test.go +++ b/backend/internal/application/accountsync/service_test.go @@ -147,6 +147,22 @@ func TestSyncAccountFetchesOnlyMissingSnapshots(t *testing.T) { } } +func TestSyncAccountRecomputesModelsAfterCreatingBillingSnapshot(t *testing.T) { + billing := &billingStub{} + models := &modelStub{hasSnapshot: true} + service := NewService(slog.Default(), accountReaderStub{provider: accountdomain.ProviderBuild}, billing, nil, models) + + if err := service.syncAccount(context.Background(), 8); err != nil { + t.Fatal(err) + } + + _, billingSyncs := billing.counts() + _, modelSyncs := models.counts() + if billingSyncs != 1 || modelSyncs != 1 { + t.Fatalf("billing syncs = %d, model syncs = %d", billingSyncs, modelSyncs) + } +} + func TestSyncAccountUsesQuotaForConsoleProvider(t *testing.T) { billing := &billingStub{} quota := "aStub{} diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index f572ccc1..c15e647d 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -27,6 +27,8 @@ const quotaProbeLease = 5 * time.Minute const successPersistInterval = 30 * time.Second const candidateCacheTTL = time.Second +const modelAccessDeniedCooldown = 5 * time.Minute + type candidateSnapshot struct { values []account.RoutingCandidate expiresAt time.Time @@ -84,21 +86,22 @@ func (l *accountLease) Release() { // Selector 实现可替换的 balanced 账号选择策略。 type Selector struct { - accounts repository.AccountRepository - concurrency repository.ConcurrencyLimiter - sticky repository.StickySessionRepository - stickyTTL time.Duration - cooldownBase time.Duration - cooldownMax time.Duration - capacityWait time.Duration - mu sync.Mutex - leaseWakeMu sync.Mutex - leaseWake chan struct{} - lastSelectedAt map[uint64]time.Time - lastSuccessAt map[uint64]time.Time - candidates map[candidateCacheKey]candidateSnapshot - candidateLoads singleflight.Group - tierOrders interface { + accounts repository.AccountRepository + concurrency repository.ConcurrencyLimiter + sticky repository.StickySessionRepository + stickyTTL time.Duration + cooldownBase time.Duration + cooldownMax time.Duration + capacityWait time.Duration + preferFreeBuild bool + mu sync.Mutex + leaseWakeMu sync.Mutex + leaseWake chan struct{} + lastSelectedAt map[uint64]time.Time + lastSuccessAt map[uint64]time.Time + candidates map[candidateCacheKey]candidateSnapshot + candidateLoads singleflight.Group + tierOrders interface { TierOrder(account.Provider, string) []account.WebTier } } @@ -124,6 +127,13 @@ func (s *Selector) UpdateConfig(stickyTTL, cooldownBase, cooldownMax time.Durati s.mu.Unlock() } +// UpdatePreferFreeBuild 热更新 Build Free 账号优先策略。 +func (s *Selector) UpdatePreferFreeBuild(value bool) { + s.mu.Lock() + s.preferFreeBuild = value + s.mu.Unlock() +} + func (s *Selector) routingConfig() (time.Duration, time.Duration, time.Duration, time.Duration) { s.mu.Lock() defer s.mu.Unlock() @@ -434,9 +444,28 @@ func (s *Selector) MarkModelQuotaExhausted(ctx context.Context, credential accou s.invalidateCandidates(credential.Provider) } +// MarkModelAccessDenied isolates a permission failure to the rejected model. +// Build OAuth accounts may still have valid video access when a chat endpoint +// returns 403, so a model denial must not invalidate the whole credential. +func (s *Selector) MarkModelAccessDenied(ctx context.Context, credential account.Credential, upstreamModel string, retryAfter time.Duration) { + upstreamModel = strings.TrimSpace(upstreamModel) + if upstreamModel == "" { + return + } + if retryAfter <= 0 { + retryAfter = modelAccessDeniedCooldown + } + now := time.Now().UTC() + _ = s.accounts.UpsertModelQuotaBlock(ctx, account.ModelQuotaBlock{ + AccountID: credential.ID, UpstreamModel: upstreamModel, Reason: "model_access_denied", + CooldownUntil: now.Add(retryAfter), UpdatedAt: now, + }) + s.invalidateCandidates(credential.Provider) +} + // MarkPaidQuotaExhausted 使用已知真实账期将付费账号移出号池,到期后才允许 Billing 探测。 func (s *Selector) MarkPaidQuotaExhausted(ctx context.Context, credential account.Credential, billing *account.Billing) bool { - if billing == nil || (billing.MonthlyLimit <= 0 && billing.OnDemandCap <= 0 && billing.OnDemandUsed <= 0 && billing.PrepaidBalance <= 0 && billing.CreditUsagePercent <= 0) { + if billing == nil || !billing.IsPaid() { return false } periodEnd, ok := billing.PeriodEnd() diff --git a/backend/internal/application/gateway/selector_plan.go b/backend/internal/application/gateway/selector_plan.go index 81fbc45c..1a50ac2c 100644 --- a/backend/internal/application/gateway/selector_plan.go +++ b/backend/internal/application/gateway/selector_plan.go @@ -12,12 +12,13 @@ import ( ) type candidateScore struct { - index int - tier int - billingFresh bool - inFlight int - remaining float64 - lastSelected time.Time + index int + tier int + preferFreeBuild bool + billingFresh bool + inFlight int + remaining float64 + lastSelected time.Time } // candidatePlan 使用线性建堆保留完整路由优先级,并允许 claim 失败后按顺序取下一账号。 @@ -64,6 +65,9 @@ func candidateScoreBetter(values []account.RoutingCandidate, leftScore, rightSco if leftCandidate.ModelCapabilityKnown != rightCandidate.ModelCapabilityKnown { return leftCandidate.ModelCapabilityKnown } + if leftScore.preferFreeBuild != rightScore.preferFreeBuild { + return leftScore.preferFreeBuild + } if leftScore.tier != rightScore.tier { return leftScore.tier < rightScore.tier } @@ -118,7 +122,8 @@ func (s *Selector) planCandidates(ctx context.Context, values []account.RoutingC for index, candidate := range values { score := candidateScore{ index: index, tier: tierOrderRank(tierOrder, candidate.Credential.WebTier), - inFlight: inFlight[index], lastSelected: s.lastSelectedAt[candidate.Credential.ID], + preferFreeBuild: s.preferFreeBuild && candidate.IsKnownFreeBuild(), + inFlight: inFlight[index], lastSelected: s.lastSelectedAt[candidate.Credential.ID], } if candidate.Billing != nil { score.remaining = candidate.Billing.Remaining() diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index 85c3e319..75e79765 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -251,6 +251,12 @@ func TestSelectorOnlyUsesAccountsSupportingRequestedModel(t *testing.T) { t.Fatal(err) } now := time.Now().UTC() + if err := accounts.SaveBilling(ctx, account.Billing{AccountID: unsupported.ID, IsUnifiedBillingUser: true, SyncedAt: now}); err != nil { + t.Fatal(err) + } + if err := accounts.SaveBilling(ctx, account.Billing{AccountID: supported.ID, MonthlyLimit: 100, SyncedAt: now}); err != nil { + t.Fatal(err) + } if err := models.ReplaceAccountCapabilities(ctx, unsupported.ID, []string{"grok-basic"}, now); err != nil { t.Fatal(err) } @@ -259,6 +265,7 @@ func TestSelectorOnlyUsesAccountsSupportingRequestedModel(t *testing.T) { } selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + selector.UpdatePreferFreeBuild(true) lease, err := selector.Acquire(ctx, account.ProviderBuild, "grok-premium", "", "", map[uint64]bool{}, true) if err != nil { t.Fatal(err) @@ -330,6 +337,7 @@ func TestSelectorHonorsWebTierPoolOrderBeforeAccountPriority(t *testing.T) { } } selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), staticTierOrder{order: []account.WebTier{account.WebTierHeavy, account.WebTierSuper, account.WebTierBasic}}, time.Hour, time.Second, time.Minute) + selector.UpdatePreferFreeBuild(true) lease, err := selector.Acquire(ctx, account.ProviderWeb, "fast-prefer-best", "fast", "", nil, false) if err != nil { t.Fatal(err) @@ -395,6 +403,78 @@ func TestSelectorUsesBatchConcurrencySnapshot(t *testing.T) { } } +func TestSelectorPreferFreeBuildHotReloadAndSaturationFallback(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "free-first.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + freeAccount, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "free", SourceKey: "free", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 1, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + superAccount, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "super", SourceKey: "super", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 100, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := accounts.SaveBilling(ctx, account.Billing{AccountID: freeAccount.ID, IsUnifiedBillingUser: true, SyncedAt: now}); err != nil { + t.Fatal(err) + } + if err := accounts.SaveBilling(ctx, account.Billing{AccountID: superAccount.ID, MonthlyLimit: 140, SyncedAt: now}); err != nil { + t.Fatal(err) + } + + selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + lease, err := selector.Acquire(ctx, account.ProviderBuild, "grok-4.5", "", "existing-session", nil, false) + if err != nil { + t.Fatal(err) + } + if lease.Credential.ID != superAccount.ID { + t.Fatalf("disabled strategy selected %d, want higher-priority Super %d", lease.Credential.ID, superAccount.ID) + } + lease.Release() + + selector.UpdatePreferFreeBuild(true) + stickyLease, err := selector.Acquire(ctx, account.ProviderBuild, "grok-4.5", "", "existing-session", nil, false) + if err != nil { + t.Fatal(err) + } + if stickyLease.Credential.ID != superAccount.ID { + t.Fatalf("existing sticky session moved to %d, want Super %d", stickyLease.Credential.ID, superAccount.ID) + } + stickyLease.Release() + + freeLease, err := selector.Acquire(ctx, account.ProviderBuild, "grok-4.5", "", "new-session", nil, false) + if err != nil { + t.Fatal(err) + } + if freeLease.Credential.ID != freeAccount.ID { + t.Fatalf("enabled strategy selected %d, want Free %d", freeLease.Credential.ID, freeAccount.ID) + } + + fallbackLease, err := selector.Acquire(ctx, account.ProviderBuild, "grok-4.5", "", "", nil, false) + if err != nil { + t.Fatal(err) + } + defer fallbackLease.Release() + defer freeLease.Release() + if fallbackLease.Credential.ID != superAccount.ID { + t.Fatalf("saturated Free selected %d, want Super fallback %d", fallbackLease.Credential.ID, superAccount.ID) + } +} + func TestCandidatePlanPreservesSelectorOrdering(t *testing.T) { now := time.Now().UTC() limiter := &batchConcurrencyLimiter{values: map[string]int{"account:2": 1}} diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index be3195f9..d7e8dba9 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -22,6 +22,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/domain/clientkey" inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" 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" @@ -91,6 +92,11 @@ type routeResolver interface { GetByProviderUpstream(ctx context.Context, providerValue accountdomain.Provider, upstreamModel string) (modeldomain.Route, error) } +// videoAssetReader 从本地媒体层读取已落盘的视频资产。 +type videoAssetReader interface { + OpenVideo(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) +} + type accountModelSyncer interface { SyncAccount(ctx context.Context, accountID uint64) (int, error) } @@ -106,6 +112,7 @@ type Service struct { responses repository.ResponseRepository maxAttempts atomic.Int64 mediaJobs repository.MediaJobRepository + mediaAssets videoAssetReader mediaQueue chan string mediaMu sync.Mutex mediaQueued map[string]struct{} @@ -134,6 +141,11 @@ func (s *Service) ConfigureMedia(repository repository.MediaJobRepository, concu s.mediaQueued = make(map[string]struct{}) } +// ConfigureMediaAssets 注入本地视频资产读取能力(可选)。 +func (s *Service) ConfigureMediaAssets(reader videoAssetReader) { + s.mediaAssets = reader +} + func NewService(models routeResolver, audits auditRecorder, accounts *accountapp.Service, clientKeys *clientkeyapp.Service, providers *provider.Registry, selector *Selector, responses repository.ResponseRepository, maxAttempts int) *Service { service := &Service{ models: models, audits: audits, accounts: accounts, clientKeys: clientKeys, providers: providers, @@ -609,6 +621,11 @@ attemptLoop: continue } lastFailure = newHTTPUpstreamFailure(response.StatusCode, body, credential.ID, credential.Name) + freeBuildForbidden := response.StatusCode == http.StatusForbidden && credential.Provider == accountdomain.ProviderBuild && (lease.Billing == nil || !lease.Billing.IsPaid()) + if freeBuildForbidden { + // XAI 不接受 Free 账号。主 Build 403 是该账号当前不可用,必须冷却并换号。 + lastFailure.AccountScoped = true + } if response.StatusCode == http.StatusTooManyRequests && response.RateLimit != nil && response.RateLimit.TeamID != "" && response.RateLimit.Model == route.UpstreamModel { limited := s.markTeamModelRateLimit(credential, route.UpstreamModel, *response.RateLimit, time.Now().UTC()) lastFailure.AccountScoped = false @@ -643,7 +660,10 @@ attemptLoop: goto handleResponse } failureHandled := false - if lease.QuotaMode != "" && response.StatusCode == http.StatusTooManyRequests { + if freeBuildForbidden { + s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter) + failureHandled = true + } else if lease.QuotaMode != "" && response.StatusCode == http.StatusTooManyRequests { exhausted, reconcileErr := s.accounts.ReconcileRateLimit(ctx, credential.ID, lease.QuotaMode, retryAfter) s.selector.MarkQuotaStateChanged(credential.Provider) failureHandled = reconcileErr == nil && exhausted @@ -660,8 +680,15 @@ attemptLoop: failureHandled = s.selector.MarkPaidQuotaExhausted(ctx, credential, lease.Billing) } if s.providers.SupportsCredentialRefresh(credential.Provider) && lastFailure.PermanentAccountDenial { - _ = s.accounts.MarkReauthRequired(ctx, credential.ID, fmt.Sprintf("%s chat endpoint access denied", credential.Provider)) - s.selector.MarkQuotaStateChanged(credential.Provider) + if credential.Provider == accountdomain.ProviderBuild { + // A Build account can lack access to one chat model while its OAuth + // credential and video entitlement remain valid. Keep the denial + // model-scoped; only an actual credential rejection requires reauth. + s.selector.MarkModelAccessDenied(ctx, credential, route.UpstreamModel, retryAfter) + } else { + _ = s.accounts.MarkReauthRequired(ctx, credential.ID, fmt.Sprintf("%s chat endpoint access denied", credential.Provider)) + s.selector.MarkQuotaStateChanged(credential.Provider) + } failureHandled = true } else if s.providers.SupportsCredentialRefresh(credential.Provider) && lastFailure.CredentialRejected { _ = s.accounts.MarkReauthRequired(ctx, credential.ID, fmt.Sprintf("%s credential rejected", credential.Provider)) diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index c3239906..c25d12f8 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -466,7 +466,7 @@ func TestParseFreeQuotaExhaustion(t *testing.T) { } } -func TestGatewayPreservesRepeatedSystemicForbiddenWithoutCoolingAccounts(t *testing.T) { +func TestGatewayCoolsFreeBuildAccountsAfterForbidden(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "systemic-forbidden.db")) if err != nil { @@ -524,11 +524,11 @@ func TestGatewayPreservesRepeatedSystemicForbiddenWithoutCoolingAccounts(t *test if !errors.As(err, &upstreamFailure) || errors.Is(err, ErrNoAvailableAccount) { t.Fatalf("error = %T %v", err, err) } - if upstreamFailure.HTTPStatus != http.StatusForbidden || upstreamFailure.Code != "upstream_forbidden" || upstreamFailure.AccountScoped { + if upstreamFailure.HTTPStatus != http.StatusForbidden || upstreamFailure.Code != "upstream_forbidden" || !upstreamFailure.AccountScoped { t.Fatalf("upstream failure = %#v", upstreamFailure) } attempts := adapter.Attempts() - if len(attempts) != 2 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID { + if len(attempts) != 3 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID || attempts[2] != credentials[2].ID { t.Fatalf("attempts = %#v", attempts) } for _, credential := range credentials { @@ -536,12 +536,12 @@ func TestGatewayPreservesRepeatedSystemicForbiddenWithoutCoolingAccounts(t *test if getErr != nil { t.Fatal(getErr) } - if observed.FailureCount != 0 || observed.CooldownUntil != nil || observed.AuthStatus != account.AuthStatusActive { - t.Fatalf("account %d was incorrectly penalized: %#v", credential.ID, observed) + if observed.FailureCount != 1 || observed.CooldownUntil == nil || observed.AuthStatus != account.AuthStatusActive { + t.Fatalf("account %d was not cooled after 403: %#v", credential.ID, observed) } } logs, total, err := auditRepo.List(ctx, 0, 10) - if err != nil || total != 1 || logs[0].StatusCode != http.StatusForbidden || logs[0].ErrorCode != "upstream_forbidden" || logs[0].AccountID == nil || *logs[0].AccountID != credentials[1].ID { + if err != nil || total != 1 || logs[0].StatusCode != http.StatusForbidden || logs[0].ErrorCode != "upstream_forbidden" || logs[0].AccountID == nil || *logs[0].AccountID != credentials[2].ID { t.Fatalf("audit = %#v, total=%d, err=%v", logs, total, err) } } @@ -631,6 +631,75 @@ func TestGatewayRefreshesAndRetriesBuildPermissionDenialOnce(t *testing.T) { } } +func TestBuildChatPermissionDenialDoesNotInvalidateVideoCredential(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-scoped-denial.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + responseRepo := relational.NewResponseRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "chat-denied-video-valid", SourceKey: "chat-denied-video-valid", + EncryptedAccessToken: "access-old", EncryptedRefreshToken: "refresh-old", ExpiresAt: time.Now().Add(time.Hour), + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 100, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + if err := accountRepo.SaveBilling(ctx, account.Billing{AccountID: credential.ID, MonthlyLimit: 140, SyncedAt: time.Now().UTC()}); err != nil { + t.Fatal(err) + } + if err := modelRepo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-chat-denied"}); err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-chat-denied"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + clientKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "chat-denied-key", Prefix: "chat-denied", SecretHash: strings.Repeat("c", 64), EncryptedSecret: "encrypted", + Enabled: true, RPMLimit: 120, MaxConcurrent: 8, + }) + if err != nil { + t.Fatal(err) + } + adapter := &authRescueAdapter{} + adapter.denyChat.Store(true) + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 2) + + if _, err := service.CreateResponse(ctx, Input{ + RequestID: "req-chat-denied", ClientKey: clientKey, PublicModel: "grok-chat-denied", + Body: []byte(`{"model":"grok-chat-denied","input":"hello"}`), + }); err == nil { + t.Fatal("chat permission denial unexpectedly succeeded") + } + updated, err := accountRepo.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if updated.AuthStatus != account.AuthStatusActive || updated.FailureCount != 0 || updated.CooldownUntil != nil { + t.Fatalf("chat denial invalidated the whole credential: %#v", updated) + } + candidates, err := accountRepo.ListRoutingCandidates(ctx, account.ProviderBuild, "grok-chat-denied", "") + if err != nil { + t.Fatal(err) + } + if len(candidates) != 1 || candidates[0].ModelQuotaBlock == nil || candidates[0].ModelQuotaBlock.Reason != "model_access_denied" { + t.Fatalf("model-scoped denial was not persisted: %#v", candidates) + } +} + func TestWebRateLimitExhaustsOnlyRequestedQuotaMode(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "web-rate-limit.db")) @@ -1095,6 +1164,7 @@ type authRescueAdapter struct { attempts atomic.Int64 refreshes atomic.Int64 rejectAll atomic.Bool + denyChat atomic.Bool } func (a *authRescueAdapter) Provider() account.Provider { return account.ProviderBuild } @@ -1103,6 +1173,12 @@ func (a *authRescueAdapter) Definition() provider.Definition { } func (a *authRescueAdapter) ForwardResponse(_ context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) { a.attempts.Add(1) + if a.denyChat.Load() { + return &provider.Response{ + StatusCode: http.StatusForbidden, Status: "403 Forbidden", Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"error":{"code":"permission_denied","message":"Access to the chat endpoint is denied"}}`)), + }, nil + } if a.rejectAll.Load() { return &provider.Response{ StatusCode: http.StatusUnauthorized, Status: "401 Unauthorized", Header: make(http.Header), diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 429a7b92..7fa544f1 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "sync" "time" @@ -106,6 +107,43 @@ func (s *Service) GetVideo(ctx context.Context, id string, key clientkey.Key) (m return job, nil } +func (s *Service) OpenVideoContent(ctx context.Context, id string, key clientkey.Key) (io.ReadCloser, string, int64, error) { + job, err := s.GetVideo(ctx, id, key) + if err != nil { + return nil, "", 0, err + } + if job.Status != media.StatusCompleted { + return nil, "", 0, fmt.Errorf("视频内容尚未可用") + } + // 本地资产优先:XAI ZDR 上传完成后不经公网回环下载。 + if job.ResultAssetID != "" && s.mediaAssets != nil { + asset, body, openErr := s.mediaAssets.OpenVideo(ctx, job.ResultAssetID) + if openErr == nil { + return body, asset.MIMEType, asset.SizeBytes, nil + } + } + if job.UpstreamURL == "" { + return nil, "", 0, fmt.Errorf("视频内容尚未可用") + } + adapter, ok := s.providers.Videos(account.Provider(job.Provider)) + if !ok { + return nil, "", 0, ErrResponseAccountUnavailable + } + downloader, ok := adapter.(provider.VideoContentDownloader) + if !ok || s.selector == nil || s.selector.accounts == nil || s.accounts == nil { + return nil, "", 0, ErrResponseAccountUnavailable + } + credential, err := s.selector.accounts.Get(ctx, job.AccountID) + if err != nil { + return nil, "", 0, ErrResponseAccountUnavailable + } + credential, err = s.accounts.EnsureCredential(ctx, credential, false) + if err != nil { + return nil, "", 0, ErrResponseAccountUnavailable + } + return downloader.DownloadVideo(ctx, credential, job.UpstreamURL) +} + func (s *Service) RecoverVideoJobs(ctx context.Context) error { if s.mediaJobs == nil { return nil @@ -261,7 +299,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } lastProgress := job.Progress result, err := adapter.GenerateVideo(ctx, provider.VideoRequest{ - Credential: lease.Credential, Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality, + Credential: lease.Credential, JobID: job.ID, Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality, ReferenceURLs: decodeVideoInput(job.InputJSON), Progress: func(value int) { value = min(99, max(1, value)) @@ -295,6 +333,14 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model case status == http.StatusForbidden && s.providers.RetryForbiddenAsEgress(lease.Credential.Provider): // Web Provider 已对 anti-bot 403 降低出口健康并重建浏览器会话; // 视频请求已提交,不能换号重试,也不能误伤账号池。 + // Build 主地址 403 的 XAI 推理回退在 Adapter 内完成,不在此禁用账号。 + failureHandled = true + case status == http.StatusForbidden && lease.Credential.Provider == account.ProviderBuild: + if lease.Billing == nil || !lease.Billing.IsPaid() { + // Free/Unknown 不具备 XAI 回退资格;主 Build 403 表示该账号当前异常。 + s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) + } + // Super 的 XAI 探测在 Adapter 内完成;其 403 保持服务级处理。 failureHandled = true case (status == http.StatusPaymentRequired || status == http.StatusTooManyRequests) && lease.QuotaMode != "": exhausted, reconcileErr := s.accounts.ReconcileRateLimit(failureCtx, lease.Credential.ID, lease.QuotaMode, 0) @@ -316,11 +362,18 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } failureCancel() applyMediaJobEgress(&job, egressTrace, route.Provider) - s.failVideoJob(parent, job, "generation_failed", err) + failureCode, publicErr := "generation_failed", err + if status, ok := provider.ErrorHTTPStatus(err); errors.Is(err, provider.ErrUnauthorized) || (ok && (status == http.StatusUnauthorized || status == http.StatusForbidden)) { + failureCode, publicErr = "provider_unavailable", errors.New("上游服务暂不可用") + } + s.failVideoJob(parent, job, failureCode, publicErr) return } now := time.Now().UTC() job.Status, job.Progress, job.UpstreamURL, job.ContentType = media.StatusCompleted, 100, result.URL, result.ContentType + if result.AssetID != "" { + job.ResultAssetID = result.AssetID + } applyMediaJobEgress(&job, egressTrace, route.Provider) job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now if err := s.persistVideoJobWithRetry(parent, job); err != nil { diff --git a/backend/internal/application/media/service.go b/backend/internal/application/media/service.go index 094916ed..522851ab 100644 --- a/backend/internal/application/media/service.go +++ b/backend/internal/application/media/service.go @@ -27,10 +27,11 @@ var ( ErrMediaJobsUnavailable = errors.New("视频任务仓储未配置") ) -// Service 负责图片校验、文件落盘和元数据持久化的一致性收口。 +// Service 负责图片/视频校验、文件落盘和元数据持久化的一致性收口。 type Service struct { assets repository.MediaAssetRepository jobs repository.MediaJobRepository + tickets repository.MediaUploadTicketRepository objects repository.MediaObjectStorage cleanupLock repository.DistributedLock publicBaseURL string @@ -66,8 +67,13 @@ type VideoStats struct { } func NewService(assets repository.MediaAssetRepository, jobs repository.MediaJobRepository, objects repository.MediaObjectStorage, cleanupLock repository.DistributedLock, cfg Config) *Service { + return NewServiceWithTickets(assets, jobs, nil, objects, cleanupLock, cfg) +} + +// NewServiceWithTickets 构造包含视频上传票据能力的媒体服务。 +func NewServiceWithTickets(assets repository.MediaAssetRepository, jobs repository.MediaJobRepository, tickets repository.MediaUploadTicketRepository, objects repository.MediaObjectStorage, cleanupLock repository.DistributedLock, cfg Config) *Service { return &Service{ - assets: assets, jobs: jobs, objects: objects, cleanupLock: cleanupLock, + assets: assets, jobs: jobs, tickets: tickets, objects: objects, cleanupLock: cleanupLock, publicBaseURL: strings.TrimRight(strings.TrimSpace(cfg.PublicBaseURL), "/"), maxImageBytes: cfg.MaxImageBytes, maxTotalBytes: cfg.MaxTotalBytes, cleanupAt: cfg.CleanupThresholdPercent, cleanupEvery: cfg.CleanupInterval, cleanupSignal: make(chan struct{}, 1), configChanged: make(chan struct{}, 1), @@ -254,7 +260,16 @@ func (s *Service) RunCleanup(ctx context.Context, onError func(error)) { } } -// Cleanup 在跨实例锁保护下删除最旧图片,直到回落到自动清理阈值。 +const ( + cleanupAssetBatchSize = 200 + cleanupTicketBatchSize = 200 + // cleanupTicketMaxBatchesPerRun 限制单次 Cleanup 调用中过期票据的删除批次数。 + // 超出部分留给后续直接/后台清理继续回收,避免一次调用无界垄断。 + cleanupTicketMaxBatchesPerRun = 1 +) + +// Cleanup 在跨实例锁保护下删除最旧媒体资产,直到回落到自动清理阈值。 +// 同时有界清理过期上传票据。受保护资产被跳过;通过 offset 前进避免整页受保护时死循环。 func (s *Service) Cleanup(ctx context.Context) (int, error) { cfg := s.runtimeConfig() if s.cleanupLock != nil { @@ -264,6 +279,18 @@ func (s *Service) Cleanup(ctx context.Context) (int, error) { } defer release() } + // 过期票据回收:不触碰未过期票据与已登记媒体资产;单次调用有批次数上限。 + if s.tickets != nil { + for batch := 0; batch < cleanupTicketMaxBatchesPerRun; batch++ { + n, err := s.tickets.DeleteExpiredUploadTickets(ctx, time.Now().UTC(), cleanupTicketBatchSize) + if err != nil { + return 0, err + } + if n < int64(cleanupTicketBatchSize) { + break + } + } + } total, err := s.assets.TotalMediaAssetBytes(ctx) if err != nil { return 0, err @@ -274,18 +301,27 @@ func (s *Service) Cleanup(ctx context.Context) (int, error) { return 0, nil } deleted := 0 + offset := 0 for total > threshold { - values, err := s.assets.ListOldestMediaAssets(ctx, 200) + values, err := s.assets.ListOldestMediaAssets(ctx, offset, cleanupAssetBatchSize) if err != nil { return deleted, err } if len(values) == 0 { break } + protected, protErr := s.assets.ListProtectedMediaAssetIDs(ctx) + if protErr != nil { + return deleted, protErr + } + deletedInBatch := 0 for _, asset := range values { if total <= threshold { break } + if _, skip := protected[asset.ID]; skip { + continue + } if err := s.objects.Delete(ctx, asset.StorageKey); err != nil { if errors.Is(err, os.ErrNotExist) { return deleted, fmt.Errorf("媒体对象缺失,已保留共享元数据: %s: %w", asset.StorageKey, err) @@ -297,7 +333,18 @@ func (s *Service) Cleanup(ctx context.Context) (int, error) { } total = max(0, total-asset.SizeBytes) deleted++ + deletedInBatch++ } + if deletedInBatch == 0 { + // 本页无可删资产:前进 offset 以越过受保护前缀,避免无限循环。 + if len(values) < cleanupAssetBatchSize { + break + } + offset += len(values) + continue + } + // 删除后最旧顺序变化,从头部重新扫描。 + offset = 0 } s.totalBytes.Store(total) return deleted, nil diff --git a/backend/internal/application/media/service_test.go b/backend/internal/application/media/service_test.go index 9b89bf38..ecbfb629 100644 --- a/backend/internal/application/media/service_test.go +++ b/backend/internal/application/media/service_test.go @@ -3,8 +3,11 @@ package media import ( "bytes" "context" + "crypto/sha256" "encoding/base64" + "encoding/hex" "errors" + "fmt" "io" "os" "path/filepath" @@ -15,6 +18,7 @@ import ( mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" localmedia "github.com/chenyme/grok2api/backend/internal/infra/media" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/repository" ) const onePixelPNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" @@ -119,6 +123,287 @@ func TestCleanupDeletesOldestAssetsAtThreshold(t *testing.T) { } } +func TestCleanupPagesPastProtectedAssetsAndDeletesLaterUnprotected(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-cleanup-protected.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := localmedia.NewLocalStore(filepath.Join(t.TempDir(), "objects-protected")) + if err != nil { + t.Fatal(err) + } + assetRepo := relational.NewMediaAssetRepository(database) + ticketRepo := relational.NewMediaUploadTicketRepository(database) + raw, _ := base64.StdEncoding.DecodeString(onePixelPNG) + now := time.Now().UTC() + // 超过 cleanupAssetBatchSize(200) 的受保护前缀 + 1 个可删资产。 + const protectedCount = cleanupAssetBatchSize + 1 + for i := 0; i < protectedCount; i++ { + id := fmt.Sprintf("img_prot_%04d_aaaaaaaaaa", i) + key, err := objects.SaveImage(ctx, id, "image/png", raw) + if err != nil { + t.Fatal(err) + } + if err := assetRepo.CreateMediaAsset(ctx, mediadomain.Asset{ + ID: id, Kind: "image", StorageKey: key, MIMEType: "image/png", SizeBytes: int64(len(raw)), + SHA256: strings.Repeat("b", 64), CreatedAt: now.Add(time.Duration(i-protectedCount-1) * time.Minute), + }); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(fmt.Sprintf("prot-ticket-%d", i))) + if err := ticketRepo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hex.EncodeToString(sum[:]), AssetID: id, JobID: fmt.Sprintf("job_prot_%d", i), + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + } + deletableID := "img_free_00000000000001" + key, err := objects.SaveImage(ctx, deletableID, "image/png", raw) + if err != nil { + t.Fatal(err) + } + if err := assetRepo.CreateMediaAsset(ctx, mediadomain.Asset{ + ID: deletableID, Kind: "image", StorageKey: key, MIMEType: "image/png", SizeBytes: int64(len(raw)), + SHA256: strings.Repeat("c", 64), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + // 阈值极低:强制触发清理;受保护资产不可删,应通过 offset 扫到可删项。 + service := NewServiceWithTickets(assetRepo, relational.NewMediaJobRepository(database), ticketRepo, objects, nil, Config{ + PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, + MaxTotalBytes: int64(len(raw)), CleanupThresholdPercent: 50, CleanupInterval: time.Minute, + }) + deleted, err := service.Cleanup(ctx) + if err != nil { + t.Fatal(err) + } + if deleted != 1 { + t.Fatalf("deleted=%d, want 1 (only unprotected asset)", deleted) + } + if _, err := assetRepo.GetMediaAsset(ctx, deletableID); !errors.Is(err, repository.ErrNotFound) { + t.Fatalf("deletable asset still present: %v", err) + } + if _, err := assetRepo.GetMediaAsset(ctx, fmt.Sprintf("img_prot_%04d_aaaaaaaaaa", 0)); err != nil { + t.Fatalf("protected oldest was deleted: %v", err) + } + if _, err := assetRepo.GetMediaAsset(ctx, fmt.Sprintf("img_prot_%04d_aaaaaaaaaa", protectedCount-1)); err != nil { + t.Fatalf("protected near-end was deleted: %v", err) + } +} + +func TestCleanupAllProtectedTerminatesWithoutDelete(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-cleanup-all-prot.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := localmedia.NewLocalStore(filepath.Join(t.TempDir(), "objects-all-prot")) + if err != nil { + t.Fatal(err) + } + assetRepo := relational.NewMediaAssetRepository(database) + ticketRepo := relational.NewMediaUploadTicketRepository(database) + raw, _ := base64.StdEncoding.DecodeString(onePixelPNG) + now := time.Now().UTC() + for i := 0; i < 3; i++ { + id := fmt.Sprintf("img_allp_%04d_aaaaaaaa", i) + key, err := objects.SaveImage(ctx, id, "image/png", raw) + if err != nil { + t.Fatal(err) + } + if err := assetRepo.CreateMediaAsset(ctx, mediadomain.Asset{ + ID: id, Kind: "image", StorageKey: key, MIMEType: "image/png", SizeBytes: int64(len(raw)), + SHA256: strings.Repeat("d", 64), CreatedAt: now.Add(time.Duration(i) * time.Minute), + }); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(fmt.Sprintf("all-prot-%d", i))) + if err := ticketRepo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hex.EncodeToString(sum[:]), AssetID: id, JobID: fmt.Sprintf("job_allp_%d", i), + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + } + service := NewServiceWithTickets(assetRepo, relational.NewMediaJobRepository(database), ticketRepo, objects, nil, Config{ + PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, + MaxTotalBytes: int64(len(raw)), CleanupThresholdPercent: 10, CleanupInterval: time.Minute, + }) + // 若仍无限循环,此用例会挂起失败。 + done := make(chan struct{}) + var deleted int + var cleanupErr error + go func() { + deleted, cleanupErr = service.Cleanup(ctx) + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("cleanup did not terminate when all assets are protected") + } + if cleanupErr != nil { + t.Fatal(cleanupErr) + } + if deleted != 0 { + t.Fatalf("deleted=%d, want 0", deleted) + } + total, err := assetRepo.TotalMediaAssetBytes(ctx) + if err != nil || total != int64(len(raw)*3) { + t.Fatalf("total=%d err=%v", total, err) + } +} + +func TestCleanupPrunesExpiredUploadTickets(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-cleanup-tickets.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := localmedia.NewLocalStore(filepath.Join(t.TempDir(), "objects-tickets")) + if err != nil { + t.Fatal(err) + } + ticketRepo := relational.NewMediaUploadTicketRepository(database) + now := time.Now().UTC() + expiredSum := sha256.Sum256([]byte("expired-token")) + activeSum := sha256.Sum256([]byte("active-token")) + expiredHash := hex.EncodeToString(expiredSum[:]) + activeHash := hex.EncodeToString(activeSum[:]) + if err := ticketRepo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: expiredHash, AssetID: "vid_expired_00000001", JobID: "job_expired", + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(-time.Minute), CreatedAt: now.Add(-time.Hour), + }); err != nil { + t.Fatal(err) + } + if err := ticketRepo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: activeHash, AssetID: "vid_active_0000000001", JobID: "job_active", + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + ticketRepo, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + if _, err := service.Cleanup(ctx); err != nil { + t.Fatal(err) + } + if _, err := ticketRepo.GetUploadTicketByHash(ctx, expiredHash); !errors.Is(err, repository.ErrNotFound) { + t.Fatalf("expired ticket should be pruned: %v", err) + } + active, err := ticketRepo.GetUploadTicketByHash(ctx, activeHash) + if err != nil { + t.Fatalf("active ticket pruned: %v", err) + } + if !active.ExpiresAt.After(now) { + t.Fatalf("active ticket corrupted: %#v", active) + } +} + +func TestCleanupCapsExpiredTicketPruningPerInvocation(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-cleanup-ticket-cap.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := localmedia.NewLocalStore(filepath.Join(t.TempDir(), "objects-ticket-cap")) + if err != nil { + t.Fatal(err) + } + ticketRepo := relational.NewMediaUploadTicketRepository(database) + now := time.Now().UTC() + // 超过单次调用上限:maxBatches * batchSize + 额外过期票据。 + expiredCount := cleanupTicketBatchSize*cleanupTicketMaxBatchesPerRun + 50 + expiredHashes := make([]string, 0, expiredCount) + for i := 0; i < expiredCount; i++ { + sum := sha256.Sum256([]byte(fmt.Sprintf("expired-cap-token-%d", i))) + hash := hex.EncodeToString(sum[:]) + expiredHashes = append(expiredHashes, hash) + if err := ticketRepo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hash, AssetID: fmt.Sprintf("vid_exp_cap_%04d", i), JobID: fmt.Sprintf("job_exp_cap_%d", i), + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(-time.Minute), CreatedAt: now.Add(-time.Hour), + }); err != nil { + t.Fatal(err) + } + } + activeSum := sha256.Sum256([]byte("active-cap-token")) + activeHash := hex.EncodeToString(activeSum[:]) + if err := ticketRepo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: activeHash, AssetID: "vid_active_cap_0000001", JobID: "job_active_cap", + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + ticketRepo, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + + if _, err := service.Cleanup(ctx); err != nil { + t.Fatal(err) + } + // 活跃票据必须保留。 + if _, err := ticketRepo.GetUploadTicketByHash(ctx, activeHash); err != nil { + t.Fatalf("active ticket must survive cleanup: %v", err) + } + // 第一次调用最多删除 cap 条,剩余过期票据仍在。 + remainingAfterFirst := 0 + for _, hash := range expiredHashes { + if _, err := ticketRepo.GetUploadTicketByHash(ctx, hash); err == nil { + remainingAfterFirst++ + } else if !errors.Is(err, repository.ErrNotFound) { + t.Fatal(err) + } + } + capPerRun := cleanupTicketBatchSize * cleanupTicketMaxBatchesPerRun + wantRemaining := expiredCount - capPerRun + if remainingAfterFirst != wantRemaining { + t.Fatalf("remaining expired after first cleanup = %d, want %d (cap=%d total=%d)", remainingAfterFirst, wantRemaining, capPerRun, expiredCount) + } + + // 后续调用继续回收剩余过期票据。 + if _, err := service.Cleanup(ctx); err != nil { + t.Fatal(err) + } + remainingAfterSecond := 0 + for _, hash := range expiredHashes { + if _, err := ticketRepo.GetUploadTicketByHash(ctx, hash); err == nil { + remainingAfterSecond++ + } else if !errors.Is(err, repository.ErrNotFound) { + t.Fatal(err) + } + } + if remainingAfterSecond != 0 { + t.Fatalf("remaining expired after second cleanup = %d, want 0", remainingAfterSecond) + } + if _, err := ticketRepo.GetUploadTicketByHash(ctx, activeHash); err != nil { + t.Fatalf("active ticket must still exist: %v", err) + } +} + func TestCleanupPreservesMetadataWhenLocalObjectIsMissing(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-missing.db")) diff --git a/backend/internal/application/media/upload.go b/backend/internal/application/media/upload.go new file mode 100644 index 00000000..451122eb --- /dev/null +++ b/backend/internal/application/media/upload.go @@ -0,0 +1,397 @@ +package media + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +const ( + // DefaultMaxVideoBytes 是视频上传与本地视频资产的安全上限(256 MiB)。 + DefaultMaxVideoBytes = 256 << 20 + // videoUploadTicketTTL 限制票据有效期,过期后不可再写入。 + videoUploadTicketTTL = 2 * time.Hour + // videoUploadWaitInterval 轮询本地资产就绪间隔。 + videoUploadWaitInterval = 500 * time.Millisecond +) + +var ( + ErrInvalidVideoUpload = errors.New("视频上传无效") + // ErrVideoUploadTooLarge 表示 body 超过票据/中间件体积上限;handler 映射为 HTTP 413。 + // 同时包装 ErrInvalidVideoUpload,便于统一归类为无效上传。 + ErrVideoUploadTooLarge = errors.New("视频超过体积上限") + ErrUploadTicketNotFound = errors.New("上传票据不存在") + ErrUploadTicketExpired = errors.New("上传票据已过期") + ErrUploadTicketConsumed = errors.New("上传票据已使用") + ErrUploadPublicBase = errors.New("公开 API 地址不可用于 XAI 视频上传") + ErrVideoUploadIncomplete = errors.New("视频尚未上传完成") + ErrUploadTicketsUnavailable = errors.New("视频上传票据仓储未配置") +) + +func errVideoTooLarge() error { + return fmt.Errorf("%w: %w", ErrInvalidVideoUpload, ErrVideoUploadTooLarge) +} + +// IssueVideoUpload 签发一次性高熵 PUT 地址,供 XAI ZDR 视频写入。 +// 错误信息不得包含完整 URL 或 token 明文。 +func (s *Service) IssueVideoUpload(ctx context.Context, jobID string) (uploadURL, assetID string, err error) { + if s.tickets == nil { + return "", "", ErrUploadTicketsUnavailable + } + publicBase, err := s.httpsPublicBaseURL() + if err != nil { + return "", "", err + } + jobID = strings.TrimSpace(jobID) + if jobID == "" { + return "", "", fmt.Errorf("%w: 缺少视频任务 ID", ErrInvalidVideoUpload) + } + token, err := newUploadToken() + if err != nil { + return "", "", err + } + assetID, err = newVideoAssetID() + if err != nil { + return "", "", err + } + now := time.Now().UTC() + ticket := repository.MediaUploadTicket{ + TokenHash: hashUploadToken(token), + AssetID: assetID, + JobID: jobID, + MaxBytes: DefaultMaxVideoBytes, + AllowedMIME: "video/mp4", + ExpiresAt: now.Add(videoUploadTicketTTL), + CreatedAt: now, + } + if err := s.tickets.CreateUploadTicket(ctx, ticket); err != nil { + return "", "", err + } + // 提前绑定任务结果资产,便于轮询/清理感知进行中的本地目标。 + // 生产中 job 已存在:真实数据库错误必须中止签发,不得返回未绑定目标的 upload URL。 + // ErrNotFound 仅保留给隔离/测试占位 job 的既有行为,且不删除已创建票据。 + if err := s.tickets.BindJobResultAsset(ctx, jobID, assetID); err != nil && !errors.Is(err, repository.ErrNotFound) { + // 补偿删除刚创建的票据,避免 bind 失败后留下不可达行直至 TTL。 + if delErr := s.tickets.DeleteUploadTicketByHash(ctx, ticket.TokenHash); delErr != nil { + return "", "", fmt.Errorf("绑定视频任务结果资产失败: %w", errors.Join(err, fmt.Errorf("回滚上传票据失败: %w", delErr))) + } + return "", "", fmt.Errorf("绑定视频任务结果资产失败: %w", err) + } + uploadURL = publicBase + "/v1/media/uploads/" + token + return uploadURL, assetID, nil +} + +// WaitVideoUpload 等待 PUT 完成后资产元数据就绪。 +func (s *Service) WaitVideoUpload(ctx context.Context, assetID string) (contentType string, err error) { + assetID = strings.TrimSpace(assetID) + if assetID == "" { + return "", fmt.Errorf("%w: 缺少资产 ID", ErrInvalidVideoUpload) + } + ticker := time.NewTicker(videoUploadWaitInterval) + defer ticker.Stop() + for { + asset, getErr := s.assets.GetMediaAsset(ctx, assetID) + if getErr == nil && asset.Kind == "video" && asset.SizeBytes > 0 { + return asset.MIMEType, nil + } + if getErr != nil && !errors.Is(getErr, repository.ErrNotFound) { + return "", getErr + } + select { + case <-ctx.Done(): + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return "", ErrVideoUploadIncomplete + } + return "", ctx.Err() + case <-ticker.C: + } + } +} + +// ReceiveVideoUpload 处理公开 PUT:校验票据、流式限长、内容嗅探、原子提交并登记资产。 +// 票据本身即授权,无需客户端 API key。 +func (s *Service) ReceiveVideoUpload(ctx context.Context, rawToken string, contentType string, body io.Reader) (mediadomain.Asset, error) { + if s.tickets == nil { + return mediadomain.Asset{}, ErrUploadTicketsUnavailable + } + token := strings.TrimSpace(rawToken) + if !validUploadToken(token) { + return mediadomain.Asset{}, ErrUploadTicketNotFound + } + tokenHash := hashUploadToken(token) + now := time.Now().UTC() + // 先读取票据以做预检,再原子消费,防止重复成功写入。 + existing, err := s.tickets.GetUploadTicketByHash(ctx, tokenHash) + if errors.Is(err, repository.ErrNotFound) { + return mediadomain.Asset{}, ErrUploadTicketNotFound + } + if err != nil { + return mediadomain.Asset{}, err + } + if existing.ConsumedAt != nil { + return mediadomain.Asset{}, ErrUploadTicketConsumed + } + if !existing.ExpiresAt.After(now) { + return mediadomain.Asset{}, ErrUploadTicketExpired + } + // 若资产已存在则视为重复成功写入,拒绝覆盖;仓储故障必须向上传播,禁止继续写入或消费票据。 + if _, getErr := s.assets.GetMediaAsset(ctx, existing.AssetID); getErr == nil { + return mediadomain.Asset{}, ErrUploadTicketConsumed + } else if getErr != nil && !errors.Is(getErr, repository.ErrNotFound) { + return mediadomain.Asset{}, getErr + } + + // XAI ZDR 当前契约为 MP4:票据 AllowedMIME 约束声明类型与嗅探结果。 + allowedMIME := normalizeVideoMIME(existing.AllowedMIME) + if allowedMIME == "" { + allowedMIME = "video/mp4" + } + if !supportedVideoMIME(allowedMIME) { + return mediadomain.Asset{}, fmt.Errorf("%w: 票据 MIME 无效", ErrInvalidVideoUpload) + } + declaredMIME := normalizeVideoMIME(contentType) + if declaredMIME != "" && declaredMIME != allowedMIME { + return mediadomain.Asset{}, fmt.Errorf("%w: Content-Type 与票据不允许的类型不一致", ErrInvalidVideoUpload) + } + + // 存储扩展名以票据允许类型为准,避免声明类型与最终元数据分叉。 + tempPath, storageKey, err := s.objects.BeginVideoUpload(ctx, existing.AssetID, allowedMIME) + if err != nil { + return mediadomain.Asset{}, err + } + cleanupTemp := true + defer func() { + if cleanupTemp { + _ = s.objects.AbortVideoUpload(context.WithoutCancel(ctx), tempPath) + } + }() + + file, err := os.OpenFile(tempPath, os.O_WRONLY|os.O_TRUNC, 0o600) + if err != nil { + return mediadomain.Asset{}, err + } + // 流式限长:最多 MaxBytes+1,用于检测超限。 + limited := io.LimitReader(body, existing.MaxBytes+1) + hasher := sha256.New() + writer := io.MultiWriter(file, hasher) + written, copyErr := io.Copy(writer, limited) + closeErr := file.Close() + if copyErr != nil { + if isBodyTooLargeError(copyErr) { + return mediadomain.Asset{}, errVideoTooLarge() + } + return mediadomain.Asset{}, copyErr + } + if closeErr != nil { + return mediadomain.Asset{}, closeErr + } + if written == 0 { + return mediadomain.Asset{}, fmt.Errorf("%w: 空内容", ErrInvalidVideoUpload) + } + if written > existing.MaxBytes { + return mediadomain.Asset{}, errVideoTooLarge() + } + + // 内容嗅探:必须与票据允许 MIME 一致(XAI 当前为 video/mp4)。 + sniffed, sniffErr := sniffVideoFile(tempPath) + if sniffErr != nil { + return mediadomain.Asset{}, sniffErr + } + if sniffed != allowedMIME { + return mediadomain.Asset{}, fmt.Errorf("%w: 内容类型与票据不允许的类型不一致", ErrInvalidVideoUpload) + } + finalMIME := allowedMIME + + // 原子消费票据:并发 PUT 仅一个能消费成功。 + ticket, consumed, err := s.tickets.ConsumeUploadTicket(ctx, tokenHash, now) + if err != nil { + return mediadomain.Asset{}, err + } + if !consumed { + return mediadomain.Asset{}, ErrUploadTicketConsumed + } + // 消费后若提交/登记失败,必须释放票据以便同 token 重试,避免永久烧毁。 + releaseTicket := true + defer func() { + if releaseTicket { + _, _ = s.tickets.ReleaseUploadTicket(context.WithoutCancel(ctx), tokenHash) + } + }() + + if err := s.objects.CommitVideoUpload(ctx, tempPath, storageKey); err != nil { + // 提交失败:临时文件由 defer Abort 清理;票据释放后可重试。 + return mediadomain.Asset{}, err + } + cleanupTemp = false + + asset := mediadomain.Asset{ + ID: ticket.AssetID, Kind: "video", StorageKey: storageKey, MIMEType: finalMIME, + SizeBytes: written, SHA256: hex.EncodeToString(hasher.Sum(nil)), CreatedAt: now, + } + if err := s.assets.CreateMediaAsset(ctx, asset); err != nil { + // 一致性补偿:删除已提交对象并释放票据,避免孤立文件与烧毁票据。 + _ = s.objects.Delete(context.WithoutCancel(ctx), storageKey) + return mediadomain.Asset{}, err + } + releaseTicket = false + _ = s.tickets.BindJobResultAsset(ctx, ticket.JobID, ticket.AssetID) + if s.totalBytes.Add(asset.SizeBytes) > cleanupThresholdBytes(s.runtimeConfig()) { + select { + case s.cleanupSignal <- struct{}{}: + default: + } + } + return asset, nil +} + +// OpenVideo 读取视频元数据与正文。 +func (s *Service) OpenVideo(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) { + asset, err := s.assets.GetMediaAsset(ctx, strings.TrimSpace(id)) + if errors.Is(err, repository.ErrNotFound) { + return mediadomain.Asset{}, nil, ErrAssetNotFound + } + if err != nil { + return mediadomain.Asset{}, nil, err + } + if asset.Kind != "video" { + return mediadomain.Asset{}, nil, ErrAssetNotFound + } + body, err := s.objects.Open(ctx, asset.StorageKey) + if errors.Is(err, os.ErrNotExist) { + return mediadomain.Asset{}, nil, ErrAssetNotFound + } + if err != nil { + return mediadomain.Asset{}, nil, err + } + return asset, body, nil +} + +func (s *Service) httpsPublicBaseURL() (string, error) { + base := strings.TrimRight(strings.TrimSpace(s.runtimeConfig().PublicBaseURL), "/") + if base == "" { + return "", ErrUploadPublicBase + } + parsed, err := url.ParseRequestURI(base) + if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { + return "", ErrUploadPublicBase + } + return base, nil +} + +func newUploadToken() (string, error) { + // 256 bit 熵,hex 编码;校验时再 SHA-256 存库。 + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", fmt.Errorf("生成上传票据: %w", err) + } + return hex.EncodeToString(raw), nil +} + +func hashUploadToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +func validUploadToken(token string) bool { + if len(token) != 64 { + return false + } + for _, c := range token { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +func newVideoAssetID() (string, error) { + raw := make([]byte, 24) + if _, err := rand.Read(raw); err != nil { + return "", fmt.Errorf("生成视频资源 ID: %w", err) + } + return "vid_" + base64.RawURLEncoding.EncodeToString(raw), nil +} + +func supportedVideoMIME(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "video/mp4", "video/webm", "video/quicktime": + return true + default: + return false + } +} + +func normalizeVideoMIME(value string) string { + value = strings.ToLower(strings.TrimSpace(strings.Split(value, ";")[0])) + if value == "application/octet-stream" || value == "" { + return "" + } + return value +} + +func sniffVideoFile(path string) (string, error) { + file, err := os.Open(path) + if err != nil { + return "", err + } + defer func() { _ = file.Close() }() + header := make([]byte, 512) + n, err := io.ReadFull(file, header) + if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) { + return "", err + } + if n == 0 { + return "", fmt.Errorf("%w: 空内容", ErrInvalidVideoUpload) + } + detected := http.DetectContentType(header[:n]) + // DetectContentType 对 mp4 通常返回 video/mp4;部分样本可能是 application/octet-stream。 + if supportedVideoMIME(detected) { + return detected, nil + } + if looksLikeMP4(header[:n]) { + return "video/mp4", nil + } + if looksLikeWebM(header[:n]) { + return "video/webm", nil + } + return "", fmt.Errorf("%w: 非视频内容", ErrInvalidVideoUpload) +} + +func looksLikeMP4(header []byte) bool { + if len(header) < 12 { + return false + } + // ISO BMFF: bytes 4-8 often "ftyp" + return string(header[4:8]) == "ftyp" +} + +func looksLikeWebM(header []byte) bool { + // EBML header 0x1A45DFA3 + return len(header) >= 4 && header[0] == 0x1A && header[1] == 0x45 && header[2] == 0xDF && header[3] == 0xA3 +} + +func isBodyTooLargeError(err error) bool { + if err == nil { + return false + } + var maxBytes *http.MaxBytesError + if errors.As(err, &maxBytes) { + return true + } + // 兼容部分包装后的 MaxBytesReader 文案。 + msg := err.Error() + return strings.Contains(msg, "http: request body too large") || strings.Contains(msg, "request body too large") +} diff --git a/backend/internal/application/media/upload_test.go b/backend/internal/application/media/upload_test.go new file mode 100644 index 00000000..bcb0bdd2 --- /dev/null +++ b/backend/internal/application/media/upload_test.go @@ -0,0 +1,589 @@ +package media + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" + "github.com/chenyme/grok2api/backend/internal/infra/media" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestIssueAndReceiveVideoUploadOnce(t *testing.T) { + service, tickets, cleanup := newUploadTestService(t) + defer cleanup() + ctx := context.Background() + + // Public base must be HTTPS for XAI. + uploadURL, assetID, err := service.IssueVideoUpload(ctx, "video_job_test") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(uploadURL, "https://api.example/v1/media/uploads/") { + t.Fatalf("uploadURL = %s", uploadURL) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + if len(token) != 64 { + t.Fatalf("token entropy length = %d", len(token)) + } + + // Minimal ftyp box so content sniff accepts MP4. + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x01}, 64)...) + asset, err := service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + if err != nil { + t.Fatal(err) + } + if asset.ID != assetID || asset.Kind != "video" || asset.SizeBytes != int64(len(payload)) { + t.Fatalf("asset = %#v", asset) + } + + // Replay must fail and not create a second asset. + _, err = service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + if err == nil { + t.Fatal("expected replay rejection") + } + + // Ticket hash is stored, not plaintext token. + sum := sha256.Sum256([]byte(token)) + stored, err := tickets.GetUploadTicketByHash(ctx, hex.EncodeToString(sum[:])) + if err != nil || stored.ConsumedAt == nil { + t.Fatalf("ticket = %#v err=%v", stored, err) + } +} + +func TestReceiveVideoUploadRejectsExpiredAndOversize(t *testing.T) { + service, tickets, cleanup := newUploadTestService(t) + defer cleanup() + ctx := context.Background() + uploadURL, _, err := service.IssueVideoUpload(ctx, "video_job_expire") + if err != nil { + t.Fatal(err) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + sum := sha256.Sum256([]byte(token)) + hash := hex.EncodeToString(sum[:]) + // Force expire by rewriting ticket row through consume path simulation: delete and recreate expired. + existing, err := tickets.GetUploadTicketByHash(ctx, hash) + if err != nil { + t.Fatal(err) + } + if _, err := tickets.DeleteExpiredUploadTickets(ctx, time.Now().UTC().Add(3*time.Hour), 10); err != nil { + t.Fatal(err) + } + existing.ExpiresAt = time.Now().UTC().Add(-time.Minute) + existing.ConsumedAt = nil + if err := tickets.CreateUploadTicket(ctx, existing); err != nil { + t.Fatal(err) + } + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p'}, bytes.Repeat([]byte{1}, 32)...) + if _, err := service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)); err == nil { + t.Fatal("expected expired rejection") + } +} + +func TestReceiveVideoUploadConcurrentOnlyOneSucceeds(t *testing.T) { + service, _, cleanup := newUploadTestService(t) + defer cleanup() + ctx := context.Background() + uploadURL, _, err := service.IssueVideoUpload(ctx, "video_job_race") + if err != nil { + t.Fatal(err) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'm', 'p', '4', '2'}, bytes.Repeat([]byte{2}, 128)...) + + var wg sync.WaitGroup + results := make(chan error, 8) + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + _, putErr := service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + results <- putErr + }() + } + wg.Wait() + close(results) + success, fail := 0, 0 + for err := range results { + if err == nil { + success++ + } else { + fail++ + } + } + if success != 1 || fail != 7 { + t.Fatalf("success=%d fail=%d", success, fail) + } +} + +func TestReceiveVideoUploadRejectsDeclaredMIMEMismatch(t *testing.T) { + service, _, cleanup := newUploadTestService(t) + defer cleanup() + ctx := context.Background() + uploadURL, _, err := service.IssueVideoUpload(ctx, "video_job_mime_declared") + if err != nil { + t.Fatal(err) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x01}, 32)...) + _, err = service.ReceiveVideoUpload(ctx, token, "video/webm", bytes.NewReader(payload)) + if err == nil || !errors.Is(err, ErrInvalidVideoUpload) { + t.Fatalf("declared mismatch err = %v", err) + } + if !strings.Contains(err.Error(), "Content-Type") { + t.Fatalf("err = %v", err) + } +} + +func TestReceiveVideoUploadRejectsSniffedNonMP4UnderMP4Ticket(t *testing.T) { + service, _, cleanup := newUploadTestService(t) + defer cleanup() + ctx := context.Background() + uploadURL, _, err := service.IssueVideoUpload(ctx, "video_job_mime_sniff") + if err != nil { + t.Fatal(err) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + // WebM EBML header — 嗅探为 video/webm,与 MP4 票据冲突。 + webm := append([]byte{0x1A, 0x45, 0xDF, 0xA3}, bytes.Repeat([]byte{0x02}, 64)...) + _, err = service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(webm)) + if err == nil || !errors.Is(err, ErrInvalidVideoUpload) { + t.Fatalf("webm sniff err = %v", err) + } + // QuickTime 声明在 MP4 票据下直接拒绝(无需写入大 body)。 + uploadURL2, _, err := service.IssueVideoUpload(ctx, "video_job_mime_qt") + if err != nil { + t.Fatal(err) + } + token2 := strings.TrimPrefix(uploadURL2, "https://api.example/v1/media/uploads/") + _, err = service.ReceiveVideoUpload(ctx, token2, "video/quicktime", bytes.NewReader(webm)) + if err == nil || !errors.Is(err, ErrInvalidVideoUpload) { + t.Fatalf("quicktime declared err = %v", err) + } +} + +func TestReceiveVideoUploadTooLargeMapsToTooLargeError(t *testing.T) { + database, objects, tickets, cleanup := openUploadTestDeps(t) + defer cleanup() + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + tickets, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + ctx := context.Background() + // 小上限票据:避免分配 256MiB。 + tokenBytes := make([]byte, 32) + for i := range tokenBytes { + tokenBytes[i] = byte(i + 1) + } + token := hex.EncodeToString(tokenBytes) + sum := sha256.Sum256([]byte(token)) + now := time.Now().UTC() + if err := tickets.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hex.EncodeToString(sum[:]), AssetID: "vid_small_limit_000001", JobID: "job_small", + MaxBytes: 40, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + // ftyp 头 + 填充使体积 > 40。 + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x09}, 64)...) + _, err := service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + if err == nil || !errors.Is(err, ErrVideoUploadTooLarge) || !errors.Is(err, ErrInvalidVideoUpload) { + t.Fatalf("ticket max err = %v", err) + } + + // MaxBytesReader 路径:模拟中间件截断。 + token2Bytes := make([]byte, 32) + for i := range token2Bytes { + token2Bytes[i] = byte(i + 40) + } + token2 := hex.EncodeToString(token2Bytes) + sum2 := sha256.Sum256([]byte(token2)) + if err := tickets.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hex.EncodeToString(sum2[:]), AssetID: "vid_small_limit_000002", JobID: "job_maxbytes", + MaxBytes: 1 << 20, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + recorder := httptest.NewRecorder() + limited := http.MaxBytesReader(recorder, io.NopCloser(bytes.NewReader(payload)), 20) + _, err = service.ReceiveVideoUpload(ctx, token2, "video/mp4", limited) + if err == nil || !errors.Is(err, ErrVideoUploadTooLarge) { + t.Fatalf("MaxBytesReader err = %v", err) + } +} + +func TestIssueVideoUploadRequiresHTTPSPublicBase(t *testing.T) { + database, objects, tickets, cleanup := openUploadTestDeps(t) + defer cleanup() + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + tickets, objects, nil, + Config{PublicBaseURL: "http://127.0.0.1:8000", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + if _, _, err := service.IssueVideoUpload(context.Background(), "job"); err == nil { + t.Fatal("expected public base error") + } +} + +// bindFailTicketRepo 在 BindJobResultAsset 注入非 NotFound 失败,用于签发失败闭环。 +type bindFailTicketRepo struct { + repository.MediaUploadTicketRepository + bindErr error + deleteErr error + lastHash string + deleteCalls atomic.Int32 +} + +func (r *bindFailTicketRepo) CreateUploadTicket(ctx context.Context, ticket repository.MediaUploadTicket) error { + r.lastHash = ticket.TokenHash + return r.MediaUploadTicketRepository.CreateUploadTicket(ctx, ticket) +} + +func (r *bindFailTicketRepo) BindJobResultAsset(ctx context.Context, jobID, assetID string) error { + if r.bindErr != nil { + return r.bindErr + } + return r.MediaUploadTicketRepository.BindJobResultAsset(ctx, jobID, assetID) +} + +func (r *bindFailTicketRepo) DeleteUploadTicketByHash(ctx context.Context, tokenHash string) error { + r.deleteCalls.Add(1) + if r.deleteErr != nil { + return r.deleteErr + } + return r.MediaUploadTicketRepository.DeleteUploadTicketByHash(ctx, tokenHash) +} + +func TestIssueVideoUploadBindFailureStopsIssuance(t *testing.T) { + database, objects, tickets, cleanup := openUploadTestDeps(t) + defer cleanup() + ctx := context.Background() + injected := errors.New("injected bind database failure") + failRepo := &bindFailTicketRepo{MediaUploadTicketRepository: tickets, bindErr: injected} + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + failRepo, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + uploadURL, assetID, err := service.IssueVideoUpload(ctx, "video_job_bind_fail") + if err == nil { + t.Fatal("expected bind failure to stop issuance") + } + if !errors.Is(err, injected) { + t.Fatalf("err = %v", err) + } + if uploadURL != "" || assetID != "" { + t.Fatalf("must not return upload URL or asset on bind failure: url=%q asset=%q", uploadURL, assetID) + } + msg := err.Error() + if strings.Contains(msg, "/v1/media/uploads/") || strings.Contains(msg, "https://") { + t.Fatalf("error must not contain upload URL: %q", msg) + } + if failRepo.lastHash == "" { + t.Fatal("expected ticket create to record token hash") + } + if failRepo.deleteCalls.Load() != 1 { + t.Fatalf("delete compensation calls = %d, want 1", failRepo.deleteCalls.Load()) + } + // 失败票据必须被精确删除,不得残留到 TTL。 + if _, getErr := tickets.GetUploadTicketByHash(ctx, failRepo.lastHash); !errors.Is(getErr, repository.ErrNotFound) { + t.Fatalf("failed ticket should be compensated away: %v", getErr) + } + + // 补偿删除失败时须保留 bind 与 delete 两因,且仍不暴露 token/URL。 + deleteInjected := errors.New("injected delete compensation failure") + failBoth := &bindFailTicketRepo{ + MediaUploadTicketRepository: tickets, + bindErr: injected, + deleteErr: deleteInjected, + } + serviceBoth := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + failBoth, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + _, _, err = serviceBoth.IssueVideoUpload(ctx, "video_job_bind_delete_fail") + if err == nil { + t.Fatal("expected combined bind+delete failure") + } + if !errors.Is(err, injected) || !errors.Is(err, deleteInjected) { + t.Fatalf("combined err must retain both causes: %v", err) + } + if strings.Contains(err.Error(), "/v1/media/uploads/") || strings.Contains(err.Error(), "https://") { + t.Fatalf("combined error must not contain upload URL: %q", err.Error()) + } + + // ErrNotFound 仍允许占位/测试路径签发,且不得触发补偿删除。 + notFoundRepo := &bindFailTicketRepo{MediaUploadTicketRepository: tickets, bindErr: repository.ErrNotFound} + serviceOK := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + notFoundRepo, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + urlOK, assetOK, err := serviceOK.IssueVideoUpload(ctx, "video_job_bind_notfound") + if err != nil || urlOK == "" || assetOK == "" { + t.Fatalf("ErrNotFound bind should still issue: url=%q asset=%q err=%v", urlOK, assetOK, err) + } + if notFoundRepo.deleteCalls.Load() != 0 { + t.Fatalf("ErrNotFound path must not delete ticket: deletes=%d", notFoundRepo.deleteCalls.Load()) + } + if _, getErr := tickets.GetUploadTicketByHash(ctx, notFoundRepo.lastHash); getErr != nil { + t.Fatalf("placeholder ticket must remain after ErrNotFound bind: %v", getErr) + } +} + +// getFailAssetRepo 在 GetMediaAsset 注入仓储故障。 +type getFailAssetRepo struct { + repository.MediaAssetRepository + getErr error + getCalls atomic.Int32 +} + +func (r *getFailAssetRepo) GetMediaAsset(ctx context.Context, id string) (mediadomain.Asset, error) { + r.getCalls.Add(1) + if r.getErr != nil { + return mediadomain.Asset{}, r.getErr + } + return r.MediaAssetRepository.GetMediaAsset(ctx, id) +} + +// countingObjectStore 统计对象写入口,验证预检失败时无写入。 +type countingObjectStore struct { + inner repository.MediaObjectStorage + beginCalls atomic.Int32 + commitCalls atomic.Int32 +} + +func (s *countingObjectStore) SaveImage(ctx context.Context, id, mimeType string, data []byte) (string, error) { + return s.inner.SaveImage(ctx, id, mimeType, data) +} +func (s *countingObjectStore) SaveVideo(ctx context.Context, id, mimeType string, data []byte) (string, error) { + return s.inner.SaveVideo(ctx, id, mimeType, data) +} +func (s *countingObjectStore) BeginVideoUpload(ctx context.Context, id, mimeType string) (string, string, error) { + s.beginCalls.Add(1) + return s.inner.BeginVideoUpload(ctx, id, mimeType) +} +func (s *countingObjectStore) CommitVideoUpload(ctx context.Context, tempPath, storageKey string) error { + s.commitCalls.Add(1) + return s.inner.CommitVideoUpload(ctx, tempPath, storageKey) +} +func (s *countingObjectStore) AbortVideoUpload(ctx context.Context, tempPath string) error { + return s.inner.AbortVideoUpload(ctx, tempPath) +} +func (s *countingObjectStore) Open(ctx context.Context, storageKey string) (io.ReadCloser, error) { + return s.inner.Open(ctx, storageKey) +} +func (s *countingObjectStore) Delete(ctx context.Context, storageKey string) error { + return s.inner.Delete(ctx, storageKey) +} + +// consumeCountingTicketRepo 统计消费调用,验证预检失败时未消费。 +type consumeCountingTicketRepo struct { + repository.MediaUploadTicketRepository + consumeCalls atomic.Int32 +} + +func (r *consumeCountingTicketRepo) ConsumeUploadTicket(ctx context.Context, tokenHash string, now time.Time) (repository.MediaUploadTicket, bool, error) { + r.consumeCalls.Add(1) + return r.MediaUploadTicketRepository.ConsumeUploadTicket(ctx, tokenHash, now) +} + +func TestReceiveVideoUploadAssetLookupFailureNoWriteOrConsume(t *testing.T) { + database, objects, tickets, cleanup := openUploadTestDeps(t) + defer cleanup() + injected := errors.New("injected asset repository failure") + assets := &getFailAssetRepo{ + MediaAssetRepository: relational.NewMediaAssetRepository(database), + getErr: injected, + } + store := &countingObjectStore{inner: objects} + ticketWrap := &consumeCountingTicketRepo{MediaUploadTicketRepository: tickets} + service := NewServiceWithTickets( + assets, relational.NewMediaJobRepository(database), ticketWrap, store, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + ctx := context.Background() + // 先用健康服务签发票据,再切换到故障资产仓储接收。 + issueService := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + tickets, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + uploadURL, _, err := issueService.IssueVideoUpload(ctx, "video_job_asset_get_fail") + if err != nil { + t.Fatal(err) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x05}, 32)...) + _, err = service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + if err == nil || !errors.Is(err, injected) { + t.Fatalf("receive err = %v", err) + } + if assets.getCalls.Load() < 1 { + t.Fatal("expected GetMediaAsset preflight call") + } + if store.beginCalls.Load() != 0 { + t.Fatalf("object write must not start on asset lookup failure: begin=%d", store.beginCalls.Load()) + } + if store.commitCalls.Load() != 0 { + t.Fatalf("commit must not run: %d", store.commitCalls.Load()) + } + if ticketWrap.consumeCalls.Load() != 0 { + t.Fatalf("ticket must not be consumed on asset lookup failure: %d", ticketWrap.consumeCalls.Load()) + } + sum := sha256.Sum256([]byte(token)) + ticket, getErr := tickets.GetUploadTicketByHash(ctx, hex.EncodeToString(sum[:])) + if getErr != nil { + t.Fatal(getErr) + } + if ticket.ConsumedAt != nil { + t.Fatalf("ticket consumed_at should remain nil: %#v", ticket) + } +} + +// failingCommitStore 首次 CommitVideoUpload 失败,后续委托真实存储,用于验证票据释放与重试。 +type failingCommitStore struct { + inner repository.MediaObjectStorage + failRemaining atomic.Int32 + commitCalls atomic.Int32 +} + +func (s *failingCommitStore) SaveImage(ctx context.Context, id, mimeType string, data []byte) (string, error) { + return s.inner.SaveImage(ctx, id, mimeType, data) +} +func (s *failingCommitStore) SaveVideo(ctx context.Context, id, mimeType string, data []byte) (string, error) { + return s.inner.SaveVideo(ctx, id, mimeType, data) +} +func (s *failingCommitStore) BeginVideoUpload(ctx context.Context, id, mimeType string) (string, string, error) { + return s.inner.BeginVideoUpload(ctx, id, mimeType) +} +func (s *failingCommitStore) CommitVideoUpload(ctx context.Context, tempPath, storageKey string) error { + s.commitCalls.Add(1) + if s.failRemaining.Add(-1) >= 0 { + return errors.New("injected commit failure") + } + return s.inner.CommitVideoUpload(ctx, tempPath, storageKey) +} +func (s *failingCommitStore) AbortVideoUpload(ctx context.Context, tempPath string) error { + return s.inner.AbortVideoUpload(ctx, tempPath) +} +func (s *failingCommitStore) Open(ctx context.Context, storageKey string) (io.ReadCloser, error) { + return s.inner.Open(ctx, storageKey) +} +func (s *failingCommitStore) Delete(ctx context.Context, storageKey string) error { + return s.inner.Delete(ctx, storageKey) +} + +func TestReceiveVideoUploadCommitFailureReleasesTicketForRetry(t *testing.T) { + database, objects, tickets, cleanup := openUploadTestDeps(t) + defer cleanup() + store := &failingCommitStore{inner: objects} + store.failRemaining.Store(1) + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + tickets, store, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + ctx := context.Background() + uploadURL, assetID, err := service.IssueVideoUpload(ctx, "video_job_commit_fail") + if err != nil { + t.Fatal(err) + } + token := strings.TrimPrefix(uploadURL, "https://api.example/v1/media/uploads/") + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x03}, 48)...) + + _, err = service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + if err == nil || !strings.Contains(err.Error(), "injected commit failure") { + t.Fatalf("first receive err = %v", err) + } + // 票据必须已释放:未消费、未产生资产。 + sum := sha256.Sum256([]byte(token)) + ticket, err := tickets.GetUploadTicketByHash(ctx, hex.EncodeToString(sum[:])) + if err != nil { + t.Fatal(err) + } + if ticket.ConsumedAt != nil { + t.Fatalf("ticket should be released after commit failure, consumed_at=%v", ticket.ConsumedAt) + } + if _, getErr := relational.NewMediaAssetRepository(database).GetMediaAsset(ctx, assetID); getErr == nil { + t.Fatal("asset must not exist after commit failure") + } + + // 同 token 重试应成功(commit 第二次放行)。 + asset, err := service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)) + if err != nil { + t.Fatalf("retry receive: %v", err) + } + if asset.ID != assetID || asset.Kind != "video" || asset.SizeBytes != int64(len(payload)) { + t.Fatalf("asset = %#v", asset) + } + if store.commitCalls.Load() < 2 { + t.Fatalf("commit calls = %d, want >= 2", store.commitCalls.Load()) + } + // 重放仍应拒绝。 + if _, err := service.ReceiveVideoUpload(ctx, token, "video/mp4", bytes.NewReader(payload)); err == nil { + t.Fatal("expected consumed rejection after successful upload") + } +} + +func newUploadTestService(t *testing.T) (*Service, *relational.MediaUploadTicketRepository, func()) { + t.Helper() + database, objects, tickets, cleanup := openUploadTestDeps(t) + service := NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + tickets, objects, nil, + Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + return service, tickets, cleanup +} + +func openUploadTestDeps(t *testing.T) (*relational.Database, *media.LocalStore, *relational.MediaUploadTicketRepository, func()) { + t.Helper() + dir := t.TempDir() + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(dir, "test.db")) + if err != nil { + t.Fatal(err) + } + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := media.NewLocalStore(filepath.Join(dir, "objects")) + if err != nil { + t.Fatal(err) + } + tickets := relational.NewMediaUploadTicketRepository(database) + return database, objects, tickets, func() { _ = database.Close() } +} + +// Silence unused imports retained for sniff/edge coverage helpers. +var ( + _ = http.StatusOK + _ = io.EOF + _ = os.ErrNotExist +) diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 34e008be..34456649 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -434,6 +434,18 @@ func (s *Service) syncAccountCapabilities(ctx context.Context, value account.Cre return nil, err } models := normalizeDiscoveredModels(values) + if normalizer, ok := adapter.(provider.AccountModelCapabilityNormalizer); ok { + var billing *account.Billing + snapshot, billingErr := s.accounts.GetBilling(ctx, credential.ID) + if billingErr == nil { + billing = &snapshot + } else if !errors.Is(billingErr, repository.ErrNotFound) { + // Billing 不存在按 Unknown 处理;其他仓储错误保留失败语义。 + s.markCapabilitySyncFailed(credential.ID, attemptedAt, billingErr) + return nil, billingErr + } + models = normalizeDiscoveredModels(normalizer.NormalizeAccountModelCapabilities(models, billing)) + } if err := s.models.ReplaceAccountCapabilities(ctx, credential.ID, models, attemptedAt); err != nil { s.markCapabilitySyncFailed(credential.ID, attemptedAt, err) return nil, err diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index 2a5c0a45..d3d00e6b 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -13,6 +13,7 @@ import ( accountapp "github.com/chenyme/grok2api/backend/internal/application/account" "github.com/chenyme/grok2api/backend/internal/domain/account" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" "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" @@ -109,6 +110,144 @@ func TestSyncAggregatesCapabilitiesFromAllAccounts(t *testing.T) { } } +func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-build-video15.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + + // Super 主 Build:上游仅 grok-4.5,未开 fallback。 + superPrimary, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "super-primary", SourceKey: "super-primary", + EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + // Super fallback:上游目录含 1.5 与其它模型。 + superFallback, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "super-fallback", SourceKey: "super-fallback", + EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, + BuildAPIFallback: true, + }) + if err != nil { + t.Fatal(err) + } + // Free:Billing 无 paid 信号,但上游目录暴露 1.5。 + freeAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "free-fallback", SourceKey: "free-fallback", + EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, + BuildAPIFallback: true, + }) + if err != nil { + t.Fatal(err) + } + // Unknown:无 Billing 快照,上游目录暴露 1.5。 + unknownAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "unknown", SourceKey: "unknown", + EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + // Web 不应实现能力归一化;目录原样写入。 + webAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierSuper, Name: "web", SourceKey: "web", + EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + + now := time.Now().UTC() + if err := accountRepo.SaveBilling(ctx, account.Billing{AccountID: superPrimary.ID, MonthlyLimit: 100, SyncedAt: now}); err != nil { + t.Fatal(err) + } + if err := accountRepo.SaveBilling(ctx, account.Billing{AccountID: superFallback.ID, OnDemandCap: 50, SyncedAt: now}); err != nil { + t.Fatal(err) + } + if err := accountRepo.SaveBilling(ctx, account.Billing{AccountID: freeAccount.ID, Used: 1, PlanName: "free", SyncedAt: now}); err != nil { + t.Fatal(err) + } + + const video15 = "grok-imagine-video-1.5" + buildAdapter := &buildCapabilityNormalizerAdapter{modelCapabilityAdapter: &modelCapabilityAdapter{models: map[uint64][]string{ + superPrimary.ID: {"grok-4.5"}, + superFallback.ID: {"grok-4.5", video15, "grok-code-fast-1", video15}, + freeAccount.ID: {"grok-4.5", video15}, + unknownAccount.ID: {video15, "grok-4.5"}, + }}} + webAdapter := &modelCapabilityAdapter{provider: account.ProviderWeb, models: map[uint64][]string{ + webAccount.ID: {"grok-chat-fast", "grok-imagine-video"}, + }} + registry := provider.NewRegistry(buildAdapter, webAdapter) + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), memory.NewStickyStore(), registry, cipher, nil) + service := NewService(modelRepo, accountRepo, accountService, registry) + + for _, id := range []uint64{superPrimary.ID, superFallback.ID, freeAccount.ID, unknownAccount.ID, webAccount.ID} { + if _, err := service.SyncAccount(ctx, id); err != nil { + t.Fatalf("sync account %d: %v", id, err) + } + } + + assertSupports := func(accountID uint64, upstream string, want bool) { + t.Helper() + candidates, listErr := accountRepo.ListRoutingCandidates(ctx, account.ProviderBuild, upstream, "") + if listErr != nil { + t.Fatal(listErr) + } + for _, candidate := range candidates { + if candidate.Credential.ID != accountID { + continue + } + if !candidate.ModelCapabilityKnown { + t.Fatalf("account %d capability unknown for %s", accountID, upstream) + } + if candidate.SupportsModel != want { + t.Fatalf("account %d supports %s = %v, want %v", accountID, upstream, candidate.SupportsModel, want) + } + return + } + t.Fatalf("account %d missing from candidates for %s", accountID, upstream) + } + + assertSupports(superPrimary.ID, video15, true) + assertSupports(superFallback.ID, video15, true) + assertSupports(freeAccount.ID, video15, false) + assertSupports(unknownAccount.ID, video15, false) + assertSupports(superPrimary.ID, "grok-4.5", true) + assertSupports(superFallback.ID, "grok-code-fast-1", true) + assertSupports(freeAccount.ID, "grok-4.5", true) + + // Build 1.5 路由默认 capability 为 video。 + route, err := modelRepo.GetByPublicID(ctx, "Build/"+video15) + if err != nil || route.Capability != modeldomain.CapabilityVideo { + t.Fatalf("build video route = %#v, err = %v", route, err) + } + // Web 未走 Build 归一化,仍支持其目录模型。 + webCandidates, err := accountRepo.ListRoutingCandidates(ctx, account.ProviderWeb, "grok-imagine-video", "") + if err != nil || len(webCandidates) != 1 || !webCandidates[0].SupportsModel { + t.Fatalf("web candidates = %#v, err = %v", webCandidates, err) + } +} + func TestSyncAccountRunsUpstreamDiscoveryConcurrently(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-account-sync.db")) @@ -192,6 +331,40 @@ type modelCapabilityAdapter struct { peak atomic.Int64 } +// buildCapabilityNormalizerAdapter 模拟 Build Adapter:实现可选能力归一化契约。 +type buildCapabilityNormalizerAdapter struct { + *modelCapabilityAdapter +} + +func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing) []string { + // 与 cli.Adapter 规则一致:Super/paid 确保 1.5;否则精确移除。不读 BuildAPIFallback。 + const video15 = "grok-imagine-video-1.5" + paid := billing != nil && billing.IsPaid() + result := make([]string, 0, len(models)+1) + seen := make(map[string]struct{}, len(models)+1) + hasVideo15 := false + for _, modelName := range models { + if modelName == "" { + continue + } + if _, exists := seen[modelName]; exists { + continue + } + if modelName == video15 { + if !paid { + continue + } + hasVideo15 = true + } + seen[modelName] = struct{}{} + result = append(result, modelName) + } + if paid && !hasVideo15 { + result = append(result, video15) + } + return result +} + func (a *modelCapabilityAdapter) Provider() account.Provider { if a.provider == "" { return account.ProviderBuild diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index 572097c7..8bbcffc7 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -21,6 +21,7 @@ var ( // ProviderBuildConfig 是管理接口使用的 Provider 可编辑输入。 type ProviderBuildConfig struct { BaseURL string + FallbackBaseURL string ClientVersion string ClientIdentifier string TokenAuth string @@ -83,11 +84,12 @@ type FrontendConfig struct { // RoutingConfig 是管理接口使用的路由可编辑输入。 type RoutingConfig struct { - StickyTTL string - CooldownBase string - CooldownMax string - CapacityWait string - MaxAttempts int + StickyTTL string + CooldownBase string + CooldownMax string + CapacityWait string + MaxAttempts int + PreferFreeBuild bool } // AuditConfig 是管理接口使用的审计可编辑输入。 @@ -260,9 +262,9 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C capacityWait = base.Routing.CapacityWait.Value() } base.Provider.Build = config.BuildProviderConfig{ - BaseURL: value.ProviderBuild.BaseURL, ClientVersion: value.ProviderBuild.ClientVersion, - ClientIdentifier: value.ProviderBuild.ClientIdentifier, TokenAuth: value.ProviderBuild.TokenAuth, - UserAgent: value.ProviderBuild.UserAgent, + BaseURL: value.ProviderBuild.BaseURL, FallbackBaseURL: config.NormalizeBuildFallbackBaseURL(value.ProviderBuild.FallbackBaseURL), + ClientVersion: value.ProviderBuild.ClientVersion, ClientIdentifier: value.ProviderBuild.ClientIdentifier, + TokenAuth: value.ProviderBuild.TokenAuth, UserAgent: value.ProviderBuild.UserAgent, } base.Provider.Web = config.WebProviderConfig{ BaseURL: value.ProviderWeb.BaseURL, QuotaTimeout: config.Duration(value.ProviderWeb.QuotaTimeout), @@ -296,6 +298,7 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C base.Routing = config.RoutingConfig{ StickyTTL: config.Duration(value.Routing.StickyTTL), CooldownBase: config.Duration(value.Routing.CooldownBase), CooldownMax: config.Duration(value.Routing.CooldownMax), CapacityWait: config.Duration(capacityWait), MaxAttempts: value.Routing.MaxAttempts, + PreferFreeBuild: value.Routing.PreferFreeBuild, } base.Audit = config.AuditConfig{ BufferSize: value.Audit.BufferSize, BatchSize: value.Audit.BatchSize, FlushInterval: config.Duration(value.Audit.FlushInterval), @@ -311,9 +314,9 @@ func toDomainConfig(value config.Config) settingsdomain.Config { return settingsdomain.Config{ Server: settingsdomain.ServerConfig{MaxConcurrentRequests: value.Server.MaxConcurrentRequests}, ProviderBuild: settingsdomain.ProviderBuildConfig{ - BaseURL: value.Provider.Build.BaseURL, ClientVersion: value.Provider.Build.ClientVersion, - ClientIdentifier: value.Provider.Build.ClientIdentifier, TokenAuth: value.Provider.Build.TokenAuth, - UserAgent: value.Provider.Build.UserAgent, + BaseURL: value.Provider.Build.BaseURL, FallbackBaseURL: config.NormalizeBuildFallbackBaseURL(value.Provider.Build.FallbackBaseURL), + ClientVersion: value.Provider.Build.ClientVersion, ClientIdentifier: value.Provider.Build.ClientIdentifier, + TokenAuth: value.Provider.Build.TokenAuth, UserAgent: value.Provider.Build.UserAgent, }, ProviderWeb: settingsdomain.ProviderWebConfig{ BaseURL: value.Provider.Web.BaseURL, QuotaTimeout: value.Provider.Web.QuotaTimeout.Value(), @@ -343,6 +346,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config { Routing: settingsdomain.RoutingConfig{ StickyTTL: value.Routing.StickyTTL.Value(), CooldownBase: value.Routing.CooldownBase.Value(), CooldownMax: value.Routing.CooldownMax.Value(), CapacityWait: value.Routing.CapacityWait.Value(), MaxAttempts: value.Routing.MaxAttempts, + PreferFreeBuild: value.Routing.PreferFreeBuild, }, Audit: settingsdomain.AuditConfig{ BufferSize: value.Audit.BufferSize, BatchSize: value.Audit.BatchSize, FlushInterval: value.Audit.FlushInterval.Value(), @@ -375,6 +379,7 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next := current next.Server.MaxConcurrentRequests = input.Server.MaxConcurrentRequests next.Provider.Build.BaseURL = strings.TrimSpace(input.ProviderBuild.BaseURL) + next.Provider.Build.FallbackBaseURL = config.NormalizeBuildFallbackBaseURL(input.ProviderBuild.FallbackBaseURL) next.Provider.Build.ClientVersion = strings.TrimSpace(input.ProviderBuild.ClientVersion) next.Provider.Build.ClientIdentifier = strings.TrimSpace(input.ProviderBuild.ClientIdentifier) if tokenAuth := strings.TrimSpace(input.ProviderBuild.TokenAuth); tokenAuth != "" { @@ -404,6 +409,7 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next.Media.CleanupThresholdPercent = input.Media.CleanupThresholdPercent next.Frontend.PublicAPIBaseURLOverride = strings.TrimSpace(input.Frontend.PublicAPIBaseURL) next.Routing.MaxAttempts = input.Routing.MaxAttempts + next.Routing.PreferFreeBuild = input.Routing.PreferFreeBuild next.Audit.BufferSize = input.Audit.BufferSize next.Audit.BatchSize = input.Audit.BatchSize next.ClientKeyDefaults.RPMLimit = input.ClientKeyDefaults.RPMLimit @@ -446,9 +452,9 @@ func toEditable(cfg config.Config) EditableConfig { return EditableConfig{ Server: ServerConfig{MaxConcurrentRequests: cfg.Server.MaxConcurrentRequests}, ProviderBuild: ProviderBuildConfig{ - 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, + BaseURL: cfg.Provider.Build.BaseURL, FallbackBaseURL: config.NormalizeBuildFallbackBaseURL(cfg.Provider.Build.FallbackBaseURL), + ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier, + TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent, }, ProviderWeb: ProviderWebConfig{ BaseURL: cfg.Provider.Web.BaseURL, QuotaTimeout: cfg.Provider.Web.QuotaTimeout.String(), @@ -478,6 +484,7 @@ func toEditable(cfg config.Config) EditableConfig { Routing: RoutingConfig{ StickyTTL: cfg.Routing.StickyTTL.String(), CooldownBase: cfg.Routing.CooldownBase.String(), CooldownMax: cfg.Routing.CooldownMax.String(), CapacityWait: cfg.Routing.CapacityWait.String(), MaxAttempts: cfg.Routing.MaxAttempts, + PreferFreeBuild: cfg.Routing.PreferFreeBuild, }, Audit: AuditConfig{ BufferSize: cfg.Audit.BufferSize, BatchSize: cfg.Audit.BatchSize, FlushInterval: cfg.Audit.FlushInterval.String(), diff --git a/backend/internal/application/settings/service_test.go b/backend/internal/application/settings/service_test.go index ce2518bb..2d74e4a3 100644 --- a/backend/internal/application/settings/service_test.go +++ b/backend/internal/application/settings/service_test.go @@ -46,6 +46,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { input := service.Get().Config input.Server.MaxConcurrentRequests = 2048 input.Routing.MaxAttempts = 5 + input.Routing.PreferFreeBuild = true input.Audit.BufferSize = cfg.Audit.BufferSize + 1 input.Media.MaxTotalBytes = 2 << 30 input.Media.CleanupThresholdPercent = 75 @@ -60,7 +61,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if err != nil { t.Fatal(err) } - if applied.Routing.MaxAttempts != 5 { + if applied.Routing.MaxAttempts != 5 || !applied.Routing.PreferFreeBuild { t.Fatalf("runtime configuration was not applied: %#v", applied.Routing) } if applied.Server.MaxConcurrentRequests != 2048 { @@ -85,7 +86,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if err != nil { t.Fatal(err) } - if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Routing.MaxAttempts != 5 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" { + if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Routing.MaxAttempts != 5 || !reloaded.Routing.PreferFreeBuild || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" { t.Fatalf("configuration was not persisted") } } diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index 662d7a82..9a47246a 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -3,6 +3,7 @@ package account import ( "crypto/sha256" "encoding/binary" + "strings" "time" ) @@ -113,8 +114,13 @@ type Credential struct { LinkedAccountID uint64 LinkedAccountName string LinkedProvider Provider - CreatedAt time.Time - UpdatedAt time.Time + // BuildAPIFallback 仅对 grok_build 有效:账号级 XAI **推理** 回退标记。 + // 已标记时 models / responses create|compact / video 走 FallbackBaseURL; + // Billing、stored GET/DELETE /responses/{id}、OAuth 与未知路径仍走主地址。 + // token refresh / SSO 转换 / 普通 upsert / 重启不得清除。 + BuildAPIFallback bool + CreatedAt time.Time + UpdatedAt time.Time } // CredentialRefreshDueAt 将账号稳定地分散到到期前 5~8 分钟,避免同批导入账号同时刷新。 @@ -302,6 +308,37 @@ func (b Billing) Remaining() float64 { return remaining } +// IsPaid 判断 Billing 快照是否呈现 Super/paid 信号。 +// 语义与 SQL accountPaidBillingPredicate 及 QuotaView paid 分支一致: +// 任一 MonthlyLimit、OnDemandCap、OnDemandUsed、PrepaidBalance、CreditUsagePercent 为正即为 paid。 +// 无快照时应由调用方按 Unknown 处理,不得调用本方法。 +func (b Billing) IsPaid() bool { + return b.MonthlyLimit > 0 || b.OnDemandCap > 0 || b.OnDemandUsed > 0 || b.PrepaidBalance > 0 || b.CreditUsagePercent > 0 +} + +// HasFreeProfileSignal 判断零付费额度快照是否包含已知 Free 账号特征。 +func (b Billing) HasFreeProfileSignal() bool { + return b.IsUnifiedBillingUser || b.UsagePeriodType != "" || b.TopUpMethod != "" || b.BillingPeriodStart != "" || len(b.History) > 0 +} + +// IsKnownFreeBuild 判断候选是否是已确认的 Grok Build Free 账号。 +// paid 信号优先,避免旧的响应模型或恢复记录把 Super 错分为 Free。 +func (c RoutingCandidate) IsKnownFreeBuild() bool { + if c.Credential.Provider != ProviderBuild { + return false + } + if c.Billing != nil && c.Billing.IsPaid() { + return false + } + if c.QuotaRecovery != nil && c.QuotaRecovery.Kind == QuotaRecoveryKindFree { + return true + } + if strings.HasSuffix(strings.ToLower(strings.TrimSpace(c.Credential.ObservedModel)), "-build-free") { + return true + } + return c.Billing != nil && c.Billing.HasFreeProfileSignal() +} + // IsExhausted 判断额度快照是否已达到账号保留阈值。 func (b Billing) IsExhausted(minimum float64) bool { if b.MonthlyLimit > 0 && b.Remaining() <= minimum { diff --git a/backend/internal/domain/account/account_test.go b/backend/internal/domain/account/account_test.go index 3633b74f..95fde415 100644 --- a/backend/internal/domain/account/account_test.go +++ b/backend/internal/domain/account/account_test.go @@ -5,6 +5,51 @@ import ( "time" ) +func TestBillingIsPaidMatchesSQLSignals(t *testing.T) { + if (Billing{}).IsPaid() { + t.Fatal("empty billing must be Unknown/free, not paid") + } + for _, billing := range []Billing{ + {MonthlyLimit: 1}, + {OnDemandCap: 0.01}, + {OnDemandUsed: 1}, + {PrepaidBalance: 5}, + {CreditUsagePercent: 0.1}, + } { + if !billing.IsPaid() { + t.Fatalf("expected paid for %#v", billing) + } + } + if (Billing{Used: 100, PlanName: "free"}).IsPaid() { + t.Fatal("usage/plan name alone must not mark paid") + } +} + +func TestRoutingCandidateIsKnownFreeBuild(t *testing.T) { + freeBilling := Billing{IsUnifiedBillingUser: true} + paidBilling := Billing{MonthlyLimit: 100} + freeRecovery := QuotaRecovery{Kind: QuotaRecoveryKindFree} + tests := []struct { + name string + candidate RoutingCandidate + want bool + }{ + {name: "billing profile", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild}, Billing: &freeBilling}, want: true}, + {name: "observed response model", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild, ObservedModel: "grok-4.5-build-free"}}, want: true}, + {name: "quota recovery", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild}, QuotaRecovery: &freeRecovery}, want: true}, + {name: "paid overrides stale free signal", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild, ObservedModel: "grok-4.5-build-free"}, Billing: &paidBilling}}, + {name: "unknown build", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild}}}, + {name: "web is never build free", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderWeb, ObservedModel: "grok-4.5-build-free"}}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := test.candidate.IsKnownFreeBuild(); got != test.want { + t.Fatalf("IsKnownFreeBuild() = %t, want %t", got, test.want) + } + }) + } +} + func TestBillingIsExhaustedForOnDemandCredits(t *testing.T) { if !(Billing{OnDemandCap: 50, CreditUsagePercent: 100}).IsExhausted(0) { t.Fatal("expected exhausted on-demand billing") diff --git a/backend/internal/domain/audit/pricing.go b/backend/internal/domain/audit/pricing.go index b05d952c..56ddb8bc 100644 --- a/backend/internal/domain/audit/pricing.go +++ b/backend/internal/domain/audit/pricing.go @@ -239,8 +239,13 @@ func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputC } // EstimateOfficialVideoCost 按请求视频时长和分辨率计算费用。 +// 仅精确支持 grok-imagine-video 与 grok-imagine-video-1.5(可带来源前缀);未知后缀拒绝。 func EstimateOfficialVideoCost(model, resolution string, seconds int) (PricingResult, bool) { - if normalizePricingModel(model) != "grok-imagine-video" || seconds <= 0 { + if seconds <= 0 { + return PricingResult{}, false + } + baseModel, ok := officialVideoPricingModel(model) + if !ok { return PricingResult{}, false } resolution = strings.ToLower(strings.TrimSpace(resolution)) @@ -254,7 +259,18 @@ func EstimateOfficialVideoCost(model, resolution string, seconds int) (PricingRe return PricingResult{}, false } return PricingResult{ - Model: "grok-imagine-video-" + resolution, + Model: baseModel + "-" + resolution, CostInUSDTicks: int64(seconds) * ticksPerSecond, }, true } + +func officialVideoPricingModel(model string) (string, bool) { + switch normalizePricingModel(model) { + case "grok-imagine-video": + return "grok-imagine-video", true + case "grok-imagine-video-1.5": + return "grok-imagine-video-1.5", true + default: + return "", false + } +} diff --git a/backend/internal/domain/audit/pricing_test.go b/backend/internal/domain/audit/pricing_test.go index 88184061..cd0aea0f 100644 --- a/backend/internal/domain/audit/pricing_test.go +++ b/backend/internal/domain/audit/pricing_test.go @@ -140,4 +140,19 @@ func TestEstimateOfficialVideoCost(t *testing.T) { if result, ok = EstimateOfficialVideoCost("grok-imagine-video", "1080p", 10); ok || result.CostInUSDTicks != 0 { t.Fatalf("unpriced video resolution = %#v, ok = %v", result, ok) } + + result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "720p", 6) + if !ok || result.Model != "grok-imagine-video-1.5-720p" || result.CostInUSDTicks != 8_400_000_000 { + t.Fatalf("1.5 720p video result = %#v, ok = %v", result, ok) + } + result, ok = EstimateOfficialVideoCost("Build/grok-imagine-video-1.5", "480p", 1) + if !ok || result.Model != "grok-imagine-video-1.5-480p" || result.CostInUSDTicks != 800_000_000 { + t.Fatalf("prefixed 1.5 video result = %#v, ok = %v", result, ok) + } + if result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5-fast", "720p", 6); ok || result.CostInUSDTicks != 0 { + t.Fatalf("unknown 1.5 suffix was priced = %#v, ok = %v", result, ok) + } + if result, ok = EstimateOfficialVideoCost("grok-imagine-video-2.0", "720p", 6); ok || result.CostInUSDTicks != 0 { + t.Fatalf("unknown video model was priced = %#v, ok = %v", result, ok) + } } diff --git a/backend/internal/domain/media/job.go b/backend/internal/domain/media/job.go index 54723688..53ec7526 100644 --- a/backend/internal/domain/media/job.go +++ b/backend/internal/domain/media/job.go @@ -35,6 +35,8 @@ type Job struct { Progress int InputJSON string UpstreamURL string + // ResultAssetID 指向本地媒体资产;XAI ZDR 上传完成后优先从此读取。 + ResultAssetID string ContentType string ErrorCode string ErrorMessage string diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index f912f8c5..c10216fd 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -66,6 +66,7 @@ type BatchConfig struct { // ProviderBuildConfig 定义 Grok Build CLI 上游协议标识。 type ProviderBuildConfig struct { BaseURL string + FallbackBaseURL string ClientVersion string ClientIdentifier string TokenAuth string @@ -74,11 +75,12 @@ type ProviderBuildConfig struct { // RoutingConfig 定义会话粘性、冷却和故障切换边界。 type RoutingConfig struct { - StickyTTL time.Duration - CooldownBase time.Duration - CooldownMax time.Duration - CapacityWait time.Duration - MaxAttempts int + StickyTTL time.Duration + CooldownBase time.Duration + CooldownMax time.Duration + CapacityWait time.Duration + MaxAttempts int + PreferFreeBuild bool } // AuditConfig 定义请求审计异步写入参数。 diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 39a80ff1..6c3184d1 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -123,12 +123,16 @@ type ProviderConfig struct { type BuildProviderConfig struct { BaseURL string `yaml:"baseURL"` + FallbackBaseURL string `yaml:"fallbackBaseURL"` ClientVersion string `yaml:"clientVersion"` ClientIdentifier string `yaml:"clientIdentifier"` TokenAuth string `yaml:"tokenAuth"` UserAgent string `yaml:"userAgent"` } +// DefaultBuildFallbackBaseURL 是主 Build API 对可回退推理操作 403 时探测的 XAI API 根地址。 +const DefaultBuildFallbackBaseURL = "https://api.x.ai/v1" + type WebProviderConfig struct { BaseURL string `yaml:"baseURL"` StatsigMode string `yaml:"-"` @@ -173,11 +177,12 @@ type LocalMediaConfig struct { } type RoutingConfig struct { - StickyTTL Duration `yaml:"stickyTTL"` - CooldownBase Duration `yaml:"cooldownBase"` - CooldownMax Duration `yaml:"cooldownMax"` - CapacityWait Duration `yaml:"capacityWait"` - MaxAttempts int `yaml:"maxAttempts"` + StickyTTL Duration `yaml:"stickyTTL"` + CooldownBase Duration `yaml:"cooldownBase"` + CooldownMax Duration `yaml:"cooldownMax"` + CapacityWait Duration `yaml:"capacityWait"` + MaxAttempts int `yaml:"maxAttempts"` + PreferFreeBuild bool `yaml:"preferFreeBuild"` } type AuditConfig struct { @@ -381,9 +386,15 @@ func (c Config) Validate() error { if c.Auth.AccessTokenTTL.Value() <= 0 || c.Auth.RefreshTokenTTL.Value() <= 0 { return errors.New("JWT 有效期必须大于零") } - providerURL, err := url.ParseRequestURI(strings.TrimSpace(c.Provider.Build.BaseURL)) - if err != nil || providerURL.Scheme == "" || providerURL.Host == "" { - return errors.New("provider.build.baseURL 必须是有效 URL") + if err := validateAPIBaseURL("provider.build.baseURL", c.Provider.Build.BaseURL, false); err != nil { + return err + } + fallbackBase := strings.TrimSpace(c.Provider.Build.FallbackBaseURL) + if fallbackBase == "" { + fallbackBase = DefaultBuildFallbackBaseURL + } + if err := validateAPIBaseURL("provider.build.fallbackBaseURL", fallbackBase, true); err != nil { + return err } if strings.TrimSpace(c.Provider.Build.ClientVersion) == "" || strings.TrimSpace(c.Provider.Build.ClientIdentifier) == "" || strings.TrimSpace(c.Provider.Build.TokenAuth) == "" || strings.TrimSpace(c.Provider.Build.UserAgent) == "" { return errors.New("provider.build 客户端标识不能为空") @@ -447,6 +458,34 @@ func (c Config) Validate() error { return nil } +// validateAPIBaseURL 仅允许无凭据、query、fragment 的 HTTP(S) API 根地址。 +// requireHTTPS 为 true 时强制 HTTPS(用于生产默认 XAI 备用地址)。 +func validateAPIBaseURL(name, raw string, requireHTTPS bool) error { + parsed, err := url.ParseRequestURI(strings.TrimSpace(raw)) + if err != nil || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { + return fmt.Errorf("%s 必须是不含凭据、查询参数和片段的 HTTP(S) URL", name) + } + switch parsed.Scheme { + case "https": + return nil + case "http": + if requireHTTPS { + return fmt.Errorf("%s 必须是 HTTPS URL", name) + } + return nil + default: + return fmt.Errorf("%s 必须是不含凭据、查询参数和片段的 HTTP(S) URL", name) + } +} + +// NormalizeBuildFallbackBaseURL 在旧配置缺字段时填入默认 XAI 备用地址。 +func NormalizeBuildFallbackBaseURL(value string) string { + if strings.TrimSpace(value) == "" { + return DefaultBuildFallbackBaseURL + } + return strings.TrimSpace(value) +} + func defaultConfig() Config { return Config{ Server: ServerConfig{ @@ -472,8 +511,8 @@ func defaultConfig() Config { }, Provider: ProviderConfig{ Build: BuildProviderConfig{ - BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: RecommendedBuildClientVersion, - ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", + BaseURL: "https://cli-chat-proxy.grok.com/v1", FallbackBaseURL: DefaultBuildFallbackBaseURL, + ClientVersion: RecommendedBuildClientVersion, ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: RecommendedBuildUserAgent, }, Web: WebProviderConfig{ @@ -499,11 +538,12 @@ func defaultConfig() Config { Local: LocalMediaConfig{Path: "./data/media"}, }, Routing: RoutingConfig{ - StickyTTL: Duration(time.Hour), - CooldownBase: Duration(30 * time.Second), - CooldownMax: Duration(30 * time.Minute), - CapacityWait: Duration(500 * time.Millisecond), - MaxAttempts: 3, + StickyTTL: Duration(time.Hour), + CooldownBase: Duration(30 * time.Second), + CooldownMax: Duration(30 * time.Minute), + CapacityWait: Duration(500 * time.Millisecond), + MaxAttempts: 3, + PreferFreeBuild: false, }, Audit: AuditConfig{BufferSize: 16384, BatchSize: 256, FlushInterval: Duration(250 * time.Millisecond)}, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent}, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index 75aa5b83..21305aa0 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -92,12 +92,13 @@ func TestLoadAcceptsRuntimeDefaultsAndRejectsUnknownFields(t *testing.T) { credentialEncryptionKey: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" routing: maxAttempts: 9 + preferFreeBuild: true `) if err := os.WriteFile(path, data, 0o600); err != nil { t.Fatal(err) } cfg, err := Load(path) - if err != nil || cfg.Routing.MaxAttempts != 9 { + if err != nil || cfg.Routing.MaxAttempts != 9 || !cfg.Routing.PreferFreeBuild { t.Fatalf("runtime defaults = %#v, err = %v", cfg.Routing, err) } data = append(data, []byte("unknownField: true\n")...) diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index 764fe065..d7ca2003 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -345,20 +345,37 @@ func TestStickyProxyForbiddenDoesNotCooldownSharedNode(t *testing.T) { } } -func TestWebAssetFallsBackToWeb(t *testing.T) { +func TestWebAssetCredentialFallsBackToWebWithSameResinIdentity(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { t.Fatal(err) } + proxyURL, err := cipher.Encrypt("socks5h://Default.{account}:token@resin:2260") + if err != nil { + t.Fatal(err) + } + accountCookie, err := cipher.Encrypt("cf_clearance=account") + if err != nil { + t.Fatal(err) + } + token := "shared-web-asset-sso" + encryptedToken, err := cipher.Encrypt(token) + if err != nil { + t.Fatal(err) + } manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{ - {ID: 2, Name: "web", Scope: domain.ScopeWeb, Enabled: true, Health: 1}, + {ID: 2, Name: "web", Scope: domain.ScopeWeb, Enabled: true, Health: 1, EncryptedProxyURL: proxyURL}, }}, cipher) - webLease, err := manager.Acquire(context.Background(), domain.ScopeWeb, "account") + credential := accountdomain.Credential{ + ID: 42, Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, + EncryptedAccessToken: encryptedToken, EncryptedCloudflareCookie: accountCookie, + } + webLease, err := manager.AcquireCredential(context.Background(), domain.ScopeWeb, credential) if err != nil { t.Fatal(err) } defer webLease.Release() - lease, err := manager.Acquire(context.Background(), domain.ScopeWebAsset, "account") + lease, err := manager.AcquireCredential(context.Background(), domain.ScopeWebAsset, credential) if err != nil { t.Fatal(err) } @@ -366,8 +383,15 @@ func TestWebAssetFallsBackToWeb(t *testing.T) { if lease.NodeID != 2 { t.Fatalf("node = %d, want web fallback node 2", lease.NodeID) } + wantAccount := "sso_" + security.HashToken(token)[:32] + if lease.ProxyURL != webLease.ProxyURL || !strings.Contains(lease.ProxyURL, "Default."+wantAccount+":") { + t.Fatalf("proxy identities web=%q asset=%q", webLease.ProxyURL, lease.ProxyURL) + } + if lease.CFCookies != "cf_clearance=account" { + t.Fatalf("asset lease cookie = %q", lease.CFCookies) + } if lease.client != webLease.client { - t.Fatal("Web Asset fallback did not reuse the matching Web browser session") + t.Fatal("Web Asset credential fallback did not reuse the matching Web browser session") } } diff --git a/backend/internal/infra/media/local_store.go b/backend/internal/infra/media/local_store.go index 2726e9d2..9167ac8f 100644 --- a/backend/internal/infra/media/local_store.go +++ b/backend/internal/infra/media/local_store.go @@ -30,24 +30,114 @@ func NewLocalStore(root string) (*LocalStore, error) { } func (s *LocalStore) SaveImage(ctx context.Context, id, mimeType string, data []byte) (string, error) { + return s.saveObject(ctx, "images", ".image-*", id, mimeType, data, imageExtension) +} + +// SaveVideo 将视频对象写入 videos/ 子目录,提交语义与图片一致(原子硬链接、no-replace)。 +func (s *LocalStore) SaveVideo(ctx context.Context, id, mimeType string, data []byte) (string, error) { + return s.saveObject(ctx, "videos", ".video-*", id, mimeType, data, videoExtension) +} + +// BeginVideoUpload 创建视频临时文件,供流式限长写入后 CommitVideoUpload 提交。 +func (s *LocalStore) BeginVideoUpload(ctx context.Context, id, mimeType string) (tempPath, storageKey string, err error) { + if err := ctx.Err(); err != nil { + return "", "", err + } + extension, ok := videoExtension(mimeType) + if !ok || len(id) < 2 { + return "", "", fmt.Errorf("视频存储参数无效") + } + storageKey = filepath.ToSlash(filepath.Join("videos", id[:2], id+extension)) + path, err := s.resolve(storageKey) + if err != nil { + return "", "", err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return "", "", fmt.Errorf("创建视频目录: %w", err) + } + // 禁止覆盖已有文件:目标已存在时拒绝新的上传会话。 + if _, statErr := os.Stat(path); statErr == nil { + return "", "", fmt.Errorf("视频对象已存在") + } else if !errors.Is(statErr, os.ErrNotExist) { + return "", "", statErr + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".video-*") + if err != nil { + return "", "", fmt.Errorf("创建视频临时文件: %w", err) + } + tempPath = temporary.Name() + if err := temporary.Chmod(0o600); err != nil { + _ = temporary.Close() + _ = s.removeTemporary(tempPath) + return "", "", err + } + if err := temporary.Close(); err != nil { + _ = s.removeTemporary(tempPath) + return "", "", err + } + return tempPath, storageKey, nil +} + +// CommitVideoUpload 将临时文件原子提交到 storageKey(硬链接 no-replace)。 +func (s *LocalStore) CommitVideoUpload(ctx context.Context, tempPath, storageKey string) error { + if err := ctx.Err(); err != nil { + return err + } + path, err := s.resolve(storageKey) + if err != nil { + return err + } + // 确保临时文件已落盘。 + file, err := os.Open(tempPath) + if err != nil { + return fmt.Errorf("打开视频临时文件: %w", err) + } + if err := file.Sync(); err != nil { + _ = file.Close() + return fmt.Errorf("同步视频文件: %w", err) + } + if err := file.Close(); err != nil { + return err + } + if err := os.Link(tempPath, path); err != nil { + return fmt.Errorf("提交视频文件: %w", err) + } + if cleanupErr := s.removeTemporary(tempPath); cleanupErr != nil && !errors.Is(cleanupErr, os.ErrNotExist) { + slog.Warn("media_temp_cleanup_failed", "path", tempPath, "error", cleanupErr) + } + return nil +} + +// AbortVideoUpload 清理未提交的临时文件。 +func (s *LocalStore) AbortVideoUpload(_ context.Context, tempPath string) error { + if strings.TrimSpace(tempPath) == "" { + return nil + } + if err := s.removeTemporary(tempPath); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +func (s *LocalStore) saveObject(ctx context.Context, kindDir, tempPattern, id, mimeType string, data []byte, extFn func(string) (string, bool)) (string, error) { if err := ctx.Err(); err != nil { return "", err } - extension, ok := imageExtension(mimeType) + extension, ok := extFn(mimeType) if !ok || len(id) < 2 { - return "", fmt.Errorf("图片存储参数无效") + return "", fmt.Errorf("媒体存储参数无效") } - storageKey := filepath.ToSlash(filepath.Join("images", id[:2], id+extension)) + storageKey := filepath.ToSlash(filepath.Join(kindDir, id[:2], id+extension)) path, err := s.resolve(storageKey) if err != nil { return "", err } if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { - return "", fmt.Errorf("创建图片目录: %w", err) + return "", fmt.Errorf("创建媒体目录: %w", err) } - temporary, err := os.CreateTemp(filepath.Dir(path), ".image-*") + temporary, err := os.CreateTemp(filepath.Dir(path), tempPattern) if err != nil { - return "", fmt.Errorf("创建图片临时文件: %w", err) + return "", fmt.Errorf("创建媒体临时文件: %w", err) } temporaryPath := temporary.Name() cleanupPending := true @@ -63,19 +153,18 @@ func (s *LocalStore) SaveImage(ctx context.Context, id, mimeType string, data [] return "", err } if _, err := temporary.Write(data); err != nil { - return "", fmt.Errorf("写入图片: %w", err) + return "", fmt.Errorf("写入媒体: %w", err) } if err := temporary.Sync(); err != nil { - return "", fmt.Errorf("同步图片文件: %w", err) + return "", fmt.Errorf("同步媒体文件: %w", err) } if err := temporary.Close(); err != nil { - return "", fmt.Errorf("关闭图片文件: %w", err) + return "", fmt.Errorf("关闭媒体文件: %w", err) } - // 硬链接提交具有 no-replace 语义,极端 ID 冲突时不会覆盖已有图片。 + // 硬链接提交具有 no-replace 语义,极端 ID 冲突时不会覆盖已有对象。 if err := os.Link(temporaryPath, path); err != nil { - return "", fmt.Errorf("提交图片文件: %w", err) + return "", fmt.Errorf("提交媒体文件: %w", err) } - // 提交已经成功,清理失败不能回滚永久文件;defer 会再重试一次并记录持续失败。 cleanupErr := s.removeTemporary(temporaryPath) cleanupPending = cleanupErr != nil && !errors.Is(cleanupErr, os.ErrNotExist) return storageKey, nil @@ -143,3 +232,16 @@ func imageExtension(mimeType string) (string, bool) { return "", false } } + +func videoExtension(mimeType string) (string, bool) { + switch strings.ToLower(strings.TrimSpace(mimeType)) { + case "video/mp4": + return ".mp4", true + case "video/webm": + return ".webm", true + case "video/quicktime": + return ".mov", true + default: + return "", false + } +} diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index b3e01693..0c9a9766 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "strings" "time" @@ -23,7 +24,8 @@ type quotaBreakdownJSON struct { } const ( - accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0 OR billing.credit_usage_percent > 0))` + accountPaidBillingSignals = `(billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0 OR billing.credit_usage_percent > 0)` + accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountPaidBillingSignals + `)` accountFreeSignalPredicate = `(LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.is_unified_billing_user = TRUE OR billing.usage_period_type <> '' OR billing.top_up_method <> '' OR billing.billing_period_start <> '' OR (billing.history_json <> '' AND billing.history_json <> '[]' AND billing.history_json <> 'null'))))` accountRecoveryPredicate = `EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status IN ('exhausted', 'probing'))` providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))` @@ -233,11 +235,24 @@ func (r *AccountRepository) ListRoutingCandidates(ctx context.Context, provider modelQuotaBlocks[row.AccountID] = account.ModelQuotaBlock{AccountID: row.AccountID, UpstreamModel: row.UpstreamModel, Reason: row.Reason, CooldownUntil: row.CooldownUntil.UTC(), UpdatedAt: row.UpdatedAt.UTC()} } } + sharedPaidBuildModel := false + if provider == account.ProviderBuild && len(bound) == 0 { + for accountID := range supported { + if billing, exists := billings[accountID]; exists && billing.IsPaid() { + sharedPaidBuildModel = true + break + } + } + } result := make([]account.RoutingCandidate, 0, len(values)) for _, value := range values { capabilityKnown, supportsModel := known[value.ID], supported[value.ID] if len(bound) > 0 { capabilityKnown, supportsModel = true, true + } else if sharedPaidBuildModel { + if billing, exists := billings[value.ID]; exists && billing.IsPaid() { + capabilityKnown, supportsModel = true, true + } } candidate := account.RoutingCandidate{Credential: value, ModelCapabilityKnown: capabilityKnown, SupportsModel: supportsModel} if billing, ok := billings[value.ID]; ok { @@ -576,6 +591,8 @@ func upsertKnownAccountByIdentity(tx *gorm.DB, value account.Credential, existin row.LastUsedAt = existing.LastUsedAt row.ObservedModel = existing.ObservedModel row.ObservedModelAt = existing.ObservedModelAt + // 账号级 Build XAI 降级标记在 upsert/转换/刷新路径中保留;仅管理端可显式清除。 + row.BuildAPIFallback = existing.BuildAPIFallback if err := tx.Save(&row).Error; err != nil { return repository.AccountUpsertResult{}, accountModel{}, err } @@ -789,6 +806,27 @@ func (r *AccountRepository) UpdateObservedModel(ctx context.Context, id uint64, return r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id = ?", id).Updates(map[string]any{"observed_model": truncate(model, 255), "observed_model_at": observedAt}).Error } +// MarkBuildAPIFallback 仅对 grok_build 账号幂等设置/清除 XAI 推理回退标记。 +func (r *AccountRepository) MarkBuildAPIFallback(ctx context.Context, id uint64, enabled bool) error { + result := r.db.db.WithContext(ctx).Model(&accountModel{}). + Where("id = ? AND provider = ?", id, account.ProviderBuild). + Update("build_api_fallback", enabled) + if result.Error != nil { + return result.Error + } + if result.RowsAffected == 0 { + var count int64 + if err := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id = ?", id).Count(&count).Error; err != nil { + return err + } + if count == 0 { + return repository.ErrNotFound + } + return fmt.Errorf("仅 grok_build 账号支持 Build API 降级标记") + } + return nil +} + func (r *AccountRepository) UpdateHealth(ctx context.Context, id uint64, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error { updates := map[string]any{"failure_count": failureCount, "cooldown_until": cooldownUntil, "last_error": truncate(lastError, 512)} if success { diff --git a/backend/internal/infra/persistence/relational/mapping.go b/backend/internal/infra/persistence/relational/mapping.go index 805c045b..d21ea939 100644 --- a/backend/internal/infra/persistence/relational/mapping.go +++ b/backend/internal/infra/persistence/relational/mapping.go @@ -63,7 +63,7 @@ func toAccountDomain(value accountModel) account.Credential { MaxConcurrent: value.MaxConcurrent, MinimumRemaining: value.MinimumRemaining, FailureCount: value.FailureCount, CooldownUntil: value.CooldownUntil, LastError: value.LastError, LastUsedAt: value.LastUsedAt, ObservedModel: value.ObservedModel, ObservedModelAt: value.ObservedModelAt, WebTier: webTier, WebTierSyncedAt: webTierSyncedAt, - CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, + BuildAPIFallback: value.BuildAPIFallback, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, } } @@ -75,7 +75,7 @@ func fromAccountDomain(value account.Credential) accountModel { MaxConcurrent: value.MaxConcurrent, MinimumRemaining: value.MinimumRemaining, FailureCount: value.FailureCount, CooldownUntil: value.CooldownUntil, LastError: value.LastError, LastUsedAt: value.LastUsedAt, ObservedModel: value.ObservedModel, ObservedModelAt: value.ObservedModelAt, - CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, + BuildAPIFallback: value.BuildAPIFallback, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, } } diff --git a/backend/internal/infra/persistence/relational/media_repository.go b/backend/internal/infra/persistence/relational/media_repository.go index 326a5150..24635835 100644 --- a/backend/internal/infra/persistence/relational/media_repository.go +++ b/backend/internal/infra/persistence/relational/media_repository.go @@ -7,6 +7,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/repository" + "gorm.io/gorm" ) type MediaJobRepository struct{ db *Database } @@ -39,8 +40,9 @@ func (r *MediaAssetRepository) GetMediaAsset(ctx context.Context, id string) (me } // ListMediaAssets 通过字段投影返回符合筛选条件的稳定分页结果。 +// 默认仅列出图片,避免管理端图库混入视频资产。 func (r *MediaAssetRepository) ListMediaAssets(ctx context.Context, input repository.MediaAssetListQuery) ([]media.Asset, int64, error) { - query := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}) + query := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}).Where("kind = ?", "image") 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) @@ -63,11 +65,11 @@ func (r *MediaAssetRepository) ListMediaAssets(ctx context.Context, input reposi return values, total, nil } -// SummarizeMediaAssets 通过单次聚合查询返回图片数量和存储占用。 +// 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"). + Select("COALESCE(SUM(CASE WHEN kind = 'image' THEN 1 ELSE 0 END), 0) AS total_images, COALESCE(SUM(size_bytes), 0) AS total_bytes"). Scan(&stats).Error return stats, err } @@ -78,12 +80,15 @@ func (r *MediaAssetRepository) TotalMediaAssetBytes(ctx context.Context) (int64, return total, err } -func (r *MediaAssetRepository) ListOldestMediaAssets(ctx context.Context, limit int) ([]media.Asset, error) { +func (r *MediaAssetRepository) ListOldestMediaAssets(ctx context.Context, offset, limit int) ([]media.Asset, error) { if limit <= 0 || limit > 1000 { limit = 200 } + if offset < 0 { + offset = 0 + } var rows []mediaAssetModel - if err := r.db.db.WithContext(ctx).Order("created_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil { + if err := r.db.db.WithContext(ctx).Order("created_at ASC, id ASC").Offset(offset).Limit(limit).Find(&rows).Error; err != nil { return nil, err } values := make([]media.Asset, 0, len(rows)) @@ -107,6 +112,145 @@ func (r *MediaAssetRepository) DeleteMediaAsset(ctx context.Context, id string) return nil } +// ListProtectedMediaAssetIDs 返回不可清理的资产:进行中视频任务结果、未消费且未过期的上传票据。 +func (r *MediaAssetRepository) ListProtectedMediaAssetIDs(ctx context.Context) (map[string]struct{}, error) { + protected := make(map[string]struct{}) + var jobAssetIDs []string + if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}). + Where("result_asset_id <> '' AND status IN ?", []string{string(media.StatusQueued), string(media.StatusInProgress)}). + Pluck("result_asset_id", &jobAssetIDs).Error; err != nil { + return nil, err + } + for _, id := range jobAssetIDs { + if id != "" { + protected[id] = struct{}{} + } + } + var ticketAssetIDs []string + now := time.Now().UTC() + if err := r.db.db.WithContext(ctx).Model(&mediaUploadTicketModel{}). + Where("consumed_at IS NULL AND expires_at > ?", now). + Pluck("asset_id", &ticketAssetIDs).Error; err != nil { + return nil, err + } + for _, id := range ticketAssetIDs { + if id != "" { + protected[id] = struct{}{} + } + } + return protected, nil +} + +type MediaUploadTicketRepository struct{ db *Database } + +func NewMediaUploadTicketRepository(db *Database) *MediaUploadTicketRepository { + return &MediaUploadTicketRepository{db: db} +} + +func (r *MediaUploadTicketRepository) CreateUploadTicket(ctx context.Context, ticket repository.MediaUploadTicket) error { + row := mediaUploadTicketModel{ + TokenHash: ticket.TokenHash, AssetID: ticket.AssetID, JobID: ticket.JobID, + MaxBytes: ticket.MaxBytes, AllowedMIME: ticket.AllowedMIME, + ExpiresAt: ticket.ExpiresAt, ConsumedAt: ticket.ConsumedAt, CreatedAt: ticket.CreatedAt, + } + return r.db.db.WithContext(ctx).Create(&row).Error +} + +func (r *MediaUploadTicketRepository) GetUploadTicketByHash(ctx context.Context, tokenHash string) (repository.MediaUploadTicket, error) { + var row mediaUploadTicketModel + if err := r.db.db.WithContext(ctx).Where("token_hash = ?", tokenHash).First(&row).Error; err != nil { + return repository.MediaUploadTicket{}, mapError(err) + } + return ticketToDomain(row), nil +} + +func (r *MediaUploadTicketRepository) ConsumeUploadTicket(ctx context.Context, tokenHash string, now time.Time) (repository.MediaUploadTicket, bool, error) { + var ticket repository.MediaUploadTicket + consumed := false + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + result := tx.Model(&mediaUploadTicketModel{}). + Where("token_hash = ? AND consumed_at IS NULL AND expires_at > ?", tokenHash, now). + Update("consumed_at", now) + if result.Error != nil { + return result.Error + } + if result.RowsAffected == 0 { + return nil + } + var row mediaUploadTicketModel + if err := tx.Where("token_hash = ?", tokenHash).First(&row).Error; err != nil { + return err + } + ticket = ticketToDomain(row) + consumed = true + return nil + }) + if err != nil { + return repository.MediaUploadTicket{}, false, err + } + return ticket, consumed, nil +} + +// ReleaseUploadTicket 撤销一次尚未落资产的消费,使同一 token 可再次 PUT。 +func (r *MediaUploadTicketRepository) ReleaseUploadTicket(ctx context.Context, tokenHash string) (bool, error) { + // 使用 map 写入 NULL:GORM Update(column, nil) 可能被忽略。 + result := r.db.db.WithContext(ctx).Model(&mediaUploadTicketModel{}). + Where("token_hash = ? AND consumed_at IS NOT NULL", tokenHash). + Updates(map[string]any{"consumed_at": nil}) + if result.Error != nil { + return false, result.Error + } + return result.RowsAffected > 0, nil +} + +// DeleteUploadTicketByHash 按 token_hash 精确删除票据;目标不存在时幂等返回 nil。 +func (r *MediaUploadTicketRepository) DeleteUploadTicketByHash(ctx context.Context, tokenHash string) error { + tokenHash = strings.TrimSpace(tokenHash) + if tokenHash == "" { + return nil + } + return r.db.db.WithContext(ctx).Where("token_hash = ?", tokenHash).Delete(&mediaUploadTicketModel{}).Error +} + +// DeleteExpiredUploadTickets 删除已过期票据行(已消费或未消费均可);未过期票据与媒体资产不受影响。 +func (r *MediaUploadTicketRepository) DeleteExpiredUploadTickets(ctx context.Context, before time.Time, limit int) (int64, error) { + if limit <= 0 || limit > 1000 { + limit = 200 + } + var hashes []string + if err := r.db.db.WithContext(ctx).Model(&mediaUploadTicketModel{}). + Where("expires_at < ?", before). + Order("expires_at ASC").Limit(limit).Pluck("token_hash", &hashes).Error; err != nil { + return 0, err + } + if len(hashes) == 0 { + return 0, nil + } + result := r.db.db.WithContext(ctx).Where("token_hash IN ?", hashes).Delete(&mediaUploadTicketModel{}) + return result.RowsAffected, result.Error +} + +func (r *MediaUploadTicketRepository) BindJobResultAsset(ctx context.Context, jobID, assetID string) error { + result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}). + Where("id = ?", jobID). + Updates(map[string]any{"result_asset_id": assetID, "updated_at": time.Now().UTC()}) + if result.Error != nil { + return result.Error + } + if result.RowsAffected == 0 { + return repository.ErrNotFound + } + return nil +} + +func ticketToDomain(row mediaUploadTicketModel) repository.MediaUploadTicket { + return repository.MediaUploadTicket{ + TokenHash: row.TokenHash, AssetID: row.AssetID, JobID: row.JobID, + MaxBytes: row.MaxBytes, AllowedMIME: row.AllowedMIME, + ExpiresAt: row.ExpiresAt, ConsumedAt: row.ConsumedAt, CreatedAt: row.CreatedAt, + } +} + func (r *MediaJobRepository) CreateMediaJob(ctx context.Context, value media.Job) error { return r.db.db.WithContext(ctx).Create(mediaJobFromDomain(value)).Error } @@ -125,7 +269,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", "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) + 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", "result_asset_id", "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 } @@ -264,7 +408,7 @@ func mediaJobFromDomain(value media.Job) *mediaJobModel { 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, + ResultAssetID: value.ResultAssetID, ContentType: value.ContentType, ErrorCode: value.ErrorCode, ErrorMessage: value.ErrorMessage, LeaseUntil: value.LeaseUntil, ClaimToken: value.ClaimToken, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, CompletedAt: value.CompletedAt, UsageRecordedAt: value.UsageRecordedAt, } @@ -279,7 +423,7 @@ func mediaJobToDomain(row mediaJobModel) media.Job { 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, + ResultAssetID: row.ResultAssetID, ContentType: row.ContentType, ErrorCode: row.ErrorCode, ErrorMessage: row.ErrorMessage, LeaseUntil: row.LeaseUntil, ClaimToken: row.ClaimToken, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, CompletedAt: row.CompletedAt, UsageRecordedAt: row.UsageRecordedAt, } diff --git a/backend/internal/infra/persistence/relational/media_repository_test.go b/backend/internal/infra/persistence/relational/media_repository_test.go index a1d3bec2..67ea4a4a 100644 --- a/backend/internal/infra/persistence/relational/media_repository_test.go +++ b/backend/internal/infra/persistence/relational/media_repository_test.go @@ -2,6 +2,7 @@ package relational import ( "context" + "errors" "strings" "testing" "time" @@ -9,6 +10,7 @@ import ( 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" + "gorm.io/gorm" ) func TestMediaJobRepositoryListMediaJobsPaginatesAndFilters(t *testing.T) { @@ -215,6 +217,89 @@ func testMediaJob(id string, accountID, clientKeyID uint64, status mediadomain.S return job } +func TestMediaUploadTicketRepositoryDeleteUploadTicketByHash(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewMediaUploadTicketRepository(database) + now := time.Now().UTC() + hash := strings.Repeat("ab", 32) + otherHash := strings.Repeat("cd", 32) + if err := repo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hash, AssetID: "vid_delete_by_hash_1", JobID: "job_delete_by_hash", + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + if err := repo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: otherHash, AssetID: "vid_delete_by_hash_2", JobID: "job_delete_keep", + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + + if err := repo.DeleteUploadTicketByHash(ctx, hash); err != nil { + t.Fatalf("delete: %v", err) + } + if _, err := repo.GetUploadTicketByHash(ctx, hash); !errors.Is(err, repository.ErrNotFound) { + t.Fatalf("deleted ticket still readable: %v", err) + } + // 精确删除不得影响其他票据。 + if _, err := repo.GetUploadTicketByHash(ctx, otherHash); err != nil { + t.Fatalf("other ticket removed: %v", err) + } + // 幂等:再次删除缺失行成功。 + if err := repo.DeleteUploadTicketByHash(ctx, hash); err != nil { + t.Fatalf("idempotent delete: %v", err) + } + if err := repo.DeleteUploadTicketByHash(ctx, ""); err != nil { + t.Fatalf("empty hash delete: %v", err) + } +} + +func TestMediaUploadTicketRepositoryConsumeRollsBackWhenTicketReadFails(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewMediaUploadTicketRepository(database) + now := time.Now().UTC() + hash := strings.Repeat("ef", 32) + if err := repo.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hash, AssetID: "vid_consume_rollback_1", JobID: "job_consume_rollback", + MaxBytes: 1024, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + + injected := errors.New("injected ticket read failure") + callbackName := "test:fail_consumed_ticket_read" + failed := false + if err := database.db.Callback().Query().Before("gorm:query").Register(callbackName, func(tx *gorm.DB) { + if !failed && tx.Statement != nil && tx.Statement.Table == "media_upload_tickets" { + failed = true + _ = tx.AddError(injected) + } + }); err != nil { + t.Fatal(err) + } + + _, consumed, err := repo.ConsumeUploadTicket(ctx, hash, now) + if removeErr := database.db.Callback().Query().Remove(callbackName); removeErr != nil { + t.Fatal(removeErr) + } + if !errors.Is(err, injected) || consumed { + t.Fatalf("consume = (%v, %v), want injected error and consumed=false", consumed, err) + } + if !failed { + t.Fatal("ticket read failure callback did not run") + } + ticket, err := repo.GetUploadTicketByHash(ctx, hash) + if err != nil { + t.Fatal(err) + } + if ticket.ConsumedAt != nil { + t.Fatalf("consume transaction was not rolled back: consumed_at=%v", ticket.ConsumedAt) + } +} + func testMediaAsset(id, storageKey string, createdAt time.Time) mediadomain.Asset { return mediadomain.Asset{ ID: id, diff --git a/backend/internal/infra/persistence/relational/model_capability_repository_test.go b/backend/internal/infra/persistence/relational/model_capability_repository_test.go index f820f11e..7fd1bc75 100644 --- a/backend/internal/infra/persistence/relational/model_capability_repository_test.go +++ b/backend/internal/infra/persistence/relational/model_capability_repository_test.go @@ -85,6 +85,105 @@ func TestModelCapabilitiesAggregateAndGateEnabledRoutes(t *testing.T) { } } +func TestBuildPaidCapabilitiesAreSharedAcrossActiveSuperAccounts(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + accounts := NewAccountRepository(database) + models := NewModelRepository(database) + + createAccount := func(name string) account.Credential { + t.Helper() + value, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: name, SourceKey: name, + EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + return value + } + observer := createAccount("super-observer") + peer := createAccount("super-peer") + freeObserver := createAccount("free-observer") + freePeer := createAccount("free-peer") + now := time.Now().UTC() + if err := accounts.SaveBilling(ctx, account.Billing{AccountID: observer.ID, MonthlyLimit: 100, SyncedAt: now}); err != nil { + t.Fatal(err) + } + if err := accounts.SaveBilling(ctx, account.Billing{AccountID: peer.ID, OnDemandCap: 50, SyncedAt: now}); err != nil { + t.Fatal(err) + } + + const sharedModel = "grok-super-shared" + if err := models.UpsertDiscovered(ctx, account.ProviderBuild, []string{sharedModel, "grok-4.5"}); err != nil { + t.Fatal(err) + } + for accountID, capabilities := range map[uint64][]string{ + observer.ID: {sharedModel, "grok-4.5"}, + peer.ID: {"grok-4.5"}, + freeObserver.ID: {sharedModel}, + freePeer.ID: {"grok-4.5"}, + } { + if err := models.ReplaceAccountCapabilities(ctx, accountID, capabilities, now); err != nil { + t.Fatal(err) + } + } + + route, err := models.GetByProviderUpstream(ctx, account.ProviderBuild, sharedModel) + if err != nil { + t.Fatal(err) + } + route, err = models.Get(ctx, route.ID) + if err != nil { + t.Fatal(err) + } + if route.SupportedAccounts != 3 || route.TotalAccounts != 4 { + t.Fatalf("shared route availability = %#v", route) + } + if _, _, err := models.List(ctx, repository.ModelListQuery{ + Page: repository.PageQuery{Limit: 20, Sort: repository.SortQuery{Field: "accountSupport", Direction: repository.SortDescending}}, + }); err != nil { + t.Fatalf("sort by shared account support: %v", err) + } + candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, sharedModel, "") + if err != nil { + t.Fatal(err) + } + byID := make(map[uint64]account.RoutingCandidate, len(candidates)) + for _, candidate := range candidates { + byID[candidate.Credential.ID] = candidate + } + for _, accountID := range []uint64{observer.ID, peer.ID, freeObserver.ID} { + if candidate := byID[accountID]; !candidate.ModelCapabilityKnown || !candidate.SupportsModel { + t.Fatalf("account %d should support shared model: %#v", accountID, candidate) + } + } + if candidate := byID[freePeer.ID]; !candidate.ModelCapabilityKnown || candidate.SupportsModel { + t.Fatalf("free peer must keep its own capability snapshot: %#v", candidate) + } + + observer.Enabled = false + if _, err := accounts.Update(ctx, observer); err != nil { + t.Fatal(err) + } + route, err = models.Get(ctx, route.ID) + if err != nil { + t.Fatal(err) + } + if route.SupportedAccounts != 1 || route.TotalAccounts != 3 { + t.Fatalf("disabled observer must not grant shared entitlement: %#v", route) + } + candidates, err = accounts.ListRoutingCandidates(ctx, account.ProviderBuild, sharedModel, "") + if err != nil { + t.Fatal(err) + } + for _, candidate := range candidates { + if candidate.Credential.ID == peer.ID && candidate.SupportsModel { + t.Fatalf("paid peer should lose shared capability without an active paid observer: %#v", candidate) + } + } +} + func TestPublicModelNameResolvesAcrossAvailableProviders(t *testing.T) { ctx := context.Background() database := openTestDatabase(t) @@ -381,3 +480,56 @@ func TestWebRediscoveryRestoresCatalogRouteDefaults(t *testing.T) { t.Fatalf("rediscovered web route defaults = %#v", items[0]) } } + +func TestBuildVideo15DiscoveredAsVideoCapability(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewModelRepository(database) + accounts := NewAccountRepository(database) + buildAccount, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "build-video", SourceKey: "build-video", + EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + webAccount, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, Name: "web-video", SourceKey: "web-video", + EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + if err := repo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-4.5", "grok-imagine-video-1.5"}); err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := repo.ReplaceAccountCapabilities(ctx, buildAccount.ID, []string{"grok-4.5", "grok-imagine-video-1.5"}, now); err != nil { + t.Fatal(err) + } + video, err := repo.GetByPublicID(ctx, "Build/grok-imagine-video-1.5") + if err != nil { + t.Fatal(err) + } + if video.Capability != model.CapabilityVideo || video.UpstreamModel != "grok-imagine-video-1.5" || video.Origin != model.OriginDiscovered { + t.Fatalf("build video 1.5 route = %#v", video) + } + chat, err := repo.GetByPublicID(ctx, "Build/grok-4.5") + if err != nil { + t.Fatal(err) + } + if chat.Capability != model.CapabilityResponses { + t.Fatalf("build chat route capability = %s", chat.Capability) + } + // Web 既有 video 分类不受影响。 + if err := repo.UpsertDiscovered(ctx, account.ProviderWeb, []string{"grok-imagine-video"}); err != nil { + t.Fatal(err) + } + if err := repo.ReplaceAccountCapabilities(ctx, webAccount.ID, []string{"grok-imagine-video"}, now); err != nil { + t.Fatal(err) + } + webVideo, err := repo.GetByPublicID(ctx, "grok-imagine-video") + if err != nil || webVideo.Capability != model.CapabilityVideo { + t.Fatalf("web video route = %#v, err = %v", webVideo, err) + } +} diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index 90cd855a..7c837591 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -41,9 +41,33 @@ const availableRoutePredicate = ` ) ` +const modelSharedPaidBuildSupportSortExpression = `(model_routes.provider = 'grok_build' + AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = account.id AND ` + accountPaidBillingSignals + `) + AND EXISTS ( + SELECT 1 + FROM provider_accounts peer + JOIN account_model_capabilities peer_capability ON peer_capability.account_id = peer.id AND peer_capability.upstream_model = model_routes.upstream_model + WHERE peer.provider = model_routes.provider + AND peer.enabled = TRUE + AND peer.auth_status = 'active' + AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = peer.id AND ` + accountPaidBillingSignals + `) + ))` + +const modelSharedPaidBuildSupportAvailabilityExpression = `(route.provider = 'grok_build' + AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = account.id AND ` + accountPaidBillingSignals + `) + AND EXISTS ( + SELECT 1 + FROM provider_accounts peer + JOIN account_model_capabilities peer_capability ON peer_capability.account_id = peer.id AND peer_capability.upstream_model = route.upstream_model + WHERE peer.provider = route.provider + AND peer.enabled = TRUE + AND peer.auth_status = 'active' + AND EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = peer.id AND ` + accountPaidBillingSignals + `) + ))` + const ( modelProviderPriorityExpression = "CASE model_routes.provider WHEN 'grok_build' THEN 0 WHEN 'grok_web' THEN 1 WHEN 'grok_console' THEN 2 ELSE 3 END" - modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model))))` + modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND (EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model) OR ` + modelSharedPaidBuildSupportSortExpression + `))))` modelSyncedSortExpression = `(SELECT MAX(sync.last_success_at) FROM provider_accounts account JOIN account_model_sync_states sync ON sync.account_id = account.id WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active')` ) @@ -297,18 +321,25 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account } func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (string, model.Capability) { - if provider != account.ProviderWeb { + switch provider { + case account.ProviderWeb: + switch upstreamModel { + case "grok-imagine-image", "grok-imagine-image-quality": + return upstreamModel, model.CapabilityImage + case "imagine-image-edit": + return "grok-imagine-image-edit", model.CapabilityImageEdit + case "grok-imagine-video": + return upstreamModel, model.CapabilityVideo + default: + return upstreamModel, model.CapabilityChat + } + case account.ProviderBuild: + if upstreamModel == "grok-imagine-video-1.5" { + return upstreamModel, model.CapabilityVideo + } return upstreamModel, model.CapabilityResponses - } - switch upstreamModel { - case "grok-imagine-image", "grok-imagine-image-quality": - return upstreamModel, model.CapabilityImage - case "imagine-image-edit": - return "grok-imagine-image-edit", model.CapabilityImageEdit - case "grok-imagine-video": - return upstreamModel, model.CapabilityVideo default: - return upstreamModel, model.CapabilityChat + return upstreamModel, model.CapabilityResponses } } @@ -605,7 +636,7 @@ func (r *ModelRepository) annotateAvailability(ctx context.Context, values []mod SELECT route.id AS route_id, CASE WHEN COUNT(DISTINCT binding.account_id) > 0 THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL THEN account.id END) - ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND capability.account_id IS NOT NULL THEN account.id END) + ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND (capability.account_id IS NOT NULL OR `+modelSharedPaidBuildSupportAvailabilityExpression+`) THEN account.id END) END AS supported_accounts, CASE WHEN COUNT(DISTINCT binding.account_id) > 0 THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL AND sync.last_success_at IS NOT NULL THEN account.id END) diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index c9a47112..84f9942c 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -44,6 +44,8 @@ type accountModel struct { LastUsedAt *time.Time ObservedModel string `gorm:"size:255;check:chk_accounts_observed_model,length(observed_model) <= 255"` ObservedModelAt *time.Time + // BuildAPIFallback 仅对 grok_build 有意义:XAI 推理回退标记;其他 Provider 保持 false。 + BuildAPIFallback bool `gorm:"not null;default:false"` CreatedAt time.Time `gorm:"not null"` UpdatedAt time.Time `gorm:"not null"` Credential *accountCredentialModel `gorm:"foreignKey:AccountID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` @@ -356,9 +358,9 @@ type mediaJobModel struct { 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')"` + EgressScope string `gorm:"size:32;not null;default:'';check:chk_media_jobs_egress_scope,egress_scope IN ('','grok_web','grok_build')"` 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')"` + Provider string `gorm:"size:32;not null;check:chk_media_jobs_provider,provider IN ('grok_web','grok_build')"` 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"` @@ -370,6 +372,7 @@ type mediaJobModel struct { 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"` + ResultAssetID string `gorm:"size:64;not null;default:'';check:chk_media_jobs_result_asset_id,result_asset_id = '' OR length(trim(result_asset_id)) BETWEEN 16 AND 64"` 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"` @@ -385,18 +388,36 @@ type mediaJobModel struct { func (mediaJobModel) TableName() string { return "media_jobs" } +// MaxVideoAssetBytes 是本地视频对象与上传接收的安全体积上限(256 MiB)。 +const MaxVideoAssetBytes = 256 << 20 + type mediaAssetModel struct { ID string `gorm:"size:64;primaryKey;check:chk_media_assets_id,length(trim(id)) BETWEEN 16 AND 64"` - Kind string `gorm:"size:16;not null;check:chk_media_assets_kind,kind IN ('image')"` + Kind string `gorm:"size:16;not null;check:chk_media_assets_kind,kind IN ('image','video')"` StorageKey string `gorm:"size:512;not null;uniqueIndex;check:chk_media_assets_storage_key,length(trim(storage_key)) BETWEEN 1 AND 512"` - MIMEType string `gorm:"size:64;not null;check:chk_media_assets_mime,mime_type IN ('image/jpeg','image/png','image/webp','image/gif')"` - SizeBytes int64 `gorm:"not null;check:chk_media_assets_size,size_bytes > 0 AND size_bytes <= 33554432"` + MIMEType string `gorm:"size:64;not null;check:chk_media_assets_mime,mime_type IN ('image/jpeg','image/png','image/webp','image/gif','video/mp4','video/webm','video/quicktime')"` + SizeBytes int64 `gorm:"not null;check:chk_media_assets_size,size_bytes > 0 AND size_bytes <= 268435456"` SHA256 string `gorm:"size:64;not null;check:chk_media_assets_sha,length(sha256) = 64"` CreatedAt time.Time `gorm:"not null"` } func (mediaAssetModel) TableName() string { return "media_assets" } +// mediaUploadTicketModel 保存上游视频 PUT 票据的不可逆摘要与一次性消费状态。 +// 明文 token 永不落库;校验时对路径 token 再哈希比对。 +type mediaUploadTicketModel struct { + TokenHash string `gorm:"size:64;primaryKey;check:chk_media_upload_tickets_token_hash,length(token_hash) = 64"` + AssetID string `gorm:"size:64;not null;uniqueIndex;check:chk_media_upload_tickets_asset_id,length(trim(asset_id)) BETWEEN 16 AND 64"` + JobID string `gorm:"size:64;not null;index;check:chk_media_upload_tickets_job_id,length(trim(job_id)) BETWEEN 1 AND 64"` + MaxBytes int64 `gorm:"not null;check:chk_media_upload_tickets_max_bytes,max_bytes > 0 AND max_bytes <= 268435456"` + AllowedMIME string `gorm:"size:128;not null;default:'video/mp4';check:chk_media_upload_tickets_mime,length(trim(allowed_mime)) BETWEEN 1 AND 128"` + ExpiresAt time.Time `gorm:"not null"` + ConsumedAt *time.Time + CreatedAt time.Time `gorm:"not null"` +} + +func (mediaUploadTicketModel) TableName() string { return "media_upload_tickets" } + type runtimeSettingsModel struct { Key string `gorm:"size:64;primaryKey;check:chk_runtime_settings_key,length(trim(key)) BETWEEN 1 AND 64"` ValueJSON string `gorm:"type:text;not null;check:chk_runtime_settings_json_length,length(value_json) <= 1048576"` diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index 5b8e8753..d4d2f4c0 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -31,6 +31,7 @@ var schemaModels = []any{ &webResponseStateModel{}, &mediaJobModel{}, &mediaAssetModel{}, + &mediaUploadTicketModel{}, &runtimeSettingsModel{}, &egressNodeModel{}, } @@ -72,6 +73,9 @@ var schemaIndexes = []string{ "CREATE INDEX IF NOT EXISTS idx_media_jobs_recovery ON media_jobs(status, lease_until, created_at, id)", "CREATE INDEX IF NOT EXISTS idx_media_jobs_usage_recovery ON media_jobs(status, usage_recorded_at, completed_at, id)", "CREATE INDEX IF NOT EXISTS idx_media_assets_created ON media_assets(created_at DESC, id)", + "CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets(kind, created_at DESC, id)", + "CREATE INDEX IF NOT EXISTS idx_media_upload_tickets_expires ON media_upload_tickets(expires_at, consumed_at)", + "CREATE INDEX IF NOT EXISTS idx_media_jobs_result_asset ON media_jobs(result_asset_id) WHERE result_asset_id <> ''", } // InitializeSchema 以当前持久化模型作为首版数据库结构基线。 @@ -89,6 +93,12 @@ func (d *Database) InitializeSchema(ctx context.Context) error { if err := d.ensureConsoleConstraints(ctx); err != nil { return fmt.Errorf("迁移 Console 数据库约束: %w", err) } + if err := d.ensureMediaJobConstraints(ctx); err != nil { + return fmt.Errorf("迁移 media job 数据库约束: %w", err) + } + if err := d.ensureMediaAssetConstraints(ctx); err != nil { + return fmt.Errorf("迁移 media asset 数据库约束: %w", err) + } for _, statement := range schemaIndexes { if err := db.Exec(statement).Error; err != nil { return fmt.Errorf("初始化数据库索引: %w", err) @@ -107,13 +117,43 @@ type consoleConstraint struct { } func (d *Database) ensureConsoleConstraints(ctx context.Context) error { - constraints := []consoleConstraint{ + return d.ensureNamedConstraints(ctx, []consoleConstraint{ {model: &accountModel{}, table: "provider_accounts", name: "chk_accounts_provider"}, {model: &modelRouteModel{}, table: "model_routes", name: "chk_model_routes_provider"}, {model: &requestAuditModel{}, table: "request_audits", name: "chk_request_audits_provider"}, {model: &responseOwnershipModel{}, table: "response_ownership", name: "chk_response_ownership_provider"}, {model: &egressNodeModel{}, table: "egress_nodes", name: "chk_egress_nodes_specific_scope"}, + }, "grok_console") +} + +// ensureMediaJobConstraints 将历史仅允许 grok_web 的 media job CHECK 升级到支持 Build 视频。 +// AutoMigrate 不会可靠替换已有 PostgreSQL CHECK,因此启动时幂等检测并重建。 +func (d *Database) ensureMediaJobConstraints(ctx context.Context) error { + return d.ensureNamedConstraints(ctx, []consoleConstraint{ + {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_provider"}, + {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_egress_scope"}, + }, "grok_build") +} + +// ensureMediaAssetConstraints 升级历史仅允许 image 的媒体资产 CHECK,以支持 video 与更大体积。 +func (d *Database) ensureMediaAssetConstraints(ctx context.Context) error { + if err := d.ensureNamedConstraints(ctx, []consoleConstraint{ + {model: &mediaAssetModel{}, table: "media_assets", name: "chk_media_assets_kind"}, + }, "video"); err != nil { + return err } + if err := d.ensureNamedConstraints(ctx, []consoleConstraint{ + {model: &mediaAssetModel{}, table: "media_assets", name: "chk_media_assets_mime"}, + }, "video/mp4"); err != nil { + return err + } + return d.ensureNamedConstraints(ctx, []consoleConstraint{ + {model: &mediaAssetModel{}, table: "media_assets", name: "chk_media_assets_size"}, + }, "268435456") +} + +// ensureNamedConstraints 在约束定义尚未包含 marker 时 drop/recreate;已升级则跳过。 +func (d *Database) ensureNamedConstraints(ctx context.Context, constraints []consoleConstraint, marker string) error { migrate := func() error { db := d.db.WithContext(ctx) for _, value := range constraints { @@ -121,7 +161,7 @@ func (d *Database) ensureConsoleConstraints(ctx context.Context) error { if err != nil { return err } - if strings.Contains(definition, "grok_console") { + if strings.Contains(definition, marker) { continue } if definition != "" { diff --git a/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go b/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go new file mode 100644 index 00000000..5c2d1e61 --- /dev/null +++ b/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go @@ -0,0 +1,222 @@ +package relational + +import ( + "context" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" +) + +func TestMediaJobModelTagsAllowBuildVideoProviderAndScope(t *testing.T) { + modelType := reflect.TypeOf(mediaJobModel{}) + providerField, ok := modelType.FieldByName("Provider") + if !ok { + t.Fatal("Provider field missing") + } + providerTag := providerField.Tag.Get("gorm") + if !strings.Contains(providerTag, "chk_media_jobs_provider") || + !strings.Contains(providerTag, "grok_web") || + !strings.Contains(providerTag, "grok_build") || + strings.Contains(providerTag, "grok_console") { + t.Fatalf("provider tag = %q", providerTag) + } + scopeField, ok := modelType.FieldByName("EgressScope") + if !ok { + t.Fatal("EgressScope field missing") + } + scopeTag := scopeField.Tag.Get("gorm") + if !strings.Contains(scopeTag, "chk_media_jobs_egress_scope") || + !strings.Contains(scopeTag, "''") || + !strings.Contains(scopeTag, "grok_web") || + !strings.Contains(scopeTag, "grok_build") || + strings.Contains(scopeTag, "grok_console") { + t.Fatalf("egress_scope tag = %q", scopeTag) + } +} + +func TestInitializeSchemaUpgradesMediaJobChecksForBuild(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "legacy-media-jobs.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + + // 先建立当前完整 schema,再将 media_jobs 回退到仅允许 Web 的旧 CHECK。 + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + if err := recreateLegacyMediaJobsTable(ctx, database); err != nil { + t.Fatal(err) + } + assertMediaJobSQLLacksBuild(t, database) + + accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, + AuthType: accountdomain.AuthTypeOAuth, + Name: "build-media-account", + SourceKey: "build-media-account", + EncryptedAccessToken: testEncryptedToken, + AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + key := clientKeyModel{ + Name: "build-media-key", Prefix: "build-media-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) + } + + // 旧约束下 Build provider 必须失败。 + now := time.Now().UTC() + legacyJob := mediadomain.Job{ + ID: "video_build_legacy_blocked", RequestID: "request-build-legacy", + ClientKeyID: key.ID, ClientKeyName: key.Name, + AccountID: accountValue.ID, AccountName: accountValue.Name, + Provider: "grok_build", Model: "grok-imagine-video-1.5", ModelRouteID: 1, + UpstreamModel: "grok-imagine-video-1.5", Prompt: "test", Seconds: 6, + Size: "16:9", Quality: "720p", Status: mediadomain.StatusQueued, + InputJSON: `{}`, CreatedAt: now, UpdatedAt: now, + } + jobs := NewMediaJobRepository(database) + if err := jobs.CreateMediaJob(ctx, legacyJob); err == nil { + t.Fatal("legacy schema unexpectedly accepted grok_build media job") + } + + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + assertMediaJobSQLContainsBuild(t, database) + + // 升级后 Build job 与 grok_build egress scope 均可写入。 + legacyJob.EgressScope = "grok_build" + if err := jobs.CreateMediaJob(ctx, legacyJob); err != nil { + t.Fatalf("upgraded schema rejected build media job: %v", err) + } + webJob := mediadomain.Job{ + ID: "video_web_still_ok", RequestID: "request-web-ok", + ClientKeyID: key.ID, ClientKeyName: key.Name, + AccountID: accountValue.ID, AccountName: accountValue.Name, + Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 2, + UpstreamModel: "grok-imagine-video", Prompt: "web", Seconds: 6, + Size: "16:9", Quality: "720p", Status: mediadomain.StatusQueued, + EgressScope: "grok_web", InputJSON: `{}`, CreatedAt: now, UpdatedAt: now, + } + if err := jobs.CreateMediaJob(ctx, webJob); err != nil { + t.Fatalf("web media job regression: %v", err) + } + + // 非法 provider / scope 仍应被拒绝。 + invalidProvider := legacyJob + invalidProvider.ID = "video_console_blocked" + invalidProvider.RequestID = "request-console-blocked" + invalidProvider.Provider = "grok_console" + if err := jobs.CreateMediaJob(ctx, invalidProvider); err == nil { + t.Fatal("console provider was accepted for media jobs") + } + invalidScope := legacyJob + invalidScope.ID = "video_scope_blocked" + invalidScope.RequestID = "request-scope-blocked" + invalidScope.EgressScope = "grok_console" + if err := jobs.CreateMediaJob(ctx, invalidScope); err == nil { + t.Fatal("console egress scope was accepted for media jobs") + } + + // 重复迁移幂等,且已有 Build 任务仍在。 + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + assertMediaJobSQLContainsBuild(t, database) + stored, err := jobs.GetMediaJob(ctx, legacyJob.ID, key.ID) + if err != nil || stored.Provider != "grok_build" || stored.EgressScope != "grok_build" { + t.Fatalf("stored build job = %#v, err = %v", stored, err) + } +} + +func recreateLegacyMediaJobsTable(ctx context.Context, database *Database) error { + return database.withSQLiteForeignKeysDisabled(ctx, func() error { + db := database.db.WithContext(ctx) + if err := db.Exec("DROP TABLE IF EXISTS media_jobs").Error; err != nil { + return err + } + // 仅保留升级测试所需字段,CHECK 复刻生产旧定义。 + return db.Exec(` + CREATE TABLE media_jobs ( + id text PRIMARY KEY, + request_id text NOT NULL, + client_key_id integer NOT NULL, + client_key_name text NOT NULL DEFAULT '', + account_id integer NOT NULL, + account_name text NOT NULL DEFAULT '', + egress_node_id integer, + egress_node_name text NOT NULL DEFAULT '', + egress_scope text NOT NULL DEFAULT '', + egress_mode text NOT NULL DEFAULT '', + provider text NOT NULL, + model text NOT NULL, + model_route_id integer NOT NULL, + upstream_model text NOT NULL, + prompt text NOT NULL, + seconds integer NOT NULL, + size text NOT NULL, + quality text NOT NULL, + status text NOT NULL, + progress integer NOT NULL DEFAULT 0, + input_json text NOT NULL DEFAULT '{}', + upstream_url text NOT NULL DEFAULT '', + content_type text NOT NULL DEFAULT '', + error_code text NOT NULL DEFAULT '', + error_message text NOT NULL DEFAULT '', + lease_until datetime, + claim_token text NOT NULL DEFAULT '', + created_at datetime NOT NULL, + updated_at datetime NOT NULL, + completed_at datetime, + usage_recorded_at datetime, + CONSTRAINT chk_media_jobs_provider CHECK (provider IN ('grok_web')), + CONSTRAINT chk_media_jobs_egress_scope CHECK (egress_scope IN ('','grok_web')), + CONSTRAINT fk_media_jobs_account FOREIGN KEY (account_id) REFERENCES provider_accounts(id) ON UPDATE CASCADE ON DELETE RESTRICT, + CONSTRAINT fk_media_jobs_client_key FOREIGN KEY (client_key_id) REFERENCES client_keys(id) ON UPDATE CASCADE ON DELETE RESTRICT + ) + `).Error + }) +} + +func assertMediaJobSQLLacksBuild(t *testing.T, database *Database) { + t.Helper() + sql := mediaJobsTableSQL(t, database) + if strings.Contains(sql, "grok_build") { + t.Fatalf("legacy media_jobs unexpectedly contains grok_build: %s", sql) + } + if !strings.Contains(sql, "grok_web") { + t.Fatalf("legacy media_jobs missing grok_web: %s", sql) + } +} + +func assertMediaJobSQLContainsBuild(t *testing.T, database *Database) { + t.Helper() + sql := mediaJobsTableSQL(t, database) + if !strings.Contains(sql, "grok_build") { + t.Fatalf("media_jobs was not upgraded with grok_build: %s", sql) + } + if strings.Contains(sql, "grok_console") { + t.Fatalf("media_jobs unexpectedly allows console: %s", sql) + } +} + +func mediaJobsTableSQL(t *testing.T, database *Database) string { + t.Helper() + var sql string + if err := database.db.Raw("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", "media_jobs").Scan(&sql).Error; err != nil { + t.Fatal(err) + } + return sql +} diff --git a/backend/internal/infra/persistence/relational/settings_repository_test.go b/backend/internal/infra/persistence/relational/settings_repository_test.go index 5e30b7ef..5211a7df 100644 --- a/backend/internal/infra/persistence/relational/settings_repository_test.go +++ b/backend/internal/infra/persistence/relational/settings_repository_test.go @@ -38,7 +38,7 @@ func TestRuntimeSettingsRepositoryRoundTrip(t *testing.T) { MaxImageBytes: 16 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: 10 * time.Minute, }, - Routing: settingsdomain.RoutingConfig{StickyTTL: time.Hour, MaxAttempts: 3}, + Routing: settingsdomain.RoutingConfig{StickyTTL: time.Hour, MaxAttempts: 3, PreferFreeBuild: true}, } updatedAt, revision, err := repository.Save(ctx, settings, 0) if err != nil { diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 4eefdb44..0ab907f2 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -28,6 +28,7 @@ import ( type Config struct { BaseURL string + FallbackBaseURL string ClientVersion string ClientIdentifier string TokenAuth string @@ -36,15 +37,17 @@ type Config struct { // Adapter 实现 Grok Build CLI Responses、模型、Billing 与 OAuth 协议。 type Adapter struct { - cfgMu sync.RWMutex - cfg Config - http *http.Client - oauth *oauthClient - cipher *security.Cipher - base http.RoundTripper - agentID string - modelsMu sync.Mutex - modelsETags map[uint64]string + cfgMu sync.RWMutex + cfg Config + http *http.Client + oauth *oauthClient + cipher *security.Cipher + base http.RoundTripper + agentID string + modelsMu sync.Mutex + modelsETags map[uint64]string + fallbackMarker FallbackMarker + uploadIssuer VideoUploadIssuer } func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter { @@ -110,34 +113,39 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response return invalidResponsesResponse(err), nil } } - var bodyReader io.Reader - if len(body) > 0 { - bodyReader = bytes.NewReader(body) - } - requestCtx := infraegress.WithAccount(ctx, string(account.ProviderBuild), request.Credential.ID) - req, err := http.NewRequestWithContext(requestCtx, request.Method, a.url(request.Path), bodyReader) + // 推理回退:create/compact 可走 XAI;stored GET/DELETE 与未知路径始终主地址。 + base := a.apiBaseForOperation(ctx, request.Credential, request.Method, request.Path) + resp, reqURL, err := a.doResponseRequest(ctx, request, accessToken, body, base) if err != nil { return nil, err } - if err := a.applyHeaders(req, request.Credential, accessToken, request.Model, request.PromptCacheKey, true); err != nil { - return nil, err - } - if len(body) > 0 { - req.Header.Set("Content-Type", "application/json") - } - if request.Streaming { - req.Header.Set("Accept", "text/event-stream") - req.Header.Set("Accept-Encoding", "identity") - } else { - req.Header.Set("Accept", "application/json") - } - if request.IdempotencyID != "" { - req.Header.Set("Idempotency-Key", request.IdempotencyID) - } - resp, err := a.http.Do(req) - if err != nil { - return nil, err + // 未标记账号:仅可回退操作在主地址明确 403 时用等价请求探测 XAI。 + if a.shouldProbeXAIInferenceFallback(ctx, request.Credential, request.Method, request.Path, resp.StatusCode) { + // 缓冲主 403 正文,备用失败时原样回放,避免二次 primary POST。 + primaryBody, primaryTruncated, readErr := provider.ReadDiagnosticBody(resp.Body) + _ = resp.Body.Close() + if readErr != nil { + return nil, readErr + } + primaryResp := cloneBufferedResponse(resp, primaryBody, primaryTruncated) + fallbackBase := a.fallbackBaseURL() + if fallbackBase != "" && !strings.EqualFold(fallbackBase, base) { + fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(ctx, request, accessToken, body, fallbackBase) + if fallbackErr == nil && isHTTPSuccess(fallbackResp.StatusCode) { + a.activateBuildAPIFallback(ctx, &request.Credential) + resp, reqURL = fallbackResp, fallbackURL + } else { + if fallbackErr == nil { + _ = fallbackResp.Body.Close() + } + // 保留原 primary 403 的 URL 与缓冲正文,不再次请求主地址。 + resp = primaryResp + } + } else { + resp = primaryResp + } } + if err := normalizeGzipResponse(resp); err != nil { return nil, err } @@ -201,15 +209,47 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if diagnostic == nil { return nil, convertErr } - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: req.URL.String(), Diagnostic: diagnostic, ModelCatalogChanged: modelCatalogChanged}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: reqURL, Diagnostic: diagnostic, ModelCatalogChanged: modelCatalogChanged}, nil } resp.Body = io.NopCloser(bytes.NewReader(converted)) resp.Header.Set("Content-Length", strconv.Itoa(len(converted))) resp.Header.Set("Content-Type", "application/json") - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: req.URL.String(), Diagnostic: diagnostic, ModelCatalogChanged: modelCatalogChanged}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: diagnostic, ModelCatalogChanged: modelCatalogChanged}, nil } } - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: req.URL.String(), ModelCatalogChanged: modelCatalogChanged}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, ModelCatalogChanged: modelCatalogChanged}, nil +} + +func (a *Adapter) doResponseRequest(ctx context.Context, request provider.ResponseResourceRequest, accessToken string, body []byte, base string) (*http.Response, string, error) { + var bodyReader io.Reader + if len(body) > 0 { + bodyReader = bytes.NewReader(body) + } + requestCtx := infraegress.WithAccount(ctx, string(account.ProviderBuild), request.Credential.ID) + req, err := http.NewRequestWithContext(requestCtx, request.Method, a.urlWithBase(base, request.Path), bodyReader) + if err != nil { + return nil, "", err + } + if err := a.applyHeaders(req, request.Credential, accessToken, request.Model, request.PromptCacheKey, true); err != nil { + return nil, "", err + } + if len(body) > 0 { + req.Header.Set("Content-Type", "application/json") + } + if request.Streaming { + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Accept-Encoding", "identity") + } else { + req.Header.Set("Accept", "application/json") + } + if request.IdempotencyID != "" { + req.Header.Set("Idempotency-Key", request.IdempotencyID) + } + resp, err := a.http.Do(req) + if err != nil { + return nil, "", err + } + return resp, req.URL.String(), nil } // invalidResponsesResponse 将本地协议校验错误转换为标准 OpenAI 错误响应,避免触发上游账号重试。 @@ -253,28 +293,93 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) if err != nil { return nil, err } - requestCtx := infraegress.WithAccount(ctx, string(account.ProviderBuild), credential.ID) - req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, a.url("/models"), nil) + // Super 的 Build 与 XAI 模型资格一致,统一以 XAI 目录作为能力快照。 + // BuildAPIFallback 只记录实际推理地址状态,不得把同一批 Super 拆成两套模型能力。 + super, policyErr := a.buildXAIEntitled(ctx, credential.ID) + if policyErr != nil { + return nil, fmt.Errorf("查询 Build Super 资格: %w", policyErr) + } + if super { + models, xaiStatus, xaiErr := a.listModelsAt(ctx, credential, accessToken, a.fallbackBaseURL()) + if models != nil { + return models, nil + } + // Super 任一端可用即视为有效。XAI 目录失败时允许退回 Build 目录; + // 两端观察到的模型差异由共享 Super entitlement 在路由层统一。 + models, buildStatus, buildErr := a.listModelsAt(ctx, credential, accessToken, a.primaryBaseURL()) + if models != nil { + return models, nil + } + if xaiErr != nil || buildErr != nil { + return nil, fmt.Errorf("读取 Super 模型目录失败(XAI status=%d: %v;Build status=%d: %v)", xaiStatus, xaiErr, buildStatus, buildErr) + } + return nil, fmt.Errorf("上游模型接口返回 XAI %d,Build %d", xaiStatus, buildStatus) + } + + // Free/Unknown 仅访问 Build,禁止探测 XAI。 + models, status, err := a.listModelsAt(ctx, credential, accessToken, a.primaryBaseURL()) if err != nil { return nil, err } + if models != nil { + return models, nil + } + return nil, fmt.Errorf("上游模型接口返回 %d", status) +} + +// NormalizeAccountModelCapabilities 按 Super/paid Billing 归一化 1.5 视频资格。 +// Super 确保包含 grok-imagine-video-1.5;Free/Unknown 精确移除。不读取 BuildAPIFallback。 +func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing) []string { + paid := billing != nil && billing.IsPaid() + result := make([]string, 0, len(models)+1) + seen := make(map[string]struct{}, len(models)+1) + hasVideo15 := false + for _, model := range models { + model = strings.TrimSpace(model) + if model == "" { + continue + } + if _, exists := seen[model]; exists { + continue + } + if model == buildVideoModel { + if !paid { + continue + } + hasVideo15 = true + } + seen[model] = struct{}{} + result = append(result, model) + } + if paid && !hasVideo15 { + result = append(result, buildVideoModel) + } + return result +} + +func (a *Adapter) listModelsAt(ctx context.Context, credential account.Credential, accessToken, base string) ([]string, int, error) { + requestCtx := infraegress.WithAccount(ctx, string(account.ProviderBuild), credential.ID) + req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, a.urlWithBase(base, "/models"), nil) + if err != nil { + return nil, 0, err + } if err := a.applyHeaders(req, credential, accessToken, "", "", false); err != nil { - return nil, err + return nil, 0, err } resp, err := a.http.Do(req) if err != nil { - return nil, err + return nil, 0, err } if err := normalizeGzipResponse(resp); err != nil { - return nil, err + return nil, 0, err } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) if err != nil { - return nil, err + return nil, 0, err } if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("上游模型接口返回 %d", resp.StatusCode) + return nil, resp.StatusCode, nil } var payload struct { Data []struct { @@ -282,7 +387,7 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) } `json:"data"` } if err := json.Unmarshal(body, &payload); err != nil { - return nil, err + return nil, resp.StatusCode, err } models := make([]string, 0, len(payload.Data)) for _, item := range payload.Data { @@ -291,7 +396,7 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) } } a.recordModelsETag(credential.ID, resp.Header.Get("ETag")) - return models, nil + return models, resp.StatusCode, nil } func (a *Adapter) recordModelsETag(accountID uint64, etag string) { diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index a44594cc..89830738 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -206,6 +206,38 @@ func TestGetBillingUsesCreditsEndpointOnce(t *testing.T) { } } +func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { + adapter := &Adapter{} + // Super / paid:主 Build 仅返回 grok-4.5 时也必须补齐 1.5。 + got := adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", " ", "grok-4.5"}, &account.Billing{MonthlyLimit: 100}) + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { + t.Fatalf("super primary catalog = %#v", got) + } + // Super + fallback 目录已含 1.5:幂等去重,其它模型不变。 + got = adapter.NormalizeAccountModelCapabilities( + []string{"grok-4.5", buildVideoModel, "grok-code-fast-1", buildVideoModel}, + &account.Billing{OnDemandCap: 10}, + ) + if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != "grok-code-fast-1" { + t.Fatalf("super fallback catalog = %#v", got) + } + // Free:即使目录暴露 1.5 也必须移除。 + got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", buildVideoModel}, &account.Billing{Used: 1, PlanName: "free"}) + if len(got) != 1 || got[0] != "grok-4.5" { + t.Fatalf("free catalog = %#v", got) + } + // Unknown(无 Billing):与 Free 相同,移除 1.5。 + got = adapter.NormalizeAccountModelCapabilities([]string{buildVideoModel, "grok-4.5"}, nil) + if len(got) != 1 || got[0] != "grok-4.5" { + t.Fatalf("unknown catalog = %#v", got) + } + // 不得依赖 BuildAPIFallback;空目录 + Super 仅补 1.5。 + got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{CreditUsagePercent: 1}) + if len(got) != 1 || got[0] != buildVideoModel { + t.Fatalf("super empty catalog = %#v", got) + } +} + func TestGrokSessionIDFollowsConversationIdentity(t *testing.T) { explicit := "019f6b02-5bae-7cf3-b26e-73e85c861749" if value, err := grokSessionID(explicit); err != nil || value != explicit { diff --git a/backend/internal/infra/provider/cli/definition.go b/backend/internal/infra/provider/cli/definition.go index 6ebafff1..da0648f5 100644 --- a/backend/internal/infra/provider/cli/definition.go +++ b/backend/internal/infra/provider/cli/definition.go @@ -12,7 +12,7 @@ func (a *Adapter) Definition() provider.Definition { Provider: account.ProviderBuild, ModelNamespace: account.ProviderBuild.ModelNamespace(), ModelCatalog: provider.ModelCatalogRemote, - ModelCapabilities: []modeldomain.Capability{modeldomain.CapabilityResponses}, + ModelCapabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityVideo}, Quota: provider.QuotaBilling, Credential: provider.CredentialSurface{ AuthType: account.AuthTypeOAuth, Import: true, Refresh: true, DeviceOAuth: true, @@ -20,6 +20,7 @@ func (a *Adapter) Definition() provider.Definition { Conversation: provider.ConversationSurface{ Responses: true, ChatCompletions: true, Messages: true, Compact: true, StoredResponses: true, }, + Media: provider.MediaSurface{VideoGeneration: true}, Inference: provider.InferencePolicy{Usage: provider.UsageUpstream}, } } diff --git a/backend/internal/infra/provider/cli/fallback.go b/backend/internal/infra/provider/cli/fallback.go new file mode 100644 index 00000000..e7502eeb --- /dev/null +++ b/backend/internal/infra/provider/cli/fallback.go @@ -0,0 +1,211 @@ +package cli + +import ( + "bytes" + "context" + "io" + "log/slog" + "net/http" + "strconv" + "strings" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/infra/config" +) + +// FallbackMarker 同时提供 Build XAI 回退资格判定与回退标记持久化。 +// XAI 仅接受 Super 账号;资格查询失败时 Adapter 必须 fail closed。 +type FallbackMarker interface { + CanUseBuildAPIFallback(ctx context.Context, accountID uint64) (bool, error) + MarkBuildAPIFallback(ctx context.Context, accountID uint64, enabled bool) error +} + +// VideoUploadIssuer 为 XAI ZDR 视频签发一次性 PUT 接收地址并等待本地资产就绪。 +type VideoUploadIssuer interface { + // IssueVideoUpload 返回可被 xAI HTTPS PUT 的 URL 与绑定的本地 assetID。 + // 不得在错误信息中回显完整 URL 或票据明文。 + IssueVideoUpload(ctx context.Context, jobID string) (uploadURL, assetID string, err error) + // WaitVideoUpload 在上游任务完成后等待本地 PUT 资产就绪。 + WaitVideoUpload(ctx context.Context, assetID string) (contentType string, err error) +} + +func (a *Adapter) SetFallbackMarker(marker FallbackMarker) { + a.cfgMu.Lock() + a.fallbackMarker = marker + a.cfgMu.Unlock() +} + +func (a *Adapter) SetVideoUploadIssuer(issuer VideoUploadIssuer) { + a.cfgMu.Lock() + a.uploadIssuer = issuer + a.cfgMu.Unlock() +} + +func (a *Adapter) fallbackMarkerRef() FallbackMarker { + a.cfgMu.RLock() + defer a.cfgMu.RUnlock() + return a.fallbackMarker +} + +func (a *Adapter) uploadIssuerRef() VideoUploadIssuer { + a.cfgMu.RLock() + defer a.cfgMu.RUnlock() + return a.uploadIssuer +} + +func (a *Adapter) primaryBaseURL() string { + return strings.TrimRight(strings.TrimSpace(a.config().BaseURL), "/") +} + +func (a *Adapter) fallbackBaseURL() string { + return strings.TrimRight(config.NormalizeBuildFallbackBaseURL(a.config().FallbackBaseURL), "/") +} + +// isXAIInferenceFallbackCapable 判断该 Build API 操作是否可走 XAI 推理回退。 +// 生产探针(账号 954 / api.x.ai/v1)已验证: +// +// 支持:GET /models、POST /responses、POST /responses/compact、视频 create/poll +// 不支持:GET/DELETE /responses/{id}、GET /billing(404);Billing 主地址 403 不得改写为 XAI 404 +// +// OAuth 认证端点始终使用独立认证 host,不受此函数影响。 +func isXAIInferenceFallbackCapable(method, path string) bool { + method = strings.ToUpper(strings.TrimSpace(method)) + path = normalizeBuildAPIPath(path) + switch { + case method == http.MethodGet && path == "/models": + return true + case method == http.MethodPost && path == "/responses": + // Responses create 与 Chat/Messages 兼容转发均走 POST /responses。 + return true + case method == http.MethodPost && path == "/responses/compact": + return true + case method == http.MethodPost && path == "/videos/generations": + return true + case method == http.MethodGet && strings.HasPrefix(path, "/videos/") && path != "/videos" && path != "/videos/generations": + // 视频任务轮询:GET /videos/{id} + return true + default: + // Billing、stored-resource GET/DELETE、未知路径:仅主地址。 + return false + } +} + +func normalizeBuildAPIPath(path string) string { + path = strings.TrimSpace(path) + if path == "" { + return "/" + } + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + if i := strings.IndexByte(path, '?'); i >= 0 { + path = path[:i] + } + if len(path) > 1 { + path = strings.TrimRight(path, "/") + } + return path +} + +// apiBaseForOperation 按操作与实时 Billing 资格选择 Build API 根地址。 +// 旧数据即使误标 BuildAPIFallback,Free/Unknown 账号也始终走主地址。 +func (a *Adapter) apiBaseForOperation(ctx context.Context, credential account.Credential, method, path string) string { + if credential.BuildAPIFallback && isXAIInferenceFallbackCapable(method, path) && a.canUseBuildAPIFallback(ctx, credential.ID) { + return a.fallbackBaseURL() + } + return a.primaryBaseURL() +} + +// shouldProbeXAIInferenceFallback 仅允许已确认 Super 的未标记账号在主地址 403 后探测 XAI。 +func (a *Adapter) shouldProbeXAIInferenceFallback(ctx context.Context, credential account.Credential, method, path string, primaryStatus int) bool { + return !credential.BuildAPIFallback && isHTTPForbidden(primaryStatus) && isXAIInferenceFallbackCapable(method, path) && a.canUseBuildAPIFallback(ctx, credential.ID) +} + +func (a *Adapter) canUseBuildAPIFallback(ctx context.Context, accountID uint64) bool { + allowed, err := a.buildXAIEntitled(ctx, accountID) + if err != nil { + slog.Warn("build_api_fallback_policy_failed", "account_id", accountID, "error", err.Error()) + return false + } + return allowed +} + +// buildXAIEntitled 返回账号是否具备 XAI 能力。调用方自行决定策略查询失败时 +// 是对推理 fail closed,还是让模型同步失败以保留上一份完整能力快照。 +func (a *Adapter) buildXAIEntitled(ctx context.Context, accountID uint64) (bool, error) { + marker := a.fallbackMarkerRef() + if marker == nil || accountID == 0 { + return false, nil + } + allowed, err := marker.CanUseBuildAPIFallback(ctx, accountID) + if err != nil { + return false, err + } + return allowed, nil +} + +func (a *Adapter) urlWithBase(base, path string) string { + return strings.TrimRight(base, "/") + "/" + strings.TrimLeft(path, "/") +} + +// activateBuildAPIFallback 在 XAI 推理回退成功后幂等标记账号;标记失败不撤销当前成功结果。 +// 仅应在可回退操作(models / responses create|compact / video)成功后调用,不得由 Billing 或 stored-resource 触发。 +func (a *Adapter) activateBuildAPIFallback(ctx context.Context, credential *account.Credential) { + if credential == nil || credential.ID == 0 || credential.BuildAPIFallback { + return + } + credential.BuildAPIFallback = true + marker := a.fallbackMarkerRef() + if marker == nil { + slog.Error("build_api_fallback_mark_skipped", "account_id", credential.ID, "reason", "marker_unavailable") + return + } + if err := marker.MarkBuildAPIFallback(ctx, credential.ID, true); err != nil { + // 不含 token;仅记录账号与错误类型,便于后续幂等重写。 + slog.Error("build_api_fallback_mark_failed", "account_id", credential.ID, "error", err.Error()) + } +} + +func isHTTPForbidden(status int) bool { + return status == http.StatusForbidden +} + +func isHTTPSuccess(status int) bool { + return status >= 200 && status < 300 +} + +// cloneBufferedResponse 用已读取的正文重建可再次消费的 HTTP 响应,保留状态与头。 +func cloneBufferedResponse(source *http.Response, body []byte, truncated bool) *http.Response { + if source == nil { + return &http.Response{ + StatusCode: http.StatusForbidden, + Status: "403 Forbidden", + Header: make(http.Header), + Body: io.NopCloser(bytes.NewReader(body)), + ContentLength: int64(len(body)), + } + } + header := source.Header.Clone() + if header == nil { + header = make(http.Header) + } + if truncated { + header.Set("X-Grok2API-Body-Truncated", "1") + } + header.Set("Content-Length", strconv.Itoa(len(body))) + return &http.Response{ + StatusCode: source.StatusCode, + Status: source.Status, + Proto: source.Proto, + ProtoMajor: source.ProtoMajor, + ProtoMinor: source.ProtoMinor, + Header: header, + Body: io.NopCloser(bytes.NewReader(body)), + ContentLength: int64(len(body)), + TransferEncoding: append([]string(nil), source.TransferEncoding...), + Uncompressed: source.Uncompressed, + Trailer: source.Trailer.Clone(), + Request: source.Request, + TLS: source.TLS, + } +} diff --git a/backend/internal/infra/provider/cli/fallback_test.go b/backend/internal/infra/provider/cli/fallback_test.go new file mode 100644 index 00000000..3596ff8e --- /dev/null +++ b/backend/internal/infra/provider/cli/fallback_test.go @@ -0,0 +1,759 @@ +package cli + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/security" +) + +type fallbackMarkerStub struct { + calls atomic.Int32 + policyCalls atomic.Int32 + err error + policyErr error + denied bool +} + +func (m *fallbackMarkerStub) CanUseBuildAPIFallback(ctx context.Context, accountID uint64) (bool, error) { + m.policyCalls.Add(1) + if m.policyErr != nil { + return false, m.policyErr + } + return !m.denied, nil +} + +func (m *fallbackMarkerStub) MarkBuildAPIFallback(ctx context.Context, accountID uint64, enabled bool) error { + m.calls.Add(1) + return m.err +} + +func TestForwardResponsePrimarySuccessDoesNotProbeFallback(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var hits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + hits.Add(1) + if !strings.Contains(request.URL.Host, "primary.test") { + t.Fatalf("unexpected host %s", request.URL.Host) + } + return jsonResponse(http.StatusOK, `{"id":"resp_1","output":[]}`, request), nil + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 9, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Body: []byte(`{"model":"grok-4.5","input":"hi"}`), + Model: "grok-4.5", NormalizeBody: false, + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + t.Fatalf("status = %d", response.StatusCode) + } + if hits.Load() != 1 { + t.Fatalf("hits = %d, want 1", hits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("marker calls = %d", marker.calls.Load()) + } +} + +func TestForwardResponsePrimary403Fallback200Activates(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":{"message":"forbidden"}}`, request), nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + return jsonResponse(http.StatusOK, `{"id":"resp_ok","output":[]}`, request), nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + credential := account.Credential{ID: 11, EncryptedAccessToken: encrypted} + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: credential, Method: http.MethodPost, Path: "/responses", + Body: []byte(`{"model":"grok-4.5","input":"hi"}`), Model: "grok-4.5", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + t.Fatalf("status = %d", response.StatusCode) + } + if !strings.Contains(response.UpstreamURL, "xai.test") { + t.Fatalf("upstream = %s", response.UpstreamURL) + } + if primaryHits.Load() < 1 || fallbackHits.Load() != 1 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if marker.calls.Load() != 1 { + t.Fatalf("marker calls = %d", marker.calls.Load()) + } +} + +func TestForwardResponseFree403NeverUsesXAI(t *testing.T) { + for _, tc := range []struct { + name string + marked bool + marker *fallbackMarkerStub + }{ + {name: "unmarked free", marker: &fallbackMarkerStub{denied: true}}, + {name: "marked free", marked: true, marker: &fallbackMarkerStub{denied: true}}, + {name: "policy lookup failure", marker: &fallbackMarkerStub{policyErr: context.DeadlineExceeded}}, + } { + t.Run(tc.name, func(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + adapter.SetFallbackMarker(tc.marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if strings.Contains(request.URL.Host, "xai.test") { + fallbackHits.Add(1) + t.Fatalf("Free account must never hit XAI") + } + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":{"message":"primary forbidden"}}`, request), nil + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 111, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildAPIFallback: tc.marked}, + Method: http.MethodPost, Path: "/responses", Body: []byte(`{"model":"grok-4.5","input":"hi"}`), Model: "grok-4.5", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusForbidden || primaryHits.Load() != 1 || fallbackHits.Load() != 0 { + t.Fatalf("status=%d primary=%d fallback=%d", response.StatusCode, primaryHits.Load(), fallbackHits.Load()) + } + if tc.marker.policyCalls.Load() != 1 || tc.marker.calls.Load() != 0 { + t.Fatalf("policy=%d mark=%d", tc.marker.policyCalls.Load(), tc.marker.calls.Load()) + } + }) + } +} + +func TestForwardResponsePrimary403FallbackFailKeepsPrimaryError(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + return jsonResponse(http.StatusBadGateway, `{"error":"xai down"}`, request), nil + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":{"message":"primary forbidden"}}`, request), nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 12, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", + Body: []byte(`{"model":"grok-4.5","input":"hi"}`), Model: "grok-4.5", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusForbidden { + t.Fatalf("status = %d, want 403", response.StatusCode) + } + body, _ := io.ReadAll(response.Body) + if !strings.Contains(string(body), "primary forbidden") { + t.Fatalf("body = %s", body) + } + // 主 403 缓冲回放:仅一次 primary POST + 一次 fallback,不得二次 primary。 + if primaryHits.Load() != 1 { + t.Fatalf("primary hits = %d, want 1 (no replay)", primaryHits.Load()) + } + if fallbackHits.Load() != 1 { + t.Fatalf("fallback hits = %d, want 1", fallbackHits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("must not mark on fallback failure, calls=%d", marker.calls.Load()) + } +} + +func TestForwardResponseMarkedAccountCreateUsesFallbackDirectly(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + t.Fatalf("marked create must not hit primary, path=%s", request.URL.Path) + return nil, nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + if request.Method != http.MethodPost || !strings.HasSuffix(request.URL.Path, "/responses") { + t.Fatalf("unexpected request %s %s", request.Method, request.URL.Path) + } + return jsonResponse(http.StatusOK, `{"id":"ok"}`, request), nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 13, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildAPIFallback: true}, + Method: http.MethodPost, Path: "/responses", + Body: []byte(`{"model":"grok-4.5","input":"hi"}`), Model: "grok-4.5", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if primaryHits.Load() != 0 || fallbackHits.Load() != 1 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("already marked account should not re-mark") + } +} + +func TestForwardResponseMarkedAccountCompactUsesFallbackDirectly(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + adapter.SetFallbackMarker(&fallbackMarkerStub{}) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + t.Fatalf("marked compact must not hit primary") + return nil, nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + if request.Method != http.MethodPost || !strings.HasSuffix(request.URL.Path, "/responses/compact") { + t.Fatalf("unexpected %s %s", request.Method, request.URL.Path) + } + return jsonResponse(http.StatusOK, `{"id":"compacted"}`, request), nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 130, EncryptedAccessToken: encrypted, BuildAPIFallback: true}, + Method: http.MethodPost, Path: "/responses/compact", + Body: []byte(`{"model":"grok-4.5","response_id":"resp_1"}`), Model: "grok-4.5", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if primaryHits.Load() != 0 || fallbackHits.Load() != 1 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } +} + +func TestForwardResponseMarkedAccountStoredResourceStaysPrimary(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + for _, tc := range []struct { + method string + path string + }{ + {http.MethodGet, "/responses/resp_1"}, + {http.MethodDelete, "/responses/resp_1"}, + } { + t.Run(tc.method, func(t *testing.T) { + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + return jsonResponse(http.StatusOK, `{"id":"resp_1"}`, request), nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + t.Fatalf("stored resource must not hit XAI") + return nil, nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 131, EncryptedAccessToken: encrypted, BuildAPIFallback: true}, + Method: tc.method, Path: tc.path, + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if primaryHits.Load() != 1 || fallbackHits.Load() != 0 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("marker calls = %d", marker.calls.Load()) + } + }) + } +} + +func TestForwardResponseUnmarkedStoredResource403DoesNotProbe(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + for _, tc := range []struct { + method string + path string + }{ + {http.MethodGet, "/responses/resp_1"}, + {http.MethodDelete, "/responses/resp_1"}, + } { + t.Run(tc.method, func(t *testing.T) { + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":{"message":"primary forbidden"}}`, request), nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + return jsonResponse(http.StatusOK, `{"id":"should-not"}`, request), nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 132, EncryptedAccessToken: encrypted}, + Method: tc.method, Path: tc.path, + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusForbidden { + t.Fatalf("status = %d, want 403", response.StatusCode) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 0 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("must not mark, calls=%d", marker.calls.Load()) + } + }) + } +} + +func TestGetBillingAlwaysPrimaryEvenWhenMarked(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + if !strings.Contains(request.URL.Path, "/billing") { + t.Fatalf("path = %s", request.URL.Path) + } + // 上游 v3.0.2 Billing 仅请求 format=credits,且始终主地址。 + if request.URL.RawQuery != "format=credits" { + t.Fatalf("query = %q, want format=credits", request.URL.RawQuery) + } + return jsonResponse(http.StatusOK, `{"config":{"onDemandCap":{"val":10},"onDemandUsed":{"val":1},"monthlyLimit":{"val":100},"used":{"val":5}}}`, request), nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + t.Fatalf("billing must never hit XAI") + return nil, nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + billing, err := adapter.GetBilling(context.Background(), account.Credential{ + ID: 140, EncryptedAccessToken: encrypted, BuildAPIFallback: true, + }) + if err != nil { + t.Fatal(err) + } + if billing.OnDemandCap != 10 || billing.OnDemandUsed != 1 { + t.Fatalf("billing = %+v", billing) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 0 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("marker calls = %d", marker.calls.Load()) + } +} + +func TestGetBillingPrimary403NeverProbesXAI(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case strings.Contains(request.URL.Host, "primary.test"): + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":"billing forbidden"}`, request), nil + case strings.Contains(request.URL.Host, "xai.test"): + fallbackHits.Add(1) + return jsonResponse(http.StatusOK, `{"config":{"monthlyLimit":{"val":1}}}`, request), nil + default: + t.Fatalf("unexpected host %s", request.URL.Host) + return nil, nil + } + }) + _, err := adapter.GetBilling(context.Background(), account.Credential{ + ID: 141, EncryptedAccessToken: encrypted, BuildAPIFallback: false, + }) + if err == nil { + t.Fatal("expected billing error") + } + if !strings.Contains(err.Error(), "403") { + t.Fatalf("err = %v", err) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 0 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("must not mark from billing 403, calls=%d", marker.calls.Load()) + } +} + +func TestIsXAIInferenceFallbackCapable(t *testing.T) { + capable := []struct{ method, path string }{ + {http.MethodGet, "/models"}, + {http.MethodPost, "/responses"}, + {http.MethodPost, "/responses/compact"}, + {http.MethodPost, "responses"}, + {http.MethodPost, "/videos/generations"}, + {http.MethodGet, "/videos/job_1"}, + } + for _, tc := range capable { + if !isXAIInferenceFallbackCapable(tc.method, tc.path) { + t.Fatalf("want capable: %s %s", tc.method, tc.path) + } + } + notCapable := []struct{ method, path string }{ + {http.MethodGet, "/responses/resp_1"}, + {http.MethodDelete, "/responses/resp_1"}, + {http.MethodGet, "/billing"}, + {http.MethodGet, "/billing?format=credits"}, + {http.MethodPost, "/unknown"}, + {http.MethodGet, "/responses"}, + } + for _, tc := range notCapable { + if isXAIInferenceFallbackCapable(tc.method, tc.path) { + t.Fatalf("want primary-only: %s %s", tc.method, tc.path) + } + } +} + +func TestListModelsSuperUsesUnifiedXAICatalog(t *testing.T) { + for _, marked := range []bool{false, true} { + t.Run(fmt.Sprintf("fallback_marked=%t", marked), func(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if strings.Contains(request.URL.Host, "primary.test") { + primaryHits.Add(1) + t.Fatalf("Super model catalog must not depend on the primary Build endpoint") + } + fallbackHits.Add(1) + return jsonResponse(http.StatusOK, `{"data":[{"id":"grok-4.5"},{"id":"grok-imagine-video"}]}`, request), nil + }) + models, err := adapter.ListModels(context.Background(), account.Credential{ID: 14, EncryptedAccessToken: encrypted, BuildAPIFallback: marked}) + if err != nil { + t.Fatal(err) + } + if len(models) != 2 || models[0] != "grok-4.5" || models[1] != "grok-imagine-video" { + t.Fatalf("models = %#v", models) + } + if primaryHits.Load() != 0 || fallbackHits.Load() != 1 || marker.policyCalls.Load() != 1 { + t.Fatalf("primary=%d fallback=%d policy=%d", primaryHits.Load(), fallbackHits.Load(), marker.policyCalls.Load()) + } + if marker.calls.Load() != 0 { + t.Fatalf("catalog sync must not change fallback state, calls=%d", marker.calls.Load()) + } + }) + } +} + +func TestListModelsSuperAcceptsPrimaryWhenXAICatalogIsForbidden(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if strings.Contains(request.URL.Host, "xai.test") { + fallbackHits.Add(1) + return jsonResponse(http.StatusForbidden, `{}`, request), nil + } + primaryHits.Add(1) + return jsonResponse(http.StatusOK, `{"data":[{"id":"grok-4.5"}]}`, request), nil + }) + models, err := adapter.ListModels(context.Background(), account.Credential{ID: 15, EncryptedAccessToken: encrypted}) + if err != nil { + t.Fatal(err) + } + if len(models) != 1 || models[0] != "grok-4.5" { + t.Fatalf("models = %#v", models) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 1 || marker.policyCalls.Load() != 1 || marker.calls.Load() != 0 { + t.Fatalf("primary=%d fallback=%d policy=%d marks=%d", primaryHits.Load(), fallbackHits.Load(), marker.policyCalls.Load(), marker.calls.Load()) + } +} + +func TestListModelsFree403NeverUsesXAI(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{denied: true} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if strings.Contains(request.URL.Host, "xai.test") { + fallbackHits.Add(1) + t.Fatalf("Free account models must never hit XAI") + } + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{}`, request), nil + }) + _, err := adapter.ListModels(context.Background(), account.Credential{ID: 114, EncryptedAccessToken: encrypted, BuildAPIFallback: true}) + if err == nil || !strings.Contains(err.Error(), "403") { + t.Fatalf("err = %v", err) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 0 || marker.policyCalls.Load() != 1 { + t.Fatalf("primary=%d fallback=%d policy=%d", primaryHits.Load(), fallbackHits.Load(), marker.policyCalls.Load()) + } +} + +func TestListModelsPolicyFailureDoesNotUsePartialPrimaryCatalog(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{policyErr: context.DeadlineExceeded} + adapter.SetFallbackMarker(marker) + var hits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + hits.Add(1) + t.Fatalf("policy failure must preserve the previous catalog without an upstream request") + return nil, nil + }) + _, err := adapter.ListModels(context.Background(), account.Credential{ID: 115, EncryptedAccessToken: encrypted}) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v", err) + } + if hits.Load() != 0 || marker.policyCalls.Load() != 1 { + t.Fatalf("hits=%d policy=%d", hits.Load(), marker.policyCalls.Load()) + } +} + +func TestGenerateVideoFallbackInjectsUploadURL(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{} + adapter.SetFallbackMarker(marker) + issuer := &uploadIssuerStub{url: "https://public.example/v1/media/uploads/aabb", assetID: "vid_test"} + adapter.SetVideoUploadIssuer(issuer) + var createPayload map[string]any + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.Method == http.MethodPost { + if strings.Contains(request.URL.Host, "primary.test") { + return jsonResponse(http.StatusForbidden, `{"error":"forbidden"}`, request), nil + } + _ = json.NewDecoder(request.Body).Decode(&createPayload) + return jsonResponse(http.StatusOK, `{"request_id":"job_1"}`, request), nil + } + return jsonResponse(http.StatusOK, `{"status":"done"}`, request), nil + }) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 15, EncryptedAccessToken: encrypted}, + JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", + }) + if err != nil { + t.Fatal(err) + } + if result.AssetID != "vid_test" { + t.Fatalf("asset = %s", result.AssetID) + } + output, _ := createPayload["output"].(map[string]any) + if output["upload_url"] != issuer.url { + t.Fatalf("payload = %#v", createPayload) + } + if marker.calls.Load() != 1 { + t.Fatalf("marker = %d", marker.calls.Load()) + } +} + +func TestGenerateVideoFree403NeverUsesXAI(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{denied: true} + adapter.SetFallbackMarker(marker) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if strings.Contains(request.URL.Host, "xai.test") { + fallbackHits.Add(1) + t.Fatalf("Free account video must never hit XAI") + } + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":"forbidden"}`, request), nil + }) + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 115, EncryptedAccessToken: encrypted, BuildAPIFallback: true}, + JobID: "video_free", Prompt: "waves", Duration: 6, Resolution: "720p", + }) + if err == nil { + t.Fatal("expected primary 403") + } + status, ok := provider.ErrorHTTPStatus(err) + if !ok || status != http.StatusForbidden { + t.Fatalf("status=%d ok=%v err=%v", status, ok, err) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 0 || marker.policyCalls.Load() != 1 { + t.Fatalf("primary=%d fallback=%d policy=%d", primaryHits.Load(), fallbackHits.Load(), marker.policyCalls.Load()) + } +} + +func TestGenerateVideoFallbackMalformedJobIDDoesNotActivate(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + // 追踪本地置位:activateBuildAPIFallback 在写库前会先把 credential.BuildAPIFallback 设为 true。 + tracking := &trackingFallbackMarker{} + adapter.SetFallbackMarker(tracking) + issuer := &uploadIssuerStub{url: "https://public.example/v1/media/uploads/ccdd", assetID: "vid_bad"} + adapter.SetVideoUploadIssuer(issuer) + var primaryHits, fallbackHits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.Method != http.MethodPost { + t.Fatalf("unexpected method %s", request.Method) + } + if strings.Contains(request.URL.Host, "primary.test") { + primaryHits.Add(1) + return jsonResponse(http.StatusForbidden, `{"error":"forbidden"}`, request), nil + } + fallbackHits.Add(1) + // 2xx 但缺少 request_id / id:不得激活降级。 + return jsonResponse(http.StatusOK, `{"status":"queued","message":"accepted"}`, request), nil + }) + cred := account.Credential{ID: 16, EncryptedAccessToken: encrypted, BuildAPIFallback: false} + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: cred, JobID: "video_job_bad", Prompt: "waves", Duration: 6, Resolution: "720p", + }) + if err == nil { + t.Fatal("expected parse error for missing job id") + } + if !strings.Contains(err.Error(), "request_id") { + t.Fatalf("err = %v", err) + } + if primaryHits.Load() != 1 || fallbackHits.Load() != 1 { + t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load()) + } + if tracking.calls.Load() != 0 { + t.Fatalf("must not persist fallback mark, calls=%d", tracking.calls.Load()) + } + if tracking.activateSeen.Load() { + t.Fatal("must not call activate/local-set path on malformed create response") + } + if cred.BuildAPIFallback { + t.Fatal("caller credential must remain unmarked") + } +} + +// trackingFallbackMarker 记录 Mark 调用;activate 路径必定会调用 Mark(marker 非 nil)。 +type trackingFallbackMarker struct { + calls atomic.Int32 + activateSeen atomic.Bool + err error +} + +func (m *trackingFallbackMarker) CanUseBuildAPIFallback(ctx context.Context, accountID uint64) (bool, error) { + return true, nil +} + +func (m *trackingFallbackMarker) MarkBuildAPIFallback(ctx context.Context, accountID uint64, enabled bool) error { + m.calls.Add(1) + if enabled { + m.activateSeen.Store(true) + } + return m.err +} + +type uploadIssuerStub struct { + url, assetID string + waitCalls atomic.Int32 +} + +func (u *uploadIssuerStub) IssueVideoUpload(ctx context.Context, jobID string) (string, string, error) { + return u.url, u.assetID, nil +} + +func (u *uploadIssuerStub) WaitVideoUpload(ctx context.Context, assetID string) (string, error) { + u.waitCalls.Add(1) + return "video/mp4", nil +} + +func newFallbackTestAdapter(t *testing.T) (*Adapter, string) { + t.Helper() + key := make([]byte, 32) + for i := range key { + key[i] = byte(i + 1) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(key)) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{ + BaseURL: "https://primary.test/v1", FallbackBaseURL: "https://xai.test/v1", + ClientVersion: "0.2.99", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", + UserAgent: "test-agent", + }, cipher) + return adapter, encrypted +} + +func TestFallbackMarkerFailureStillReturnsSuccess(t *testing.T) { + adapter, encrypted := newFallbackTestAdapter(t) + marker := &fallbackMarkerStub{err: context.DeadlineExceeded} + adapter.SetFallbackMarker(marker) + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if strings.Contains(request.URL.Host, "primary.test") { + return jsonResponse(http.StatusForbidden, `{}`, request), nil + } + return jsonResponse(http.StatusOK, `{"id":"ok"}`, request), nil + }) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 99, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Body: []byte(`{"model":"x","input":"y"}`), Model: "x", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + t.Fatalf("status = %d", response.StatusCode) + } + if marker.calls.Load() != 1 { + t.Fatalf("marker should still be attempted") + } +} diff --git a/backend/internal/infra/provider/cli/video.go b/backend/internal/infra/provider/cli/video.go new file mode 100644 index 00000000..ca77b3a1 --- /dev/null +++ b/backend/internal/infra/provider/cli/video.go @@ -0,0 +1,539 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +const ( + buildVideoModel = "grok-imagine-video-1.5" + buildVideoMaxImages = 1 + buildVideoPollEvery = 2 * time.Second + buildVideoMaxBodySize = 2 << 20 + buildVideoErrorSummaryLimit = 256 + buildVideoErrorMessageLimit = 160 +) + +// mediaUploadSecretPattern 匹配上传路径及其中的 64-hex 一次性 token(含完整 URL 前缀)。 +var mediaUploadSecretPattern = regexp.MustCompile(`(?i)(?:https?://[^\s"'\\<>]+)?/v1/media/uploads/[0-9a-f]{64}`) + +// bareUploadTokenPattern 匹配无路径前缀的 64-hex 上传 token(上游可能仅回显 token 本身)。 +var bareUploadTokenPattern = regexp.MustCompile(`(?i)\b[0-9a-f]{64}\b`) + +// videoUpstreamError 是上游非 2xx 的可分类错误:保留 HTTP 状态,摘要经密钥脱敏且长度有界。 +// 不得将原始响应体写入 Error(),避免 upload_url / token 泄漏到 media_jobs.error_message、日志或审计。 +type videoUpstreamError struct { + status int + summary string +} + +func (e *videoUpstreamError) Error() string { + if e == nil { + return "" + } + return e.summary +} + +func (e *videoUpstreamError) HTTPStatusCode() int { + if e == nil { + return 0 + } + return e.status +} + +// newVideoUpstreamError 从上游响应构造密钥安全、有界的错误摘要。 +func newVideoUpstreamError(status int, body []byte) *videoUpstreamError { + return &videoUpstreamError{status: status, summary: summarizeVideoUpstreamError(status, body)} +} + +func summarizeVideoUpstreamError(status int, body []byte) string { + code, message := extractVideoUpstreamErrorFields(body) + parts := []string{fmt.Sprintf("Build 视频上游返回 %d", status)} + if code != "" { + parts = append(parts, code) + } + if message != "" { + parts = append(parts, message) + } else if code == "" { + // 非结构化正文:仅作有界、脱敏片段,避免整包原文进入错误链。 + if snippet := redactVideoUploadSecrets(strings.TrimSpace(string(body))); snippet != "" { + parts = append(parts, boundDiagnosticText(snippet, buildVideoErrorMessageLimit)) + } + } + return boundDiagnosticText(strings.Join(parts, ": "), buildVideoErrorSummaryLimit) +} + +func extractVideoUpstreamErrorFields(body []byte) (code, message string) { + body = bytes.TrimSpace(body) + if len(body) == 0 || body[0] != '{' { + return "", "" + } + var root map[string]any + if err := json.Unmarshal(body, &root); err != nil { + return "", "" + } + if errObj, ok := root["error"].(map[string]any); ok { + code = firstString(errObj, "code", "type", "error") + message = firstString(errObj, "message", "error", "detail") + } + if code == "" { + code = firstString(root, "code", "error_code", "type") + } + if message == "" { + message = firstString(root, "message", "error_message", "detail") + } + if code != "" { + code = boundDiagnosticText(redactVideoUploadSecrets(strings.TrimSpace(code)), 64) + } + if message != "" { + message = safeVideoDiagnosticMessage(message) + } + return code, message +} + +func redactVideoUploadSecrets(value string) string { + if value == "" { + return value + } + // 先替换完整 upload 路径,再替换残留的裸 64-hex token。 + value = mediaUploadSecretPattern.ReplaceAllString(value, "/v1/media/uploads/[REDACTED]") + value = bareUploadTokenPattern.ReplaceAllString(value, "[REDACTED]") + return value +} + +// safeVideoDiagnosticMessage 对上游派生的 code/message 做密钥脱敏与长度有界处理。 +// 用于非 2xx 摘要以及 2xx JSON 中的 error.message 等字段,避免 upload token 进入错误链。 +func safeVideoDiagnosticMessage(message string) string { + return boundDiagnosticText(redactVideoUploadSecrets(strings.TrimSpace(message)), buildVideoErrorMessageLimit) +} + +func boundDiagnosticText(value string, limit int) string { + if limit <= 0 || value == "" { + return "" + } + if len(value) <= limit { + return value + } + for limit > 0 && !utf8.ValidString(value[:limit]) { + limit-- + } + return value[:limit] +} + +// GenerateVideo 通过 Build OAuth 固定模型 grok-imagine-video-1.5 创建并轮询视频任务。 +// 最多 1 张首图;多于 1 张在调用上游前失败,不静默截断。 +// 主地址不注入 output.upload_url;仅在已标记 XAI 推理回退或主 403 后探测 XAI 时签发 PUT 地址。 +func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { + if len(request.ReferenceURLs) > buildVideoMaxImages { + return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + } + accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) + if err != nil { + return provider.VideoResult{}, err + } + credential := request.Credential + if credential.BuildAPIFallback { + if a.canUseBuildAPIFallback(ctx, credential.ID) { + return a.generateVideoOnBase(ctx, request, credential, accessToken, a.fallbackBaseURL(), true) + } + } + // 未标记:先走主地址,不添加 upload_url。 + primaryBase := a.primaryBaseURL() + payload, err := buildVideoCreatePayload(request, "") + if err != nil { + return provider.VideoResult{}, err + } + body, err := json.Marshal(payload) + if err != nil { + return provider.VideoResult{}, err + } + createResp, createErr := a.doVideoJSON(ctx, credential, accessToken, http.MethodPost, primaryBase, "/videos/generations", body, true) + if createErr == nil { + jobID, parseErr := parseVideoCreateResponse(createResp) + if parseErr != nil { + return provider.VideoResult{}, parseErr + } + if request.Progress != nil { + request.Progress(1) + } + return a.pollVideoJob(ctx, credential, accessToken, primaryBase, jobID, "", request.Progress) + } + var upstream *videoUpstreamError + if !asVideoUpstreamError(createErr, &upstream) || !isHTTPForbidden(upstream.status) { + return provider.VideoResult{}, createErr + } + // Free/Unknown 的主 403 直接返回;仅 Super 可签发 upload_url 后探测 XAI。 + if credential.BuildAPIFallback || !a.canUseBuildAPIFallback(ctx, credential.ID) { + return provider.VideoResult{}, createErr + } + // 主 403:签发 upload_url 后探测 XAI;创建成功才标记降级。 + return a.generateVideoOnBase(ctx, request, credential, accessToken, a.fallbackBaseURL(), true) +} + +func (a *Adapter) generateVideoOnBase(ctx context.Context, request provider.VideoRequest, credential account.Credential, accessToken, base string, withUploadURL bool) (provider.VideoResult, error) { + uploadURL, assetID := "", "" + var err error + if withUploadURL { + issuer := a.uploadIssuerRef() + if issuer == nil { + return provider.VideoResult{}, fmt.Errorf("XAI 视频回退需要媒体上传接收服务") + } + jobKey := strings.TrimSpace(request.JobID) + if jobKey == "" { + jobKey = "video-pending" + } + uploadURL, assetID, err = issuer.IssueVideoUpload(ctx, jobKey) + if err != nil { + // 配置错误(例如 PublicAPIBaseURL 不可用)不得误标降级。 + return provider.VideoResult{}, err + } + } + payload, err := buildVideoCreatePayload(request, uploadURL) + if err != nil { + return provider.VideoResult{}, err + } + body, err := json.Marshal(payload) + if err != nil { + return provider.VideoResult{}, err + } + createResp, err := a.doVideoJSON(ctx, credential, accessToken, http.MethodPost, base, "/videos/generations", body, true) + if err != nil { + return provider.VideoResult{}, err + } + // 必须先解析到可用 job ID,再标记降级;畸形 2xx 不得激活或本地置位。 + jobID, err := parseVideoCreateResponse(createResp) + if err != nil { + return provider.VideoResult{}, err + } + if withUploadURL && !credential.BuildAPIFallback { + a.activateBuildAPIFallback(ctx, &credential) + } + if request.Progress != nil { + request.Progress(1) + } + return a.pollVideoJob(ctx, credential, accessToken, base, jobID, assetID, request.Progress) +} + +// DownloadVideo 通过 Build egress 拉取已完成任务的公开 CDN URL。 +// 资源域不需要 OAuth;不得解密或转发 token 与客户端身份头。 +func (a *Adapter) DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error) { + parsed, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil || parsed.Scheme != "https" || parsed.User != nil || !trustedBuildVideoAssetHost(parsed.Hostname()) { + return nil, "", 0, fmt.Errorf("视频内容 URL 不受信任") + } + requestCtx := infraegress.WithAccount(ctx, string(account.ProviderBuild), credential.ID) + req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, parsed.String(), nil) + if err != nil { + return nil, "", 0, err + } + // 仅保留 egress 路径上的匿名 GET;禁止 Authorization / Token-Auth / 会话身份头。 + req.Header.Set("Accept", "*/*") + response, err := a.http.Do(req) + if err != nil { + return nil, "", 0, err + } + if err := normalizeGzipResponse(response); err != nil { + return nil, "", 0, err + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + _ = response.Body.Close() + return nil, "", 0, fmt.Errorf("下载视频返回 %d", response.StatusCode) + } + contentType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0])) + if contentType == "" || contentType == "application/octet-stream" { + contentType = "video/mp4" + } + if !strings.HasPrefix(contentType, "video/") { + _ = response.Body.Close() + return nil, "", 0, fmt.Errorf("上游视频 Content-Type 无效") + } + return response.Body, contentType, response.ContentLength, nil +} + +func buildVideoCreatePayload(request provider.VideoRequest, uploadURL string) (map[string]any, error) { + payload := map[string]any{ + "model": buildVideoModel, + } + if prompt := strings.TrimSpace(request.Prompt); prompt != "" { + payload["prompt"] = prompt + } + if request.Duration > 0 { + payload["duration"] = request.Duration + } + if ratio := strings.TrimSpace(request.AspectRatio); ratio != "" { + payload["aspect_ratio"] = ratio + } + if resolution := strings.TrimSpace(request.Resolution); resolution != "" { + payload["resolution"] = resolution + } + if len(request.ReferenceURLs) == 1 { + imageURL := strings.TrimSpace(request.ReferenceURLs[0]) + if imageURL == "" { + return nil, fmt.Errorf("视频首图 URL 不能为空") + } + payload["image"] = map[string]any{"image_url": imageURL} + } + if _, hasPrompt := payload["prompt"]; !hasPrompt { + if _, hasImage := payload["image"]; !hasImage { + return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } + } + if uploadURL = strings.TrimSpace(uploadURL); uploadURL != "" { + payload["output"] = map[string]any{"upload_url": uploadURL} + } + return payload, nil +} + +func (a *Adapter) pollVideoJob(ctx context.Context, credential account.Credential, accessToken, base, jobID, assetID string, progress func(int)) (provider.VideoResult, error) { + ticker := time.NewTicker(buildVideoPollEvery) + defer ticker.Stop() + for { + statusBody, err := a.doVideoJSON(ctx, credential, accessToken, http.MethodGet, base, "/videos/"+url.PathEscape(jobID), nil, false) + if err != nil { + return provider.VideoResult{}, err + } + result, done, pollErr := parseVideoStatusResponse(statusBody, progress, assetID != "") + if pollErr != nil { + return provider.VideoResult{}, pollErr + } + if done { + if assetID != "" { + issuer := a.uploadIssuerRef() + if issuer == nil { + return provider.VideoResult{}, fmt.Errorf("XAI 视频回退需要媒体上传接收服务") + } + contentType, waitErr := issuer.WaitVideoUpload(ctx, assetID) + if waitErr != nil { + // 上游 done 但本地未收到上传:若 status 带 CDN URL 仍可回退远程读取。 + if result.URL != "" { + return result, nil + } + return provider.VideoResult{}, waitErr + } + if contentType == "" { + contentType = "video/mp4" + } + return provider.VideoResult{ContentType: contentType, AssetID: assetID}, nil + } + return result, nil + } + select { + case <-ctx.Done(): + return provider.VideoResult{}, ctx.Err() + case <-ticker.C: + } + } +} + +func (a *Adapter) doVideoJSON(ctx context.Context, credential account.Credential, accessToken, method, base, path string, body []byte, withTrace bool) ([]byte, error) { + var bodyReader io.Reader + if len(body) > 0 { + bodyReader = bytes.NewReader(body) + } + requestCtx := infraegress.WithAccount(ctx, string(account.ProviderBuild), credential.ID) + req, err := http.NewRequestWithContext(requestCtx, method, a.urlWithBase(base, path), bodyReader) + if err != nil { + return nil, err + } + if err := a.applyHeaders(req, credential, accessToken, buildVideoModel, "", withTrace); err != nil { + return nil, err + } + if len(body) > 0 { + req.Header.Set("Content-Type", "application/json") + } + req.Header.Set("Accept", "application/json") + resp, err := a.http.Do(req) + if err != nil { + return nil, err + } + if err := normalizeGzipResponse(resp); err != nil { + return nil, err + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, buildVideoMaxBodySize+1)) + if err != nil { + return nil, err + } + if len(data) > buildVideoMaxBodySize { + return nil, fmt.Errorf("Build 视频上游响应超过 %d 字节", buildVideoMaxBodySize) + } + if resp.StatusCode == http.StatusUnauthorized { + return nil, provider.ErrUnauthorized + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, newVideoUpstreamError(resp.StatusCode, data) + } + return data, nil +} + +func parseVideoCreateResponse(body []byte) (string, error) { + var root map[string]any + if err := json.Unmarshal(body, &root); err != nil { + return "", fmt.Errorf("解析 Build 视频创建响应: %w", err) + } + if message := firstNestedString(root, "error", "message"); message != "" { + return "", fmt.Errorf("Build 视频创建失败: %s", safeVideoDiagnosticMessage(message)) + } + if id := firstString(root, "request_id", "id"); id != "" { + return id, nil + } + if data, ok := root["data"].(map[string]any); ok { + if id := firstString(data, "request_id", "id"); id != "" { + return id, nil + } + } + return "", fmt.Errorf("Build 视频创建响应缺少 request_id") +} + +func parseVideoStatusResponse(body []byte, progress func(int), allowMissingURL bool) (provider.VideoResult, bool, error) { + var root map[string]any + if err := json.Unmarshal(body, &root); err != nil { + return provider.VideoResult{}, false, fmt.Errorf("解析 Build 视频状态响应: %w", err) + } + if message := firstNestedString(root, "error", "message"); message != "" { + return provider.VideoResult{}, false, fmt.Errorf("Build 视频生成失败: %s", safeVideoDiagnosticMessage(message)) + } + statusSource := root + if data, ok := root["data"].(map[string]any); ok { + statusSource = data + } + if value, ok := numberAsInt(firstValue(statusSource, "progress")); ok && progress != nil { + progress(value) + } + status := strings.ToLower(strings.TrimSpace(firstString(statusSource, "status", "state"))) + switch status { + case "failed", "error", "cancelled", "canceled": + message := firstNestedString(statusSource, "error", "message") + if message == "" { + message = firstString(statusSource, "error_message", "message") + } + if message == "" { + message = status + } + return provider.VideoResult{}, false, fmt.Errorf("Build 视频生成失败: %s", safeVideoDiagnosticMessage(message)) + case "completed", "succeeded", "success", "ready", "done": + videoURL := extractBuildVideoURL(root) + if videoURL == "" && !allowMissingURL { + return provider.VideoResult{}, false, fmt.Errorf("视频生成完成但没有返回内容 URL") + } + return provider.VideoResult{URL: videoURL, ContentType: "video/mp4"}, true, nil + default: + if videoURL := extractBuildVideoURL(root); videoURL != "" { + return provider.VideoResult{URL: videoURL, ContentType: "video/mp4"}, true, nil + } + return provider.VideoResult{}, false, nil + } +} + +func asVideoUpstreamError(err error, target **videoUpstreamError) bool { + if err == nil { + return false + } + if v, ok := err.(*videoUpstreamError); ok { + *target = v + return true + } + return false +} + +func extractBuildVideoURL(root map[string]any) string { + candidates := []string{ + firstString(root, "video_url", "url"), + firstNestedString(root, "video", "url"), + firstNestedString(root, "output", "url"), + firstNestedString(root, "result", "url"), + } + if data, ok := root["data"].(map[string]any); ok { + candidates = append(candidates, + firstString(data, "video_url", "url"), + firstNestedString(data, "video", "url"), + firstNestedString(data, "output", "url"), + ) + if items, ok := data["data"].([]any); ok { + for _, item := range items { + if m, ok := item.(map[string]any); ok { + if u := firstString(m, "url", "video_url"); u != "" { + candidates = append(candidates, u) + } + } + } + } + } + if items, ok := root["data"].([]any); ok { + for _, item := range items { + if m, ok := item.(map[string]any); ok { + if u := firstString(m, "url", "video_url"); u != "" { + candidates = append(candidates, u) + } + } + } + } + for _, value := range candidates { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +func trustedBuildVideoAssetHost(host string) bool { + host = strings.ToLower(strings.TrimSpace(host)) + if host == "" { + return false + } + trusted := []string{ + "x.ai", "grok.com", "assets.grok.com", "cdn.x.ai", "videos.x.ai", + } + for _, suffix := range trusted { + if host == suffix || strings.HasSuffix(host, "."+suffix) { + return true + } + } + return false +} + +func firstString(values map[string]any, keys ...string) string { + for _, key := range keys { + if text := strings.TrimSpace(stringValue(values[key])); text != "" { + return text + } + } + return "" +} + +func firstNestedString(values map[string]any, objectKey, field string) string { + nested, _ := values[objectKey].(map[string]any) + if nested == nil { + return "" + } + return strings.TrimSpace(stringValue(nested[field])) +} + +func numberAsInt(value any) (int, bool) { + switch typed := value.(type) { + case float64: + return int(typed), true + case int: + return typed, true + case int64: + return int(typed), true + case json.Number: + n, err := typed.Int64() + return int(n), err == nil + default: + return 0, false + } +} diff --git a/backend/internal/infra/provider/cli/video_test.go b/backend/internal/infra/provider/cli/video_test.go new file mode 100644 index 00000000..33cc05bd --- /dev/null +++ b/backend/internal/infra/provider/cli/video_test.go @@ -0,0 +1,473 @@ +package cli + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + 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" +) + +func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) { + noImage, err := buildVideoCreatePayload(provider.VideoRequest{ + Prompt: "animate waves", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + }, "") + if err != nil { + t.Fatal(err) + } + if noImage["model"] != buildVideoModel || noImage["prompt"] != "animate waves" || noImage["duration"] != 6 { + t.Fatalf("no-image payload = %#v", noImage) + } + if _, exists := noImage["image"]; exists { + t.Fatalf("unexpected image field: %#v", noImage) + } + if _, exists := noImage["output"]; exists { + t.Fatalf("primary payload must not include output: %#v", noImage) + } + + withImage, err := buildVideoCreatePayload(provider.VideoRequest{ + Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"}, + }, "") + if err != nil { + t.Fatal(err) + } + image, ok := withImage["image"].(map[string]any) + if !ok || image["image_url"] != "https://cdn.example.com/r2/first.png" { + t.Fatalf("image payload = %#v", withImage) + } + if withImage["model"] != buildVideoModel || withImage["resolution"] != "720p" || withImage["aspect_ratio"] != "16:9" { + t.Fatalf("single-image payload = %#v", withImage) + } + + withUpload, err := buildVideoCreatePayload(provider.VideoRequest{Prompt: "x", Duration: 6}, "https://api.example/v1/media/uploads/tok") + if err != nil { + t.Fatal(err) + } + output, ok := withUpload["output"].(map[string]any) + if !ok || output["upload_url"] != "https://api.example/v1/media/uploads/tok" { + t.Fatalf("upload payload = %#v", withUpload) + } +} + +func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) { + payload, err := buildVideoCreatePayload(provider.VideoRequest{ + Prompt: " ", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{"https://r2.example.com/first.png"}, + }, "") + if err != nil { + t.Fatal(err) + } + if _, exists := payload["prompt"]; exists { + t.Fatalf("empty prompt should be omitted: %#v", payload) + } + image, ok := payload["image"].(map[string]any) + if !ok || image["image_url"] != "https://r2.example.com/first.png" || payload["model"] != buildVideoModel { + t.Fatalf("image-only payload = %#v", payload) + } +} + +func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var hits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + hits.Add(1) + t.Fatalf("two-image request must not reach upstream: %s %s", request.Method, request.URL) + return nil, nil + }) + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, + Prompt: "animate", + ReferenceURLs: []string{ + "https://cdn.example.com/one.png", + "https://cdn.example.com/two.png", + }, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持 1 张首图") { + t.Fatalf("error = %v", err) + } + if hits.Load() != 0 { + t.Fatalf("upstream hits = %d", hits.Load()) + } +} + +func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var createBody map[string]any + var pollCount atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if identity := infraegress.AccountFromContext(request.Context()); identity != "grok_build_9" { + t.Fatalf("egress account identity = %q", identity) + } + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + if request.Header.Get("Authorization") != "Bearer access-token" { + t.Fatalf("missing auth header: %#v", request.Header) + } + if request.Header.Get("x-grok-model-override") != buildVideoModel { + t.Fatalf("model override = %q", request.Header.Get("x-grok-model-override")) + } + if err := json.NewDecoder(request.Body).Decode(&createBody); err != nil { + t.Fatal(err) + } + return jsonResponse(http.StatusOK, `{"request_id":"vid_123","status":"queued"}`, request), nil + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/vid_123": + count := pollCount.Add(1) + if count == 1 { + return jsonResponse(http.StatusOK, `{"status":"processing","progress":40}`, request), nil + } + return jsonResponse(http.StatusOK, `{"status":"completed","progress":100,"video":{"url":"https://assets.grok.com/videos/out.mp4"}}`, request), nil + default: + t.Fatalf("unexpected request %s %s", request.Method, request.URL) + return nil, nil + } + }) + + var progressValues []int + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted}, + Prompt: "animate knife", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{"https://r2.example.com/first.png"}, + Progress: func(value int) { + progressValues = append(progressValues, value) + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://assets.grok.com/videos/out.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("result = %#v", result) + } + image, _ := createBody["image"].(map[string]any) + if createBody["model"] != buildVideoModel || image["image_url"] != "https://r2.example.com/first.png" || createBody["duration"] != float64(6) { + t.Fatalf("create body = %#v", createBody) + } + if pollCount.Load() < 2 { + t.Fatalf("poll count = %d", pollCount.Load()) + } + if len(progressValues) == 0 || progressValues[0] != 1 { + t.Fatalf("progress = %#v", progressValues) + } +} + +func TestGenerateVideoMapsUnauthorizedAndUpstreamErrors(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + return jsonResponse(http.StatusUnauthorized, `{"error":{"message":"bad token"}}`, request), nil + }) + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{EncryptedAccessToken: encrypted}, + Prompt: "test", + }) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("401 err = %v", err) + } + + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + return jsonResponse(http.StatusBadRequest, `{"error":{"message":"invalid image"}}`, request), nil + }) + _, err = adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{EncryptedAccessToken: encrypted}, + Prompt: "test", + }) + status, ok := provider.ErrorHTTPStatus(err) + if !ok || status != http.StatusBadRequest || !strings.Contains(err.Error(), "invalid image") { + t.Fatalf("4xx err = %v status=%d ok=%v", err, status, ok) + } + + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + return jsonResponse(http.StatusBadGateway, `upstream unavailable`, request), nil + }) + _, err = adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{EncryptedAccessToken: encrypted}, + Prompt: "test", + }) + status, ok = provider.ErrorHTTPStatus(err) + if !ok || status != http.StatusBadGateway { + t.Fatalf("5xx err = %v status=%d ok=%v", err, status, ok) + } +} + +func TestVideoUpstreamErrorRedactsUploadTokenFromBody(t *testing.T) { + const token = "aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899" + if len(token) != 64 { + t.Fatalf("fixture token length = %d", len(token)) + } + fullURL := "https://api.example.com/v1/media/uploads/" + token + // 上游校验响应可能回显完整 output.upload_url(含一次性 token)。 + body := []byte(`{"error":{"code":"invalid_request","message":"output.upload_url is not reachable: ` + fullURL + `"}}`) + err := newVideoUpstreamError(http.StatusBadRequest, body) + if err == nil { + t.Fatal("expected videoUpstreamError") + } + status, ok := provider.ErrorHTTPStatus(err) + if !ok || status != http.StatusBadRequest { + t.Fatalf("status = %d ok=%v", status, ok) + } + msg := err.Error() + if strings.Contains(msg, token) { + t.Fatalf("error must not contain upload token: %q", msg) + } + if strings.Contains(msg, fullURL) { + t.Fatalf("error must not contain full upload URL: %q", msg) + } + if strings.Contains(msg, "/v1/media/uploads/"+token) { + t.Fatalf("error must not contain upload path with token: %q", msg) + } + if !strings.Contains(msg, "invalid_request") { + t.Fatalf("safe error code should be preserved: %q", msg) + } + if !strings.Contains(msg, "not reachable") { + t.Fatalf("safe error message fragment should be preserved: %q", msg) + } + if !strings.Contains(msg, "[REDACTED]") { + t.Fatalf("expected redaction marker in summary: %q", msg) + } + + // 非 JSON 正文中的完整路径同样脱敏。 + plain := newVideoUpstreamError(http.StatusUnprocessableEntity, []byte("reject upload_url="+fullURL)) + plainMsg := plain.Error() + if strings.Contains(plainMsg, token) || strings.Contains(plainMsg, fullURL) { + t.Fatalf("plain body error leaked secret: %q", plainMsg) + } + if plain.HTTPStatusCode() != http.StatusUnprocessableEntity { + t.Fatalf("plain status = %d", plain.HTTPStatusCode()) + } +} + +func TestParseVideoCreateAndStatusRedactUploadSecretsIn2xxErrors(t *testing.T) { + const token = "11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff" + if len(token) != 64 { + t.Fatalf("fixture token length = %d", len(token)) + } + fullURL := "https://public.example/v1/media/uploads/" + token + + assertNoSecret := func(t *testing.T, msg string) { + t.Helper() + if strings.Contains(msg, token) { + t.Fatalf("error leaked bare token: %q", msg) + } + if strings.Contains(msg, fullURL) { + t.Fatalf("error leaked full upload URL: %q", msg) + } + if strings.Contains(msg, "/v1/media/uploads/"+token) { + t.Fatalf("error leaked upload path+token: %q", msg) + } + } + + // 2xx create:error.message 回显完整 upload URL。 + _, err := parseVideoCreateResponse([]byte(`{"error":{"message":"invalid output.upload_url ` + fullURL + `"}}`)) + if err == nil { + t.Fatal("expected create error") + } + createMsg := err.Error() + assertNoSecret(t, createMsg) + if !strings.Contains(createMsg, "invalid output.upload_url") { + t.Fatalf("safe create diagnostics missing: %q", createMsg) + } + if !strings.Contains(createMsg, "[REDACTED]") { + t.Fatalf("expected redaction in create error: %q", createMsg) + } + + // 2xx create:error.message 仅含裸 64-hex token。 + _, err = parseVideoCreateResponse([]byte(`{"error":{"message":"token rejected: ` + token + `"}}`)) + if err == nil { + t.Fatal("expected create bare-token error") + } + assertNoSecret(t, err.Error()) + if !strings.Contains(err.Error(), "token rejected") { + t.Fatalf("safe bare-token fragment missing: %q", err.Error()) + } + + // 2xx status:顶层 error.message 含完整 URL。 + _, _, err = parseVideoStatusResponse([]byte(`{"error":{"message":"upload failed `+fullURL+`"}}`), nil, false) + if err == nil { + t.Fatal("expected status top-level error") + } + assertNoSecret(t, err.Error()) + + // 2xx status:failed 状态 + error_message 含裸 token。 + _, _, err = parseVideoStatusResponse([]byte(`{"status":"failed","error_message":"moderation token=`+token+`"}`), nil, false) + if err == nil { + t.Fatal("expected failed status error") + } + statusMsg := err.Error() + assertNoSecret(t, statusMsg) + if !strings.Contains(statusMsg, "moderation") { + t.Fatalf("safe status diagnostics missing: %q", statusMsg) + } + + // 2xx status:failed + nested error.message 含完整 URL。 + _, _, err = parseVideoStatusResponse([]byte(`{"status":"failed","error":{"message":"bad upload_url `+fullURL+`"}}`), nil, false) + if err == nil { + t.Fatal("expected nested failed status error") + } + assertNoSecret(t, err.Error()) +} + +func TestGenerateVideoFailedStatusAndDownloadTrustedURL(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + switch { + case request.Method == http.MethodPost: + return jsonResponse(http.StatusOK, `{"id":"vid_fail"}`, request), nil + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/vid_fail": + return jsonResponse(http.StatusOK, `{"status":"failed","error":{"message":"moderation"}}`, request), nil + default: + t.Fatalf("unexpected %s %s", request.Method, request.URL) + return nil, nil + } + }) + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{EncryptedAccessToken: encrypted}, + Prompt: "bad", + }) + if err == nil || !strings.Contains(err.Error(), "moderation") { + t.Fatalf("failed status err = %v", err) + } + + const assetURL = "https://vidgen.x.ai/videos/done.mp4" + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.Method != http.MethodGet || request.URL.String() != assetURL { + t.Fatalf("download request = %s %s", request.Method, request.URL) + } + if identity := infraegress.AccountFromContext(request.Context()); identity != "grok_build_99" { + t.Fatalf("download egress account identity = %q", identity) + } + for _, key := range []string{ + "Authorization", "X-XAI-Token-Auth", "x-userid", + "x-grok-model-override", "x-grok-session-id", "x-grok-agent-id", + "x-grok-conv-id", "x-grok-req-id", "x-grok-conversation-id", + "x-grok-session-id-legacy", "x-grok-request-id", + "x-grok-client-version", "x-grok-client-identifier", + } { + if value := request.Header.Get(key); value != "" { + t.Fatalf("resource download must not send %s=%q", key, value) + } + } + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"video/mp4"}}, + Body: io.NopCloser(strings.NewReader("mp4-bytes")), + ContentLength: 9, + Request: request, + }, nil + }) + // 即使传入凭据,下载也不得解密或转发 OAuth / 身份头。 + body, contentType, size, err := adapter.DownloadVideo(context.Background(), account.Credential{ + ID: 99, UserID: "user-1", EncryptedAccessToken: encrypted, + }, assetURL) + if err != nil { + t.Fatal(err) + } + defer func() { _ = body.Close() }() + data, _ := io.ReadAll(body) + if string(data) != "mp4-bytes" || contentType != "video/mp4" || size != 9 { + t.Fatalf("download = %q %s %d", data, contentType, size) + } + if !trustedBuildVideoAssetHost("vidgen.x.ai") { + t.Fatal("vidgen.x.ai must be trusted") + } + + _, _, _, err = adapter.DownloadVideo(context.Background(), account.Credential{EncryptedAccessToken: encrypted}, "https://evil.example/video.mp4") + if err == nil || !strings.Contains(err.Error(), "不受信任") { + t.Fatalf("untrusted download err = %v", err) + } +} + +func TestGenerateVideoRespectsContextCancelDuringPoll(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.Method == http.MethodPost { + return jsonResponse(http.StatusOK, `{"request_id":"vid_slow"}`, request), nil + } + return jsonResponse(http.StatusOK, `{"status":"processing","progress":10}`, request), nil + }) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err := adapter.GenerateVideo(ctx, provider.VideoRequest{ + Credential: account.Credential{EncryptedAccessToken: encrypted}, + Prompt: "slow", + }) + if err == nil || !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) { + t.Fatalf("cancel err = %v", err) + } +} + +func TestRegistryExposesBuildVideoAdapter(t *testing.T) { + registry := provider.NewRegistry(NewAdapter(Config{}, nil)) + adapter, ok := registry.Videos(account.ProviderBuild) + if !ok { + t.Fatal("Build video adapter not registered") + } + if _, ok := adapter.(provider.VideoContentDownloader); !ok { + t.Fatal("Build adapter must implement VideoContentDownloader") + } + definition, ok := registry.Definition(account.ProviderBuild) + if !ok || !definition.SupportsModelCapability(modeldomain.CapabilityVideo) || !definition.Media.VideoGeneration { + t.Fatalf("build definition = %#v", definition) + } +} + +func TestBuildVideoDefinitionDeclaresVideoCapability(t *testing.T) { + adapter := NewAdapter(Config{}, nil) + definition := adapter.Definition() + if !definition.Media.VideoGeneration { + t.Fatal("Media.VideoGeneration not enabled") + } + if !definition.SupportsModelCapability(modeldomain.CapabilityVideo) { + t.Fatalf("capabilities = %#v", definition.ModelCapabilities) + } + if err := definition.Validate(); err != nil { + t.Fatal(err) + } +} + +func newTestBuildVideoAdapter(t *testing.T) (*Adapter, string) { + t.Helper() + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{ + BaseURL: "https://cli-chat-proxy.grok.com/v1", + ClientVersion: "0.2.99", + ClientIdentifier: "grok-shell", + TokenAuth: "xai-grok-cli", + UserAgent: "grok-shell/0.2.99 (linux; x86_64)", + }, cipher) + return adapter, encrypted +} + +func jsonResponse(status int, body string, request *http.Request) *http.Response { + return &http.Response{ + StatusCode: status, + Status: http.StatusText(status), + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: request, + } +} diff --git a/backend/internal/infra/provider/definition_contract_test.go b/backend/internal/infra/provider/definition_contract_test.go index 4512cb58..aeb50b7d 100644 --- a/backend/internal/infra/provider/definition_contract_test.go +++ b/backend/internal/infra/provider/definition_contract_test.go @@ -46,9 +46,10 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T) }{ { provider: account.ProviderBuild, catalog: provider.ModelCatalogRemote, quota: provider.QuotaBilling, - capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses}, + capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityVideo}, credential: provider.CredentialSurface{AuthType: account.AuthTypeOAuth, Import: true, Refresh: true, DeviceOAuth: true}, conversation: provider.ConversationSurface{Responses: true, ChatCompletions: true, Messages: true, Compact: true, StoredResponses: true}, + media: provider.MediaSurface{VideoGeneration: true}, inference: provider.InferencePolicy{Usage: provider.UsageUpstream}, }, { diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 814da3bc..999decac 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -239,7 +239,9 @@ type ImageEditRequest struct { } type VideoRequest struct { - Credential account.Credential + Credential account.Credential + // JobID 绑定本地视频任务,供 XAI ZDR 上传票据与结果资产关联。 + JobID string Prompt string Duration int AspectRatio string @@ -251,6 +253,8 @@ type VideoRequest struct { type VideoResult struct { URL string ContentType string + // AssetID 非空时表示结果已写入本地媒体资产,内容读取应走 MediaObjectStorage。 + AssetID string } // RefreshedCredential 表示 OAuth 刷新后的旋转凭据。 @@ -275,6 +279,13 @@ type ModelCatalogAdapter interface { ListModels(ctx context.Context, credential account.Credential) ([]string, error) } +// AccountModelCapabilityNormalizer 可选:按 Billing 快照归一化账号模型能力。 +// 未实现时模型同步原样写入上游目录;billing 为 nil 表示 Unknown(无快照)。 +type AccountModelCapabilityNormalizer interface { + Adapter + NormalizeAccountModelCapabilities(models []string, billing *account.Billing) []string +} + type BillingAdapter interface { Adapter GetBilling(ctx context.Context, credential account.Credential) (account.Billing, error) @@ -331,6 +342,13 @@ type VideoAdapter interface { GenerateVideo(ctx context.Context, request VideoRequest) (VideoResult, error) } +// VideoContentDownloader streams a completed provider video using the +// credential that created the job. Callers must enforce job ownership first. +type VideoContentDownloader interface { + VideoAdapter + DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error) +} + type RoutingMetadataAdapter interface { Adapter QuotaMode(upstreamModel string) string diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index e4976095..ecdb1745 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -876,6 +876,18 @@ func TestParseVideoConcatenatedJSONFixture(t *testing.T) { } } +func TestParseVideoStreamUsesModelResponseAttachment(t *testing.T) { + fixture := `data: {"result":{"response":{"streamingVideoGenerationResponse":{"progress":100,"videoPostId":"post_1"},"modelResponse":{"fileAttachments":["users/user_1/generated/video_1/generated_video.mp4"]}}}}` + "\n" + response := &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(fixture))} + result, postID, err := parseVideoStream(response, nil) + if err != nil { + t.Fatal(err) + } + if postID != "post_1" || result.URL != "https://assets.grok.com/users/user_1/generated/video_1/generated_video.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("result = %#v, post = %q", result, postID) + } +} + func MarshalJSONBytes(value any) []byte { data, _ := json.Marshal(value) return data diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index ba49222a..ebab3acb 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -307,12 +307,18 @@ func parseWeeklyCreditsResponse(body []byte, accountID uint64, syncedAt time.Tim config = config[consumed:] } } - if !usagePresent || math.IsNaN(usagePercent) || math.IsInf(usagePercent, 0) || usagePercent < 0 || usagePercent > 100 { + if usagePresent && (math.IsNaN(usagePercent) || math.IsInf(usagePercent, 0) || usagePercent < 0 || usagePercent > 100) { return account.QuotaWindow{}, fmt.Errorf("Grok Web 周额度响应缺少有效使用率") } if periodStart == nil || periodEnd == nil || !periodEnd.After(*periodStart) { return account.QuotaWindow{}, fmt.Errorf("Grok Web 周额度响应缺少有效周期") } + if !usagePresent && periodStart.Nanosecond() == 0 && periodEnd.Nanosecond() == 0 { + // Free accounts return a coarse entitlement period without a usage rate. + // A paid, unused weekly pool has the same rate omitted but retains its + // precise period boundaries, which represents zero percent used. + return account.QuotaWindow{}, fmt.Errorf("Grok Web 周额度响应缺少有效使用率") + } windowSeconds := int(periodEnd.Sub(*periodStart).Seconds()) if windowSeconds < 24*60*60 || windowSeconds > 31*24*60*60 { return account.QuotaWindow{}, fmt.Errorf("Grok Web 周额度周期长度异常") diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index 5280829a..abf70c51 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -42,6 +42,30 @@ func TestParseCapturedWeeklyCreditsResponse(t *testing.T) { } } +func TestParseUnusedPreciseWeeklyCreditsResponse(t *testing.T) { + body, err := hex.DecodeString("00000000480a4612001a00220c08c5d5d3d20610c0c7a1ee012a0c08c5caf8d20610c0c7a1ee01421e0802120c08c5d5d3d20610c0c7a1ee011a0c08c5caf8d20610c0c7a1ee01580162006801800000000f677270632d7374617475733a300d0a") + if err != nil { + t.Fatal(err) + } + window, err := parseWeeklyCreditsResponse(body, 42, time.Now().UTC()) + if err != nil { + t.Fatal(err) + } + if window.Total != 10000 || window.Remaining != 10000 || window.UsagePercent != 0 || window.ResetAt == nil || window.ResetAt.Nanosecond() == 0 { + t.Fatalf("window = %#v", window) + } +} + +func TestParseCoarseWeeklyCreditsResponseRemainsUnavailable(t *testing.T) { + body, err := hex.DecodeString("00000000300a2e12001a0022060880a6b6d2062a0608809bdbd2064212080212060880a6b6d2061a0608809bdbd206580162006801800000000f677270632d7374617475733a300d0a") + if err != nil { + t.Fatal(err) + } + if _, err := parseWeeklyCreditsResponse(body, 42, time.Now().UTC()); err == nil { + t.Fatal("expected coarse period without usage to be rejected") + } +} + func TestSyncQuotaFetchesWeeklyOnlyAfterPaidTierIsConfirmed(t *testing.T) { weeklyBody, err := hex.DecodeString(capturedWeeklyCreditsHex) if err != nil { diff --git a/backend/internal/infra/provider/web/upstream_test.go b/backend/internal/infra/provider/web/upstream_test.go index 76fbe4d3..74a8e9d1 100644 --- a/backend/internal/infra/provider/web/upstream_test.go +++ b/backend/internal/infra/provider/web/upstream_test.go @@ -21,4 +21,4 @@ func TestResponseUpstreamURLReturnsRequestURL(t *testing.T) { if got := responseUpstreamURL(response); got != request.URL.String() { t.Fatalf("responseUpstreamURL() = %q, want %q", got, request.URL.String()) } -} \ No newline at end of file +} diff --git a/backend/internal/infra/provider/web/video.go b/backend/internal/infra/provider/web/video.go index f7fafaeb..0e28959a 100644 --- a/backend/internal/infra/provider/web/video.go +++ b/backend/internal/infra/provider/web/video.go @@ -7,9 +7,11 @@ import ( "fmt" "io" "net/http" + "net/url" "strings" "time" + "github.com/chenyme/grok2api/backend/internal/domain/account" domainegress "github.com/chenyme/grok2api/backend/internal/domain/egress" "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" @@ -98,6 +100,67 @@ func (a *Adapter) prepareVideoReference(ctx context.Context, cfg Config, lease * return uploaded.URI, nil } +type videoContentReadCloser struct { + io.ReadCloser + release func() +} + +func (c *videoContentReadCloser) Close() error { + err := c.ReadCloser.Close() + if c.release != nil { + c.release() + c.release = nil + } + return err +} + +// DownloadVideo retrieves a completed Grok asset through its source SSO +// session. Direct asset URLs are not public and must not be exposed as a +// substitute for this authenticated transfer. +func (a *Adapter) DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error) { + parsed, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil || parsed.Scheme != "https" || !trustedImageAssetHost(parsed.Hostname()) || parsed.User != nil { + return nil, "", 0, fmt.Errorf("视频内容 URL 不受信任") + } + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, "", 0, err + } + // 视频生成与成品下载必须复用同一账号身份;否则 Resin 会为 WebAsset + // 重新分配租约,账号级 Cloudflare clearance 也不会进入下载请求。 + lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWebAsset, credential) + if err != nil { + return nil, "", 0, err + } + request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil) + if err != nil { + lease.Release() + return nil, "", 0, err + } + request.Header = buildHeaders(token, lease, "") + request.Header.Del("Content-Type") + response, err := lease.Do(request) + if err != nil { + lease.Release() + return nil, "", 0, err + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + _ = response.Body.Close() + lease.Release() + return nil, "", 0, fmt.Errorf("下载视频返回 %d", response.StatusCode) + } + contentType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0])) + if contentType == "" || contentType == "application/octet-stream" { + contentType = "video/mp4" + } + if !strings.HasPrefix(contentType, "video/") { + _ = response.Body.Close() + lease.Release() + return nil, "", 0, fmt.Errorf("上游视频 Content-Type 无效") + } + return &videoContentReadCloser{ReadCloser: response.Body, release: lease.Release}, contentType, response.ContentLength, nil +} + func parseVideoStream(response *http.Response, progress func(int)) (provider.VideoResult, string, error) { if response.StatusCode < 200 || response.StatusCode >= 300 { body, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20)) @@ -112,26 +175,31 @@ func parseVideoStream(response *http.Response, progress func(int)) (provider.Vid if errorValue, ok := root["error"].(map[string]any); ok { return false, fmt.Errorf("视频上游错误: %v", errorValue["message"]) } + if errorValue := nestedMap(root, "result", "response", "error"); errorValue != nil { + return false, fmt.Errorf("视频上游错误: %v", errorValue["message"]) + } stream := nestedMap(root, "result", "response", "streamingVideoGenerationResponse") - if stream == nil { - return false, nil + if stream != nil { + if value, ok := numberAsInt(stream["progress"]); ok && progress != nil { + progress(value) + } + if value, _ := stream["videoPostId"].(string); value != "" { + postID = value + } else if value, _ := stream["videoId"].(string); value != "" { + postID = value + } + moderated, _ := stream["moderated"].(bool) + if moderated { + return false, nil + } + if setVideoResultURL(&result, firstString(stream, "videoUrl", "contentUrl", "contentURL", "assetUrl", "assetURL", "fileUri", "fileURL")) { + return true, nil + } } - if value, ok := numberAsInt(stream["progress"]); ok && progress != nil { - progress(value) - } - if value, _ := stream["videoPostId"].(string); value != "" { - postID = value - } else if value, _ := stream["videoId"].(string); value != "" { - postID = value - } - moderated, _ := stream["moderated"].(bool) - if moderated { - return false, nil - } - if value, _ := stream["videoUrl"].(string); value != "" { - result.URL = absoluteAssetURL(value) - result.ContentType = "video/mp4" - return true, nil + for _, attachment := range videoFileAttachments(root) { + if setVideoResultURL(&result, attachment) { + return true, nil + } } return false, nil } @@ -151,6 +219,35 @@ func parseVideoStream(response *http.Response, progress func(int)) (provider.Vid return result, postID, nil } +func videoFileAttachments(root map[string]any) []string { + modelResponse := nestedMap(root, "result", "response", "modelResponse") + if modelResponse == nil { + return nil + } + values, _ := modelResponse["fileAttachments"].([]any) + attachments := make([]string, 0, len(values)) + for _, value := range values { + if attachment, _ := value.(string); attachment != "" { + attachments = append(attachments, attachment) + } + } + return attachments +} + +func setVideoResultURL(result *provider.VideoResult, value string) bool { + value = strings.TrimSpace(value) + if value == "" { + return false + } + lower := strings.ToLower(value) + if !strings.HasSuffix(strings.SplitN(lower, "?", 2)[0], ".mp4") && !strings.Contains(lower, "/content") { + return false + } + result.URL = absoluteAssetURL(value) + result.ContentType = "video/mp4" + return true +} + func consumeVideoSSE(reader io.Reader, handle func(map[string]any) (bool, error)) error { scanner := bufio.NewScanner(reader) scanner.Buffer(make([]byte, 64<<10), 8<<20) diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index a94ee2b8..4417406f 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -55,6 +55,8 @@ type AccountRepository interface { UpdateCredentialRefreshFailure(ctx context.Context, id uint64, failureCount int, retryAt time.Time, errorCode string, permanent bool) error UpdateObservedModel(ctx context.Context, id uint64, model string, observedAt time.Time) error UpdateHealth(ctx context.Context, id uint64, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error + // MarkBuildAPIFallback 幂等写入 Build 账号的 XAI 推理回退标记;非 Build 账号返回错误。 + MarkBuildAPIFallback(ctx context.Context, id uint64, enabled bool) error UpsertModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error PruneExpiredModelQuotaBlocks(ctx context.Context, now time.Time, limit int) (int64, error) SaveBilling(ctx context.Context, value account.Billing) error diff --git a/backend/internal/repository/media.go b/backend/internal/repository/media.go index 525ec405..bb70bc14 100644 --- a/backend/internal/repository/media.go +++ b/backend/internal/repository/media.go @@ -30,6 +30,18 @@ type MediaAssetStats struct { TotalBytes int64 } +// MediaUploadTicket 表示上游视频 PUT 的一次性票据元数据(不含明文 token)。 +type MediaUploadTicket struct { + TokenHash string + AssetID string + JobID string + MaxBytes int64 + AllowedMIME string + ExpiresAt time.Time + ConsumedAt *time.Time + CreatedAt time.Time +} + // MediaJobStats 表示各状态视频任务的聚合统计结果。 type MediaJobStats struct { TotalJobs int64 @@ -58,13 +70,36 @@ type MediaAssetRepository interface { 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) + // ListOldestMediaAssets 按 created_at ASC, id ASC 分页;offset 用于跳过已扫描的受保护资产。 + ListOldestMediaAssets(ctx context.Context, offset, limit int) ([]media.Asset, error) DeleteMediaAsset(ctx context.Context, id string) error + // ListActiveVideoAssetIDs 返回进行中任务或未消费票据绑定的资产 ID,清理时必须跳过。 + ListProtectedMediaAssetIDs(ctx context.Context) (map[string]struct{}, error) +} + +// MediaUploadTicketRepository 定义视频上传票据的持久化能力。 +type MediaUploadTicketRepository interface { + CreateUploadTicket(ctx context.Context, ticket MediaUploadTicket) error + GetUploadTicketByHash(ctx context.Context, tokenHash string) (MediaUploadTicket, error) + // ConsumeUploadTicket 原子消费票据;已消费或过期返回 false。 + ConsumeUploadTicket(ctx context.Context, tokenHash string, now time.Time) (MediaUploadTicket, bool, error) + // ReleaseUploadTicket 在尚未登记资产时撤销消费,允许同票据重试。 + // 仅当票据当前为已消费状态时清除 consumed_at;返回是否成功释放。 + ReleaseUploadTicket(ctx context.Context, tokenHash string) (bool, error) + // DeleteUploadTicketByHash 按 token_hash 精确删除票据;行不存在时幂等成功。 + // 用于签发过程中 bind 失败后的补偿回滚,不得按 job/asset 批量删除。 + DeleteUploadTicketByHash(ctx context.Context, tokenHash string) error + DeleteExpiredUploadTickets(ctx context.Context, before time.Time, limit int) (int64, error) + BindJobResultAsset(ctx context.Context, jobID, assetID string) error } // MediaObjectStorage 定义媒体二进制对象的存取边界。 type MediaObjectStorage interface { SaveImage(ctx context.Context, id, mimeType string, data []byte) (string, error) + SaveVideo(ctx context.Context, id, mimeType string, data []byte) (string, error) + BeginVideoUpload(ctx context.Context, id, mimeType string) (tempPath, storageKey string, err error) + CommitVideoUpload(ctx context.Context, tempPath, storageKey string) error + AbortVideoUpload(ctx context.Context, tempPath string) error Open(ctx context.Context, storageKey string) (io.ReadCloser, error) Delete(ctx context.Context, storageKey string) error } diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index 2cbe0011..f7c2d2f4 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -900,7 +900,11 @@ func (h *Handler) update(c *gin.Context) { response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") return } - value, err := h.service.Update(c.Request.Context(), id, accountapp.UpdateInput{Name: request.Name, Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining, CloudflareCookies: request.CloudflareCookies, ClearCloudflareCookies: request.ClearCloudflareCookies}) + value, err := h.service.Update(c.Request.Context(), id, accountapp.UpdateInput{ + Name: request.Name, Enabled: request.Enabled, Priority: request.Priority, + MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining, + CloudflareCookies: request.CloudflareCookies, ClearCloudflareCookies: request.ClearCloudflareCookies, + }) if err != nil { h.writeServiceError(c, "accountUpdateFailed", err, http.StatusInternalServerError, "更新账号失败") return diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index b48ca627..6edd7a4c 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -8,6 +8,7 @@ import ( "io" "mime" "net/http" + "net/url" "strconv" "strings" "time" @@ -23,9 +24,11 @@ import ( ) type Handler struct { - gateway *gateway.Service - models *modelapp.Service - maxBodyBytes int64 + gateway *gateway.Service + models *modelapp.Service + maxBodyBytes int64 + publicAPIBaseURL string + publicBaseURL func() string } const ( @@ -42,8 +45,19 @@ var errResponseTransferLimit = errors.New("响应超过代理安全上限") const mediaTransferErrorTrailer = "X-Grok2API-Transfer-Error" -func NewHandler(gatewayService *gateway.Service, models *modelapp.Service, maxBodyBytes int64) *Handler { - return &Handler{gateway: gatewayService, models: models, maxBodyBytes: maxBodyBytes} +func NewHandler(gatewayService *gateway.Service, models *modelapp.Service, maxBodyBytes int64, publicAPIBaseURL ...string) *Handler { + baseURL := "" + if len(publicAPIBaseURL) > 0 { + baseURL = strings.TrimRight(strings.TrimSpace(publicAPIBaseURL[0]), "/") + } + return &Handler{gateway: gatewayService, models: models, maxBodyBytes: maxBodyBytes, publicAPIBaseURL: baseURL} +} + +// SetPublicAPIBaseURLResolver 让视频内容 URL 跟随运行设置热更新。 +// 应在 Register 前设置;请求处理期间只读取该函数。 +func (h *Handler) SetPublicAPIBaseURLResolver(resolve func() string) *Handler { + h.publicBaseURL = resolve + return h } func (h *Handler) Register(router *gin.RouterGroup) { @@ -55,6 +69,7 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/images/edits", h.editImage) router.POST("/videos/generations", h.generateVideo) router.GET("/videos/:requestId", h.getVideo) + router.GET("/videos/:requestId/content", h.getVideoContent) router.POST("/responses/compact", h.compactResponse) router.GET("/responses/:responseId", h.getResponse) router.DELETE("/responses/:responseId", h.deleteResponse) @@ -240,7 +255,7 @@ func (h *Handler) createMessage(c *gin.Context) { writeGatewayAnthropicError(c, err) return } - h.writeResult(c, result, request.Stream) + h.writeAnthropicResult(c, result, request.Stream) } func (h *Handler) generateImage(c *gin.Context) { @@ -303,6 +318,11 @@ func (h *Handler) writeMediaResult(c *gin.Context, result *gateway.Result) { errorCode := "" defer result.Body.Close() defer func() { result.Finalize(gateway.Usage{}, "", errorCode) }() + if isUpstreamCredentialStatus(result.StatusCode) { + errorCode = "upstream_unavailable" + writeOpenAIError(c, http.StatusServiceUnavailable, "upstream_unavailable", "上游服务暂不可用") + return + } contentLength, contentLengthErr := strconv.ParseInt(result.Header.Get("Content-Length"), 10, 64) if contentLengthErr == nil && contentLength > maxMediaResponseTransferBytes { errorCode = "response_too_large" @@ -563,7 +583,57 @@ func (h *Handler) getVideo(c *gin.Context) { writeGatewayError(c, err) return } - c.JSON(http.StatusOK, videoGenerationResponse(job)) + c.JSON(http.StatusOK, videoGenerationResponse(job, h.videoContentURL(job.ID))) +} + +func (h *Handler) videoContentURL(jobID string) string { + path := "/v1/videos/" + url.PathEscape(jobID) + "/content" + baseURL := h.publicAPIBaseURL + if h.publicBaseURL != nil { + baseURL = strings.TrimRight(strings.TrimSpace(h.publicBaseURL()), "/") + } + if baseURL == "" { + return path + } + return baseURL + path +} + +func (h *Handler) getVideoContent(c *gin.Context) { + clientKey, _, ok := requestIdentity(c) + if !ok { + return + } + body, contentType, size, err := h.gateway.OpenVideoContent(c.Request.Context(), strings.TrimSpace(c.Param("requestId")), clientKey) + if err != nil { + writeGatewayError(c, err) + return + } + defer func() { _ = body.Close() }() + writeVideoContent(c, body, contentType, size) +} + +func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size int64) { + if size > maxMediaResponseTransferBytes { + writeOpenAIError(c, http.StatusBadGateway, "media_too_large", "上游媒体超过 2 GiB 安全上限") + return + } + c.Header("Content-Type", contentType) + c.Header("Content-Disposition", "inline") + c.Header("Cache-Control", "private, no-store") + c.Header("X-Content-Type-Options", "nosniff") + if size >= 0 { + c.Header("Content-Length", strconv.FormatInt(size, 10)) + } else { + c.Header("Trailer", mediaTransferErrorTrailer) + } + c.Status(http.StatusOK) + if err := copyMedia(responseDeadlineWriter{ResponseWriter: c.Writer}, body, maxMediaResponseTransferBytes); err != nil && size < 0 { + errorCode := "stream_interrupted" + if errors.Is(err, errResponseTransferLimit) { + errorCode = "response_too_large" + } + c.Header(mediaTransferErrorTrailer, errorCode) + } } func parseVideoDuration(durationRaw json.RawMessage) (int, error) { @@ -614,12 +684,16 @@ func validVideoAspectRatio(value string) bool { } } -func videoGenerationResponse(job mediadomain.Job) gin.H { +func videoGenerationResponse(job mediadomain.Job, contentURLs ...string) gin.H { switch job.Status { case mediadomain.StatusCompleted: + videoURL := job.UpstreamURL + if len(contentURLs) > 0 && contentURLs[0] != "" { + videoURL = contentURLs[0] + } return gin.H{ "status": "done", "model": job.Model, "progress": 100, - "video": gin.H{"url": job.UpstreamURL, "duration": job.Seconds, "respect_moderation": true}, + "video": gin.H{"url": videoURL, "duration": job.Seconds, "respect_moderation": true}, } case mediadomain.StatusFailed: return gin.H{ @@ -749,11 +823,28 @@ func (h *Handler) handleOwnedResource(c *gin.Context, deleteResource bool) { } func (h *Handler) writeResult(c *gin.Context, result *gateway.Result, stream bool) { + h.writeProtocolResult(c, result, stream, false) +} + +func (h *Handler) writeAnthropicResult(c *gin.Context, result *gateway.Result, stream bool) { + h.writeProtocolResult(c, result, stream, true) +} + +func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, stream, anthropic bool) { usage := gateway.Usage{} responseID := "" errorCode := "" defer result.Body.Close() defer func() { result.Finalize(usage, responseID, errorCode) }() + if isUpstreamCredentialStatus(result.StatusCode) { + errorCode = "upstream_unavailable" + if anthropic { + writeAnthropicError(c, http.StatusServiceUnavailable, "overloaded_error", "上游服务暂不可用") + } else { + writeOpenAIError(c, http.StatusServiceUnavailable, "upstream_unavailable", "上游服务暂不可用") + } + return + } transferLimit := int64(maxJSONResponseTransferBytes) if stream { transferLimit = maxStreamResponseTransferBytes @@ -1068,8 +1159,12 @@ func writeGatewayError(c *gin.Context, err error) { status, code = http.StatusBadRequest, "unsupported_parameter" message = err.Error() case errors.As(err, &upstreamFailure): - status, code, message = upstreamFailure.HTTPStatus, upstreamFailure.Code, upstreamFailure.PublicMessage - if upstreamFailure.RetryAfter > 0 { + if isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) { + status, code, message = http.StatusServiceUnavailable, "upstream_unavailable", "上游服务暂不可用" + } else { + status, code, message = upstreamFailure.HTTPStatus, upstreamFailure.Code, upstreamFailure.PublicMessage + } + if !isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) && upstreamFailure.RetryAfter > 0 { c.Header("Retry-After", strconv.FormatInt(max(1, int64(upstreamFailure.RetryAfter.Round(time.Second)/time.Second)), 10)) } case errors.As(err, &selectionFailure): @@ -1097,8 +1192,12 @@ func writeGatewayAnthropicError(c *gin.Context, err error) { status, errorType = http.StatusBadRequest, "invalid_request_error" message = err.Error() case errors.As(err, &upstreamFailure): - status, message = upstreamFailure.HTTPStatus, upstreamFailure.PublicMessage - if upstreamFailure.RetryAfter > 0 { + if isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) { + status, errorType, message = http.StatusServiceUnavailable, "overloaded_error", "上游服务暂不可用" + } else { + status, message = upstreamFailure.HTTPStatus, upstreamFailure.PublicMessage + } + if !isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) && upstreamFailure.RetryAfter > 0 { c.Header("Retry-After", strconv.FormatInt(max(1, int64(upstreamFailure.RetryAfter.Round(time.Second)/time.Second)), 10)) } if status == http.StatusTooManyRequests { @@ -1118,6 +1217,10 @@ func writeGatewayAnthropicError(c *gin.Context, err error) { writeAnthropicError(c, status, errorType, message) } +func isUpstreamCredentialStatus(status int) bool { + return status == http.StatusUnauthorized || status == http.StatusForbidden +} + func selectionErrorResponse(c *gin.Context, failure *gateway.SelectionUnavailableError) (int, string, string) { status, code, message := http.StatusServiceUnavailable, "upstream_unavailable", "当前没有可用的上游账号" if failure == nil { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 7457c4be..95660346 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "strings" @@ -85,11 +86,44 @@ func TestVideoGenerationUsesOfficialXAIEndpointsAndFields(t *testing.T) { } contentRecorder := httptest.NewRecorder() router.ServeHTTP(contentRecorder, httptest.NewRequest(http.MethodGet, "/v1/videos/request_1/content", nil)) - if contentRecorder.Code != http.StatusNotFound { + if contentRecorder.Code != http.StatusUnauthorized { t.Fatalf("video content endpoint status=%d", contentRecorder.Code) } } +func TestWriteVideoContentRejectsDeclaredOversizeMedia(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + writeVideoContent(context, strings.NewReader("ignored"), "video/mp4", maxMediaResponseTransferBytes+1) + if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), "media_too_large") { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } +} + +func TestVideoContentURLUsesConfiguredPublicAPIBase(t *testing.T) { + handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") + response := videoGenerationResponse(mediadomain.Job{ID: "video_request_1", Status: mediadomain.StatusCompleted, UpstreamURL: "https://assets.grok.com/source.mp4"}, handler.videoContentURL("video_request_1")) + video, ok := response["video"].(gin.H) + if !ok || video["url"] != "https://api.example.com/grok2api/v1/videos/video_request_1/content" { + t.Fatalf("response = %#v", response) + } +} + +func TestVideoContentURLFollowsRuntimePublicAPIBase(t *testing.T) { + baseURL := "https://old.example.com" + handler := NewHandler(nil, nil, 1<<20, "https://static.example.com").SetPublicAPIBaseURLResolver(func() string { + return baseURL + }) + if got := handler.videoContentURL("video_request_1"); got != "https://old.example.com/v1/videos/video_request_1/content" { + t.Fatalf("initial URL = %q", got) + } + baseURL = "https://new.example.com/api/" + if got := handler.videoContentURL("video_request_2"); got != "https://new.example.com/api/v1/videos/video_request_2/content" { + t.Fatalf("updated URL = %q", got) + } +} + func TestGatewayErrorDoesNotExposeInternalDetails(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() @@ -103,7 +137,7 @@ func TestGatewayErrorDoesNotExposeInternalDetails(t *testing.T) { } } -func TestGatewayErrorPreservesSanitizedUpstreamClassification(t *testing.T) { +func TestGatewayErrorHidesUpstreamCredentialStatus(t *testing.T) { gin.SetMode(gin.TestMode) openAIRouter := gin.New() openAIRouter.GET("/", func(c *gin.Context) { @@ -114,7 +148,7 @@ func TestGatewayErrorPreservesSanitizedUpstreamClassification(t *testing.T) { }) openAIRecorder := httptest.NewRecorder() openAIRouter.ServeHTTP(openAIRecorder, httptest.NewRequest(http.MethodGet, "/", nil)) - if openAIRecorder.Code != http.StatusForbidden || !strings.Contains(openAIRecorder.Body.String(), `"code":"upstream_forbidden"`) || strings.Contains(openAIRecorder.Body.String(), "secret") { + if openAIRecorder.Code != http.StatusServiceUnavailable || !strings.Contains(openAIRecorder.Body.String(), `"code":"upstream_unavailable"`) || strings.Contains(openAIRecorder.Body.String(), "secret") || strings.Contains(openAIRecorder.Body.String(), "拒绝") { t.Fatalf("OpenAI status=%d body=%s", openAIRecorder.Code, openAIRecorder.Body.String()) } @@ -129,6 +163,61 @@ func TestGatewayErrorPreservesSanitizedUpstreamClassification(t *testing.T) { if anthropicRecorder.Code != http.StatusTooManyRequests || !strings.Contains(anthropicRecorder.Body.String(), `"type":"rate_limit_error"`) { t.Fatalf("Anthropic status=%d body=%s", anthropicRecorder.Code, anthropicRecorder.Body.String()) } + + credentialRouter := gin.New() + credentialRouter.GET("/", func(c *gin.Context) { + writeGatewayAnthropicError(c, &gateway.UpstreamFailure{ + HTTPStatus: http.StatusUnauthorized, Code: "upstream_unauthorized", PublicMessage: "上游账号认证失败", + }) + }) + credentialRecorder := httptest.NewRecorder() + credentialRouter.ServeHTTP(credentialRecorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if credentialRecorder.Code != http.StatusServiceUnavailable || !strings.Contains(credentialRecorder.Body.String(), `"type":"overloaded_error"`) || strings.Contains(credentialRecorder.Body.String(), "认证") { + t.Fatalf("Anthropic credential status=%d body=%s", credentialRecorder.Code, credentialRecorder.Body.String()) + } +} + +func TestDirectUpstreamCredentialResponsesAreRewritten(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + for _, tc := range []struct { + name string + status int + anthropic bool + media bool + }{ + {name: "openai unauthorized", status: http.StatusUnauthorized}, + {name: "anthropic forbidden", status: http.StatusForbidden, anthropic: true}, + {name: "media forbidden", status: http.StatusForbidden, media: true}, + } { + t.Run(tc.name, func(t *testing.T) { + finalCode := "" + result := &gateway.Result{ + StatusCode: tc.status, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"secret upstream credential detail"}`)), + Finalize: func(_ gateway.Usage, _, code string) { + finalCode = code + }, + } + router := gin.New() + router.GET("/", func(c *gin.Context) { + switch { + case tc.media: + handler.writeMediaResult(c, result) + case tc.anthropic: + handler.writeAnthropicResult(c, result, false) + default: + handler.writeResult(c, result, false) + } + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusServiceUnavailable || strings.Contains(recorder.Body.String(), "secret") || finalCode != "upstream_unavailable" { + t.Fatalf("status=%d body=%s finalize=%s", recorder.Code, recorder.Body.String(), finalCode) + } + }) + } } func TestMessagesEndpointUsesAnthropicContract(t *testing.T) { diff --git a/backend/internal/transport/http/media/handler.go b/backend/internal/transport/http/media/handler.go index 4e7863d6..6f824981 100644 --- a/backend/internal/transport/http/media/handler.go +++ b/backend/internal/transport/http/media/handler.go @@ -19,10 +19,12 @@ type Handler struct { func NewHandler(service *mediaapp.Service) *Handler { return &Handler{service: service} } -// RegisterPublic 注册使用不可猜测资源 ID 的公开图片读取端点。 +// RegisterPublic 注册使用不可猜测资源 ID 的公开图片读取与视频上传接收端点。 +// 上传 PUT 不使用客户端 API key:xAI 无法携带,票据本身即授权。 func (h *Handler) RegisterPublic(router *gin.Engine) { router.GET("/v1/media/images/:assetId", h.getImage) router.HEAD("/v1/media/images/:assetId", h.getImage) + router.PUT("/v1/media/uploads/:token", h.putVideoUpload) } // RegisterAdmin 注册管理端媒体列表和统计端点。 @@ -63,6 +65,30 @@ func (h *Handler) getImage(c *gin.Context) { _, _ = io.Copy(c.Writer, body) } +// putVideoUpload 接收 XAI ZDR 视频 PUT。响应与错误不得回显完整票据。 +func (h *Handler) putVideoUpload(c *gin.Context) { + _, err := h.service.ReceiveVideoUpload(c.Request.Context(), c.Param("token"), c.GetHeader("Content-Type"), c.Request.Body) + switch { + case err == nil: + c.Status(http.StatusNoContent) + case errors.Is(err, mediaapp.ErrUploadTicketNotFound): + c.Status(http.StatusNotFound) + case errors.Is(err, mediaapp.ErrUploadTicketExpired): + c.Status(http.StatusGone) + case errors.Is(err, mediaapp.ErrUploadTicketConsumed): + c.Status(http.StatusConflict) + case errors.Is(err, mediaapp.ErrVideoUploadTooLarge): + // 体积超限优先于通用无效上传,返回 413。 + c.Status(http.StatusRequestEntityTooLarge) + case errors.Is(err, mediaapp.ErrInvalidVideoUpload): + c.Status(http.StatusBadRequest) + case errors.Is(err, mediaapp.ErrUploadTicketsUnavailable): + c.Status(http.StatusServiceUnavailable) + default: + c.Status(http.StatusInternalServerError) + } +} + 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")) diff --git a/backend/internal/transport/http/media/handler_test.go b/backend/internal/transport/http/media/handler_test.go index ce83de2d..f510626b 100644 --- a/backend/internal/transport/http/media/handler_test.go +++ b/backend/internal/transport/http/media/handler_test.go @@ -1,8 +1,11 @@ package media import ( + "bytes" "context" + "crypto/sha256" "encoding/base64" + "encoding/hex" "net/http" "net/http/httptest" "path/filepath" @@ -12,6 +15,7 @@ import ( mediaapp "github.com/chenyme/grok2api/backend/internal/application/media" localmedia "github.com/chenyme/grok2api/backend/internal/infra/media" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/repository" "github.com/gin-gonic/gin" ) @@ -62,6 +66,91 @@ func TestPublicImageSupportsGetHeadAndETag(t *testing.T) { } } +func TestPutVideoUploadReturns413WhenBodyTooLarge(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-upload-413.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := localmedia.NewLocalStore(filepath.Join(t.TempDir(), "objects-413")) + if err != nil { + t.Fatal(err) + } + tickets := relational.NewMediaUploadTicketRepository(database) + service := mediaapp.NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + tickets, objects, nil, + mediaapp.Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + tokenRaw := make([]byte, 32) + for i := range tokenRaw { + tokenRaw[i] = byte(i + 7) + } + token := hex.EncodeToString(tokenRaw) + sum := sha256.Sum256([]byte(token)) + now := time.Now().UTC() + if err := tickets.CreateUploadTicket(ctx, repository.MediaUploadTicket{ + TokenHash: hex.EncodeToString(sum[:]), AssetID: "vid_http_413_00000001", JobID: "job_413", + MaxBytes: 32, AllowedMIME: "video/mp4", ExpiresAt: now.Add(time.Hour), CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x0a}, 64)...) + router := gin.New() + NewHandler(service).RegisterPublic(router) + req := httptest.NewRequest(http.MethodPut, "/v1/media/uploads/"+token, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "video/mp4") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + if recorder.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413, body=%s", recorder.Code, recorder.Body.String()) + } +} + +func TestPutVideoUploadReturns400ForInvalidMIME(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-upload-400.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + objects, err := localmedia.NewLocalStore(filepath.Join(t.TempDir(), "objects-400")) + if err != nil { + t.Fatal(err) + } + service := mediaapp.NewServiceWithTickets( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + relational.NewMediaUploadTicketRepository(database), objects, nil, + mediaapp.Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + uploadURL, _, err := service.IssueVideoUpload(ctx, "job_400_mime") + if err != nil { + t.Fatal(err) + } + token := uploadURL[len("https://api.example/v1/media/uploads/"):] + router := gin.New() + NewHandler(service).RegisterPublic(router) + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p'}, bytes.Repeat([]byte{1}, 16)...) + req := httptest.NewRequest(http.MethodPut, "/v1/media/uploads/"+token, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "video/webm") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + if recorder.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", recorder.Code) + } +} + func TestAdminVideoListRejectsInvalidFilters(t *testing.T) { gin.SetMode(gin.TestMode) ctx := context.Background() diff --git a/backend/internal/transport/http/middleware/request.go b/backend/internal/transport/http/middleware/request.go index bfd00222..18acf22c 100644 --- a/backend/internal/transport/http/middleware/request.go +++ b/backend/internal/transport/http/middleware/request.go @@ -61,10 +61,19 @@ func Timeout(duration time.Duration) gin.HandlerFunc { } // MaxBodyBytes 对所有请求体应用统一硬上限,避免管理端绑定无界读取。 +// XAI 视频 PUT(/v1/media/uploads/)使用更高的视频安全上限,由票据再次限长。 func MaxBodyBytes(limit int64) gin.HandlerFunc { + const mediaUploadPathPrefix = "/v1/media/uploads/" + const mediaUploadMaxBytes = 256 << 20 return func(c *gin.Context) { if c.Request.Body != nil && limit > 0 { - c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit) + effective := limit + if strings.HasPrefix(c.Request.URL.Path, mediaUploadPathPrefix) && c.Request.Method == http.MethodPut { + if mediaUploadMaxBytes > effective { + effective = mediaUploadMaxBytes + } + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, effective) } c.Next() } diff --git a/backend/internal/transport/http/server.go b/backend/internal/transport/http/server.go index 1a1d7570..b74c5413 100644 --- a/backend/internal/transport/http/server.go +++ b/backend/internal/transport/http/server.go @@ -170,7 +170,11 @@ func New(deps Dependencies) *gin.Engine { }) } v1.Use(middleware.ClientAuth(deps.ClientKeys)) - inference.NewHandler(deps.Gateway, deps.Models, deps.MaxBodyBytes).Register(v1) + inferenceHandler := inference.NewHandler(deps.Gateway, deps.Models, deps.MaxBodyBytes, deps.PublicAPIBaseURL) + if deps.Settings != nil { + inferenceHandler.SetPublicAPIBaseURLResolver(deps.Settings.PublicAPIBaseURL) + } + inferenceHandler.Register(v1) registerFrontend(router, deps.FrontendStaticPath) return router } diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index af6577dd..a7404db9 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -56,6 +56,7 @@ type frontendConfigDTO struct { type providerBuildConfigDTO struct { BaseURL string `json:"baseURL"` + FallbackBaseURL string `json:"fallbackBaseURL"` ClientVersion string `json:"clientVersion"` ClientIdentifier string `json:"clientIdentifier"` TokenAuth string `json:"tokenAuth"` @@ -88,11 +89,12 @@ type batchConfigDTO struct { } type routingConfigDTO struct { - StickyTTL string `json:"stickyTTL"` - CooldownBase string `json:"cooldownBase"` - CooldownMax string `json:"cooldownMax"` - CapacityWait string `json:"capacityWait"` - MaxAttempts int `json:"maxAttempts"` + StickyTTL string `json:"stickyTTL"` + CooldownBase string `json:"cooldownBase"` + CooldownMax string `json:"cooldownMax"` + CapacityWait string `json:"capacityWait"` + MaxAttempts int `json:"maxAttempts"` + PreferFreeBuild bool `json:"preferFreeBuild"` } type auditConfigDTO struct { @@ -154,9 +156,9 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { return settingsapp.EditableConfig{ Server: settingsapp.ServerConfig{MaxConcurrentRequests: value.Server.MaxConcurrentRequests}, ProviderBuild: settingsapp.ProviderBuildConfig{ - BaseURL: value.ProviderBuild.BaseURL, ClientVersion: value.ProviderBuild.ClientVersion, - ClientIdentifier: value.ProviderBuild.ClientIdentifier, TokenAuth: value.ProviderBuild.TokenAuth, - UserAgent: value.ProviderBuild.UserAgent, + BaseURL: value.ProviderBuild.BaseURL, FallbackBaseURL: value.ProviderBuild.FallbackBaseURL, + ClientVersion: value.ProviderBuild.ClientVersion, ClientIdentifier: value.ProviderBuild.ClientIdentifier, + TokenAuth: value.ProviderBuild.TokenAuth, UserAgent: value.ProviderBuild.UserAgent, }, ProviderWeb: settingsapp.ProviderWebConfig{ BaseURL: value.ProviderWeb.BaseURL, QuotaTimeout: value.ProviderWeb.QuotaTimeout, @@ -186,6 +188,7 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { Routing: settingsapp.RoutingConfig{ StickyTTL: value.Routing.StickyTTL, CooldownBase: value.Routing.CooldownBase, CooldownMax: value.Routing.CooldownMax, CapacityWait: value.Routing.CapacityWait, MaxAttempts: value.Routing.MaxAttempts, + PreferFreeBuild: value.Routing.PreferFreeBuild, }, Audit: settingsapp.AuditConfig{ BufferSize: value.Audit.BufferSize, BatchSize: value.Audit.BatchSize, FlushInterval: value.Audit.FlushInterval, @@ -202,9 +205,9 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { Config: settingsConfigDTO{ Server: serverConfigDTO{MaxConcurrentRequests: config.Server.MaxConcurrentRequests}, ProviderBuild: providerBuildConfigDTO{ - BaseURL: config.ProviderBuild.BaseURL, ClientVersion: config.ProviderBuild.ClientVersion, - ClientIdentifier: config.ProviderBuild.ClientIdentifier, TokenAuthConfigured: strings.TrimSpace(config.ProviderBuild.TokenAuth) != "", - UserAgent: config.ProviderBuild.UserAgent, + BaseURL: config.ProviderBuild.BaseURL, FallbackBaseURL: config.ProviderBuild.FallbackBaseURL, + ClientVersion: config.ProviderBuild.ClientVersion, ClientIdentifier: config.ProviderBuild.ClientIdentifier, + TokenAuthConfigured: strings.TrimSpace(config.ProviderBuild.TokenAuth) != "", UserAgent: config.ProviderBuild.UserAgent, }, ProviderWeb: providerWebConfigDTO{ BaseURL: config.ProviderWeb.BaseURL, QuotaTimeout: config.ProviderWeb.QuotaTimeout, @@ -234,6 +237,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { Routing: routingConfigDTO{ StickyTTL: config.Routing.StickyTTL, CooldownBase: config.Routing.CooldownBase, CooldownMax: config.Routing.CooldownMax, CapacityWait: config.Routing.CapacityWait, MaxAttempts: config.Routing.MaxAttempts, + PreferFreeBuild: config.Routing.PreferFreeBuild, }, Audit: auditConfigDTO{ BufferSize: config.Audit.BufferSize, BatchSize: config.Audit.BatchSize, FlushInterval: config.Audit.FlushInterval, diff --git a/backend/internal/transport/http/settings/security_test.go b/backend/internal/transport/http/settings/security_test.go index 984c6221..cb6afa47 100644 --- a/backend/internal/transport/http/settings/security_test.go +++ b/backend/internal/transport/http/settings/security_test.go @@ -53,3 +53,12 @@ func TestSettingsResponseIncludesRecommendedBuildBaseline(t *testing.T) { t.Fatalf("recommended build = %#v", response.RecommendedProviderBuild) } } + +func TestSettingsResponseIncludesPreferFreeBuild(t *testing.T) { + response := newSettingsResponse(settingsapp.Snapshot{Config: settingsapp.EditableConfig{ + Routing: settingsapp.RoutingConfig{PreferFreeBuild: true}, + }}) + if !response.Config.Routing.PreferFreeBuild { + t.Fatal("preferFreeBuild was lost from settings response") + } +} diff --git a/config.example.yaml b/config.example.yaml index f7d311a2..ace1bbc5 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -72,3 +72,7 @@ media: local: # [按需修改] 图片二进制目录;数据库只保存资源元数据。 path: "./data/media" + +routing: + # [按需修改] 开启后优先使用已确认可用的 Grok Build Free 账号;也可在管理端热更新。 + preferFreeBuild: false diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index 17c73298..575414b7 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -137,7 +137,10 @@ export function AccountsPage() { type AccountForm = z.infer; const form = useForm({ resolver: zodResolver(accountSchema), - defaultValues: { name: "", enabled: true, priority: 1, maxConcurrent: 8, minimumRemaining: 0, cloudflareCookies: "", clearCloudflareCookies: false }, + defaultValues: { + name: "", enabled: true, priority: 1, maxConcurrent: 8, minimumRemaining: 0, + cloudflareCookies: "", clearCloudflareCookies: false, + }, }); const accountEnabled = useWatch({ control: form.control, name: "enabled" }); const clearCloudflareCookies = useWatch({ control: form.control, name: "clearCloudflareCookies" }); diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index 4ae24a21..f5240013 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -4,7 +4,7 @@ import type { SortOrder } from "@/shared/lib/table-sort"; export type SettingsConfigDTO = { server: { maxConcurrentRequests: number }; - providerBuild: { baseURL: string; clientVersion: string; clientIdentifier: string; tokenAuth: string; tokenAuthConfigured: boolean; userAgent: string }; + providerBuild: { baseURL: string; fallbackBaseURL: string; clientVersion: string; clientIdentifier: string; tokenAuth: string; tokenAuthConfigured: boolean; userAgent: string }; providerWeb: { baseURL: string; quotaTimeout: string; chatTimeout: string; imageTimeout: string; videoTimeout: string; statsigMode: "manual" | "url"; statsigManualValue?: string; statsigManualConfigured: boolean; statsigSignerURL: string; @@ -18,7 +18,7 @@ export type SettingsConfigDTO = { cleanupInterval: string; }; frontend: { publicApiBaseURL: string }; - routing: { stickyTTL: string; cooldownBase: string; cooldownMax: string; capacityWait: string; maxAttempts: number }; + routing: { stickyTTL: string; cooldownBase: string; cooldownMax: string; capacityWait: string; maxAttempts: number; preferFreeBuild: boolean }; audit: { bufferSize: number; batchSize: number; flushInterval: string }; clientKeyDefaults: { rpmLimit: number; maxConcurrent: number }; }; @@ -47,7 +47,7 @@ export type SettingsSnapshotDTO = { const settingsConfigValidator = hasShape({ server: hasShape({ maxConcurrentRequests: isNumber }), - providerBuild: hasShape({ baseURL: isString, clientVersion: isString, clientIdentifier: isString, tokenAuth: isString, tokenAuthConfigured: isBoolean, userAgent: isString }), + providerBuild: hasShape({ baseURL: isString, fallbackBaseURL: isString, clientVersion: isString, clientIdentifier: isString, tokenAuth: isString, tokenAuthConfigured: isBoolean, userAgent: isString }), providerWeb: hasShape({ baseURL: isString, quotaTimeout: isString, chatTimeout: isString, imageTimeout: isString, videoTimeout: isString, statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean, @@ -57,7 +57,7 @@ const settingsConfigValidator = hasShape({ batch: hasShape({ importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }), media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }), frontend: hasShape({ publicApiBaseURL: isString }), - routing: hasShape({ stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber }), + routing: hasShape({ stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber, preferFreeBuild: isBoolean }), audit: hasShape({ bufferSize: isNumber, batchSize: isNumber, flushInterval: isString }), clientKeyDefaults: hasShape({ rpmLimit: isNumber, maxConcurrent: isNumber }), }); diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 0be68841..75aa5fd3 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -40,6 +40,7 @@ export const settingsSchema = z.object({ }), providerBuild: z.object({ baseURL: z.url(), + fallbackBaseURL: z.url().refine((value) => value.startsWith("https://")), clientVersion: z.string().trim().min(1), clientIdentifier: z.string().trim().min(1), tokenAuth: z.string().trim(), @@ -102,6 +103,7 @@ export const settingsSchema = z.object({ cooldownMax: routingCooldownDuration, capacityWait: routingCapacityWaitDuration, maxAttempts: positiveInteger.max(10), + preferFreeBuild: z.boolean(), }).refine((value) => durationSeconds(value.cooldownMax) >= durationSeconds(value.cooldownBase), { path: ["cooldownMax"] }), audit: z.object({ bufferSize: positiveInteger.max(262_144), batchSize: positiveInteger.max(4_096), flushInterval: auditFlushDuration }) .refine((value) => value.batchSize <= value.bufferSize, { path: ["batchSize"] }), @@ -134,6 +136,7 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm { routing: { stickyTTL: parseDuration(config.routing.stickyTTL), cooldownBase: parseDuration(config.routing.cooldownBase), cooldownMax: parseDuration(config.routing.cooldownMax), capacityWait: parseDuration(config.routing.capacityWait), maxAttempts: config.routing.maxAttempts, + preferFreeBuild: config.routing.preferFreeBuild, }, audit: { bufferSize: config.audit.bufferSize, batchSize: config.audit.batchSize, flushInterval: parseDuration(config.audit.flushInterval) }, clientKeyDefaults: config.clientKeyDefaults, @@ -163,6 +166,7 @@ export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO { routing: { stickyTTL: formatDuration(config.routing.stickyTTL), cooldownBase: formatDuration(config.routing.cooldownBase), cooldownMax: formatDuration(config.routing.cooldownMax), capacityWait: formatDuration(config.routing.capacityWait), maxAttempts: config.routing.maxAttempts, + preferFreeBuild: config.routing.preferFreeBuild, }, audit: { bufferSize: config.audit.bufferSize, batchSize: config.audit.batchSize, flushInterval: formatDuration(config.audit.flushInterval) }, clientKeyDefaults: config.clientKeyDefaults, diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index aac3b960..7edfe25e 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -89,6 +89,7 @@ export function SettingsPage() { >
+ @@ -191,6 +192,7 @@ export function SettingsPage() { } /> } /> +
} />
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 26f53d3a..e2415b4f 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -624,12 +624,12 @@ const resources = { durationUnit: "时长单位", groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略", about: "关于" }, server: { title: "服务容量", maxConcurrentRequests: "API 请求并发上限", maxConcurrentRequestsHelp: "单实例同时处理的 /v1 请求数;调低不会中断进行中的请求。" }, - provider: { title: "Grok Build", baseURL: "上游地址", clientVersion: "客户端版本", clientIdentifier: "客户端标识", tokenAuth: "Token Auth", userAgent: "User-Agent", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步推荐版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "填入后端当前已完成兼容回归的版本和 User-Agent,保存后生效。" }, + provider: { title: "Grok Build", baseURL: "上游地址", fallbackBaseURL: "XAI 备用地址", clientVersion: "客户端版本", clientIdentifier: "客户端标识", tokenAuth: "Token Auth", userAgent: "User-Agent", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步推荐版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "填入后端当前已完成兼容回归的版本和 User-Agent,保存后生效。" }, web: { title: "Grok Web", baseURL: "上游地址", statsigMode: "x-statsig 获取方式", statsigManual: "手动填写", statsigURL: "URL 获取", statsigValue: "x-statsig-id", statsigConfigured: "已配置", statsigKeepConfigured: "留空保持当前配置", statsigValuePlaceholder: "粘贴 x-statsig-id", statsigSignerURL: "签名服务 URL", quotaTimeout: "额度请求超时", chatTimeout: "聊天超时", imageTimeout: "图片超时", videoTimeout: "视频超时", mediaConcurrency: "媒体任务并发", recoveryBackoffBase: "额度恢复退避", recoveryBackoffMax: "额度恢复最大退避", allowNSFW: "允许 NSFW 图片" }, batch: { title: "批量任务", importConcurrency: "导入同步并发", conversionConcurrency: "账号转换并发", syncConcurrency: "数据同步并发", refreshConcurrency: "凭据刷新并发", randomDelay: "随机延迟上限(ms)" }, media: { title: "媒体存储", maxImageSize: "单张图片上限", maxTotalSize: "媒体存储上限", cleanupThresholdPercent: "自动清理阈值", cleanupInterval: "容量检查间隔", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" }, egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 与 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H;Resin 可在用户名中使用 {account} 绑定账号租约。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败" }, - routing: { title: "路由策略", stickyTTL: "会话粘性时长", cooldownBase: "基础冷却时间", cooldownMax: "最大冷却时间", capacityWait: "账号满载等待", maxAttempts: "最大尝试次数" }, + routing: { title: "路由策略", stickyTTL: "会话粘性时长", cooldownBase: "基础冷却时间", cooldownMax: "最大冷却时间", capacityWait: "账号满载等待", maxAttempts: "最大尝试次数", preferFreeBuild: "Grok Build Free 账号优先" }, audit: { title: "请求审计", bufferSize: "队列容量", batchSize: "批量写入数", flushInterval: "刷新间隔" }, clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", maxConcurrent: "默认并发数" }, units: { seconds: "秒", minutes: "分", hours: "时", days: "天" }, @@ -1046,7 +1046,8 @@ const resources = { errorFrameCount_one: "{{count}} error frame", errorFrameCount_other: "{{count}} error frames", }, - settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", 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", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, 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. Resin users can put {account} in the username to bind one lease per account.", 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" } }, + settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", fallbackBaseURL: "XAI fallback 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", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, 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. Resin users can put {account} in the username to bind one lease per account.", 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", capacityWait: "Saturated account wait", maxAttempts: "Maximum attempts", preferFreeBuild: "Prefer Grok Build Free accounts" }, 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.",