mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
feat: add account-aware XAI fallback and video uploads
This commit is contained in:
1 parent
b46a11aae3
commit
f811ffa6dc
47 files changed
+4358
-168
No files matched your search
@@ -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}` | 查询视频任务 |
|
||||
|
||||
@@ -257,6 +259,21 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
|
||||
Provider(包括 Console 上游地址与 User-Agent)、服务容量、批量任务并发、路由、媒体、审计和代理参数统一在管理端 `/settings` 修改,不需要直接编辑数据库;除页面明确标记“重启生效”的字段外均会热加载。导入同步、账号转换、数据同步和凭据刷新默认并发均为 `25`,可分别限制为 `1–50`,并支持随机启动延迟;多实例使用 Redis 时,分类上限和总上限均在集群范围内生效。
|
||||
|
||||
## 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`。
|
||||
- **账号**:账号编辑页可查看并手动开启/清除「XAI 推理回退」;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 被拒绝且不产生资产。
|
||||
- **恢复主地址**:在账号管理中关闭「XAI 推理回退」后,新推理请求重新探测主地址;已创建视频任务的轮询 base 不受影响。
|
||||
|
||||
## 生产部署
|
||||
|
||||
- 使用 HTTPS,并设置 `auth.secureCookies: true`
|
||||
@@ -265,6 +282,7 @@ Provider(包括 Console 上游地址与 User-Agent)、服务容量、批量
|
||||
- 本地媒体目录在多实例下必须使用共享卷或实例亲和
|
||||
- 持久化备份 `config.yaml`、关系型数据库和媒体目录
|
||||
- 不要将 OAuth、SSO、Cloudflare Cookie 或账号导出文件提交到 Git
|
||||
- 若使用 Build 视频 XAI 回退,确保公网 HTTPS `publicApiBaseURL` 可被 xAI PUT 访问
|
||||
- 对外暴露前建议配置反向代理、访问日志和基础网络防护
|
||||
|
||||
## 开发
|
||||
|
||||
@@ -100,6 +100,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()
|
||||
@@ -152,11 +153,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)
|
||||
@@ -186,6 +192,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,6 +243,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
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)
|
||||
@@ -260,9 +268,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))
|
||||
|
||||
@@ -113,6 +113,8 @@ type UpdateInput struct {
|
||||
Priority *int
|
||||
MaxConcurrent *int
|
||||
MinimumRemaining *float64
|
||||
// BuildAPIFallback 仅对 grok_build 有效(XAI 推理回退);nil 表示不修改。
|
||||
BuildAPIFallback *bool
|
||||
}
|
||||
|
||||
type DeviceStartResult struct {
|
||||
@@ -1242,6 +1244,12 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie
|
||||
}
|
||||
value.MinimumRemaining = *input.MinimumRemaining
|
||||
}
|
||||
if input.BuildAPIFallback != nil {
|
||||
if value.Provider != accountdomain.ProviderBuild {
|
||||
return View{}, invalidInput("仅 grok_build 账号支持 Build API 降级标记")
|
||||
}
|
||||
value.BuildAPIFallback = *input.BuildAPIFallback
|
||||
}
|
||||
updated, err := s.accounts.Update(ctx, value)
|
||||
if err != nil {
|
||||
return View{}, mapRepositoryError(err)
|
||||
@@ -1254,6 +1262,11 @@ 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))
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, id uint64) error {
|
||||
if s.sticky != nil {
|
||||
_ = s.sticky.DeleteByAccount(ctx, id)
|
||||
|
||||
@@ -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
|
||||
@@ -434,6 +436,25 @@ 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) {
|
||||
|
||||
@@ -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"
|
||||
@@ -90,6 +91,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)
|
||||
}
|
||||
|
||||
// Service 负责模型路由、账号选择、故障切换与审计收口。
|
||||
type Service struct {
|
||||
models routeResolver
|
||||
@@ -101,6 +107,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{}
|
||||
@@ -119,6 +126,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, selector: selector, responses: responses, logger: slog.Default()}
|
||||
service.UpdateMaxAttempts(maxAttempts)
|
||||
@@ -532,8 +544,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))
|
||||
|
||||
@@ -496,6 +496,72 @@ 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 := 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"))
|
||||
@@ -918,6 +984,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 }
|
||||
@@ -926,6 +993,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),
|
||||
|
||||
@@ -112,7 +112,17 @@ func (s *Service) OpenVideoContent(ctx context.Context, id string, key clientkey
|
||||
if err != nil {
|
||||
return nil, "", 0, err
|
||||
}
|
||||
if job.Status != media.StatusCompleted || job.UpstreamURL == "" {
|
||||
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))
|
||||
@@ -289,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))
|
||||
@@ -323,6 +333,10 @@ 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:
|
||||
// Build API 主地址 403 不禁用账号、不标记 reauth、不增加 cooldown。
|
||||
failureHandled = true
|
||||
case (status == http.StatusPaymentRequired || status == http.StatusTooManyRequests) && lease.QuotaMode != "":
|
||||
exhausted, reconcileErr := s.accounts.ReconcileRateLimit(failureCtx, lease.Credential.ID, lease.QuotaMode, 0)
|
||||
@@ -349,6 +363,9 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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 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")
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -21,6 +21,7 @@ var (
|
||||
// ProviderBuildConfig 是管理接口使用的 Provider 可编辑输入。
|
||||
type ProviderBuildConfig struct {
|
||||
BaseURL string
|
||||
FallbackBaseURL string
|
||||
ClientVersion string
|
||||
ClientIdentifier string
|
||||
TokenAuth string
|
||||
@@ -260,9 +261,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),
|
||||
@@ -308,9 +309,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(),
|
||||
@@ -372,6 +373,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 != "" {
|
||||
@@ -443,9 +445,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(),
|
||||
|
||||
@@ -112,8 +112,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 分钟,避免同批导入账号同时刷新。
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,8 @@ type Job struct {
|
||||
Progress int
|
||||
InputJSON string
|
||||
UpstreamURL string
|
||||
// ResultAssetID 指向本地媒体资产;XAI ZDR 上传完成后优先从此读取。
|
||||
ResultAssetID string
|
||||
ContentType string
|
||||
ErrorCode string
|
||||
ErrorMessage string
|
||||
|
||||
@@ -66,6 +66,7 @@ type BatchConfig struct {
|
||||
// ProviderBuildConfig 定义 Grok Build CLI 上游协议标识。
|
||||
type ProviderBuildConfig struct {
|
||||
BaseURL string
|
||||
FallbackBaseURL string
|
||||
ClientVersion string
|
||||
ClientIdentifier string
|
||||
TokenAuth string
|
||||
|
||||
@@ -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:"-"`
|
||||
@@ -381,9 +385,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 +457,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 +510,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{
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -569,6 +570,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
|
||||
}
|
||||
@@ -635,6 +638,9 @@ func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, update
|
||||
if updates.MaxConcurrent != nil {
|
||||
values["max_concurrent"] = *updates.MaxConcurrent
|
||||
}
|
||||
if updates.BuildAPIFallback != nil {
|
||||
values["build_api_fallback"] = *updates.BuildAPIFallback
|
||||
}
|
||||
if updates.MinimumRemaining != nil {
|
||||
values["minimum_remaining"] = *updates.MinimumRemaining
|
||||
}
|
||||
@@ -782,6 +788,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 {
|
||||
|
||||
@@ -60,7 +60,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +72,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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,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 +64,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 +79,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 +111,135 @@ 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) {
|
||||
result := r.db.db.WithContext(ctx).Model(&mediaUploadTicketModel{}).
|
||||
Where("token_hash = ? AND consumed_at IS NULL AND expires_at > ?", tokenHash, now).
|
||||
Update("consumed_at", now)
|
||||
if result.Error != nil {
|
||||
return repository.MediaUploadTicket{}, false, result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return repository.MediaUploadTicket{}, false, nil
|
||||
}
|
||||
ticket, err := r.GetUploadTicketByHash(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return repository.MediaUploadTicket{}, false, err
|
||||
}
|
||||
return ticket, true, 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 +258,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 +397,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 +412,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,
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -215,6 +216,45 @@ 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 testMediaAsset(id, storageKey string, createdAt time.Time) mediadomain.Asset {
|
||||
return mediadomain.Asset{
|
||||
ID: id,
|
||||
|
||||
@@ -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"`
|
||||
@@ -354,9 +356,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"`
|
||||
@@ -368,6 +370,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"`
|
||||
@@ -383,18 +386,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"`
|
||||
|
||||
@@ -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 != "" {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
|
||||
type Config struct {
|
||||
BaseURL string
|
||||
FallbackBaseURL string
|
||||
ClientVersion string
|
||||
ClientIdentifier string
|
||||
TokenAuth string
|
||||
@@ -33,14 +34,16 @@ 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
|
||||
identityMu sync.Mutex
|
||||
identities map[uint64]clientIdentity
|
||||
cfgMu sync.RWMutex
|
||||
cfg Config
|
||||
http *http.Client
|
||||
oauth *oauthClient
|
||||
cipher *security.Cipher
|
||||
base http.RoundTripper
|
||||
identityMu sync.Mutex
|
||||
identities map[uint64]clientIdentity
|
||||
fallbackMarker FallbackMarker
|
||||
uploadIssuer VideoUploadIssuer
|
||||
}
|
||||
|
||||
type clientIdentity struct {
|
||||
@@ -105,33 +108,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)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, request.Method, a.url(request.Path), bodyReader)
|
||||
// 推理回退:create/compact 可走 XAI;stored GET/DELETE 与未知路径始终主地址。
|
||||
base := a.apiBaseForOperation(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 shouldProbeXAIInferenceFallback(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
|
||||
}
|
||||
@@ -194,15 +203,46 @@ 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}, nil
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: reqURL, Diagnostic: diagnostic}, 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}, nil
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, Diagnostic: diagnostic}, nil
|
||||
}
|
||||
}
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: req.URL.String()}, nil
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL}, 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)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, 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 错误响应,避免触发上游账号重试。
|
||||
@@ -246,27 +286,47 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, a.url("/models"), nil)
|
||||
// 模型目录为 XAI 推理回退能力面:已标记直连 XAI,未标记主 403 可探测。
|
||||
base := a.apiBaseForOperation(credential, http.MethodGet, "/models")
|
||||
models, status, err := a.listModelsAt(ctx, credential, accessToken, base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if models != nil {
|
||||
return models, nil
|
||||
}
|
||||
if shouldProbeXAIInferenceFallback(credential, http.MethodGet, "/models", status) {
|
||||
fallbackModels, fallbackStatus, fallbackErr := a.listModelsAt(ctx, credential, accessToken, a.fallbackBaseURL())
|
||||
if fallbackErr == nil && fallbackModels != nil && isHTTPSuccess(fallbackStatus) {
|
||||
a.activateBuildAPIFallback(ctx, &credential)
|
||||
return fallbackModels, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("上游模型接口返回 %d", status)
|
||||
}
|
||||
|
||||
func (a *Adapter) listModelsAt(ctx context.Context, credential account.Credential, accessToken, base string) ([]string, int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, 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 {
|
||||
@@ -274,7 +334,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 {
|
||||
@@ -282,24 +342,31 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
|
||||
models = append(models, item.ID)
|
||||
}
|
||||
}
|
||||
return models, nil
|
||||
return models, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// GetBilling 始终使用主 Build API。XAI /billing 生产返回 404,无法恢复额度;
|
||||
// 主地址 403 也不得探测 XAI 或激活 BuildAPIFallback,以免把可诊断的 403 改写成误导性 404。
|
||||
func (a *Adapter) GetBilling(ctx context.Context, credential account.Credential) (account.Billing, error) {
|
||||
accessToken, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return account.Billing{}, err
|
||||
}
|
||||
monthly, err := a.getBilling(ctx, credential, accessToken, "")
|
||||
base := a.primaryBaseURL()
|
||||
monthly, status, err := a.getBillingAt(ctx, credential, accessToken, "", base)
|
||||
if err != nil {
|
||||
return account.Billing{}, err
|
||||
}
|
||||
monthly.AccountID = credential.ID
|
||||
if credits, creditsErr := a.getBilling(ctx, credential, accessToken, "format=credits"); creditsErr == nil {
|
||||
monthly = mergeBillingSnapshots(monthly, credits)
|
||||
if monthly == nil {
|
||||
return account.Billing{}, fmt.Errorf("上游 Billing 接口返回 %d", status)
|
||||
}
|
||||
monthly.SyncedAt = time.Now().UTC()
|
||||
return monthly, nil
|
||||
result := *monthly
|
||||
result.AccountID = credential.ID
|
||||
if credits, _, creditsErr := a.getBillingAt(ctx, credential, accessToken, "format=credits", base); creditsErr == nil && credits != nil {
|
||||
result = mergeBillingSnapshots(result, *credits)
|
||||
}
|
||||
result.SyncedAt = time.Now().UTC()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// mergeBillingSnapshots 合并套餐 credits 与 /usage 使用的当前限额周期,周周期优先作为恢复时间。
|
||||
@@ -506,36 +573,36 @@ func (b *gzipResponseBody) Close() error {
|
||||
return sourceErr
|
||||
}
|
||||
|
||||
func (a *Adapter) url(path string) string {
|
||||
return strings.TrimRight(a.config().BaseURL, "/") + "/" + strings.TrimLeft(path, "/")
|
||||
}
|
||||
|
||||
func (a *Adapter) getBilling(ctx context.Context, credential account.Credential, accessToken, query string) (account.Billing, error) {
|
||||
endpoint := a.url("/billing")
|
||||
func (a *Adapter) getBillingAt(ctx context.Context, credential account.Credential, accessToken, query, base string) (*account.Billing, int, error) {
|
||||
endpoint := a.urlWithBase(base, "/billing")
|
||||
if query != "" {
|
||||
endpoint += "?" + query
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return account.Billing{}, err
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := a.applyHeaders(req, credential, accessToken, "", "", false); err != nil {
|
||||
return account.Billing{}, err
|
||||
return nil, 0, err
|
||||
}
|
||||
resp, err := a.http.Do(req)
|
||||
if err != nil {
|
||||
return account.Billing{}, err
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := normalizeGzipResponse(resp); err != nil {
|
||||
return account.Billing{}, err
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
if err != nil {
|
||||
return account.Billing{}, err
|
||||
return nil, 0, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return account.Billing{}, fmt.Errorf("上游 Billing 接口返回 %d", resp.StatusCode)
|
||||
return nil, resp.StatusCode, nil
|
||||
}
|
||||
return parseBilling(body)
|
||||
parsed, err := parseBilling(body)
|
||||
if err != nil {
|
||||
return nil, resp.StatusCode, err
|
||||
}
|
||||
return &parsed, resp.StatusCode, nil
|
||||
}
|
||||
@@ -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},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
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 在主 API 403 且备用 API 成功后幂等持久化账号降级标记。
|
||||
// 当前请求成功不因标记失败而丢失;失败时记录结构化日志供后续重试。
|
||||
type FallbackMarker interface {
|
||||
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 按操作选择 Build API 根地址。
|
||||
// BuildAPIFallback 是账号级 XAI **推理** 回退标记:仅对 isXAIInferenceFallbackCapable 的操作直连 XAI;
|
||||
// Billing、stored GET/DELETE 与未知路径即使已标记也始终走主地址。OAuth 不受影响。
|
||||
func (a *Adapter) apiBaseForOperation(credential account.Credential, method, path string) string {
|
||||
if credential.BuildAPIFallback && isXAIInferenceFallbackCapable(method, path) {
|
||||
return a.fallbackBaseURL()
|
||||
}
|
||||
return a.primaryBaseURL()
|
||||
}
|
||||
|
||||
// shouldProbeXAIInferenceFallback 未标记账号仅在主地址明确 403 且操作可回退时探测 XAI。
|
||||
func shouldProbeXAIInferenceFallback(credential account.Credential, method, path string, primaryStatus int) bool {
|
||||
return !credential.BuildAPIFallback && isHTTPForbidden(primaryStatus) && isXAIInferenceFallbackCapable(method, path)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"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
|
||||
err error
|
||||
}
|
||||
|
||||
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 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)
|
||||
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)
|
||||
}
|
||||
if request.URL.RawQuery == "format=credits" {
|
||||
return jsonResponse(http.StatusOK, `{"config":{"onDemandCap":{"val":10},"onDemandUsed":{"val":1}}}`, request), nil
|
||||
}
|
||||
return jsonResponse(http.StatusOK, `{"config":{"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.MonthlyLimit != 100 || billing.Used != 5 {
|
||||
t.Fatalf("billing = %+v", billing)
|
||||
}
|
||||
// monthly + credits,均只打主地址。
|
||||
if primaryHits.Load() != 2 || 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 TestListModelsPrimary403FallbackSuccess(t *testing.T) {
|
||||
adapter, encrypted := newFallbackTestAdapter(t)
|
||||
marker := &fallbackMarkerStub{}
|
||||
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, `{"data":[{"id":"grok-4.5"},{"id":"grok-imagine-video-1.5"}]}`, request), nil
|
||||
})
|
||||
models, err := adapter.ListModels(context.Background(), account.Credential{ID: 14, EncryptedAccessToken: encrypted})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(models) != 2 || models[0] != "grok-4.5" {
|
||||
t.Fatalf("models = %#v", models)
|
||||
}
|
||||
if marker.calls.Load() != 1 {
|
||||
t.Fatalf("marker calls = %d", marker.calls.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 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) 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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
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"
|
||||
"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 {
|
||||
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
|
||||
}
|
||||
// 主 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, _ 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 不受信任")
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, 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)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
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"
|
||||
"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) {
|
||||
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)
|
||||
}
|
||||
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 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,
|
||||
}
|
||||
}
|
||||
@@ -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},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -219,6 +219,8 @@ type ImageEditRequest struct {
|
||||
|
||||
type VideoRequest struct {
|
||||
Credential account.Credential
|
||||
// JobID 绑定本地视频任务,供 XAI ZDR 上传票据与结果资产关联。
|
||||
JobID string
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
@@ -230,6 +232,8 @@ type VideoRequest struct {
|
||||
type VideoResult struct {
|
||||
URL string
|
||||
ContentType string
|
||||
// AssetID 非空时表示结果已写入本地媒体资产,内容读取应走 MediaObjectStorage。
|
||||
AssetID string
|
||||
}
|
||||
|
||||
// RefreshedCredential 表示 OAuth 刷新后的旋转凭据。
|
||||
|
||||
@@ -13,6 +13,7 @@ type AccountUpdates struct {
|
||||
Priority *int
|
||||
MaxConcurrent *int
|
||||
MinimumRemaining *float64
|
||||
BuildAPIFallback *bool
|
||||
}
|
||||
|
||||
type AccountUpsertResult struct {
|
||||
@@ -55,6 +56,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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -158,6 +158,7 @@ type updateRequest struct {
|
||||
Priority *int `json:"priority"`
|
||||
MaxConcurrent *int `json:"maxConcurrent"`
|
||||
MinimumRemaining *float64 `json:"minimumRemaining"`
|
||||
BuildAPIFallback *bool `json:"buildApiFallback"`
|
||||
}
|
||||
|
||||
type batchUpdateRequest struct {
|
||||
@@ -221,33 +222,35 @@ type accountImportResponse struct {
|
||||
}
|
||||
|
||||
type accountResponse struct {
|
||||
ID uint64 `json:"id,string"`
|
||||
Provider string `json:"provider"`
|
||||
AuthType string `json:"authType"`
|
||||
WebTier string `json:"webTier,omitempty"`
|
||||
WebTierSyncedAt *time.Time `json:"webTierSyncedAt,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
UserID string `json:"userId,omitempty"`
|
||||
TeamID string `json:"teamId,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
AuthStatus string `json:"authStatus"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
Refreshable bool `json:"refreshable"`
|
||||
RefreshDueAt *time.Time `json:"refreshDueAt,omitempty"`
|
||||
LastRefreshAt *time.Time `json:"lastRefreshAt,omitempty"`
|
||||
RefreshFailures int `json:"refreshFailureCount"`
|
||||
LastRefreshError string `json:"lastRefreshErrorCode,omitempty"`
|
||||
Priority int `json:"priority"`
|
||||
MaxConcurrent int `json:"maxConcurrent"`
|
||||
MinimumRemaining float64 `json:"minimumRemaining"`
|
||||
FailureCount int `json:"failureCount"`
|
||||
CooldownUntil *time.Time `json:"cooldownUntil,omitempty"`
|
||||
LastError string `json:"lastError,omitempty"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
|
||||
LinkedAccountID uint64 `json:"linkedAccountId,omitempty,string"`
|
||||
LinkedName string `json:"linkedAccountName,omitempty"`
|
||||
LinkedProvider string `json:"linkedProvider,omitempty"`
|
||||
ID uint64 `json:"id,string"`
|
||||
Provider string `json:"provider"`
|
||||
AuthType string `json:"authType"`
|
||||
WebTier string `json:"webTier,omitempty"`
|
||||
WebTierSyncedAt *time.Time `json:"webTierSyncedAt,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
UserID string `json:"userId,omitempty"`
|
||||
TeamID string `json:"teamId,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
AuthStatus string `json:"authStatus"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
Refreshable bool `json:"refreshable"`
|
||||
RefreshDueAt *time.Time `json:"refreshDueAt,omitempty"`
|
||||
LastRefreshAt *time.Time `json:"lastRefreshAt,omitempty"`
|
||||
RefreshFailures int `json:"refreshFailureCount"`
|
||||
LastRefreshError string `json:"lastRefreshErrorCode,omitempty"`
|
||||
Priority int `json:"priority"`
|
||||
MaxConcurrent int `json:"maxConcurrent"`
|
||||
MinimumRemaining float64 `json:"minimumRemaining"`
|
||||
FailureCount int `json:"failureCount"`
|
||||
CooldownUntil *time.Time `json:"cooldownUntil,omitempty"`
|
||||
LastError string `json:"lastError,omitempty"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
|
||||
LinkedAccountID uint64 `json:"linkedAccountId,omitempty,string"`
|
||||
LinkedName string `json:"linkedAccountName,omitempty"`
|
||||
LinkedProvider string `json:"linkedProvider,omitempty"`
|
||||
// BuildAPIFallback 仅 grok_build 有意义;true 表示 XAI 推理回退(models/responses create|compact/video)。
|
||||
BuildAPIFallback bool `json:"buildApiFallback,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ObservedModel string `json:"observedModel,omitempty"`
|
||||
ObservedModelAt *time.Time `json:"observedModelAt,omitempty"`
|
||||
@@ -893,7 +896,7 @@ 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})
|
||||
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, BuildAPIFallback: request.BuildAPIFallback})
|
||||
if err != nil {
|
||||
h.writeServiceError(c, "accountUpdateFailed", err, http.StatusInternalServerError, "更新账号失败")
|
||||
return
|
||||
@@ -1014,7 +1017,7 @@ func newAccountResponse(value accountapp.View) accountResponse {
|
||||
Priority: c.Priority, MaxConcurrent: c.MaxConcurrent, MinimumRemaining: c.MinimumRemaining,
|
||||
FailureCount: c.FailureCount, CooldownUntil: c.CooldownUntil, LastError: c.LastError,
|
||||
LastUsedAt: c.LastUsedAt, LinkedAccountID: c.LinkedAccountID, LinkedName: c.LinkedAccountName, LinkedProvider: string(c.LinkedProvider),
|
||||
CreatedAt: c.CreatedAt, ObservedModel: c.ObservedModel, ObservedModelAt: c.ObservedModelAt,
|
||||
BuildAPIFallback: c.BuildAPIFallback, CreatedAt: c.CreatedAt, ObservedModel: c.ObservedModel, ObservedModelAt: c.ObservedModelAt,
|
||||
Quota: newQuotaResponse(value.Quota), QuotaWindows: make([]quotaWindowResponse, 0, len(value.QuotaWindows)),
|
||||
}
|
||||
for _, window := range value.QuotaWindows {
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
@@ -154,9 +155,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,
|
||||
@@ -202,9 +203,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,
|
||||
|
||||
@@ -83,6 +83,8 @@ export type AccountDTO = {
|
||||
linkedAccountId?: string;
|
||||
linkedAccountName?: string;
|
||||
linkedProvider?: "grok_build" | "grok_web";
|
||||
/** Build 账号是否启用 XAI 推理回退(models / responses create|compact / video) */
|
||||
buildApiFallback?: boolean;
|
||||
createdAt: string;
|
||||
billing?: BillingDTO;
|
||||
quota: QuotaDTO;
|
||||
@@ -95,6 +97,7 @@ export type AccountUpdateInput = {
|
||||
priority: number;
|
||||
maxConcurrent: number;
|
||||
minimumRemaining: number;
|
||||
buildApiFallback?: boolean;
|
||||
};
|
||||
|
||||
export type AccountSummaryDTO = {
|
||||
@@ -154,6 +157,7 @@ const accountValidator = hasShape({
|
||||
lastRefreshErrorCode: isOptional(isString), priority: isNumber, maxConcurrent: isNumber, minimumRemaining: isNumber,
|
||||
failureCount: isNumber, cooldownUntil: isOptional(isString), lastError: isOptional(isString), lastUsedAt: isOptional(isString),
|
||||
linkedAccountId: isOptional(isString), linkedAccountName: isOptional(isString), linkedProvider: isOptional(isOneOf("grok_build", "grok_web")),
|
||||
buildApiFallback: isOptional(isBoolean),
|
||||
createdAt: isString, billing: isOptional(billingValidator), quota: quotaValidator, quotaWindows: isOptional(isArrayOf(quotaWindowValidator)),
|
||||
});
|
||||
const decodeBilling = createValidatedDecoder<BillingDTO>("billing", billingValidator);
|
||||
|
||||
@@ -131,13 +131,15 @@ export function AccountsPage() {
|
||||
priority: z.number().int(),
|
||||
maxConcurrent: z.number().int().min(1, t("errors.positive")).max(256),
|
||||
minimumRemaining: z.number().min(0),
|
||||
buildApiFallback: z.boolean(),
|
||||
});
|
||||
type AccountForm = z.infer<typeof accountSchema>;
|
||||
const form = useForm<AccountForm>({
|
||||
resolver: zodResolver(accountSchema),
|
||||
defaultValues: { name: "", enabled: true, priority: 1, maxConcurrent: 8, minimumRemaining: 0 },
|
||||
defaultValues: { name: "", enabled: true, priority: 1, maxConcurrent: 8, minimumRemaining: 0, buildApiFallback: false },
|
||||
});
|
||||
const accountEnabled = useWatch({ control: form.control, name: "enabled" });
|
||||
const accountBuildFallback = useWatch({ control: form.control, name: "buildApiFallback" });
|
||||
|
||||
const accountsQuery = useQuery({
|
||||
queryKey: ["accounts", provider, page, pageSize, debouncedSearch, typeFilter, statusFilter, renewalFilter, sort.field, sort.order],
|
||||
@@ -450,6 +452,7 @@ export function AccountsPage() {
|
||||
priority: account.priority,
|
||||
maxConcurrent: account.maxConcurrent,
|
||||
minimumRemaining: account.minimumRemaining,
|
||||
buildApiFallback: Boolean(account.buildApiFallback),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -836,6 +839,15 @@ export function AccountsPage() {
|
||||
<form className="space-y-4" onSubmit={form.handleSubmit((values) => updateMutation.mutate(values))}>
|
||||
<div className="space-y-2"><Label htmlFor="account-name">{t("accounts.name")}</Label><Input id="account-name" {...form.register("name")} />{form.formState.errors.name ? <p className="text-xs text-destructive">{form.formState.errors.name.message}</p> : null}</div>
|
||||
<div className="flex items-center justify-between border-b py-2"><Label htmlFor="account-enabled">{accountEnabled ? t("common.enabled") : t("common.disabled")}</Label><Switch id="account-enabled" checked={accountEnabled} onCheckedChange={(checked) => form.setValue("enabled", checked)} /></div>
|
||||
{editing?.provider === "grok_build" ? (
|
||||
<div className="flex items-center justify-between border-b py-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="account-build-fallback">{t("accounts.buildApiFallback")}</Label>
|
||||
<p className="text-xs text-muted-foreground">{t("accounts.buildApiFallbackHelp")}</p>
|
||||
</div>
|
||||
<Switch id="account-build-fallback" checked={accountBuildFallback} onCheckedChange={(checked) => form.setValue("buildApiFallback", checked, { shouldDirty: true })} />
|
||||
</div>
|
||||
) : null}
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2"><Label htmlFor="account-priority">{t("accounts.priority")}</Label><Input id="account-priority" type="number" {...form.register("priority", { valueAsNumber: true })} /></div>
|
||||
<div className="space-y-2"><Label htmlFor="account-concurrency">{t("accounts.maxConcurrent")}</Label><Input id="account-concurrency" type="number" min="1" max="256" {...form.register("maxConcurrent", { valueAsNumber: true })} /></div>
|
||||
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -87,6 +87,7 @@ export function SettingsPage() {
|
||||
>
|
||||
<div className="grid gap-x-4 gap-y-5 sm:grid-cols-2">
|
||||
<SettingsField controlId="provider-base-url" className="sm:col-span-2" label={t("settings.provider.baseURL")} error={form.formState.errors.providerBuild?.baseURL?.message}><Input id="provider-base-url" {...form.register("providerBuild.baseURL")} /></SettingsField>
|
||||
<SettingsField controlId="provider-fallback-base-url" className="sm:col-span-2" label={t("settings.provider.fallbackBaseURL")} error={form.formState.errors.providerBuild?.fallbackBaseURL?.message}><Input id="provider-fallback-base-url" {...form.register("providerBuild.fallbackBaseURL")} /></SettingsField>
|
||||
<SettingsField controlId="provider-client-version" label={t("settings.provider.clientVersion")} badge={t("settings.provider.recommendedVersion", { version: recommendedBuild?.clientVersion ?? "-" })} error={form.formState.errors.providerBuild?.clientVersion?.message}><Input id="provider-client-version" {...form.register("providerBuild.clientVersion")} /></SettingsField>
|
||||
<SettingsField controlId="provider-client-identifier" label={t("settings.provider.clientIdentifier")} error={form.formState.errors.providerBuild?.clientIdentifier?.message}><Input id="provider-client-identifier" {...form.register("providerBuild.clientIdentifier")} /></SettingsField>
|
||||
<SettingsField controlId="provider-token-auth" label={t("settings.provider.tokenAuth")} badge={form.watch("providerBuild.tokenAuthConfigured") ? t("settings.web.statsigConfigured") : undefined} error={form.formState.errors.providerBuild?.tokenAuth?.message}><Input id="provider-token-auth" type="password" autoComplete="off" placeholder={form.watch("providerBuild.tokenAuthConfigured") ? t("settings.web.statsigKeepConfigured") : undefined} {...form.register("providerBuild.tokenAuth")} /></SettingsField>
|
||||
|
||||
@@ -292,6 +292,8 @@ const resources = {
|
||||
priority: "优先级",
|
||||
maxConcurrent: "最大并发",
|
||||
minimumRemaining: "最低剩余阈值",
|
||||
buildApiFallback: "XAI 推理回退",
|
||||
buildApiFallbackHelp: "开启后该 Build 账号的推理相关请求(模型目录、Responses 创建/Compact、视频)固定走 XAI;Billing 与已存储 Response 的 GET/DELETE 仍走主地址。关闭后恢复主地址探测。",
|
||||
routingSummary: "优先级 {{priority}} · {{count}} 并发",
|
||||
minimumRemainingSummary: "最低剩余阈值 {{value}}",
|
||||
minimumRemainingNotApplicable: "最低剩余阈值不适用于 Free",
|
||||
@@ -547,7 +549,7 @@ const resources = {
|
||||
durationUnit: "时长单位",
|
||||
groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略" },
|
||||
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。" },
|
||||
@@ -822,7 +824,7 @@ const resources = {
|
||||
auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" },
|
||||
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
|
||||
dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", resourcesTitle: "Resource status", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 models", model: "Model", share: "Call share", noTopModels: "No model calls in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" },
|
||||
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking
Line truncated
|
||||
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", buildApiFallback: "XAI inference fallback", buildApiFallbackHelp: "When enabled, inference traffic for this Build account (model catalog, Responses create/compact, video) uses XAI; Billing and stored GET/DELETE /responses/{id} stay on the primary Build base. Disable to restore primary probing.", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamCLine truncated
|
||||
models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "When enabled, only selected accounts are routed and treated as manually confirmed to support the model. Otherwise model sync decides automatically.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
|
||||
audits: {
|
||||
@@ -915,7 +917,7 @@ 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" }, 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.", 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" }, 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.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } },
|
||||
docs: {
|
||||
title: "API documentation",
|
||||
description: "OpenAI Responses compatibility, account routing, and conversation-state behavior for this gateway.",
|
||||
|
||||
Reference in new issue
Block a user