Skip to content

feat: add error handling better logging and tests for mux uploads#8700

Open
tanflem wants to merge 3 commits intomainfrom
tannerfleming/vmt-210-add-better-logging-and-tests-for-mux-uploads
Open

feat: add error handling better logging and tests for mux uploads#8700
tanflem wants to merge 3 commits intomainfrom
tannerfleming/vmt-210-add-better-logging-and-tests-for-mux-uploads

Conversation

@tanflem
Copy link
Contributor

@tanflem tanflem commented Feb 5, 2026

Summary by CodeRabbit

  • Bug Fixes

    • More robust video processing: faster detection of failed encodes, explicit handling of errored/timeouts, improved retry and cleanup behavior for downstream downloads, and clearer structured diagnostics for failures.
  • Tests

    • Added end-to-end tests covering successful processing and error paths to validate control flow, retries, and logging.

@tanflem tanflem requested a review from Kneesal February 5, 2026 17:30
@tanflem tanflem self-assigned this Feb 5, 2026
@linear
Copy link

linear bot commented Feb 5, 2026

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 5, 2026

Walkthrough

Adds tests for processVideoUploads and expands ProcessVideoUploadJobData export. Changes introduce explicit mux 'errored' and 'timeout' handling with early returns, structured logging enhancements, and updated control flow for creating variants, DB updates, and enqueueing download jobs.

Changes

Cohort / File(s) Summary
Tests
apis/api-media/src/workers/processVideoUploads/service/service.spec.ts
Adds test suite covering success (mux ready → playbackId recorded, variant/video updated, download job enqueued) and error (mux errored → errors logged, no DB/queue actions) paths; mocks Mux, Prisma, and download queue.
Service Implementation
apis/api-media/src/workers/processVideoUploads/service/service.ts
Exports ProcessVideoUploadJobData with new fields (version, muxVideoId, metadata, originalFilename). Adds early-return handling for errored mux status and explicit timeout branch. Replaces string logs with structured logging across wait/poll/create/update flows and enriches error contexts. Updates waitForMuxVideoCompletion types and adds immediate errored detection during polling.

Sequence Diagram(s)

sequenceDiagram
    participant Worker
    participant Service
    participant MuxAPI
    participant Database
    participant DownloadQueue
    participant Logger

    Worker->>Service: invoke processVideoUpload(jobData)
    Service->>Database: getVideo(videoId)
    Service->>MuxAPI: poll waitForMuxVideoCompletion(muxVideoId)
    alt mux ready
        MuxAPI-->>Service: playbackId, status=ready
        Service->>Database: createVideoVariant(...) / updateVideo(...)
        Service->>DownloadQueue: enqueue download job (backoff, cleanup)
        Service->>Logger: info structured (videoId, muxVideoId, playbackId)
    else mux errored
        MuxAPI-->>Service: status=errored
        Service->>Logger: error structured (videoId, muxVideoId, assetId)
        Service-->>Worker: return / exit
    else timeout
        MuxAPI-->>Service: status=timeout
        Service->>Logger: warn structured (videoId, muxVideoId)
        Service-->>Worker: return / exit
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • mikeallisonJS
  • philuren66
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: adding error handling, improving logging, and introducing tests for mux upload processing.
Linked Issues check ✅ Passed The pull request implements error handling improvements, enhanced logging with structured data, and comprehensive tests for mux video uploads as indicated by the linked issue.
Out of Scope Changes check ✅ Passed All changes are directly related to improving error handling, logging, and test coverage for the mux upload service, with no out-of-scope modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tannerfleming/vmt-210-add-better-logging-and-tests-for-mux-uploads

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apis/api-media/src/workers/processVideoUploads/service/service.ts`:
- Around line 205-206: The code may throw a TypeError when
muxVideoAsset.playback_ids is an empty array because playback_ids?.[0].id
assumes the first element exists; update the playbackId extraction to use safe
optional chaining (e.g., use muxVideoAsset?.playback_ids?.[0]?.id) so it yields
undefined when no playback id exists, and keep the existing ready-status check
(muxVideoAsset.status === 'ready') to gate downstream logic; modify the
playbackId assignment where the variable playbackId is defined in the service.ts
file to use the additional ?. before .id.
🧹 Nitpick comments (3)
apis/api-media/src/workers/processVideoUploads/service/service.ts (1)

133-158: Consider using early return after successful variant creation.

Per coding guidelines, early returns improve readability. After successfully creating the variant, an early return would clarify that the success path is complete and avoid unnecessary condition checks.

♻️ Suggested refactor
     if (finalStatus === 'ready' && playbackId) {
       await createVideoVariant({
         videoId,
         edition,
         languageId,
         version,
         muxVideoId,
         playbackId,
         metadata,
         logger
       })
+      return
     }
+
     if (finalStatus === 'errored') {
       logger?.error(
         { videoId, muxVideoId, finalStatus },
         'Video upload processing failed due to Mux error'
       )
       return
     }

     if (finalStatus === 'timeout') {
       logger?.warn(
         { videoId, muxVideoId, finalStatus },
         'Video upload processing failed due to timeout'
       )
     }
apis/api-media/src/workers/processVideoUploads/service/service.spec.ts (2)

44-132: Consider adding test coverage for timeout and edge cases.

The service has additional code paths that could benefit from test coverage:

  • Timeout scenario (finalStatus === 'timeout')
  • muxVideo not found (returns early)
  • muxVideo.assetId is null (returns early)

These would increase confidence in the error handling logic.

📋 Example test for timeout scenario
it('logs warning when mux video processing times out', async () => {
  prismaMock.muxVideo.findUnique.mockResolvedValue({
    id: 'mux-video-id',
    assetId: 'asset-id'
  } as any)

  // Mock getVideo to always return 'preparing' status
  ;(getVideo as jest.Mock).mockResolvedValue({
    status: 'preparing',
    playback_ids: []
  })

  // Note: This test would be slow with real intervals.
  // Consider extracting interval/maxAttempts as injectable config for testing.
  
  // ... assertions for timeout logging
})

21-25: Mock logger typing could be more precise.

The as unknown as Logger cast works but loses type safety. Consider using jest.mocked<Logger>() or a more complete mock that matches the Logger interface.

Comment on lines 205 to 206
const playbackId = muxVideoAsset?.playback_ids?.[0].id
if (playbackId != null && muxVideoAsset.status === 'ready') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Potential TypeError when playback_ids is an empty array.

If playback_ids is [], then playback_ids?.[0] returns undefined, and accessing .id on undefined will throw a TypeError. Add optional chaining before .id.

🐛 Proposed fix
-      const playbackId = muxVideoAsset?.playback_ids?.[0].id
+      const playbackId = muxVideoAsset?.playback_ids?.[0]?.id
🤖 Prompt for AI Agents
In `@apis/api-media/src/workers/processVideoUploads/service/service.ts` around
lines 205 - 206, The code may throw a TypeError when muxVideoAsset.playback_ids
is an empty array because playback_ids?.[0].id assumes the first element exists;
update the playbackId extraction to use safe optional chaining (e.g., use
muxVideoAsset?.playback_ids?.[0]?.id) so it yields undefined when no playback id
exists, and keep the existing ready-status check (muxVideoAsset.status ===
'ready') to gate downstream logic; modify the playbackId assignment where the
variable playbackId is defined in the service.ts file to use the additional ?.
before .id.

@nx-cloud
Copy link

nx-cloud bot commented Feb 5, 2026

View your CI Pipeline Execution ↗ for commit e6f47d2

Command Status Duration Result
nx affected --target=subgraph-check --base=2ea4... ✅ Succeeded 3s View ↗
nx affected --target=extract-translations --bas... ✅ Succeeded <1s View ↗
nx affected --target=lint --base=2ea40fa76c12ff... ✅ Succeeded 1s View ↗
nx affected --target=type-check --base=2ea40fa7... ✅ Succeeded <1s View ↗
nx run-many --target=codegen --all --parallel=3 ✅ Succeeded 1s View ↗
nx run-many --target=prisma-generate --all --pa... ✅ Succeeded 6s View ↗

☁️ Nx Cloud last updated this comment at 2026-02-05 17:43:43 UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant