mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 16:01:07 +00:00
feat: add video input size limit and related error handling
This commit is contained in:
1 parent
9bf43ad168
commit
6aa4f3fd60
12 files changed
+432
-49
No files matched your search
@@ -37,6 +37,7 @@ var (
|
||||
ErrResponseAccountUnavailable = errors.New("Response 绑定的上游账号不可用")
|
||||
ErrResponseStateUnsupported = errors.New("目标模型不支持有状态 Response")
|
||||
ErrConversationUnsupported = errors.New("目标模型不支持当前对话协议")
|
||||
ErrVideoInputTooLarge = errors.New("视频参考图片总大小超过 32 MiB")
|
||||
)
|
||||
|
||||
const responseOwnershipTTL = 30 * 24 * time.Hour
|
||||
|
||||
@@ -46,6 +46,10 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
if len(input.Prompt) > 100000 || (len(input.Prompt) == 0 && len(input.ReferenceURLs) == 0) {
|
||||
return media.Job{}, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
}
|
||||
inputJSON, err := encodeVideoInput(input.ReferenceURLs)
|
||||
if err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
routes, err := s.models.GetByPublicIDCandidates(ctx, input.PublicModel)
|
||||
if err != nil {
|
||||
return media.Job{}, ErrModelNotFound
|
||||
@@ -76,7 +80,7 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
AccountID: accountID, AccountName: lease.Credential.Name,
|
||||
Provider: string(route.Provider), Model: externalModel, ModelRouteID: route.ID, UpstreamModel: model.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Prompt: input.Prompt,
|
||||
Seconds: input.Duration, Size: input.AspectRatio, Quality: input.Resolution,
|
||||
Status: media.StatusQueued, Progress: 0, InputJSON: encodeVideoInput(input.ReferenceURLs), CreatedAt: now, UpdatedAt: now,
|
||||
Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(input.ReferenceURLs), CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
reserved := false
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(externalModel, input.Resolution, input.Duration); ok {
|
||||
@@ -488,7 +492,7 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM
|
||||
Provider: job.Provider, Operation: audit.OperationVideo, UsageSource: audit.UsageSourceNone,
|
||||
AccountID: accountID, AccountName: job.AccountName, StatusCode: statusCode, ErrorCode: job.ErrorCode,
|
||||
EgressNodeID: job.EgressNodeID, EgressNodeName: job.EgressNodeName, EgressScope: job.EgressScope, EgressMode: audit.EgressMode(job.EgressMode),
|
||||
MediaInputImages: int64(len(decodeVideoInput(job.InputJSON))),
|
||||
MediaInputImages: int64(job.InputImageCount),
|
||||
DurationMS: durationMS, CreatedAt: createdAt,
|
||||
}
|
||||
if job.Status == media.StatusCompleted {
|
||||
@@ -513,9 +517,15 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM
|
||||
return s.mediaJobs.MarkMediaJobUsageRecorded(markCtx, job.ID, time.Now().UTC())
|
||||
}
|
||||
|
||||
func encodeVideoInput(referenceURLs []string) string {
|
||||
data, _ := json.Marshal(map[string][]string{"image_urls": referenceURLs})
|
||||
return string(data)
|
||||
func encodeVideoInput(referenceURLs []string) (string, error) {
|
||||
data, err := json.Marshal(map[string][]string{"image_urls": referenceURLs})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码视频输入: %w", err)
|
||||
}
|
||||
if len(data) > media.MaxInputJSONBytes {
|
||||
return "", ErrVideoInputTooLarge
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func decodeVideoInput(value string) []string {
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
ID: "video_usage_recovery", RequestID: "request-usage-recovery",
|
||||
ClientKeyID: 1, ClientKeyName: "client", AccountID: 2, AccountName: "account",
|
||||
Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 3, UpstreamModel: "video",
|
||||
Seconds: 8, Quality: "720p", Status: media.StatusCompleted, InputJSON: `{}`, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt,
|
||||
Seconds: 8, Quality: "720p", Status: media.StatusCompleted, InputImageCount: 2, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt,
|
||||
}}
|
||||
recorder := &durableVideoAuditRecorder{failures: 1}
|
||||
service := &Service{mediaJobs: repository, audits: recorder}
|
||||
@@ -38,11 +38,23 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
if repository.job.UsageRecordedAt == nil || recorder.calls != 2 {
|
||||
t.Fatalf("recordedAt = %v, audit calls = %d", repository.job.UsageRecordedAt, recorder.calls)
|
||||
}
|
||||
if recorder.last.EventID != "video_usage_video_usage_recovery" || recorder.last.EstimatedCostInUSDTicks <= 0 {
|
||||
if recorder.last.EventID != "video_usage_video_usage_recovery" || recorder.last.EstimatedCostInUSDTicks <= 0 || recorder.last.MediaInputImages != 2 {
|
||||
t.Fatalf("audit = %#v", recorder.last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeVideoInputEnforcesPersistedLimit(t *testing.T) {
|
||||
overhead := len(`{"image_urls":[""]}`)
|
||||
atLimit := strings.Repeat("A", media.MaxInputJSONBytes-overhead)
|
||||
encoded, err := encodeVideoInput([]string{atLimit})
|
||||
if err != nil || len(encoded) != media.MaxInputJSONBytes {
|
||||
t.Fatalf("encoded len=%d err=%v", len(encoded), err)
|
||||
}
|
||||
if _, err := encodeVideoInput([]string{atLimit + "A"}); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
t.Fatalf("oversized input error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) {
|
||||
completedAt := time.Now().UTC()
|
||||
nodeID := uint64(42)
|
||||
|
||||
@@ -11,6 +11,13 @@ const (
|
||||
StatusFailed Status = "failed"
|
||||
)
|
||||
|
||||
// MaxInputJSONBytes is the persisted media_jobs.input_json ceiling (32 MiB).
|
||||
// Keep the relational CHECK constraint and gateway encode guard aligned with this value.
|
||||
const MaxInputJSONBytes = 32 << 20
|
||||
|
||||
// MaxInputImages is the maximum number of reference images accepted for a video job.
|
||||
const MaxInputImages = 8
|
||||
|
||||
// Job 表示可跨进程重启恢复的异步视频任务。
|
||||
type Job struct {
|
||||
ID string
|
||||
@@ -34,6 +41,7 @@ type Job struct {
|
||||
Status Status
|
||||
Progress int
|
||||
InputJSON string
|
||||
InputImageCount int
|
||||
UpstreamURL string
|
||||
// ResultAssetID 指向本地媒体资产;XAI ZDR 上传完成后优先从此读取。
|
||||
ResultAssetID string
|
||||
|
||||
@@ -266,7 +266,9 @@ func (r *MediaJobRepository) CreateMediaJob(ctx context.Context, value media.Job
|
||||
|
||||
func (r *MediaJobRepository) GetMediaJob(ctx context.Context, id string, clientKeyID uint64) (media.Job, error) {
|
||||
var row mediaJobModel
|
||||
if err := r.db.db.WithContext(ctx).Where("id = ? AND client_key_id = ?", id, clientKeyID).First(&row).Error; err != nil {
|
||||
// Public polling and content download do not consume the potentially large,
|
||||
// immutable reference payload. Keep it off this hot path.
|
||||
if err := r.db.db.WithContext(ctx).Omit("input_json").Where("id = ? AND client_key_id = ?", id, clientKeyID).First(&row).Error; err != nil {
|
||||
return media.Job{}, mapError(err)
|
||||
}
|
||||
return mediaJobToDomain(row), nil
|
||||
@@ -278,7 +280,7 @@ func (r *MediaJobRepository) GetMediaJobsByIDs(ctx context.Context, ids []string
|
||||
return []media.Job{}, nil
|
||||
}
|
||||
var rows []mediaJobModel
|
||||
if err := r.db.db.WithContext(ctx).Where("id IN ?", ids).Find(&rows).Error; err != nil {
|
||||
if err := r.db.db.WithContext(ctx).Omit("input_json").Where("id IN ?", ids).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values := make([]media.Job, 0, len(rows))
|
||||
@@ -294,7 +296,9 @@ 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", "result_asset_id", "content_type", "error_code", "error_message", "lease_until", "claim_token", "updated_at", "completed_at", "usage_recorded_at").Updates(updates)
|
||||
// InputJSON and InputImageCount are immutable creation metadata. Progress and
|
||||
// terminal updates must not resend a multi-megabyte Base64 payload.
|
||||
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", "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
|
||||
}
|
||||
@@ -376,7 +380,7 @@ func (r *MediaJobRepository) ListUnrecordedTerminalMediaJobs(ctx context.Context
|
||||
limit = 200
|
||||
}
|
||||
var rows []mediaJobModel
|
||||
if err := r.db.db.WithContext(ctx).Where("status IN ? AND usage_recorded_at IS NULL", []media.Status{media.StatusCompleted, media.StatusFailed}).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil {
|
||||
if err := r.db.db.WithContext(ctx).Omit("input_json").Where("status IN ? AND usage_recorded_at IS NULL", []media.Status{media.StatusCompleted, media.StatusFailed}).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values := make([]media.Job, 0, len(rows))
|
||||
@@ -388,7 +392,11 @@ func (r *MediaJobRepository) ListUnrecordedTerminalMediaJobs(ctx context.Context
|
||||
|
||||
func (r *MediaJobRepository) MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error {
|
||||
terminalStatuses := []media.Status{media.StatusCompleted, media.StatusFailed}
|
||||
result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NULL", id, terminalStatuses).Update("usage_recorded_at", recordedAt)
|
||||
// Once the durable audit owns the input-image count, terminal jobs no longer
|
||||
// need raw Base64 references. Compact them in the same idempotent update.
|
||||
result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).
|
||||
Where("id = ? AND status IN ? AND usage_recorded_at IS NULL", id, terminalStatuses).
|
||||
Updates(map[string]any{"usage_recorded_at": recordedAt, "input_json": "{}"})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -407,7 +415,9 @@ func (r *MediaJobRepository) MarkMediaJobUsageRecorded(ctx context.Context, id s
|
||||
func (r *MediaJobRepository) ListRecoverableMediaJobs(ctx context.Context, limit int) ([]media.Job, error) {
|
||||
var rows []mediaJobModel
|
||||
now := time.Now().UTC()
|
||||
if err := r.db.db.WithContext(ctx).Where("status = ? OR (status = ? AND (lease_until IS NULL OR lease_until <= ?))", media.StatusQueued, media.StatusInProgress, now).Order("created_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil {
|
||||
// Recovery only enqueues IDs. The bounded worker reads one complete payload
|
||||
// after it atomically claims the job.
|
||||
if err := r.db.db.WithContext(ctx).Select("id").Where("status = ? OR (status = ? AND (lease_until IS NULL OR lease_until <= ?))", media.StatusQueued, media.StatusInProgress, now).Order("created_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values := make([]media.Job, 0, len(rows))
|
||||
@@ -446,7 +456,7 @@ func mediaJobFromDomain(value media.Job) *mediaJobModel {
|
||||
Provider: value.Provider,
|
||||
Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel,
|
||||
Prompt: value.Prompt, Seconds: value.Seconds, Size: value.Size, Quality: value.Quality,
|
||||
Status: string(value.Status), Progress: value.Progress, InputJSON: value.InputJSON, UpstreamURL: value.UpstreamURL,
|
||||
Status: string(value.Status), Progress: value.Progress, InputJSON: value.InputJSON, InputImageCount: mediaJobInputImageCount(value.InputImageCount), UpstreamURL: value.UpstreamURL,
|
||||
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,
|
||||
@@ -458,6 +468,10 @@ func mediaJobToDomain(row mediaJobModel) media.Job {
|
||||
if row.AccountID != nil {
|
||||
accountID = *row.AccountID
|
||||
}
|
||||
var inputImageCount int
|
||||
if row.InputImageCount != nil {
|
||||
inputImageCount = *row.InputImageCount
|
||||
}
|
||||
return media.Job{
|
||||
ID: row.ID, RequestID: row.RequestID, ClientKeyID: row.ClientKeyID, ClientKeyName: row.ClientKeyName,
|
||||
AccountID: accountID, AccountName: row.AccountName,
|
||||
@@ -465,13 +479,15 @@ func mediaJobToDomain(row mediaJobModel) media.Job {
|
||||
Provider: row.Provider,
|
||||
Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel,
|
||||
Prompt: row.Prompt, Seconds: row.Seconds, Size: row.Size, Quality: row.Quality,
|
||||
Status: media.Status(row.Status), Progress: row.Progress, InputJSON: row.InputJSON, UpstreamURL: row.UpstreamURL,
|
||||
Status: media.Status(row.Status), Progress: row.Progress, InputJSON: row.InputJSON, InputImageCount: inputImageCount, UpstreamURL: row.UpstreamURL,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
func mediaJobInputImageCount(value int) *int { return &value }
|
||||
|
||||
func mediaJobAccountID(value uint64) *uint64 {
|
||||
if value == 0 {
|
||||
return nil
|
||||
|
||||
@@ -125,6 +125,68 @@ func TestMediaJobRepositoryListMediaJobsPaginatesAndFilters(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaJobRepositoryKeepsLargeInputOffHotPaths(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "large-input-account", SourceKey: "large-input-account",
|
||||
EncryptedAccessToken: testEncryptedToken, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := clientKeyModel{Name: "large-input-key", Prefix: "large-input-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)
|
||||
}
|
||||
repository := NewMediaJobRepository(database)
|
||||
now := time.Now().UTC()
|
||||
job := testMediaJob("media_job_large_input", accountValue.ID, key.ID, mediadomain.StatusQueued, now)
|
||||
job.InputJSON = `{"image_urls":["` + strings.Repeat("A", (1<<20)+1) + `"]}`
|
||||
job.InputImageCount = 1
|
||||
if err := repository.CreateMediaJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
polled, err := repository.GetMediaJob(ctx, job.ID, key.ID)
|
||||
if err != nil || polled.InputJSON != "" || polled.InputImageCount != 1 {
|
||||
t.Fatalf("poll projection input len=%d count=%d err=%v", len(polled.InputJSON), polled.InputImageCount, err)
|
||||
}
|
||||
recoverable, err := repository.ListRecoverableMediaJobs(ctx, 1000)
|
||||
if err != nil || len(recoverable) != 1 || recoverable[0].ID != job.ID || recoverable[0].InputJSON != "" {
|
||||
t.Fatalf("recoverable jobs=%#v err=%v", recoverable, err)
|
||||
}
|
||||
claimed, ok, err := repository.TryClaimMediaJob(ctx, job.ID, now, now.Add(time.Hour), "claim_large_input_1234")
|
||||
if err != nil || !ok || claimed.InputJSON != job.InputJSON || claimed.InputImageCount != 1 {
|
||||
t.Fatalf("claimed input len=%d count=%d ok=%v err=%v", len(claimed.InputJSON), claimed.InputImageCount, ok, err)
|
||||
}
|
||||
claimed.Progress = 20
|
||||
claimed.InputJSON = `{"image_urls":["should-not-overwrite"]}`
|
||||
if err := repository.UpdateMediaJob(ctx, claimed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var storedInput string
|
||||
if err := database.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ?", job.ID).Pluck("input_json", &storedInput).Error; err != nil || storedInput != job.InputJSON {
|
||||
t.Fatalf("progress update changed immutable input len=%d err=%v", len(storedInput), err)
|
||||
}
|
||||
completedAt := now.Add(time.Minute)
|
||||
claimed.Status, claimed.Progress, claimed.CompletedAt = mediadomain.StatusCompleted, 100, &completedAt
|
||||
if err := repository.UpdateMediaJob(ctx, claimed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
terminal, err := repository.ListUnrecordedTerminalMediaJobs(ctx, 200)
|
||||
if err != nil || len(terminal) != 1 || terminal[0].InputJSON != "" || terminal[0].InputImageCount != 1 {
|
||||
t.Fatalf("terminal jobs=%#v err=%v", terminal, err)
|
||||
}
|
||||
if err := repository.MarkMediaJobUsageRecorded(ctx, job.ID, completedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ?", job.ID).Pluck("input_json", &storedInput).Error; err != nil || storedInput != "{}" {
|
||||
t.Fatalf("recorded terminal input=%q err=%v", storedInput, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountDeleteDetachesTerminalMediaJobsAndRejectsActiveJobs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
|
||||
@@ -371,32 +371,35 @@ type webResponseStateModel struct {
|
||||
func (webResponseStateModel) TableName() string { return "web_response_states" }
|
||||
|
||||
type mediaJobModel struct {
|
||||
ID string `gorm:"size:64;primaryKey;check:chk_media_jobs_id,length(id) BETWEEN 1 AND 64"`
|
||||
RequestID string `gorm:"size:64;not null;check:chk_media_jobs_request_id,length(request_id) BETWEEN 1 AND 64"`
|
||||
ClientKeyID uint64 `gorm:"not null;check:chk_media_jobs_client_key_id,client_key_id > 0"`
|
||||
ClientKeyName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_client_key_name,length(client_key_name) <= 160"`
|
||||
AccountID *uint64 `gorm:"check:chk_media_jobs_account_id,account_id IS NULL OR account_id > 0"`
|
||||
AccountName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_account_name,length(account_name) <= 160"`
|
||||
EgressNodeID *uint64 `gorm:"check:chk_media_jobs_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"`
|
||||
EgressNodeName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_egress_node_name,length(egress_node_name) <= 160"`
|
||||
EgressScope string `gorm:"size:32;not null;default:'';check:chk_media_jobs_egress_scope,egress_scope IN ('','grok_web','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','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"`
|
||||
Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"`
|
||||
Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"`
|
||||
Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"`
|
||||
Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"`
|
||||
Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"`
|
||||
Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"`
|
||||
InputJSON string `gorm:"type:text;not null;default:'{}';check:chk_media_jobs_input_json,length(input_json) <= 33554432"`
|
||||
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"`
|
||||
ID string `gorm:"size:64;primaryKey;check:chk_media_jobs_id,length(id) BETWEEN 1 AND 64"`
|
||||
RequestID string `gorm:"size:64;not null;check:chk_media_jobs_request_id,length(request_id) BETWEEN 1 AND 64"`
|
||||
ClientKeyID uint64 `gorm:"not null;check:chk_media_jobs_client_key_id,client_key_id > 0"`
|
||||
ClientKeyName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_client_key_name,length(client_key_name) <= 160"`
|
||||
AccountID *uint64 `gorm:"check:chk_media_jobs_account_id,account_id IS NULL OR account_id > 0"`
|
||||
AccountName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_account_name,length(account_name) <= 160"`
|
||||
EgressNodeID *uint64 `gorm:"check:chk_media_jobs_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"`
|
||||
EgressNodeName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_egress_node_name,length(egress_node_name) <= 160"`
|
||||
EgressScope string `gorm:"size:32;not null;default:'';check:chk_media_jobs_egress_scope,egress_scope IN ('','grok_web','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','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"`
|
||||
Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"`
|
||||
Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"`
|
||||
Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"`
|
||||
Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"`
|
||||
Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"`
|
||||
Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"`
|
||||
// InputJSON limit 33554432 must stay equal to media.MaxInputJSONBytes (GORM tags require literals).
|
||||
InputJSON string `gorm:"type:text;not null;default:'{}';check:chk_media_jobs_input_json,length(input_json) <= 33554432"`
|
||||
// InputImageCount upper bound 8 must stay equal to media.MaxInputImages.
|
||||
InputImageCount *int `gorm:"check:chk_media_jobs_input_image_count,input_image_count IS NULL OR input_image_count BETWEEN 0 AND 8"`
|
||||
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"`
|
||||
LeaseUntil *time.Time
|
||||
ClaimToken string `gorm:"size:64;not null;default:'';check:chk_media_jobs_claim_token,claim_token = '' OR length(claim_token) BETWEEN 16 AND 64"`
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
|
||||
@@ -5,10 +5,13 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
)
|
||||
|
||||
func TestPostgresRepositoriesIntegration(t *testing.T) {
|
||||
@@ -25,6 +28,7 @@ func TestPostgresRepositoriesIntegration(t *testing.T) {
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifyPostgresMediaJobInputConstraintUpgrade(t, ctx, database)
|
||||
repository := NewAccountRepository(database)
|
||||
created, wasCreated, err := repository.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: "postgres", SourceKey: "postgres-integration-" + time.Now().UTC().Format("150405.000000"),
|
||||
@@ -110,3 +114,29 @@ func TestPostgresRepositoriesIntegration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func verifyPostgresMediaJobInputConstraintUpgrade(t *testing.T, ctx context.Context, database *Database) {
|
||||
t.Helper()
|
||||
tx := database.db.WithContext(ctx).Begin()
|
||||
if tx.Error != nil {
|
||||
t.Fatal(tx.Error)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := tx.Exec("ALTER TABLE media_jobs DROP CONSTRAINT IF EXISTS chk_media_jobs_input_json").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tx.Exec("ALTER TABLE media_jobs ADD CONSTRAINT chk_media_jobs_input_json CHECK (length(input_json) <= 1048576) NOT VALID").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testDatabase := &Database{db: tx, dialect: "postgres"}
|
||||
if err := testDatabase.ensureMediaJobInputConstraint(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
definition, err := testDatabase.constraintDefinition(ctx, consoleConstraint{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_input_json"})
|
||||
if err != nil || !strings.Contains(definition, strconv.Itoa(media.MaxInputJSONBytes)) || strings.Contains(definition, "1048576") {
|
||||
t.Fatalf("postgres input constraint = %q, err=%v", definition, err)
|
||||
}
|
||||
if err := testDatabase.ensureMediaJobInputConstraint(ctx); err != nil {
|
||||
t.Fatalf("postgres input constraint migration is not idempotent: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,16 @@ package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
)
|
||||
|
||||
const mediaJobInputMetadataPendingIndex = "CREATE INDEX IF NOT EXISTS idx_media_jobs_input_metadata_pending ON media_jobs(id) WHERE input_image_count IS NULL"
|
||||
|
||||
var schemaModels = []any{
|
||||
&adminModel{},
|
||||
&adminSessionModel{},
|
||||
@@ -77,6 +83,8 @@ var schemaIndexes = []string{
|
||||
"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 <> ''",
|
||||
// Pending input metadata rows only; keeps startup backfill scans off the full table after migration completes.
|
||||
mediaJobInputMetadataPendingIndex,
|
||||
}
|
||||
|
||||
// InitializeSchema 以当前持久化模型作为首版数据库结构基线。
|
||||
@@ -114,6 +122,14 @@ func (d *Database) InitializeSchema(ctx context.Context) error {
|
||||
if err := d.ensureMediaJobInputConstraint(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media job 输入长度约束: %w", err)
|
||||
}
|
||||
// Create the pending-metadata partial index before backfill so both first
|
||||
// upgrade and subsequent empty scans avoid walking the full media_jobs table.
|
||||
if err := d.ensureMediaJobInputMetadataPendingIndex(ctx); err != nil {
|
||||
return fmt.Errorf("初始化 media job 输入元数据索引: %w", err)
|
||||
}
|
||||
if err := d.migrateMediaJobInputMetadata(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media job 输入元数据: %w", err)
|
||||
}
|
||||
if err := d.ensureMediaJobAccountForeignKey(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media job 账号外键: %w", err)
|
||||
}
|
||||
@@ -173,9 +189,73 @@ func (d *Database) ensureMediaJobConstraints(ctx context.Context) error {
|
||||
// ensureMediaJobInputConstraint 允许异步视频任务持久化 Base64 首图。
|
||||
// SQLite 和 PostgreSQL 都不会由 AutoMigrate 可靠替换已有的同名 CHECK。
|
||||
func (d *Database) ensureMediaJobInputConstraint(ctx context.Context) error {
|
||||
return d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
if err := d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_input_json"},
|
||||
}, "33554432")
|
||||
}, strconv.Itoa(media.MaxInputJSONBytes)); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_input_image_count"},
|
||||
}, strconv.Itoa(media.MaxInputImages))
|
||||
}
|
||||
|
||||
// ensureMediaJobInputMetadataPendingIndex accelerates the one-shot input_image_count
|
||||
// backfill and keeps later startup probes from full-scanning media_jobs after completion.
|
||||
func (d *Database) ensureMediaJobInputMetadataPendingIndex(ctx context.Context) error {
|
||||
if err := d.db.WithContext(ctx).Exec(mediaJobInputMetadataPendingIndex).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateMediaJobInputMetadata backfills the compact image count introduced
|
||||
// after InputJSON began accepting large Base64 references. Already-audited
|
||||
// terminal jobs can discard the raw payload immediately; active and unaudited
|
||||
// jobs retain it for worker recovery.
|
||||
func (d *Database) migrateMediaJobInputMetadata(ctx context.Context) error {
|
||||
db := d.db.WithContext(ctx)
|
||||
terminal := []string{"completed", "failed"}
|
||||
if err := db.Model(&mediaJobModel{}).
|
||||
Where("status IN ? AND usage_recorded_at IS NOT NULL AND input_json <> ?", terminal, "{}").
|
||||
UpdateColumn("input_json", "{}").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
type inputRow struct {
|
||||
ID string
|
||||
InputJSON string
|
||||
}
|
||||
const batchSize = 8
|
||||
cursor := ""
|
||||
for {
|
||||
var rows []inputRow
|
||||
query := db.Model(&mediaJobModel{}).
|
||||
Select("id", "input_json").
|
||||
Where("id > ? AND input_image_count IS NULL", cursor).
|
||||
Order("id ASC").Limit(batchSize)
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, row := range rows {
|
||||
var input struct {
|
||||
ImageURLs []string `json:"image_urls"`
|
||||
}
|
||||
parseErr := json.Unmarshal([]byte(row.InputJSON), &input)
|
||||
count := min(len(input.ImageURLs), media.MaxInputImages)
|
||||
updates := map[string]any{"input_image_count": count}
|
||||
// Historical code treated malformed or empty input as no references.
|
||||
// Normalize it once so future startups do not rescan the same row.
|
||||
if parseErr != nil || count == 0 {
|
||||
updates["input_json"] = "{}"
|
||||
}
|
||||
if err := db.Model(&mediaJobModel{}).Where("id = ?", row.ID).UpdateColumns(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cursor = rows[len(rows)-1].ID
|
||||
}
|
||||
}
|
||||
|
||||
// ensureMediaJobAccountForeignKey 让终态视频任务在账号删除后保留快照,
|
||||
|
||||
@@ -2,8 +2,11 @@ package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -42,9 +45,113 @@ func TestMediaJobModelTagsAllowBuildVideoProviderAndScope(t *testing.T) {
|
||||
t.Fatal("InputJSON field missing")
|
||||
}
|
||||
inputTag := inputField.Tag.Get("gorm")
|
||||
limitLiteral := strconv.Itoa(mediadomain.MaxInputJSONBytes)
|
||||
if !strings.Contains(inputTag, "chk_media_jobs_input_json") ||
|
||||
!strings.Contains(inputTag, "33554432") || strings.Contains(inputTag, "1048576") {
|
||||
t.Fatalf("input_json tag = %q", inputTag)
|
||||
!strings.Contains(inputTag, limitLiteral) || strings.Contains(inputTag, "1048576") {
|
||||
t.Fatalf("input_json tag = %q, want limit %s", inputTag, limitLiteral)
|
||||
}
|
||||
countField, ok := modelType.FieldByName("InputImageCount")
|
||||
if !ok {
|
||||
t.Fatal("InputImageCount field missing")
|
||||
}
|
||||
countTag := countField.Tag.Get("gorm")
|
||||
maxImages := strconv.Itoa(mediadomain.MaxInputImages)
|
||||
if !strings.Contains(countTag, "chk_media_jobs_input_image_count") ||
|
||||
!strings.Contains(countTag, "IS NULL OR input_image_count BETWEEN 0 AND "+maxImages) {
|
||||
t.Fatalf("input_image_count tag = %q, want max %s", countTag, maxImages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaJobInputMetadataPendingIndexExists(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-input-pending-index.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err := database.db.WithContext(ctx).Raw(
|
||||
`SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?`,
|
||||
"idx_media_jobs_input_metadata_pending",
|
||||
).Scan(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("pending metadata index count = %d", count)
|
||||
}
|
||||
var sql string
|
||||
if err := database.db.WithContext(ctx).Raw(
|
||||
`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?`,
|
||||
"idx_media_jobs_input_metadata_pending",
|
||||
).Scan(&sql).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(sql), "input_image_count is null") {
|
||||
t.Fatalf("pending index sql = %q", sql)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeSchemaUpgradesOnlyPreviousMediaJobInputConstraint(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "previous-media-input.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "previous-media-account", SourceKey: "previous-media-account",
|
||||
EncryptedAccessToken: testEncryptedToken, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := clientKeyModel{Name: "previous-media-key", Prefix: "previous-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)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
existing := testMediaJob("video_previous_input", accountValue.ID, key.ID, mediadomain.StatusQueued, now)
|
||||
existing.InputJSON = `{"image_urls":["data:image/png;base64,AAAA"]}`
|
||||
if err := NewMediaJobRepository(database).CreateMediaJob(ctx, existing); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ?", existing.ID).UpdateColumn("input_image_count", nil).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := downgradeOnlyMediaJobInputConstraint(ctx, database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertMediaJobSQLLacksNewInputLimit(t, database)
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertMediaJobSQLContainsBuild(t, database)
|
||||
var migrated mediaJobModel
|
||||
if err := database.db.WithContext(ctx).Where("id = ?", existing.ID).First(&migrated).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if migrated.InputJSON != existing.InputJSON || migrated.InputImageCount == nil || *migrated.InputImageCount != 1 {
|
||||
t.Fatalf("migrated input json len=%d count=%v", len(migrated.InputJSON), migrated.InputImageCount)
|
||||
}
|
||||
large := testMediaJob("video_previous_large", accountValue.ID, key.ID, mediadomain.StatusQueued, now)
|
||||
large.InputJSON = `{"image_urls":["` + strings.Repeat("A", (1<<20)+1) + `"]}`
|
||||
large.InputImageCount = 1
|
||||
if err := NewMediaJobRepository(database).CreateMediaJob(ctx, large); err != nil {
|
||||
t.Fatalf("upgraded input constraint rejected large payload: %v", err)
|
||||
}
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.db.WithContext(ctx).Where("id = ?", existing.ID).First(&migrated).Error; err != nil || migrated.InputImageCount == nil || *migrated.InputImageCount != 1 {
|
||||
t.Fatalf("idempotent migration lost existing job: %#v, err=%v", migrated, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +321,17 @@ func assertMediaJobSQLLacksBuild(t *testing.T, database *Database) {
|
||||
}
|
||||
}
|
||||
|
||||
func assertMediaJobSQLLacksNewInputLimit(t *testing.T, database *Database) {
|
||||
t.Helper()
|
||||
sql := mediaJobsTableSQL(t, database)
|
||||
if !strings.Contains(sql, "1048576") || strings.Contains(sql, strconv.Itoa(mediadomain.MaxInputJSONBytes)) {
|
||||
t.Fatalf("previous media_jobs input constraint was not installed: %s", sql)
|
||||
}
|
||||
if !strings.Contains(sql, "grok_build") || !strings.Contains(strings.ToUpper(sql), "ON DELETE SET NULL") {
|
||||
t.Fatalf("fixture changed unrelated v3.0.6 constraints: %s", sql)
|
||||
}
|
||||
}
|
||||
|
||||
func assertMediaJobSQLContainsBuild(t *testing.T, database *Database) {
|
||||
t.Helper()
|
||||
sql := mediaJobsTableSQL(t, database)
|
||||
@@ -226,8 +344,9 @@ func assertMediaJobSQLContainsBuild(t *testing.T, database *Database) {
|
||||
if !strings.Contains(strings.ToUpper(sql), "ON DELETE SET NULL") {
|
||||
t.Fatalf("media_jobs account history is not detached on account delete: %s", sql)
|
||||
}
|
||||
if !strings.Contains(sql, "33554432") || strings.Contains(sql, "1048576") {
|
||||
t.Fatalf("media_jobs input_json limit was not upgraded: %s", sql)
|
||||
limitLiteral := strconv.Itoa(mediadomain.MaxInputJSONBytes)
|
||||
if !strings.Contains(sql, limitLiteral) || strings.Contains(sql, "1048576") {
|
||||
t.Fatalf("media_jobs input_json limit was not upgraded to %s: %s", limitLiteral, sql)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,3 +358,29 @@ func mediaJobsTableSQL(t *testing.T, database *Database) string {
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
func downgradeOnlyMediaJobInputConstraint(ctx context.Context, database *Database) error {
|
||||
return database.withSQLiteForeignKeysDisabled(ctx, func() error {
|
||||
db := database.db.WithContext(ctx)
|
||||
var currentSQL string
|
||||
if err := db.Raw("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", "media_jobs").Scan(¤tSQL).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
createPattern := regexp.MustCompile("(?i)^CREATE TABLE\\s+[`\"]?media_jobs[`\"]?")
|
||||
previousSQL := createPattern.ReplaceAllString(currentSQL, "CREATE TABLE media_jobs_previous")
|
||||
previousSQL = strings.Replace(previousSQL, strconv.Itoa(mediadomain.MaxInputJSONBytes), "1048576", 1)
|
||||
if previousSQL == currentSQL || !strings.Contains(previousSQL, "1048576") {
|
||||
return fmt.Errorf("无法构造上一版本 media_jobs schema")
|
||||
}
|
||||
if err := db.Exec(previousSQL).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Exec("INSERT INTO media_jobs_previous SELECT * FROM media_jobs").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Exec("DROP TABLE media_jobs").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Exec("ALTER TABLE media_jobs_previous RENAME TO media_jobs").Error
|
||||
})
|
||||
}
|
||||
@@ -584,8 +584,8 @@ func (h *Handler) generateVideo(c *gin.Context) {
|
||||
if request.Image != nil {
|
||||
inputs = append([]videoGenerationImage{*request.Image}, inputs...)
|
||||
}
|
||||
if len(inputs) > 8 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image 与 reference_images 合计不能超过 8 张")
|
||||
if len(inputs) > mediadomain.MaxInputImages {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("image 与 reference_images 合计不能超过 %d 张", mediadomain.MaxInputImages))
|
||||
return
|
||||
}
|
||||
referenceURLs := make([]string, 0, len(inputs))
|
||||
@@ -1468,6 +1468,9 @@ func writeGatewayError(c *gin.Context, err error) {
|
||||
case errors.Is(err, gateway.ErrResponseStateUnsupported), errors.Is(err, gateway.ErrConversationUnsupported):
|
||||
status, code = http.StatusBadRequest, "unsupported_parameter"
|
||||
message = err.Error()
|
||||
case errors.Is(err, gateway.ErrVideoInputTooLarge):
|
||||
status, code = http.StatusBadRequest, "invalid_request"
|
||||
message = err.Error()
|
||||
case errors.As(err, &upstreamFailure):
|
||||
if isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) {
|
||||
code = upstreamFailure.ClientCredentialErrorCode()
|
||||
|
||||
@@ -138,6 +138,19 @@ func TestGatewayErrorDoesNotExposeInternalDetails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayErrorMapsOversizedVideoInputToBadRequest(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
writeGatewayError(c, gateway.ErrVideoInputTooLarge)
|
||||
})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":"invalid_request"`) || !strings.Contains(recorder.Body.String(), "32 MiB") {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayErrorHidesUpstreamCredentialStatus(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
openAIRouter := gin.New()
|
||||
|
||||
Reference in new issue
Block a user