From 845bff84df7ab0836b055a88f964efde4e8f3577 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Tue, 14 Jul 2026 18:11:15 +0800 Subject: [PATCH] refactor: enhance media job auditing and error handling with egress tracking and improved job status management --- .../internal/application/gateway/service.go | 49 +++++++++++++------ .../application/gateway/service_test.go | 43 +++++++++++++++- backend/internal/application/gateway/video.go | 44 ++++++++++------- .../application/gateway/video_test.go | 31 +++++++++++- backend/internal/infra/egress/trace.go | 3 ++ .../relational/media_repository.go | 10 ++-- .../relational/web_state_repository_test.go | 18 ++++++- backend/internal/repository/media.go | 2 +- 8 files changed, 157 insertions(+), 43 deletions(-) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 36aa7b00..a77c0629 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -747,6 +747,32 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client if !ok { return nil, ErrNoAvailableAccount } + auditBase := audit.Record{ + EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name, + ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), + Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: streaming, + } + if operation == audit.OperationImageEdit { + auditBase.MediaInputImages = int64(max(0, inputImageCount)) + } + writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) { + record := auditBase + record.StatusCode = statusCode + record.ErrorCode = errorCode + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + if credential != nil { + accountID := credential.ID + record.AccountID = &accountID + record.AccountName = credential.Name + } + applyAuditEgress(&record, egressTrace, route.Provider) + persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) + defer cancel() + if auditErr := s.audits.Create(persistCtx, record); auditErr != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr) + } + } pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel) var reservation audit.PricingResult var priced bool @@ -781,6 +807,7 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client for attempt := 0; attempt < attempts; attempt++ { lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, "", excluded, false) if err != nil { + writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", nil) return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) } excluded[lease.Credential.ID] = true @@ -788,6 +815,7 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client if err != nil { s.logger.Error("image_credential_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", lease.Credential.ID, "error", err) lease.Release() + writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &lease.Credential) return nil, err } response, err = execute(ctx, adapter, credential, route.UpstreamModel) @@ -795,6 +823,7 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client s.logger.Error("image_upstream_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", credential.ID, "error", err) s.selector.MarkFailure(ctx, credential, 0, 0) lease.Release() + writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential) return nil, err } if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attempt+1 < attempts { @@ -830,23 +859,13 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client lease.Release() persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) defer cancel() - record := audit.Record{ - EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name, - ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), - Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, - AccountID: &accountID, AccountName: credential.Name, StatusCode: response.StatusCode, - Streaming: streaming, ErrorCode: errorCode, - DurationMS: time.Since(startedAt).Milliseconds(), CreatedAt: time.Now().UTC(), - } + record := auditBase + record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode + record.ErrorCode = errorCode + record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC() applyAuditEgress(&record, egressTrace, route.Provider) - switch operation { - case audit.OperationImage: - record.MediaOutputImages = int64(max(0, requestedCount)) - case audit.OperationImageEdit: - record.MediaInputImages = int64(max(0, inputImageCount)) - record.MediaOutputImages = int64(max(0, requestedCount)) - } if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" { + record.MediaOutputImages = int64(max(0, requestedCount)) var pricing audit.PricingResult var priced bool switch operation { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 005ebbf6..c2f998bd 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -19,8 +19,10 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/domain/clientkey" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" @@ -651,6 +653,30 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { if adapter.EditResolution() != "2k" { t.Fatalf("image edit resolution = %q", adapter.EditResolution()) } + + billingBeforeFailure, err := keyRepo.Get(ctx, key.ID) + if err != nil { + t.Fatal(err) + } + adapter.FailWithEgress(infraegress.NewManager(relational.NewEgressRepository(database), testCipher(t))) + if _, err := service.GenerateImage(ctx, ImageGenerationInput{ + RequestID: "req-image-failed", ClientKey: key, PublicModel: "grok-imagine-image-quality", + Prompt: "test", Count: 1, Resolution: "1k", ResponseFormat: "url", + }); err == nil { + t.Fatal("expected image transport failure") + } + logs, total, err = auditRepo.List(ctx, 0, 10) + if err != nil || total != 5 || len(logs) != 5 { + t.Fatalf("failure audit logs=%#v total=%d err=%v", logs, total, err) + } + failureAudit := logs[0] + if failureAudit.RequestID != "req-image-failed" || failureAudit.StatusCode != http.StatusBadGateway || failureAudit.ErrorCode != "upstream_unavailable" || failureAudit.MediaOutputImages != 0 || failureAudit.EstimatedCostInUSDTicks != 0 || failureAudit.EgressMode != audit.EgressModeDirect || failureAudit.EgressScope != string(egressdomain.ScopeWeb) || failureAudit.EgressNodeName != "direct" { + t.Fatalf("failure audit = %#v", failureAudit) + } + updatedKey, err := keyRepo.Get(ctx, key.ID) + if err != nil || updatedKey.ReservedUsageUSDTicks != 0 || updatedKey.BilledUsageUSDTicks != billingBeforeFailure.BilledUsageUSDTicks { + t.Fatalf("failed image billing key = %#v, err = %v", updatedKey, err) + } } func TestSuccessfulWebChatRefreshesCurrentModeQuota(t *testing.T) { @@ -844,6 +870,7 @@ type webImageStreamAdapter struct { streaming bool editResolution string synced chan string + failureEgress *infraegress.Manager } type webChatQuotaAdapter struct { @@ -877,10 +904,19 @@ func (a *webImageStreamAdapter) QuotaMode(model string) string { func (a *webImageStreamAdapter) TierOrder(string) []account.WebTier { return []account.WebTier{account.WebTierSuper, account.WebTierHeavy} } -func (a *webImageStreamAdapter) GenerateImage(_ context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { +func (a *webImageStreamAdapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { a.mu.Lock() a.streaming = request.Streaming + failureEgress := a.failureEgress a.mu.Unlock() + if failureEgress != nil { + lease, err := failureEgress.Acquire(ctx, egressdomain.ScopeWeb, "image-failure") + if err != nil { + return nil, err + } + lease.Release() + return nil, errors.New("simulated image transport failure") + } body := "event: image_generation.completed\ndata: {}\n\ndata: [DONE]\n\n" return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body)), QuotaUnits: 1}, nil } @@ -909,6 +945,11 @@ func (a *webImageStreamAdapter) EditResolution() string { defer a.mu.Unlock() return a.editResolution } +func (a *webImageStreamAdapter) FailWithEgress(manager *infraegress.Manager) { + a.mu.Lock() + a.failureEgress = manager + a.mu.Unlock() +} func (a *webImageStreamAdapter) SyncQuota(context.Context, account.Credential) (provider.QuotaSnapshot, error) { return provider.QuotaSnapshot{}, errors.New("unexpected full quota sync") } diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index a3b8298b..bb83734d 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -201,16 +201,7 @@ func (s *Service) processVideoJob(ctx context.Context, id string) { route, err = s.models.GetByPublicID(ctx, job.Model) } if err != nil { - now := time.Now().UTC() - job.Status = media.StatusFailed - job.ErrorCode = "model_not_found" - job.ErrorMessage = "模型路由不存在" - job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now - if err := s.mediaJobs.UpdateMediaJob(ctx, job); err != nil { - s.logger.Warn("video_job_terminal_write_failed", "job_id", job.ID, "error", err) - } else { - s.cancelBillingReservation("video_usage_" + job.ID) - } + s.failVideoJob(ctx, job, "model_not_found", errors.New("模型路由不存在")) return } s.runVideoJob(ctx, job, route) @@ -293,6 +284,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model _ = s.accounts.MarkReauthRequired(context.Background(), lease.Credential.ID, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider)) } s.selector.MarkFailure(context.Background(), lease.Credential, 0, 0) + applyMediaJobEgress(&job, egressTrace, route.Provider) s.failVideoJob(parent, job, "generation_failed", err) return } @@ -305,7 +297,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } s.selector.MarkSuccess(context.Background(), lease.Credential) - if err := s.recordVideoUsage(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { + if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", err) } if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode == "weekly" { @@ -314,7 +306,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } func (s *Service) reconcileVideoUsage(ctx context.Context) error { - jobs, err := s.mediaJobs.ListUnrecordedCompletedMediaJobs(ctx, 200) + jobs, err := s.mediaJobs.ListUnrecordedTerminalMediaJobs(ctx, 200) if err != nil { return err } @@ -324,29 +316,42 @@ func (s *Service) reconcileVideoUsage(ctx context.Context) error { if job.CompletedAt != nil { durationMS = max(int64(0), job.CompletedAt.Sub(job.CreatedAt).Milliseconds()) } - if err := s.recordVideoUsage(ctx, job, durationMS); err != nil { + if err := s.recordVideoAudit(ctx, job, durationMS); err != nil { result = firstError(result, fmt.Errorf("任务 %s: %w", job.ID, err)) } } return result } -func (s *Service) recordVideoUsage(ctx context.Context, job media.Job, durationMS int64) error { +func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationMS int64) error { accountID := job.AccountID createdAt := time.Now().UTC() if job.CompletedAt != nil && !job.CompletedAt.IsZero() { createdAt = job.CompletedAt.UTC() } + statusCode := http.StatusOK + if job.Status == media.StatusFailed { + statusCode = http.StatusBadGateway + switch job.ErrorCode { + case "account_unavailable", "provider_unavailable": + statusCode = http.StatusServiceUnavailable + case "model_not_found": + statusCode = http.StatusNotFound + } + } record := audit.Record{ EventID: "video_usage_" + job.ID, RequestID: job.RequestID, ClientKeyID: job.ClientKeyID, ClientKeyName: job.ClientKeyName, ModelRouteID: job.ModelRouteID, ModelPublicID: job.Model, ModelUpstreamModel: job.UpstreamModel, Provider: job.Provider, Operation: audit.OperationVideo, UsageSource: audit.UsageSourceNone, - AccountID: &accountID, AccountName: job.AccountName, StatusCode: http.StatusOK, + 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))), MediaOutputSeconds: int64(max(0, job.Seconds)), - DurationMS: durationMS, CreatedAt: createdAt, + MediaInputImages: int64(len(decodeVideoInput(job.InputJSON))), + DurationMS: durationMS, CreatedAt: createdAt, } - if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok { + if job.Status == media.StatusCompleted { + record.MediaOutputSeconds = int64(max(0, job.Seconds)) + } + if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok && job.Status == media.StatusCompleted { record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks record.PricingModel = pricing.Model record.PricingVersion = audit.OfficialPricingAsOf @@ -387,6 +392,9 @@ func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", updateErr) return } + if auditErr := s.recordVideoAudit(context.Background(), job, max(int64(0), now.Sub(job.CreatedAt).Milliseconds())); auditErr != nil { + s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", auditErr) + } s.cancelBillingReservation("video_usage_" + job.ID) } diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index f3bad936..d2ff1291 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -39,6 +39,33 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { } } +func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) { + completedAt := time.Now().UTC() + nodeID := uint64(42) + repository := &videoUsageRepository{job: media.Job{ + ID: "video_failed_recovery", RequestID: "request-failed-recovery", + ClientKeyID: 1, ClientKeyName: "client", AccountID: 2, AccountName: "account", + Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 3, UpstreamModel: "video", + Seconds: 8, Quality: "720p", Status: media.StatusFailed, ErrorCode: "generation_failed", ErrorMessage: "upstream disconnected", + EgressNodeID: &nodeID, EgressNodeName: "warp", EgressScope: "grok_web", EgressMode: "proxy", + InputJSON: `{}`, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt, + }} + recorder := &durableVideoAuditRecorder{} + service := &Service{mediaJobs: repository, audits: recorder} + if err := service.RecoverVideoJobs(context.Background()); err != nil { + t.Fatal(err) + } + if repository.job.UsageRecordedAt == nil || recorder.calls != 1 { + t.Fatalf("recordedAt = %v, audit calls = %d", repository.job.UsageRecordedAt, recorder.calls) + } + if recorder.last.StatusCode != 502 || recorder.last.ErrorCode != "generation_failed" || recorder.last.EgressNodeID == nil || *recorder.last.EgressNodeID != nodeID || recorder.last.EgressNodeName != "warp" || recorder.last.EgressMode != audit.EgressModeProxy { + t.Fatalf("audit = %#v", recorder.last) + } + if recorder.last.EstimatedCostInUSDTicks != 0 || recorder.last.MediaOutputSeconds != 0 { + t.Fatalf("failed job was billed: %#v", recorder.last) + } +} + func TestVideoQueueIsBoundedAndDeduplicated(t *testing.T) { service := &Service{} service.ConfigureMedia(&videoUsageRepository{}, 1) @@ -95,8 +122,8 @@ func (r *videoUsageRepository) ListRecoverableMediaJobs(context.Context, int) ([ return nil, nil } -func (r *videoUsageRepository) ListUnrecordedCompletedMediaJobs(context.Context, int) ([]media.Job, error) { - if r.job.UsageRecordedAt != nil { +func (r *videoUsageRepository) ListUnrecordedTerminalMediaJobs(context.Context, int) ([]media.Job, error) { + if r.job.UsageRecordedAt != nil || (r.job.Status != media.StatusCompleted && r.job.Status != media.StatusFailed) { return nil, nil } return []media.Job{r.job}, nil diff --git a/backend/internal/infra/egress/trace.go b/backend/internal/infra/egress/trace.go index 53b7065a..79267b8d 100644 --- a/backend/internal/infra/egress/trace.go +++ b/backend/internal/infra/egress/trace.go @@ -25,6 +25,7 @@ type Trace struct { type traceContextKey struct{} +// WithTrace 为一次网关请求创建或复用并发安全的出口选择轨迹。 func WithTrace(ctx context.Context) (context.Context, *Trace) { if existing := TraceFromContext(ctx); existing != nil { return ctx, existing @@ -33,6 +34,7 @@ func WithTrace(ctx context.Context) (context.Context, *Trace) { return context.WithValue(ctx, traceContextKey{}, trace), trace } +// TraceFromContext 返回上下文中的出口轨迹;未配置时返回 nil。 func TraceFromContext(ctx context.Context) *Trace { if ctx == nil { return nil @@ -41,6 +43,7 @@ func TraceFromContext(ctx context.Context) *Trace { return trace } +// Selection 返回指定作用域最后一次实际出口选择的安全快照。 func (t *Trace) Selection(scope domain.Scope) (Selection, bool) { if t == nil { return Selection{}, false diff --git a/backend/internal/infra/persistence/relational/media_repository.go b/backend/internal/infra/persistence/relational/media_repository.go index b405c143..326a5150 100644 --- a/backend/internal/infra/persistence/relational/media_repository.go +++ b/backend/internal/infra/persistence/relational/media_repository.go @@ -187,12 +187,13 @@ func (r *MediaJobRepository) SummarizeMediaJobs(ctx context.Context) (repository return stats, err } -func (r *MediaJobRepository) ListUnrecordedCompletedMediaJobs(ctx context.Context, limit int) ([]media.Job, error) { +// ListUnrecordedTerminalMediaJobs 返回尚未完成审计写入的成功或失败任务。 +func (r *MediaJobRepository) ListUnrecordedTerminalMediaJobs(ctx context.Context, limit int) ([]media.Job, error) { if limit <= 0 || limit > 1000 { limit = 200 } var rows []mediaJobModel - if err := r.db.db.WithContext(ctx).Where("status = ? AND usage_recorded_at IS NULL", media.StatusCompleted).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil { + if err := r.db.db.WithContext(ctx).Where("status IN ? AND usage_recorded_at IS NULL", []media.Status{media.StatusCompleted, media.StatusFailed}).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil { return nil, err } values := make([]media.Job, 0, len(rows)) @@ -203,13 +204,14 @@ func (r *MediaJobRepository) ListUnrecordedCompletedMediaJobs(ctx context.Contex } func (r *MediaJobRepository) MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error { - result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status = ? AND usage_recorded_at IS NULL", id, media.StatusCompleted).Update("usage_recorded_at", recordedAt) + terminalStatuses := []media.Status{media.StatusCompleted, media.StatusFailed} + result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NULL", id, terminalStatuses).Update("usage_recorded_at", recordedAt) if result.Error != nil { return result.Error } if result.RowsAffected == 0 { var count int64 - if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status = ? AND usage_recorded_at IS NOT NULL", id, media.StatusCompleted).Count(&count).Error; err != nil { + if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NOT NULL", id, terminalStatuses).Count(&count).Error; err != nil { return err } if count == 0 { diff --git a/backend/internal/infra/persistence/relational/web_state_repository_test.go b/backend/internal/infra/persistence/relational/web_state_repository_test.go index a3e0b62a..f0a1fc7e 100644 --- a/backend/internal/infra/persistence/relational/web_state_repository_test.go +++ b/backend/internal/infra/persistence/relational/web_state_repository_test.go @@ -68,15 +68,29 @@ func TestWebResponseStateAndMediaJobRoundTrip(t *testing.T) { if err := jobs.UpdateMediaJob(ctx, claimed); err != nil { t.Fatal(err) } - unrecorded, err := jobs.ListUnrecordedCompletedMediaJobs(ctx, 10) + unrecorded, err := jobs.ListUnrecordedTerminalMediaJobs(ctx, 10) if err != nil || len(unrecorded) != 1 || unrecorded[0].RequestID != job.RequestID || unrecorded[0].ModelRouteID != job.ModelRouteID { t.Fatalf("unrecorded jobs = %#v, err = %v", unrecorded, err) } if err := jobs.MarkMediaJobUsageRecorded(ctx, job.ID, completedAt.Add(time.Second)); err != nil { t.Fatal(err) } - unrecorded, err = jobs.ListUnrecordedCompletedMediaJobs(ctx, 10) + unrecorded, err = jobs.ListUnrecordedTerminalMediaJobs(ctx, 10) if err != nil || len(unrecorded) != 0 { t.Fatalf("recorded jobs = %#v, err = %v", unrecorded, err) } + failedAt := completedAt.Add(2 * time.Second) + failed := job + failed.ID, failed.RequestID, failed.Status, failed.ErrorCode = "video_failed", "request-video-failed", mediadomain.StatusFailed, "generation_failed" + failed.Progress, failed.ClaimToken, failed.CompletedAt, failed.UpdatedAt = 50, "", &failedAt, failedAt + if err := jobs.CreateMediaJob(ctx, failed); err != nil { + t.Fatal(err) + } + unrecorded, err = jobs.ListUnrecordedTerminalMediaJobs(ctx, 10) + if err != nil || len(unrecorded) != 1 || unrecorded[0].ID != failed.ID { + t.Fatalf("failed unrecorded jobs = %#v, err = %v", unrecorded, err) + } + if err := jobs.MarkMediaJobUsageRecorded(ctx, failed.ID, failedAt.Add(time.Second)); err != nil { + t.Fatal(err) + } } diff --git a/backend/internal/repository/media.go b/backend/internal/repository/media.go index b1fbd920..525ec405 100644 --- a/backend/internal/repository/media.go +++ b/backend/internal/repository/media.go @@ -46,7 +46,7 @@ type MediaJobRepository interface { ListMediaJobs(ctx context.Context, query MediaJobListQuery) ([]media.Job, int64, error) SummarizeMediaJobs(ctx context.Context) (MediaJobStats, error) ListRecoverableMediaJobs(ctx context.Context, limit int) ([]media.Job, error) - ListUnrecordedCompletedMediaJobs(ctx context.Context, limit int) ([]media.Job, error) + ListUnrecordedTerminalMediaJobs(ctx context.Context, limit int) ([]media.Job, error) TryClaimMediaJob(ctx context.Context, id string, now, leaseUntil time.Time, claimToken string) (media.Job, bool, error) MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error }