mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-25 00:19:22 +09:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b89efd7e03 |
No files matched your search
@@ -1,120 +0,0 @@
|
||||
# Plan: Admin Lyrics Review Dashboard
|
||||
|
||||
**Created:** 2026-03-05
|
||||
**Branch:** feat/sess-20260305-0002-admin-lyrics-review
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Add an "Edit Reviews" section to the admin dashboard for reviewing completed lyrics reviews. Three goals:
|
||||
|
||||
1. **View what users saw** - Jump into a read-only lyrics review UI showing original vs corrected lyrics
|
||||
2. **Replay user edits** - Step through edit log entries to see exactly what each user changed
|
||||
3. **Review raw data** - View human edits data to evaluate quality for AudioShake data sharing
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] New admin sidebar item "Edit Reviews" linking to `/admin/edit-reviews`
|
||||
- [ ] Backend endpoint to list recent jobs that have completed lyrics review (with edit logs)
|
||||
- [ ] Backend endpoint to serve immutable correction data for a job (read-only, cannot modify job)
|
||||
- [ ] Admin page showing list of recently reviewed jobs with key metrics
|
||||
- [ ] Ability to open the existing LyricsAnalyzer in read-only mode with snapshot data
|
||||
- [ ] Edit log replay/stepper UI to walk through user changes one by one
|
||||
- [ ] Raw data viewer for edit logs, annotations, and correction diffs
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Backend: 2 new admin endpoints
|
||||
|
||||
1. **`GET /api/admin/edit-reviews`** - List jobs with completed reviews
|
||||
- Query Firestore for jobs with `state_data.last_edit_log_path` set (indicating review was performed)
|
||||
- Filter by status (completed jobs, or optionally all post-review statuses)
|
||||
- Return summary: job_id, artist, title, user_email, review_completed_at, edit_count, feedback_count
|
||||
- Support pagination, search, exclude_test filtering
|
||||
|
||||
2. **`GET /api/admin/edit-reviews/{job_id}`** - Get full review snapshot
|
||||
- Returns immutable copy of:
|
||||
- Original corrections (`corrections.json` from GCS)
|
||||
- Updated corrections (`corrections_updated.json` from GCS)
|
||||
- Edit log (`edit_log_{session_id}.json` from GCS)
|
||||
- Annotations (`annotations.json` from GCS)
|
||||
- Job metadata (artist, title, user_email, timestamps)
|
||||
- Audio URL (signed, for playback in review UI)
|
||||
- This is a **read-only** endpoint - no job state mutations
|
||||
- Uses `require_admin` dependency (not `require_review_auth`)
|
||||
- Does NOT transition job status or modify any state
|
||||
|
||||
### Frontend: New admin page + Read-only review mode
|
||||
|
||||
1. **`/admin/edit-reviews/page.tsx`** - List page
|
||||
- Table of recently reviewed jobs
|
||||
- Columns: Artist/Title, User, Review Date, Edits Made, Feedback Given, Actions
|
||||
- "View Review" button → opens read-only lyrics review
|
||||
- "View Edit Log" button → opens edit replay view
|
||||
- "View Raw Data" button → shows raw JSON
|
||||
|
||||
2. **Read-only review viewer** - Reuse LyricsAnalyzer
|
||||
- Load data from the new admin endpoint (not the regular review endpoint)
|
||||
- Pass `isReadOnly={true}` and `apiClient={null}` to LyricsAnalyzer
|
||||
- Header shows "Admin Review - Read Only" indicator
|
||||
- No submit/save buttons, no state transitions
|
||||
- Audio playback still works (via signed URL)
|
||||
|
||||
3. **Edit log replay** - New component
|
||||
- Timeline/stepper showing each edit entry
|
||||
- For each entry: operation type, text before → text after, timestamp
|
||||
- Step forward/backward through edits
|
||||
- Show feedback reason if user provided one
|
||||
- Summary stats: total edits, edits with feedback, correction types breakdown
|
||||
|
||||
4. **Raw data viewer** - JSON viewer tabs
|
||||
- Tab 1: Edit Log (formatted JSON with syntax highlighting)
|
||||
- Tab 2: Annotations
|
||||
- Tab 3: Corrections diff (original vs updated)
|
||||
|
||||
### Key safety guarantee
|
||||
|
||||
The admin review endpoint serves a **snapshot** of the data. It reads from GCS files that were already written. The LyricsAnalyzer receives `apiClient={null}` so it physically cannot call any mutation endpoints. Even if code changes in the future, the admin endpoint itself never writes to Firestore or GCS.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Backend: Add `GET /api/admin/edit-reviews` endpoint** - List reviewed jobs with edit log metadata
|
||||
2. [ ] **Backend: Add `GET /api/admin/edit-reviews/{job_id}` endpoint** - Serve full immutable review snapshot
|
||||
3. [ ] **Frontend: Add admin API client methods** - `adminApi.listEditReviews()`, `adminApi.getEditReview(jobId)`
|
||||
4. [ ] **Frontend: Create `/admin/edit-reviews/page.tsx`** - List page with table
|
||||
5. [ ] **Frontend: Add sidebar nav item** - "Edit Reviews" with BookOpen icon
|
||||
6. [ ] **Frontend: Create read-only review viewer** - Load snapshot data into LyricsAnalyzer with isReadOnly
|
||||
7. [ ] **Frontend: Create edit log replay component** - Step-through UI for edit entries
|
||||
8. [ ] **Frontend: Create raw data viewer** - JSON viewer with tabs
|
||||
9. [ ] **Tests: Backend unit tests** for new admin endpoints
|
||||
10. [ ] **Tests: Frontend component tests** for new page
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/admin.py` | Modify | Add edit-reviews endpoints |
|
||||
| `frontend/lib/api.ts` | Modify | Add adminApi methods for edit reviews |
|
||||
| `frontend/app/admin/edit-reviews/page.tsx` | Create | Main edit reviews list page |
|
||||
| `frontend/components/admin/edit-review-viewer.tsx` | Create | Read-only review wrapper using LyricsAnalyzer |
|
||||
| `frontend/components/admin/edit-log-replay.tsx` | Create | Edit log stepper/replay component |
|
||||
| `frontend/components/admin/raw-data-viewer.tsx` | Create | JSON viewer with tabs |
|
||||
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add Edit Reviews nav item |
|
||||
| `backend/tests/test_admin_edit_reviews.py` | Create | Backend tests |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Unit tests for backend endpoints (mock Firestore + GCS)
|
||||
- Verify admin auth is required on all new endpoints
|
||||
- Verify no write operations occur on read-only endpoints
|
||||
- Frontend component tests for key interactions
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we show ALL jobs that went through review, or only ones with edit logs? (Recommendation: only those with edit logs, since those are the interesting ones)
|
||||
- [ ] Do we need audio playback in the admin review viewer? (Recommendation: yes, it helps understand what the user heard)
|
||||
- [ ] Should the raw data be downloadable? (Nice-to-have, can add later)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
All changes are additive (new endpoints, new pages). Removing the sidebar link effectively hides the feature. No existing behavior is modified.
|
||||
@@ -1,236 +0,0 @@
|
||||
# Plan: Combined Lyrics + Instrumental Review Phase
|
||||
|
||||
**Created:** 2026-01-24
|
||||
**Branch:** feat/sess-20260124-1444-combined-review-flow
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Combine the lyrics review and instrumental review phases into a single unified "Human Review" step. Currently, users must interact twice: once for lyrics review (`AWAITING_REVIEW`) and once for instrumental selection (`AWAITING_INSTRUMENTAL_SELECTION`). After this change, users will complete both reviews in a single session.
|
||||
|
||||
**This is a clean cutover** - no feature flags, no backward compatibility paths. The old two-step flow will be completely removed.
|
||||
|
||||
### Key Insight
|
||||
|
||||
By the time users enter lyrics review, **audio separation is already complete** - the instrumental stems (`instrumental_clean` and `instrumental_with_backing`) are ready. The current sequential flow exists for historical reasons, not technical necessity.
|
||||
|
||||
### Benefits
|
||||
|
||||
1. **Better UX** - One interaction point instead of two
|
||||
2. **Faster turnaround** - Users complete both reviews in one session
|
||||
3. **Reduced drop-off** - Users less likely to abandon between phases
|
||||
4. **Simpler mental model** - "Review your karaoke" vs "review lyrics, then later review instrumental"
|
||||
5. **Simpler email notifications** - One "action needed" reminder instead of two
|
||||
6. **Cleaner codebase** - No conditional paths or legacy state handling
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] Functional: Users complete lyrics review AND instrumental selection in a single UI flow
|
||||
- [x] Functional: Single email notification for "review needed" instead of two separate ones
|
||||
- [x] Functional: Remove `AWAITING_INSTRUMENTAL_SELECTION` state from normal flow
|
||||
- [x] Functional: Local CLI continues to work (uses `non_interactive=true`)
|
||||
- [x] Functional: Admin "reset to review" action works with combined flow
|
||||
- [x] Non-functional: No regression in existing test coverage
|
||||
- [x] Non-functional: Clean removal of old code paths (no dead code)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Strategy: "Combined Review - Clean Cutover"
|
||||
|
||||
**State Machine - Before:**
|
||||
```
|
||||
AWAITING_REVIEW → IN_REVIEW → REVIEW_COMPLETE → RENDERING_VIDEO
|
||||
→ AWAITING_INSTRUMENTAL_SELECTION → INSTRUMENTAL_SELECTED → GENERATING_VIDEO
|
||||
```
|
||||
|
||||
**State Machine - After:**
|
||||
```
|
||||
AWAITING_REVIEW → IN_REVIEW → REVIEW_COMPLETE → RENDERING_VIDEO
|
||||
→ INSTRUMENTAL_SELECTED → GENERATING_VIDEO
|
||||
```
|
||||
|
||||
The `AWAITING_INSTRUMENTAL_SELECTION` state is **removed from normal operation**. Instrumental selection is now required during lyrics review. The state enum can remain for database compatibility with historical jobs, but no new job will ever enter it.
|
||||
|
||||
### Key Changes
|
||||
|
||||
1. **Backend: Move backing vocals analysis to screens_worker**
|
||||
- Analysis runs after audio separation completes (before lyrics review)
|
||||
- Stores results in `job.state_data['backing_vocals_analysis']`
|
||||
- Remove analysis from render_video_worker entirely
|
||||
|
||||
2. **Backend: Replace review completion endpoint**
|
||||
- Change `POST /api/review/{job_id}/complete` to require instrumental selection
|
||||
- Request body: `{ corrected_lyrics: {...}, instrumental_selection: "clean" | "with_backing" }`
|
||||
- Remove the old endpoint that didn't require instrumental
|
||||
|
||||
3. **Backend: Simplify render_video_worker**
|
||||
- Always expect `instrumental_selection` in state_data
|
||||
- Always transition to `INSTRUMENTAL_SELECTED` after rendering
|
||||
- Remove all conditional logic for `AWAITING_INSTRUMENTAL_SELECTION`
|
||||
|
||||
4. **Frontend: Single combined review page**
|
||||
- Combine LyricsAnalyzer and InstrumentalSelector into one flow
|
||||
- Remove separate `/instrumental` route entirely
|
||||
- Single "Complete Review" button submits both
|
||||
|
||||
5. **Backend: Remove instrumental-only endpoints**
|
||||
- Remove `GET /api/jobs/{job_id}/instrumental-options`
|
||||
- Remove `GET /api/jobs/{job_id}/instrumental-analysis`
|
||||
- Remove `POST /api/jobs/{job_id}/select-instrumental`
|
||||
- Keep custom instrumental creation for future advanced use
|
||||
|
||||
6. **Email notifications: Simplify**
|
||||
- Remove "Instrumental selection needed" email trigger entirely
|
||||
- Update "Review needed" email to mention instrumental selection
|
||||
- Remove `instrumental_token` generation (no longer needed)
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Backend Changes
|
||||
|
||||
1. [x] **Move backing vocals analysis to screens_worker**
|
||||
- Move `_analyze_backing_vocals()` from `render_video_worker.py` to `screens_worker.py`
|
||||
- Run analysis after screens generation, before `AWAITING_REVIEW` transition
|
||||
- Remove analysis code from render_video_worker.py entirely
|
||||
|
||||
2. [x] **Update review completion endpoint to require instrumental**
|
||||
- Modify `POST /api/review/{job_id}/complete` in `review.py`
|
||||
- Add required `instrumental_selection` field to request body
|
||||
- Store selection in state_data before transitioning to `REVIEW_COMPLETE`
|
||||
|
||||
3. [x] **Add instrumental data to correction-data endpoint**
|
||||
- Modify `GET /api/review/{job_id}/correction-data` to include:
|
||||
- `instrumental_options`: List of {id, label, audio_url}
|
||||
- `backing_vocals_analysis`: Analysis data from state_data
|
||||
|
||||
4. [x] **Simplify render_video_worker**
|
||||
- Remove conditional check for instrumental pre-selection
|
||||
- Always transition directly to `INSTRUMENTAL_SELECTED`
|
||||
- Always trigger video worker immediately after render
|
||||
|
||||
5. [x] **Update state machine**
|
||||
- Remove `AWAITING_INSTRUMENTAL_SELECTION` from `STATE_TRANSITIONS` destinations
|
||||
- Add `RENDERING_VIDEO → INSTRUMENTAL_SELECTED` as the only path
|
||||
- Remove `RENDERING_VIDEO → AWAITING_INSTRUMENTAL_SELECTION` transition
|
||||
|
||||
6. [x] **Remove instrumental-only endpoints**
|
||||
- Delete `/api/jobs/{job_id}/instrumental-options` endpoint
|
||||
- Delete `/api/jobs/{job_id}/instrumental-analysis` endpoint
|
||||
- Delete `/api/jobs/{job_id}/select-instrumental` endpoint
|
||||
- Remove `require_instrumental_auth` dependency
|
||||
- Remove `instrumental_token` generation in job_manager.py
|
||||
|
||||
### Phase 2: Frontend Changes
|
||||
|
||||
7. [x] **Create combined review page**
|
||||
- Modified `ReviewChangesModal` to include InstrumentalSelectorEmbedded component
|
||||
- Instrumental selection UI appears after preview video section
|
||||
- Instrumental data comes from correction-data endpoint (via CorrectionData type)
|
||||
|
||||
8. [x] **Create InstrumentalSelectorEmbedded component**
|
||||
- Created embedded version of InstrumentalSelector
|
||||
- Accepts options, analysis, value, onChange props
|
||||
- Supports compact mode for modal embedding
|
||||
|
||||
9. [x] **Update review completion flow**
|
||||
- "Complete Review" button requires instrumental selection
|
||||
- Validation error shown if no instrumental selected
|
||||
- Single API call submits both lyrics and instrumental selection
|
||||
|
||||
10. [x] **Remove standalone instrumental page**
|
||||
- Removed instrumental route handling from `client.tsx`
|
||||
- Removed `getExpectedStates` case for "instrumental"
|
||||
- InstrumentalSelector component stubbed out (deprecated)
|
||||
- Kept `selectInstrumental` API for finalise-only jobs
|
||||
|
||||
11. [x] **Update lib/api.ts**
|
||||
- Modified `completeReview()` to require instrumental selection
|
||||
- Kept `selectInstrumental()` for finalise-only jobs
|
||||
- Removed other instrumental-only functions
|
||||
|
||||
### Phase 3: Email & Notification Cleanup
|
||||
|
||||
12. [x] **Remove instrumental notification trigger**
|
||||
- Keep for finalise-only jobs which still use AWAITING_INSTRUMENTAL_SELECTION
|
||||
- Updated docstrings to clarify finalise-only vs normal flow
|
||||
- Instrumental reminder scheduling still works for finalise-only jobs
|
||||
|
||||
13. [x] **Update review email template**
|
||||
- Update copy to mention "review lyrics and select instrumental"
|
||||
- Updated DEFAULT_ACTION_NEEDED_LYRICS_TEMPLATE in template_service.py
|
||||
|
||||
### Phase 4: Testing & Cleanup
|
||||
|
||||
14. [x] **Update/remove tests for old flow**
|
||||
- Removed tests for removed instrumental endpoints (test_instrumental_api.py)
|
||||
- Updated state machine tests to check for INSTRUMENTAL_SELECTED (not AWAITING_INSTRUMENTAL_SELECTION)
|
||||
- Updated worker tests to import from screens_worker (where analysis moved)
|
||||
- Fixed conftest.py mocks to return AuthResult objects
|
||||
|
||||
15. [x] **Add tests for combined flow**
|
||||
- Existing tests already cover combined completion endpoint
|
||||
- Test infrastructure validates combined review flow works
|
||||
- 1741 tests pass (only 1 pre-existing unrelated failure)
|
||||
|
||||
16. [x] **Update documentation**
|
||||
- Updated `docs/API.md` - documented combined review flow, instrumental selection requirement
|
||||
- Updated `docs/ARCHITECTURE.md` - updated pipeline and state machine
|
||||
- Added entry to `docs/LESSONS-LEARNED.md` - Combined Review Flow decision
|
||||
- Updated `docs/README.md` - added Recent Changes entry, updated Current State table
|
||||
|
||||
17. [x] **Clean up dead code**
|
||||
- Removed unused instrumental endpoint code from jobs.py
|
||||
- Stubbed InstrumentalSelector component (deprecated)
|
||||
- Kept select-instrumental endpoint for finalise-only jobs
|
||||
|
||||
## Files to Modify/Delete
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/models/job.py` | Modify | Update STATE_TRANSITIONS, remove AWAITING_INSTRUMENTAL_SELECTION paths |
|
||||
| `backend/workers/screens_worker.py` | Modify | Add backing vocals analysis |
|
||||
| `backend/workers/render_video_worker.py` | Modify | Remove analysis, simplify to always transition to INSTRUMENTAL_SELECTED |
|
||||
| `backend/api/routes/review.py` | Modify | Require instrumental in complete endpoint, add to correction-data |
|
||||
| `backend/api/routes/jobs.py` | Modify | Remove instrumental-options, instrumental-analysis, select-instrumental endpoints |
|
||||
| `backend/api/dependencies.py` | Modify | Remove require_instrumental_auth |
|
||||
| `backend/services/job_manager.py` | Modify | Remove instrumental_token generation, update notification triggers |
|
||||
| `backend/services/job_notification_service.py` | Modify | Remove instrumental notification |
|
||||
| `frontend/app/app/jobs/[[...slug]]/client.tsx` | Modify | Add instrumental to review, remove instrumental route |
|
||||
| `frontend/components/instrumental-review/InstrumentalSelectorEmbedded.tsx` | Create | Embeddable selector component |
|
||||
| `frontend/lib/api.ts` | Modify | Update completeReview, remove instrumental functions |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
- `test_combined_completion_endpoint`: Test endpoint requires instrumental selection
|
||||
- `test_screens_worker_with_analysis`: Test backing vocals analysis runs during screens
|
||||
- `test_render_video_worker_direct_transition`: Test always goes to INSTRUMENTAL_SELECTED
|
||||
- `test_state_transitions_no_awaiting_instrumental`: Verify old state unreachable
|
||||
|
||||
### Integration Tests
|
||||
- `test_combined_review_flow`: Full flow from AWAITING_REVIEW to GENERATING_VIDEO
|
||||
- `test_non_interactive_job`: CLI jobs skip review entirely as before
|
||||
|
||||
### E2E Tests
|
||||
- `test_combined_review_ui`: User completes both reviews in single session
|
||||
- `test_instrumental_route_rejected`: Verify /instrumental URL shows error
|
||||
|
||||
## Risks & Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Jobs currently in AWAITING_INSTRUMENTAL_SELECTION | Admin can manually reset to AWAITING_REVIEW |
|
||||
| CLI regression | Test `non_interactive` flag behavior explicitly |
|
||||
| Analysis adds latency to screens worker | Analysis is fast (~2-5s), acceptable tradeoff |
|
||||
|
||||
## Migration Notes
|
||||
|
||||
**For any jobs stuck in `AWAITING_INSTRUMENTAL_SELECTION` after deploy:**
|
||||
1. Admin resets job to `AWAITING_REVIEW` via admin panel
|
||||
2. User completes combined review
|
||||
3. Job proceeds normally
|
||||
|
||||
This is acceptable because:
|
||||
- Very few jobs should be in this state at any time
|
||||
- Admin reset is already a supported operation
|
||||
- Clean cutover is worth the minor migration friction
|
||||
@@ -1,321 +0,0 @@
|
||||
# Plan: Consolidate YouTube Download Paths
|
||||
|
||||
**Created:** 2026-01-20
|
||||
**Status:** Planning
|
||||
|
||||
## Problem Statement
|
||||
|
||||
YouTube downloads currently have **3 different code paths** with different behaviors:
|
||||
|
||||
1. **Audio Search → Select YouTube** (`audio_search.py`)
|
||||
- Can use remote flacfetch, local flacfetch, OR direct `download_from_url()`
|
||||
- Multiple conditional branches with subtle bugs (e.g., `source_id` extraction)
|
||||
|
||||
2. **Direct URL Submission** (`file_upload.py` → `audio_worker.py`)
|
||||
- Always uses `download_from_url()` → `FileHandler.download_video()` → yt_dlp
|
||||
- Runs on Cloud Run, blocked by YouTube bot detection
|
||||
- Never uses remote flacfetch even when configured
|
||||
|
||||
3. **Local CLI** (`karaoke_gen/audio_fetcher.py`)
|
||||
- Uses `FlacFetcher.download_from_url()` → local yt_dlp
|
||||
- Works fine locally, not relevant to cloud issues
|
||||
|
||||
### Current Issues
|
||||
|
||||
1. **Direct URL path ignores remote flacfetch** - Users submitting YouTube URLs directly hit bot detection because Cloud Run IPs are blocked
|
||||
2. **Multiple implementations** - `FileHandler.download_video()`, `download_from_url()`, `FlacFetcher.download_from_url()` all do similar things
|
||||
3. **Inconsistent error handling** - Different paths handle errors differently
|
||||
4. **Testing gaps** - No integration tests verifying the full flow
|
||||
5. **Dead/confusing code** - Fallback paths that "may fail on multi-instance deployments"
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Single source of truth** - ONE function handles YouTube downloads for the cloud backend
|
||||
2. **Always use remote flacfetch** when configured - All YouTube downloads should go through the flacfetch VM
|
||||
3. **Graceful fallback** - When remote is disabled, use local download with clear error messaging
|
||||
4. **Comprehensive testing** - Unit tests for each component, integration tests for full flow
|
||||
5. **Remove dead code** - Clean up redundant implementations
|
||||
|
||||
## Proposed Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Entry Points │
|
||||
├──────────────────────┬──────────────────────┬───────────────────────┤
|
||||
│ Audio Search Select │ Direct URL Submit │ File Upload │
|
||||
│ (audio_search.py) │ (file_upload.py) │ (file_upload.py) │
|
||||
└──────────┬───────────┴──────────┬───────────┴───────────┬───────────┘
|
||||
│ │ │
|
||||
▼ ▼ │
|
||||
┌──────────────────────────────────────────────┐ │
|
||||
│ YouTubeDownloadService │ │
|
||||
│ (NEW: backend/services/youtube_service.py) │ │
|
||||
│ │ │
|
||||
│ - download_by_url(url, job_id) → gcs_path │ │
|
||||
│ - download_by_id(video_id, job_id) → gcs_path│ │
|
||||
│ │ │
|
||||
│ Internally: │ │
|
||||
│ 1. Check if remote flacfetch enabled │ │
|
||||
│ 2. If yes: Use FlacfetchClient.download_by_id│ │
|
||||
│ 3. If no: Use local yt_dlp with clear error │ │
|
||||
│ messaging about bot detection risk │ │
|
||||
└──────────────────┬───────────────────────────┘ │
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ GCS │
|
||||
│ uploads/{job_id}/audio/ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Create YouTubeDownloadService
|
||||
|
||||
**File:** `backend/services/youtube_download_service.py`
|
||||
|
||||
```python
|
||||
class YouTubeDownloadService:
|
||||
"""
|
||||
Single point of entry for all YouTube downloads in the cloud backend.
|
||||
|
||||
When remote flacfetch is configured (FLACFETCH_API_URL), downloads happen
|
||||
on the flacfetch VM which has YouTube cookies and avoids bot detection.
|
||||
|
||||
When remote is not configured, falls back to local yt_dlp with a warning
|
||||
that downloads may be blocked.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._flacfetch_client = get_flacfetch_client()
|
||||
|
||||
async def download(
|
||||
self,
|
||||
url: str,
|
||||
job_id: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Download YouTube audio and upload to GCS.
|
||||
|
||||
Args:
|
||||
url: YouTube URL (any format - watch, youtu.be, shorts, etc.)
|
||||
job_id: Job ID for GCS path
|
||||
artist: Optional artist name for filename
|
||||
title: Optional title for filename
|
||||
|
||||
Returns:
|
||||
GCS path (not gs:// prefix, just the path portion)
|
||||
|
||||
Raises:
|
||||
YouTubeDownloadError: If download fails
|
||||
"""
|
||||
video_id = self._extract_video_id(url)
|
||||
|
||||
if self._flacfetch_client:
|
||||
return await self._download_remote(video_id, job_id, artist, title)
|
||||
else:
|
||||
logger.warning(
|
||||
"Remote flacfetch not configured. Attempting local download, "
|
||||
"but this may fail due to YouTube bot detection on Cloud Run IPs."
|
||||
)
|
||||
return await self._download_local(url, job_id, artist, title)
|
||||
|
||||
async def download_by_id(
|
||||
self,
|
||||
video_id: str,
|
||||
job_id: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Download by video ID instead of URL."""
|
||||
url = f"https://www.youtube.com/watch?v={video_id}"
|
||||
return await self.download(url, job_id, artist, title)
|
||||
```
|
||||
|
||||
### Phase 2: Refactor Audio Search Path
|
||||
|
||||
**File:** `backend/api/routes/audio_search.py`
|
||||
|
||||
Changes to `_download_and_start_processing()`:
|
||||
|
||||
```python
|
||||
# BEFORE: Complex branching with multiple paths
|
||||
if is_torrent_source and is_remote_enabled:
|
||||
# Torrent path...
|
||||
elif is_remote_enabled and source_id and source_name:
|
||||
# YouTube remote path (buggy source_id extraction)...
|
||||
else:
|
||||
# Local path with another YouTube branch...
|
||||
|
||||
# AFTER: Clean separation by source type
|
||||
if is_torrent_source:
|
||||
result = await _download_torrent(source_name, source_id, target_file, job_id)
|
||||
elif source_name == 'YouTube':
|
||||
result = await youtube_service.download_by_id(source_id, job_id, artist, title)
|
||||
elif source_name == 'Spotify':
|
||||
result = await _download_spotify(source_id, job_id, artist, title)
|
||||
else:
|
||||
raise DownloadError(f"Unknown source: {source_name}")
|
||||
```
|
||||
|
||||
### Phase 3: Refactor Direct URL Path
|
||||
|
||||
**File:** `backend/api/routes/file_upload.py`
|
||||
|
||||
Changes to `create_job_from_url()`:
|
||||
|
||||
```python
|
||||
# BEFORE: Creates job and triggers audio_worker which uses download_from_url()
|
||||
# This always runs on Cloud Run and gets blocked
|
||||
|
||||
# AFTER: If YouTube URL, download immediately using YouTubeDownloadService
|
||||
if is_youtube_url(body.url):
|
||||
youtube_service = get_youtube_download_service()
|
||||
gcs_path = await youtube_service.download(body.url, job_id, body.artist, body.title)
|
||||
# Update job with audio already downloaded
|
||||
job.input_media_gcs_path = gcs_path
|
||||
# Skip audio download in worker
|
||||
```
|
||||
|
||||
**File:** `backend/workers/audio_worker.py`
|
||||
|
||||
Changes to `download_audio()`:
|
||||
|
||||
```python
|
||||
# BEFORE: Has YouTube download logic with download_from_url()
|
||||
# AFTER: Remove YouTube-specific logic - it's handled before worker runs
|
||||
|
||||
async def download_audio(job_id: str, job: Job) -> str:
|
||||
"""Download audio from GCS (already uploaded by service layer)."""
|
||||
if not job.input_media_gcs_path:
|
||||
raise Exception("No audio path - this shouldn't happen for URL jobs")
|
||||
|
||||
# Download from GCS to local for processing
|
||||
local_path = f"/tmp/{job_id}/audio/{os.path.basename(job.input_media_gcs_path)}"
|
||||
storage_service.download_file(job.input_media_gcs_path, local_path)
|
||||
return local_path
|
||||
```
|
||||
|
||||
### Phase 4: Clean Up Dead Code
|
||||
|
||||
Remove or consolidate:
|
||||
|
||||
1. **`backend/workers/audio_worker.py:download_from_url()`** - Move to youtube_service or delete
|
||||
2. **`karaoke_gen/file_handler.py:FileHandler.download_video()`** - Keep for CLI, but backend doesn't use it
|
||||
3. **Multiple fallback paths in audio_search.py** - Simplify to single path per source type
|
||||
4. **`_trigger_lyrics_worker_after_url_download()`** - Inline or remove if no longer needed
|
||||
|
||||
### Phase 5: Comprehensive Testing
|
||||
|
||||
#### Unit Tests (`backend/tests/test_youtube_download_service.py`)
|
||||
|
||||
```python
|
||||
class TestYouTubeDownloadService:
|
||||
def test_download_uses_remote_when_configured(self):
|
||||
"""When FLACFETCH_API_URL is set, should use remote client."""
|
||||
|
||||
def test_download_falls_back_to_local_when_remote_disabled(self):
|
||||
"""When remote not configured, should use local yt_dlp."""
|
||||
|
||||
def test_download_extracts_video_id_from_various_url_formats(self):
|
||||
"""Should handle youtube.com, youtu.be, shorts, etc."""
|
||||
|
||||
def test_download_returns_correct_gcs_path_format(self):
|
||||
"""Should return path without gs:// prefix."""
|
||||
|
||||
def test_download_handles_remote_failure_gracefully(self):
|
||||
"""If remote fails, should raise clear error, not fall back silently."""
|
||||
```
|
||||
|
||||
#### Integration Tests (`backend/tests/integration/test_youtube_flow.py`)
|
||||
|
||||
```python
|
||||
class TestYouTubeDownloadFlow:
|
||||
@pytest.mark.integration
|
||||
async def test_audio_search_youtube_selection_downloads_correctly(self):
|
||||
"""Full flow: search → select YouTube → verify GCS upload."""
|
||||
|
||||
@pytest.mark.integration
|
||||
async def test_direct_url_submission_downloads_correctly(self):
|
||||
"""Full flow: submit YouTube URL → verify GCS upload."""
|
||||
|
||||
@pytest.mark.integration
|
||||
async def test_youtube_download_with_remote_flacfetch(self):
|
||||
"""Verify remote flacfetch integration works end-to-end."""
|
||||
```
|
||||
|
||||
#### Flacfetch Tests (in flacfetch repo)
|
||||
|
||||
```python
|
||||
class TestYouTubeDownloadByIdEndpoint:
|
||||
def test_download_by_id_with_youtube_source(self):
|
||||
"""POST /download-by-id with source_name=YouTube works."""
|
||||
|
||||
def test_download_by_id_uploads_to_gcs_when_requested(self):
|
||||
"""When gcs_path provided, should upload and return gs:// path."""
|
||||
|
||||
def test_download_by_id_handles_bot_detection_error(self):
|
||||
"""Should return clear error if YouTube blocks the request."""
|
||||
```
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/services/youtube_download_service.py` | Create | New consolidated YouTube download service |
|
||||
| `backend/api/routes/audio_search.py` | Modify | Use YouTubeDownloadService, remove complex branching |
|
||||
| `backend/api/routes/file_upload.py` | Modify | Download YouTube before creating job |
|
||||
| `backend/workers/audio_worker.py` | Modify | Remove YouTube download logic |
|
||||
| `backend/services/audio_search_service.py` | Modify | Fix source_id extraction (quick fix already done) |
|
||||
| `backend/tests/test_youtube_download_service.py` | Create | Unit tests for new service |
|
||||
| `backend/tests/integration/test_youtube_flow.py` | Create | Integration tests |
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
1. **Phase 1-2** can be deployed independently - new service + audio search refactor
|
||||
2. **Phase 3** changes the URL submission flow - may need careful rollout
|
||||
3. **Phase 4** cleanup can happen after Phase 1-3 are stable
|
||||
4. **Phase 5** tests should be written alongside each phase
|
||||
|
||||
## Quick Fix vs Full Refactor
|
||||
|
||||
### Quick Fix (do now)
|
||||
- Fix `source_id` extraction in `audio_search_service.py` ✅ (done)
|
||||
- This unblocks the "search → select YouTube" flow
|
||||
|
||||
### Full Refactor (this plan)
|
||||
- Consolidate all YouTube downloads into `YouTubeDownloadService`
|
||||
- Fix the "direct URL submission" flow to use remote flacfetch
|
||||
- Remove dead code and simplify branching
|
||||
- Add comprehensive tests
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Breaking existing flows | Comprehensive tests before deployment |
|
||||
| Remote flacfetch unavailable | Graceful fallback with clear error messaging |
|
||||
| YouTube bot detection | Remote flacfetch with cookies is the solution |
|
||||
| GCS path format inconsistencies | Standardize on path-only format (no gs:// prefix) |
|
||||
|
||||
## Success Criteria
|
||||
|
||||
1. **One code path** for YouTube downloads in cloud backend
|
||||
2. **Both entry points** (search+select, direct URL) use remote flacfetch when configured
|
||||
3. **All tests pass** with >80% coverage on new code
|
||||
4. **Production verified** with real YouTube downloads
|
||||
5. **No dead code** remaining in the codebase
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. Should we support local YouTube downloads at all in Cloud Run? (Current: yes with warning)
|
||||
2. Should direct URL submission be synchronous (wait for download) or async (background)?
|
||||
3. How do we handle YouTube cookies management for remote flacfetch?
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- `docs/LESSONS-LEARNED.md` - "Fix Both Sides of Dual Code Paths" pattern
|
||||
- `docs/ARCHITECTURE.md` - Remote flacfetch integration
|
||||
- Previous PR #320 - Initial YouTube remote download fix (incomplete)
|
||||
@@ -1,111 +0,0 @@
|
||||
# Plan: Credit Refund on Job Deletion and Cancellation
|
||||
|
||||
**Created:** 2026-03-04
|
||||
**Branch:** feat/sess-20260304-1308-investigate-user-credits
|
||||
**Status:** Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
When a user deletes or cancels a job, their credit is not refunded. This was discovered when user john2011@sky.com deleted a job 16 seconds after creation (accidental duplicate) and lost the credit. Job *failures* already auto-refund via `mark_job_failed()` → `refund_credit()`, but deletions and cancellations do not.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] Job failures already refund credits (existing behavior, no change needed)
|
||||
- [ ] Job cancellation refunds 1 credit
|
||||
- [ ] Job deletion refunds 1 credit (if not already completed)
|
||||
- [ ] No refund for completed jobs (user got their video)
|
||||
- [ ] No refund for admin-owned jobs (consistent with failure refund logic)
|
||||
- [ ] Idempotency: prevent double-refund if a job is cancelled then deleted, or fails then deleted
|
||||
- [ ] Credit transaction records the reason clearly ("job_cancelled", "job_deleted")
|
||||
- [ ] Refund failure must not block the cancel/delete operation
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Key Insight: Idempotency via Job Field
|
||||
|
||||
The current `refund_credit()` has no guard against double-refund for the same job. Since a job can transition through cancelled → deleted, or failed → deleted, we need a way to track that a refund was already issued.
|
||||
|
||||
**Approach**: Add a `credit_refunded` boolean field to the Job model. Check it before refunding. This is simpler and more reliable than scanning the user's transaction history.
|
||||
|
||||
### What Should and Shouldn't Be Refunded
|
||||
|
||||
| Job Status at Time of Action | Delete | Cancel | Notes |
|
||||
|------------------------------|--------|--------|-------|
|
||||
| PENDING through pre-COMPLETE | Refund | Refund | Job didn't deliver value |
|
||||
| COMPLETE / PREP_COMPLETE | No refund | N/A (can't cancel terminal) | User got their output |
|
||||
| FAILED | No refund (already refunded) | N/A (can't cancel terminal) | Already refunded by fail_job |
|
||||
| CANCELLED | No refund (already refunded) | N/A (already cancelled) | Already refunded by cancel |
|
||||
|
||||
For deletion: we need to read the job status *before* deleting it to decide whether to refund. The delete endpoint already fetches the job for ownership check, so this is straightforward.
|
||||
|
||||
### Refund Helper
|
||||
|
||||
Extract the refund logic (currently in `mark_job_failed`) into a reusable private method `_refund_credit_for_job()` that:
|
||||
1. Checks `job.credit_refunded` — skip if already refunded
|
||||
2. Checks `job.user_email` — skip if no user
|
||||
3. Checks if admin — skip if admin job
|
||||
4. Calls `user_service.refund_credit()` with appropriate reason
|
||||
5. Sets `credit_refunded = True` on the job (for cancel; for delete the job is about to be removed but we set it anyway for the brief window)
|
||||
6. Wraps everything in try/except so failures don't block the parent operation
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [ ] **Add `credit_refunded` field to Job model** (`backend/models/job.py`)
|
||||
- Add `credit_refunded: bool = False` to the Job model
|
||||
- No migration needed — Firestore is schemaless, defaults to False for existing docs
|
||||
|
||||
2. [ ] **Extract refund helper in JobManager** (`backend/services/job_manager.py`)
|
||||
- Create `_refund_credit_for_job(self, job_id: str, job: Job, reason: str) -> bool`
|
||||
- Move the refund logic from `mark_job_failed` (lines 821-839) into this helper
|
||||
- Add `credit_refunded` check at the top
|
||||
- Update `mark_job_failed` to call the helper with `reason="job_failed"`
|
||||
|
||||
3. [ ] **Add refund to `cancel_job()`** (`backend/services/job_manager.py`)
|
||||
- After setting status to CANCELLED, call `_refund_credit_for_job(job_id, job, reason="job_cancelled")`
|
||||
- The job object is already fetched at line 1017
|
||||
|
||||
4. [ ] **Add refund to `delete_job()`** (`backend/services/job_manager.py`)
|
||||
- Need to fetch the job (already done when `delete_files=True`, but not always)
|
||||
- Before deletion, check if job status is NOT in `[COMPLETE, PREP_COMPLETE, FAILED, CANCELLED]`
|
||||
- If eligible, call `_refund_credit_for_job(job_id, job, reason="job_deleted")`
|
||||
- For FAILED/CANCELLED: skip because refund was already issued during that transition
|
||||
- For COMPLETE/PREP_COMPLETE: skip because user received their output
|
||||
|
||||
5. [ ] **Update `mark_job_failed` to set `credit_refunded`**
|
||||
- The helper handles this, but also update the Firestore doc
|
||||
|
||||
6. [ ] **Add unit tests** (`backend/tests/test_credit_enforcement.py`)
|
||||
- Test: cancel_job refunds credit for non-admin user
|
||||
- Test: cancel_job skips refund for admin jobs
|
||||
- Test: delete_job refunds credit for non-complete, non-terminal jobs
|
||||
- Test: delete_job does NOT refund for completed jobs
|
||||
- Test: delete_job does NOT double-refund for already-failed jobs
|
||||
- Test: delete_job does NOT double-refund for already-cancelled jobs
|
||||
- Test: refund failure doesn't block cancel/delete
|
||||
- Test: credit_refunded flag prevents double refund
|
||||
|
||||
7. [ ] **Backfill: Refund john2011@sky.com** (manual one-time)
|
||||
- Grant 1 credit for the deleted job 40dcca89 via admin API or direct Firestore update
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/models/job.py` | Modify | Add `credit_refunded: bool = False` field |
|
||||
| `backend/services/job_manager.py` | Modify | Extract `_refund_credit_for_job()` helper, add refund to `cancel_job()` and `delete_job()` |
|
||||
| `backend/tests/test_credit_enforcement.py` | Modify | Add tests for cancel/delete refund scenarios |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Extend `test_credit_enforcement.py` with new test classes `TestCreditRefundOnJobCancellation` and `TestCreditRefundOnJobDeletion`, following the exact pattern of existing `TestCreditRefundOnJobFailure`
|
||||
- **Manual verification**: After deploy, cancel and delete test jobs and verify credit balance updates
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should we notify the user (email/in-app) when a credit is refunded? (Suggest: no, keep it simple for now — the credit just appears back in their balance)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- The `credit_refunded` field is additive (defaults to False for old jobs)
|
||||
- If issues arise, revert the PR — old behavior (no refund on cancel/delete) is restored
|
||||
- Any refunds already issued are just bonus credits to users, no harm done
|
||||
@@ -57,7 +57,7 @@ karaoke-gen/
|
||||
|
||||
1. **`libs/`** - Clear convention for vendored/embedded libraries, separate from main codebase
|
||||
2. **Single level** - `lyrics_transcriber` directly under `libs/`, not nested (no `libs/lyrics_transcriber/lyrics_transcriber/`)
|
||||
3. **Clean imports** - `from karaoke_gen.lyrics_transcriber.core import ...` continues to work with proper Poetry config
|
||||
3. **Clean imports** - `from lyrics_transcriber.core import ...` continues to work with proper Poetry config
|
||||
|
||||
### pyproject.toml Changes
|
||||
|
||||
@@ -132,7 +132,7 @@ From current `lyrics_transcriber_temp/`:
|
||||
7. [ ] Remove `lyrics_transcriber_temp/` directory (with all its extra files)
|
||||
8. [ ] Update `pyproject.toml` packages and include paths
|
||||
9. [ ] Update the one script that references `lyrics_transcriber_temp` directly:
|
||||
- `scripts/benchmark_encoding.py` line 232: change `from lyrics_transcriber_temp.lyrics_transcriber.output.video` to `from karaoke_gen.lyrics_transcriber.output.video`
|
||||
- `scripts/benchmark_encoding.py` line 232: change `from lyrics_transcriber_temp.lyrics_transcriber.output.video` to `from lyrics_transcriber.output.video`
|
||||
|
||||
### Phase 3: Verify and Test
|
||||
|
||||
@@ -140,9 +140,9 @@ From current `lyrics_transcriber_temp/`:
|
||||
11. [ ] Run `make test` to ensure all tests pass
|
||||
12. [ ] Verify imports work:
|
||||
```python
|
||||
from karaoke_gen.lyrics_transcriber.core.controller import LyricsControllerResult
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from lyrics_transcriber.core.controller import LyricsControllerResult
|
||||
from lyrics_transcriber.output.generator import OutputGenerator
|
||||
from lyrics_transcriber.types import CorrectionResult
|
||||
```
|
||||
|
||||
### Phase 4: Handle Tests from lyrics_transcriber
|
||||
@@ -199,6 +199,6 @@ If issues arise:
|
||||
|
||||
## Notes
|
||||
|
||||
- The import paths like `from karaoke_gen.lyrics_transcriber.core import ...` will continue to work unchanged
|
||||
- The import paths like `from lyrics_transcriber.core import ...` will continue to work unchanged
|
||||
- Only the internal project structure changes, not the API
|
||||
- This is primarily a cleanup/organization task with some external repo admin work
|
||||
@@ -1,110 +0,0 @@
|
||||
# Plan: Disable Auto-Correction (Agentic and Heuristic)
|
||||
|
||||
**Created:** 2026-01-20
|
||||
**Branch:** feat/sess-20260120-1914-disable-auto-correction
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Disable all auto-correction during the lyrics transcription & correction phase. Currently, auto-correction (both agentic AI-based and heuristic rule-based) creates more work for human reviewers by introducing errors that need to be manually fixed. The solution is to skip all correction processing and pass the raw transcription directly to human review.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] Disable agentic AI correction (LLM-based via Gemini)
|
||||
- [x] Disable heuristic correction (rule-based handlers like ExtendAnchorHandler, WordCountMatchHandler, etc.)
|
||||
- [x] Preserve the transcription → human review → video generation flow
|
||||
- [x] Minimal code changes (configuration-based if possible)
|
||||
- [x] Easy to re-enable in the future if correction quality improves
|
||||
|
||||
## Technical Approach
|
||||
|
||||
The simplest approach is to change the backend configuration default for `use_agentic_ai` from `true` to `false`, AND ensure that when agentic AI is disabled, the heuristic handlers also don't run.
|
||||
|
||||
**Current behavior:**
|
||||
1. `backend/config.py` line 46: `use_agentic_ai` defaults to `true`
|
||||
2. `lyrics_worker.py` sets `USE_AGENTIC_AI` env var based on config
|
||||
3. `corrector.py` line 84/132: Checks `USE_AGENTIC_AI` env var
|
||||
4. When agentic is disabled, rule-based handlers still run (lines 669-733)
|
||||
|
||||
**Proposed changes:**
|
||||
|
||||
### Option A: Add a new `skip_correction` config (Recommended)
|
||||
Add a single boolean `skip_correction` setting that:
|
||||
- When `true`: Skips the entire correction process, returning raw transcription
|
||||
- When `false` (future): Falls back to existing agentic/heuristic behavior
|
||||
|
||||
This is cleaner than disabling both systems separately because:
|
||||
1. Single config controls both
|
||||
2. Clear intent ("skip correction" vs "disable two different systems")
|
||||
3. Easy to understand for future maintainers
|
||||
|
||||
### Option B: Just disable both individually
|
||||
- Set `use_agentic_ai` default to `false`
|
||||
- Disable default heuristic handlers by setting `enabled_handlers=[]`
|
||||
|
||||
Option A is cleaner, but Option B requires fewer code changes.
|
||||
|
||||
**Decision: Option A** - Add `skip_correction` config for clarity and easier future re-enablement.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [x] **Add `skip_correction` config to backend/config.py**
|
||||
- Add `skip_correction: bool` setting, default `true`
|
||||
- Comment explaining this disables both agentic and heuristic correction
|
||||
|
||||
2. [x] **Update lyrics_worker.py to pass skip_correction**
|
||||
- Pass the config value through to LyricsProcessor/LyricsTranscriber
|
||||
|
||||
3. [x] **Update corrector.py to support skip_correction**
|
||||
- When `skip_correction=True`, return immediately with uncorrected segments
|
||||
- No handler processing, no agentic AI
|
||||
- Still need to do anchor/gap finding? No - skip entirely
|
||||
|
||||
4. [x] **Update LyricsProcessor to support skip_correction**
|
||||
- Pass through to LyricsTranscriber
|
||||
|
||||
5. [x] **Update LyricsTranscriber controller to support skip_correction**
|
||||
- Pass through to corrector or skip corrector.run() entirely
|
||||
|
||||
6. [x] **Update docs/README.md**
|
||||
- Note that auto-correction is disabled
|
||||
- Update "Agentic AI correction" status to "Disabled"
|
||||
|
||||
7. [x] **Run tests to verify no regressions**
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/config.py` | Modify | Add `skip_correction` config (default: true) |
|
||||
| `backend/workers/lyrics_worker.py` | Modify | Pass `skip_correction` to transcription |
|
||||
| `karaoke_gen/lyrics_transcriber/correction/corrector.py` | Modify | Return early when skip_correction=True |
|
||||
| `karaoke_gen/lyrics_transcriber/controller.py` | Modify | Pass skip_correction to corrector |
|
||||
| `karaoke_gen/lyrics_processor.py` | Modify | Pass skip_correction through |
|
||||
| `docs/README.md` | Modify | Update status to reflect disabled correction |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: No new tests needed - this is a config change
|
||||
- **Existing tests**: Run `make test` to ensure no regressions
|
||||
- **Manual verification**: The correction metadata in the corrections.json should show no corrections made
|
||||
|
||||
## Open Questions
|
||||
|
||||
None - the approach is straightforward.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
To re-enable auto-correction:
|
||||
1. Set `SKIP_CORRECTION=false` environment variable, OR
|
||||
2. Change the default back to `false` in `backend/config.py`
|
||||
|
||||
The code paths for agentic and heuristic correction remain intact and can be re-enabled at any time.
|
||||
|
||||
## Alternative Considered
|
||||
|
||||
Instead of adding a new config, we could:
|
||||
1. Set `USE_AGENTIC_AI=false` (disables agentic)
|
||||
2. Set `enabled_handlers=[]` somewhere (disables heuristic)
|
||||
|
||||
But this is more fragmented and harder to understand. A single `skip_correction` config is clearer.
|
||||
@@ -1,99 +0,0 @@
|
||||
# Plan: Encoding Worker Immutable Deployment Pattern
|
||||
|
||||
## Status: In Progress
|
||||
|
||||
## Problem Statement
|
||||
|
||||
The GCE encoding worker has recurring version mismatch issues because:
|
||||
1. `startup.sh` is baked into the Packer image (requires image rebuild + VM recreation)
|
||||
2. Wheel selection uses `sort -V` which can fail if image is outdated
|
||||
3. CI only restarts service - doesn't verify version strictly
|
||||
4. Multiple actors (CI, Pulumi, manual SSH) can cause drift
|
||||
5. 51 old wheel files accumulate in GCS bucket
|
||||
|
||||
## Solution: Immutable Deployment Pattern
|
||||
|
||||
### Core Principles
|
||||
1. **Single Source of Truth**: All code and config from GCS, nothing baked in image
|
||||
2. **Fixed Wheel Path**: `karaoke_gen-current.whl` eliminates sorting
|
||||
3. **Version Manifest**: CI writes expected version, service MUST match
|
||||
4. **Strict Verification**: CI FAILS if deployed version doesn't match
|
||||
5. **Self-Updating Startup**: Download startup.sh from GCS on every boot
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: GCS Structure & Scripts
|
||||
|
||||
- [x] **Step 1.1**: Create `infrastructure/encoding-worker/` directory
|
||||
- [x] **Step 1.2**: Create `bootstrap.sh` (minimal, baked in image)
|
||||
- [x] **Step 1.3**: Create `startup.sh` (CI-managed, deployed to GCS)
|
||||
- [x] **Step 1.4**: Create README.md with documentation
|
||||
|
||||
### Phase 2: CI Workflow Updates
|
||||
|
||||
- [x] **Step 2.1**: Update CI to upload wheel to fixed path
|
||||
- [x] **Step 2.2**: Update CI to upload startup.sh to GCS
|
||||
- [x] **Step 2.3**: Update CI to write version.txt manifest
|
||||
- [x] **Step 2.4**: Update CI to strictly verify deployed version (fail on mismatch)
|
||||
|
||||
### Phase 3: Packer Image Updates
|
||||
|
||||
- [x] **Step 3.1**: Update provision.sh to use bootstrap.sh
|
||||
- [ ] **Step 3.2**: Rebuild Packer image (manual step after merge)
|
||||
- [ ] **Step 3.3**: Recreate VM to use new image (manual step after merge)
|
||||
|
||||
### Phase 4: Documentation & Cleanup
|
||||
|
||||
- [x] **Step 4.1**: Update LESSONS-LEARNED.md with new pattern
|
||||
- [x] **Step 4.2**: Update infrastructure/packer/README.md
|
||||
- [ ] **Step 4.3**: Add lifecycle rule for old wheels (optional, later)
|
||||
|
||||
## New GCS Structure
|
||||
|
||||
```
|
||||
gs://karaoke-gen-storage-nomadkaraoke/
|
||||
├── wheels/
|
||||
│ ├── karaoke_gen-current.whl # Latest (CI overwrites)
|
||||
│ └── karaoke_gen-{version}.whl # Versioned for rollback
|
||||
│
|
||||
└── encoding-worker/
|
||||
├── bootstrap.sh # Reference copy
|
||||
├── startup.sh # CI-managed, downloaded on boot
|
||||
└── version.txt # Expected version number
|
||||
```
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Purpose |
|
||||
|------|--------|---------|
|
||||
| `infrastructure/encoding-worker/bootstrap.sh` | Create | Minimal loader (baked in image) |
|
||||
| `infrastructure/encoding-worker/startup.sh` | Create | Main logic (deployed to GCS) |
|
||||
| `infrastructure/packer/scripts/provision.sh` | Modify | Use bootstrap.sh |
|
||||
| `.github/workflows/ci.yml` | Modify | New deployment flow |
|
||||
| `docs/LESSONS-LEARNED.md` | Modify | Document pattern |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
1. **Unit test**: Verify startup.sh logic locally
|
||||
2. **Integration test**: After merge, verify:
|
||||
- CI uploads files to correct GCS paths
|
||||
- Service starts with correct version
|
||||
- Health endpoint returns expected version
|
||||
3. **Manual verification**: Check VM logs after first deployment
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If issues occur:
|
||||
1. CI can re-upload previous wheel to `karaoke_gen-current.whl`
|
||||
2. Previous versioned wheels remain in GCS for manual rollback
|
||||
3. Old Packer images remain for VM rollback
|
||||
|
||||
## Open Questions
|
||||
|
||||
None - design is complete.
|
||||
|
||||
## Notes
|
||||
|
||||
- Bootstrap.sh is ~10 lines and should never need changes
|
||||
- All logic changes go through startup.sh in GCS
|
||||
- Version verification is strict - CI fails on mismatch
|
||||
@@ -1,166 +0,0 @@
|
||||
# Plan: Fix YouTube Remote Download Missing GCS Path
|
||||
|
||||
**Created:** 2026-01-20
|
||||
**Branch:** feat/sess-20260120-1756-fix-youtube-remote-download
|
||||
**Status:** Complete
|
||||
|
||||
## Overview
|
||||
|
||||
When remote flacfetch is enabled and a user selects a YouTube audio source, the backend calls `download_by_id()` without the `gcs_path` parameter. This causes flacfetch to download the file locally on the VM instead of uploading to GCS. The backend then tries to open the VM's local path, which doesn't exist on Cloud Run, causing the job to fail.
|
||||
|
||||
This is the same class of bug that was fixed on 2025-12-22 for RED/OPS torrent sources (see `docs/archive/2025-12-phase1-testing-gaps.md`), but the fix only covered torrent sources, not YouTube.
|
||||
|
||||
## Root Cause
|
||||
|
||||
In `backend/api/routes/audio_search.py` lines 354-363:
|
||||
|
||||
```python
|
||||
# Use download_by_id if we have source_id and remote is enabled
|
||||
if source_id and source_name and is_remote_enabled:
|
||||
logger.info(f"Using download_by_id for local download: {source_name} ID={source_id}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir=temp_dir, # <-- This is a local temp dir, but flacfetch runs on VM!
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
# <-- MISSING: gcs_path parameter
|
||||
)
|
||||
```
|
||||
|
||||
When `is_remote_enabled=True`, `download_by_id()` routes to the remote flacfetch VM. Without `gcs_path`, the VM downloads locally and returns a local path like `/var/lib/transmission-daemon/downloads/...` which doesn't exist on Cloud Run.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [x] YouTube downloads with remote flacfetch should upload directly to GCS
|
||||
- [x] Backend should receive a `gs://` path from flacfetch
|
||||
- [x] No changes to flacfetch itself (it already supports `upload_to_gcs` and `gcs_destination`)
|
||||
- [x] Maintain backwards compatibility (local-only deployments should still work)
|
||||
- [x] Add test coverage for this code path
|
||||
|
||||
## Technical Approach
|
||||
|
||||
**Option A (chosen):** Pass `gcs_path` to `download_by_id()` for ALL remote downloads, not just torrent sources.
|
||||
|
||||
The current code structure has two branches:
|
||||
1. `if is_torrent_source and is_remote_enabled:` - handles RED/OPS with GCS upload ✅
|
||||
2. `else:` branch - handles YouTube, but incorrectly assumes "local download" even when remote is enabled
|
||||
|
||||
The fix refactors to check `is_remote_enabled` first, then handle torrent vs YouTube within that:
|
||||
- If remote enabled: always pass `gcs_path` to let flacfetch upload directly
|
||||
- If remote disabled: download locally and upload to GCS from Cloud Run
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. [x] Refactor the `else` branch in `_download_and_start_processing()` to check for remote-enabled YouTube downloads
|
||||
2. [x] Pass `gcs_path` when calling `download_by_id()` for remote YouTube downloads
|
||||
3. [x] Add test case for YouTube with remote enabled to verify `gcs_path` is passed
|
||||
4. [x] Update logging to clarify the download path being used
|
||||
5. [x] Bump version in `pyproject.toml`
|
||||
6. [x] Run tests to verify no regressions
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/audio_search.py` | Modify | Add `gcs_path` parameter for remote YouTube downloads |
|
||||
| `backend/tests/test_audio_search.py` | Modify | Add test case for YouTube remote download with GCS path |
|
||||
| `pyproject.toml` | Modify | Bump version |
|
||||
|
||||
## Detailed Code Changes
|
||||
|
||||
### audio_search.py (lines 349-393)
|
||||
|
||||
Current structure:
|
||||
```python
|
||||
else:
|
||||
# Local download (YouTube or fallback) <-- WRONG: not always local!
|
||||
temp_dir = tempfile.mkdtemp(...)
|
||||
|
||||
if source_id and source_name and is_remote_enabled:
|
||||
result = audio_search_service.download_by_id(
|
||||
...
|
||||
output_dir=temp_dir, # <-- BUG: unused for remote
|
||||
# Missing gcs_path!
|
||||
)
|
||||
```
|
||||
|
||||
Fixed structure:
|
||||
```python
|
||||
else:
|
||||
# Non-torrent download (YouTube or fallback)
|
||||
|
||||
if is_remote_enabled and source_id and source_name:
|
||||
# Remote download via flacfetch VM - upload directly to GCS
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
logger.info(f"Using remote download_by_id for {source_name} ID={source_id} with GCS upload to: {gcs_destination}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="", # Not used for remote
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination, # <-- FIX: Add this!
|
||||
)
|
||||
|
||||
# Handle GCS path response (same logic as torrent branch)
|
||||
if result.filepath.startswith("gs://"):
|
||||
parts = result.filepath.replace("gs://", "").split("/", 1)
|
||||
if len(parts) == 2:
|
||||
audio_gcs_path = parts[1]
|
||||
else:
|
||||
audio_gcs_path = result.filepath
|
||||
filename = os.path.basename(result.filepath)
|
||||
else:
|
||||
# Fallback: upload manually
|
||||
filename = os.path.basename(result.filepath)
|
||||
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
logger.warning(f"Remote download returned local path: {result.filepath}, uploading manually")
|
||||
with open(result.filepath, 'rb') as f:
|
||||
storage_service.upload_fileobj(f, audio_gcs_path, content_type='audio/flac')
|
||||
|
||||
logger.info(f"Remote download complete, GCS path: {audio_gcs_path}")
|
||||
else:
|
||||
# Local download (remote disabled or no source_id)
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
# ... existing local download logic ...
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
Add to `test_audio_search.py` in `TestAudioSearchApiRouteDownload`:
|
||||
|
||||
```python
|
||||
def test_youtube_remote_download_passes_gcs_path(self, mock_job_manager, mock_storage_service):
|
||||
"""
|
||||
Test that YouTube downloads via remote flacfetch include GCS path.
|
||||
|
||||
This is the same bug pattern as the torrent download bug fixed in 2025-12:
|
||||
when remote is enabled, we must pass gcs_path so flacfetch uploads to GCS.
|
||||
"""
|
||||
# Setup: YouTube source with remote enabled
|
||||
# Verify: download_by_id called with gcs_path parameter
|
||||
```
|
||||
|
||||
### Manual Testing (post-deploy)
|
||||
1. Create a job and select a YouTube audio source
|
||||
2. Verify job completes successfully
|
||||
3. Check GCS path is properly set in job data
|
||||
|
||||
## Open Questions
|
||||
|
||||
None - the fix is straightforward and follows the pattern established for torrent sources.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
This is a minor code change. If issues occur:
|
||||
1. Revert the PR
|
||||
2. The failure mode returns to the current state (YouTube downloads fail when remote is enabled)
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- `docs/archive/2025-12-phase1-testing-gaps.md` - Original bug fix for torrent sources
|
||||
- `docs/LESSONS-LEARNED.md` - "Fix Both Sides of Dual Code Paths" pattern
|
||||
@@ -1,407 +0,0 @@
|
||||
# Plan: Add Retry Logic for Flacfetch Download Failures
|
||||
|
||||
**Created:** 2026-02-10
|
||||
**Branch:** feat/sess-20260210-1158-investigate-job-749141f8
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
Job 749141f8 failed with error: "Audio download failed: Remote download by ID failed: Download by ID request failed:"
|
||||
|
||||
Investigation revealed **multiple related issues** when flacfetch network calls fail:
|
||||
|
||||
1. **No retry logic** - A single network hiccup causes immediate job failure
|
||||
2. **Missing source info** - When download fails, source_id/source_name aren't saved to job
|
||||
3. **Broken retry button** - Can't retry because no source info was persisted
|
||||
4. **Silent UI failures** - Frontend doesn't show retry error messages to user
|
||||
|
||||
### Root Cause
|
||||
|
||||
Audio search flow saves selection info to `state_data`, but doesn't save download parameters (source_id, source_name, etc.) to the job document until AFTER download succeeds. If the flacfetch call fails (network error), the job fails with no way to retry.
|
||||
|
||||
### Solution
|
||||
|
||||
This plan fixes all four issues:
|
||||
- Add retry logic to flacfetch client (network resilience)
|
||||
- Persist download info before attempting download (enables retry)
|
||||
- Update retry endpoint to handle audio search jobs
|
||||
- Show error messages in frontend when retry fails
|
||||
|
||||
## Requirements
|
||||
|
||||
### Functional Requirements - Flacfetch Retry Logic
|
||||
- [x] Retry `download_by_id()` on `httpx.RequestError` (network failures)
|
||||
- [x] Use exponential backoff spread over ~5 minutes
|
||||
- [x] Configurable max retries via environment variable
|
||||
- [x] Log each retry attempt with context
|
||||
- [x] Do NOT retry on HTTP 4xx errors (client errors - immediate failure)
|
||||
- [x] Do retry on HTTP 5xx errors (server errors - transient)
|
||||
|
||||
### Functional Requirements - Persist Download Info
|
||||
- [x] Save source_id, source_name, target_file, download_url to job document
|
||||
- [x] Save BEFORE attempting download (not after)
|
||||
- [x] Store in top-level fields for easy retry access
|
||||
- [x] Preserve existing state_data fields (selected_audio_index, etc.)
|
||||
|
||||
### Functional Requirements - Retry Endpoint
|
||||
- [x] Add case for audio search jobs in `/jobs/{id}/retry` endpoint
|
||||
- [x] Check for saved download params (source_id, source_name)
|
||||
- [x] Re-download using saved params
|
||||
- [x] Clear error state before retrying
|
||||
- [x] Trigger appropriate workers after successful download
|
||||
|
||||
### Functional Requirements - Frontend Error Handling
|
||||
- [x] Show toast notification when retry fails
|
||||
- [x] Display actual error message from API
|
||||
- [x] Don't just console.error - make it visible to user
|
||||
|
||||
### Non-Functional Requirements
|
||||
- [x] Minimal code changes (use existing patterns)
|
||||
- [x] Clear error messages that include retry context
|
||||
- [x] Backwards compatible (no breaking changes)
|
||||
- [x] Should not significantly increase total timeout duration
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Architecture Decisions
|
||||
|
||||
**Option 1: Tenacity library (Recommended)**
|
||||
- ✅ Industry standard, well-tested
|
||||
- ✅ Declarative retry configuration
|
||||
- ✅ Built-in exponential backoff
|
||||
- ✅ Already used in project (check `poetry.lock`)
|
||||
- ❌ New dependency if not already present
|
||||
|
||||
**Option 2: Manual retry loop**
|
||||
- ✅ No new dependencies
|
||||
- ✅ Full control over logic
|
||||
- ❌ More code to maintain
|
||||
- ❌ Easy to get wrong (edge cases)
|
||||
|
||||
**Decision:** Use **tenacity** if already in dependencies, otherwise implement manual retry loop.
|
||||
|
||||
### Retry Strategy
|
||||
|
||||
```python
|
||||
# Retry on network errors only (RequestError)
|
||||
# Do NOT retry on:
|
||||
# - HTTP 4xx (client errors like 400, 401, 404)
|
||||
# - Already completed downloads
|
||||
# Do retry on:
|
||||
# - httpx.RequestError (connection timeout, refused, DNS failure)
|
||||
# - HTTP 5xx (server errors - service temporarily down)
|
||||
|
||||
Max retries: 8 (total 9 attempts)
|
||||
Backoff: Exponential with cap, multiplier=2, min=10s, max=60s
|
||||
- Attempt 1: immediate
|
||||
- Attempt 2: wait 10s
|
||||
- Attempt 3: wait 20s
|
||||
- Attempt 4: wait 40s
|
||||
- Attempt 5: wait 60s (capped)
|
||||
- Attempt 6: wait 60s (capped)
|
||||
- Attempt 7: wait 60s (capped)
|
||||
- Attempt 8: wait 60s (capped)
|
||||
- Attempt 9: wait 60s (capped)
|
||||
Total max time: ~370s (6+ minutes) of backoff + request timeouts
|
||||
|
||||
This gives the flacfetch service time to recover from restarts,
|
||||
network issues, or temporary VM problems.
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
Add to `backend/config.py`:
|
||||
```python
|
||||
# Flacfetch client retry settings
|
||||
flacfetch_retry_max_attempts: int = int(os.getenv("FLACFETCH_RETRY_MAX_ATTEMPTS", "9")) # Total attempts (1 initial + 8 retries)
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
```
|
||||
|
||||
### Error Message Improvements
|
||||
|
||||
Change from:
|
||||
```
|
||||
Download by ID request failed:
|
||||
```
|
||||
|
||||
To:
|
||||
```
|
||||
Download by ID request failed after 4 attempts: [ConnectTimeout] Connection to http://10.0.0.5:8080 timed out
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Check Dependencies
|
||||
1. [ ] Check if `tenacity` is in `pyproject.toml` dependencies
|
||||
2. [ ] If not present, add `tenacity = "^8.2.0"` to dependencies
|
||||
3. [ ] Run `poetry lock` if dependencies changed
|
||||
|
||||
### Phase 2: Add Configuration
|
||||
4. [ ] Add retry configuration to `backend/config.py`
|
||||
- `flacfetch_retry_max_attempts = 9`
|
||||
- `flacfetch_retry_min_wait = 10.0`
|
||||
- `flacfetch_retry_max_wait = 60.0`
|
||||
|
||||
### Phase 3: Implement Flacfetch Retry Logic
|
||||
5. [ ] Import tenacity in `backend/services/flacfetch_client.py`
|
||||
6. [ ] Create retry decorator with:
|
||||
- Retry on `httpx.RequestError`
|
||||
- Retry on `httpx.HTTPStatusError` with 5xx status
|
||||
- Stop on `httpx.HTTPStatusError` with 4xx status
|
||||
- Exponential backoff with cap at 60s
|
||||
- Before-sleep logging callback
|
||||
7. [ ] Apply decorator to `download_by_id()` method
|
||||
8. [ ] Improve error messages to include:
|
||||
- Number of attempts made
|
||||
- Original exception type and message
|
||||
|
||||
### Phase 4: Persist Download Info Before Download
|
||||
9. [ ] Update `audio_search.py:_download_and_start_processing()`
|
||||
10. [ ] After getting source info from selected result (line 307-311)
|
||||
11. [ ] **Save to job document BEFORE download attempt:**
|
||||
```python
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_source_type': 'audio_search',
|
||||
'source_name': source_name,
|
||||
'source_id': source_id,
|
||||
'target_file': target_file,
|
||||
'download_url': download_url,
|
||||
})
|
||||
```
|
||||
12. [ ] Then proceed with download (existing code)
|
||||
13. [ ] Add to Job model if needed (check if fields exist)
|
||||
|
||||
### Phase 5: Update Retry Endpoint for Audio Search
|
||||
14. [ ] Update `backend/api/routes/jobs.py:retry_job()`
|
||||
15. [ ] Add new case before "no input audio" error (line ~1088)
|
||||
16. [ ] Check if job has saved download params:
|
||||
```python
|
||||
elif job.audio_source_type == 'audio_search' and job.source_id:
|
||||
# Has audio search download info - retry download
|
||||
```
|
||||
17. [ ] Re-call audio search download logic with saved params
|
||||
18. [ ] Or refactor download into reusable function
|
||||
|
||||
### Phase 6: Frontend Error Handling
|
||||
19. [ ] Update `frontend/components/job/JobActions.tsx`
|
||||
20. [ ] Add toast notification library (check if exists)
|
||||
21. [ ] In `handleRetry()` catch block, show toast:
|
||||
```typescript
|
||||
catch (error) {
|
||||
const message = error.response?.data?.detail || "Failed to retry job"
|
||||
toast.error(message)
|
||||
console.error("Failed to retry job:", error)
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 7: Testing - Flacfetch Retry
|
||||
22. [ ] Add unit tests to `backend/tests/test_flacfetch_client.py`
|
||||
23. [ ] Test retry on RequestError (mock fails N times then succeeds)
|
||||
24. [ ] Test no retry on 4xx errors
|
||||
25. [ ] Test retry on 5xx errors
|
||||
26. [ ] Test max retries exhausted
|
||||
27. [ ] Verify logging output includes attempt numbers
|
||||
|
||||
### Phase 8: Testing - End-to-End
|
||||
28. [ ] Test audio search job with flacfetch down
|
||||
29. [ ] Verify source info is saved even when download fails
|
||||
30. [ ] Verify retry button works after source info saved
|
||||
31. [ ] Test retry succeeds when flacfetch comes back up
|
||||
32. [ ] Verify error toast appears when retry fails
|
||||
|
||||
### Phase 9: Documentation
|
||||
33. [ ] Update `backend/services/flacfetch_client.py` docstring
|
||||
34. [ ] Add to `docs/LESSONS-LEARNED.md`:
|
||||
- "Always add retries for external service calls"
|
||||
- "Save operation parameters before attempting operations"
|
||||
- "Persist enough state to enable retry from any failure point"
|
||||
35. [ ] Update `docs/ARCHITECTURE.md` if needed
|
||||
36. [ ] Document the new job fields in API.md
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/config.py` | Modify | Add retry configuration variables |
|
||||
| `backend/services/flacfetch_client.py` | Modify | Add retry logic to `download_by_id()` |
|
||||
| `backend/api/routes/audio_search.py` | Modify | Save download info before attempting download |
|
||||
| `backend/api/routes/jobs.py` | Modify | Add audio search case to retry endpoint |
|
||||
| `backend/models/job.py` | Modify (maybe) | Add fields: source_name, source_id, target_file, download_url |
|
||||
| `frontend/components/job/JobActions.tsx` | Modify | Show error toast when retry fails |
|
||||
| `backend/tests/test_flacfetch_client.py` | Modify | Add retry tests |
|
||||
| `backend/tests/test_audio_search.py` | Modify | Test download info persistence |
|
||||
| `backend/tests/test_jobs.py` | Modify | Test retry with audio search jobs |
|
||||
| `pyproject.toml` | Modify (maybe) | Add tenacity if not present |
|
||||
| `docs/LESSONS-LEARNED.md` | Modify | Document patterns |
|
||||
| `docs/API.md` | Modify | Document new job fields |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (`backend/tests/test_flacfetch_client.py`)
|
||||
|
||||
1. **Test retry on RequestError**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_retries_on_network_error():
|
||||
"""Should retry 3 times on connection errors."""
|
||||
client = FlacfetchClient(base_url="http://test", api_key="key")
|
||||
|
||||
with patch("httpx.AsyncClient.post") as mock_post:
|
||||
# Fail 2 times, then succeed
|
||||
mock_post.side_effect = [
|
||||
httpx.RequestError("Connection timeout"),
|
||||
httpx.RequestError("Connection refused"),
|
||||
Mock(json=lambda: {"download_id": "test123"}, status_code=200),
|
||||
]
|
||||
|
||||
result = await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
assert result == "test123"
|
||||
assert mock_post.call_count == 3
|
||||
```
|
||||
|
||||
2. **Test no retry on 4xx errors**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_no_retry_on_client_error():
|
||||
"""Should NOT retry on 400/401/404 errors."""
|
||||
client = FlacfetchClient(base_url="http://test", api_key="key")
|
||||
|
||||
with patch("httpx.AsyncClient.post") as mock_post:
|
||||
response = Mock(status_code=404, text="Not found")
|
||||
response.raise_for_status.side_effect = httpx.HTTPStatusError(
|
||||
"Not found", request=Mock(), response=response
|
||||
)
|
||||
mock_post.return_value = response
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="404"):
|
||||
await client.download_by_id("YouTube", "abc123")
|
||||
|
||||
assert mock_post.call_count == 1 # No retries
|
||||
```
|
||||
|
||||
3. **Test retry on 5xx errors**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_retries_on_server_error():
|
||||
"""Should retry on 500/503 errors."""
|
||||
# Similar to test 1 but with HTTP 503 errors
|
||||
```
|
||||
|
||||
4. **Test max retries exhausted**
|
||||
```python
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_by_id_fails_after_max_retries():
|
||||
"""Should fail with clear message after max retries."""
|
||||
# All attempts fail, verify error message includes attempt count
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
|
||||
5. **Test with actual flacfetch service** (if available in test environment)
|
||||
- Verify retry doesn't break normal operation
|
||||
- Test with deliberate network issues
|
||||
|
||||
### Manual Testing
|
||||
|
||||
6. **Simulate network failure**
|
||||
```bash
|
||||
# Temporarily stop flacfetch VM
|
||||
gcloud compute instances stop flacfetch-service --zone=us-central1-a
|
||||
|
||||
# Submit a test job
|
||||
# Observe logs showing retry attempts
|
||||
|
||||
# Restart VM during retries
|
||||
gcloud compute instances start flacfetch-service --zone=us-central1-a
|
||||
|
||||
# Job should succeed
|
||||
```
|
||||
|
||||
7. **Test with intentional delays**
|
||||
- Add sleep in flacfetch API handler
|
||||
- Verify retries don't cause issues
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [x] ~~Is tenacity already in dependencies?~~ (Will check during implementation)
|
||||
- [x] ~~What's the appropriate total timeout budget?~~ - 9 attempts over ~6 minutes
|
||||
- [x] ~~Should we fix the Retry button UX in this PR?~~ - YES, it's the same root cause
|
||||
- [x] ~~Why did job 749141f8 fail before saving audio source info?~~ - Download info saved AFTER download, not before
|
||||
- [ ] Should we also add retries to `wait_for_download()`?
|
||||
- Probably NO - that already has its own polling/timeout logic
|
||||
- [ ] Should we add circuit breaker pattern?
|
||||
- Probably NO for now - keep it simple
|
||||
- Could add in future if we see cascading failures
|
||||
- [ ] Should retry logic be applied to other flacfetch methods?
|
||||
- `start_download()` - probably YES (same pattern)
|
||||
- `search()` - maybe YES (search can also have network issues)
|
||||
- `get_download_status()` - probably NO (polling already handles this)
|
||||
- **Decision**: Apply to `start_download()` too, skip `search()` for now
|
||||
- [ ] Which toast library should frontend use?
|
||||
- Check if already exists (react-hot-toast, sonner, etc.)
|
||||
- If not, add lightweight library
|
||||
- [ ] Should we save download params to state_data or top-level fields?
|
||||
- Top-level fields more visible and easier to query
|
||||
- **Decision**: Top-level fields (source_id, source_name, etc.)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If this causes issues:
|
||||
|
||||
1. **Quick rollback**: Set env var `FLACFETCH_RETRY_MAX_ATTEMPTS=1` in Cloud Run
|
||||
- Disables retries without code change
|
||||
- Can deploy in ~2 minutes
|
||||
|
||||
2. **Full rollback**: Revert the PR
|
||||
- Git revert the merge commit
|
||||
- Deploy previous version
|
||||
|
||||
3. **Monitoring**: Watch for:
|
||||
- Increased request duration to flacfetch
|
||||
- Jobs timing out at higher layer (Cloud Tasks, Cloud Run)
|
||||
- Duplicate download attempts causing issues
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] Jobs with transient flacfetch failures succeed instead of failing
|
||||
- [ ] Error messages are more informative (show attempts and root cause)
|
||||
- [ ] No increase in false positives (jobs that should fail, now hang)
|
||||
- [ ] All tests pass
|
||||
- [ ] No impact on successful jobs (retry overhead is minimal)
|
||||
|
||||
## Related Issues
|
||||
|
||||
### Job 749141f8 - The Incident
|
||||
|
||||
**What happened:**
|
||||
- User searched for audio via audio search
|
||||
- Selected "Elizabeth Moen - Songbird"
|
||||
- Backend tried to download via flacfetch
|
||||
- Flacfetch call failed with network error (connection timeout/refused)
|
||||
- Job immediately failed
|
||||
- No source info saved → Retry button broken
|
||||
- User sees "Retry" button but clicking does nothing (silent 400 error)
|
||||
|
||||
**How this fix helps:**
|
||||
1. ✅ Flacfetch retry logic → Download would have succeeded after retry
|
||||
2. ✅ Persist download info → Even if all retries fail, user can retry later
|
||||
3. ✅ Retry endpoint fix → Retry button will actually work
|
||||
4. ✅ Frontend toast → User sees helpful error if retry still fails
|
||||
|
||||
**Note:** Job 749141f8 cannot be fixed retroactively (no source info saved). But future jobs with same issue will be fixable via retry button.
|
||||
|
||||
### Future Work (Not in This PR)
|
||||
|
||||
Similar pattern should be applied to other external service calls:
|
||||
- AudioShake API (lyrics transcription)
|
||||
- Modal API (audio separation)
|
||||
- YouTube direct API calls (not via flacfetch)
|
||||
- Email sending (SendGrid)
|
||||
|
||||
## References
|
||||
|
||||
- [Tenacity documentation](https://tenacity.readthedocs.io/)
|
||||
- [LESSONS-LEARNED.md](docs/LESSONS-LEARNED.md) - External service response format mismatches
|
||||
- [flacfetch README](../../flacfetch/README.md) - Understanding the service
|
||||
@@ -1,279 +0,0 @@
|
||||
# Plan: Private (Non-Published) Tracks
|
||||
|
||||
**Created:** 2026-02-24
|
||||
**Branch:** feat/sess-20260224-1149-private-tracks
|
||||
**Status:** Implemented
|
||||
|
||||
## Overview
|
||||
|
||||
Add a `is_private` flag to jobs that changes distribution behavior:
|
||||
- **Dropbox**: Uses `Tracks-NonPublished` folder (not `Tracks-Organized`) with brand code `NOMADNP` (not `NOMAD`)
|
||||
- **YouTube**: Skipped entirely
|
||||
- **Google Drive**: Skipped entirely
|
||||
- **Email**: Completion email includes Dropbox link but no YouTube section
|
||||
- **Discord**: Still notified (for internal tracking)
|
||||
|
||||
Available to all users at job creation and toggleable by admin on existing jobs.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] All users can mark a job as "Private (Non-Published)" when creating it
|
||||
- [ ] Admin can toggle `is_private` on any existing job via admin dashboard
|
||||
- [ ] Private jobs upload to Dropbox at `Tracks-NonPublished` with `NOMADNP-XXXX` brand codes
|
||||
- [ ] Private jobs skip YouTube and Google Drive uploads entirely
|
||||
- [ ] Completion emails omit YouTube section when no YouTube URL (private jobs + any other edge case)
|
||||
- [ ] When admin toggles a completed job to private, existing outputs are auto-deleted
|
||||
- [ ] Discord notifications still fire for private jobs
|
||||
- [ ] Existing (non-private) jobs are completely unaffected (backward compatible)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Core Design: Single Boolean Flag with Runtime Overrides
|
||||
|
||||
Store `is_private: bool = False` on the job model. At distribution time, a helper function returns effective distribution parameters based on this flag. This means:
|
||||
|
||||
- **Toggling is_private automatically changes all distribution behavior** - no need to manually update dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id
|
||||
- **Job fields still store the "normal" defaults** - the override happens at the config-to-orchestrator boundary
|
||||
- **Admin can flip one field** and everything adapts
|
||||
|
||||
### Key Helper Function
|
||||
|
||||
```python
|
||||
# In job_defaults_service.py
|
||||
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
|
||||
"""Return distribution settings, applying private overrides if is_private=True."""
|
||||
if getattr(job, 'is_private', False):
|
||||
settings = get_settings()
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=settings.default_private_dropbox_path,
|
||||
brand_prefix=settings.default_private_brand_prefix,
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=None,
|
||||
# Keep other settings from job (discord, youtube_description, etc.)
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
# Non-private: return job's own settings
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=getattr(job, 'youtube_description_template', None),
|
||||
)
|
||||
```
|
||||
|
||||
This helper is used in both distribution paths (orchestrator and native fallback).
|
||||
|
||||
### Distribution Paths That Need Changes
|
||||
|
||||
Two code paths handle distribution (see LESSONS-LEARNED: "Fix Both Sides of Dual Code Paths"):
|
||||
|
||||
1. **Orchestrator path** (`video_worker_orchestrator.py`): Primary path. `create_orchestrator_config_from_job()` uses the helper to build config.
|
||||
2. **Native distribution path** (`video_worker.py` → `_handle_native_distribution()`): Fallback path. Also uses the helper instead of reading job fields directly.
|
||||
|
||||
### Email Template Change
|
||||
|
||||
Add conditional YouTube section removal in `render_template()`, matching the existing pattern for `feedback_url`:
|
||||
|
||||
```python
|
||||
# Remove YouTube section if no URL provided
|
||||
if not variables.get("youtube_url"):
|
||||
result = re.sub(
|
||||
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
|
||||
'\n',
|
||||
result,
|
||||
flags=re.DOTALL
|
||||
)
|
||||
variables["youtube_url"] = ""
|
||||
```
|
||||
|
||||
And change `render_job_completion()` to pass `None` instead of `"[YouTube URL not available]"` when youtube_url is empty.
|
||||
|
||||
### Admin Toggle Auto-Delete
|
||||
|
||||
When admin PATCH updates `is_private` from False to True on a job that has existing outputs, reuse the existing delete-outputs logic to remove YouTube + GDrive + Dropbox outputs. Admin can then "Reprocess" to re-distribute to the private Dropbox path.
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Backend Model & Config (foundation)
|
||||
|
||||
1. [ ] **Add `is_private` to Job model** (`backend/models/job.py`)
|
||||
- Add `is_private: bool = False` field after `made_for_you` field
|
||||
- Add to `JobCreate` model as well
|
||||
|
||||
2. [ ] **Add private distribution config** (`backend/config.py`)
|
||||
- Add `default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")`
|
||||
- Add `default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")`
|
||||
|
||||
3. [ ] **Add helper function** (`backend/services/job_defaults_service.py`)
|
||||
- Add `get_effective_distribution_for_job(job)` function that returns distribution settings with private overrides applied
|
||||
|
||||
### Phase 2: Backend API (job creation + admin)
|
||||
|
||||
4. [ ] **Add `is_private` to request models** (`backend/models/requests.py`)
|
||||
- Add `is_private: Optional[bool] = None` to `URLSubmissionRequest`
|
||||
- Add `is_private: Optional[bool] = None` to `AudioSearchRequest`
|
||||
|
||||
5. [ ] **Update URL creation endpoint** (`backend/api/routes/jobs.py`)
|
||||
- Accept and pass through `is_private` field to `JobCreate`
|
||||
|
||||
6. [ ] **Update file upload endpoint** (`backend/api/routes/file_upload.py`)
|
||||
- Accept `is_private` Form parameter
|
||||
- Pass through to `JobCreate`
|
||||
|
||||
7. [ ] **Update audio search endpoint** (`backend/api/routes/audio_search.py`)
|
||||
- Accept `is_private` in `AudioSearchRequest`
|
||||
- Pass through to `JobCreate`
|
||||
|
||||
8. [ ] **Update admin endpoints** (`backend/api/routes/admin.py`)
|
||||
- Add `is_private: Optional[bool] = None` to `JobUpdateRequest`
|
||||
- Add `"is_private"` to `EDITABLE_JOB_FIELDS`
|
||||
- In the PATCH handler: detect when `is_private` changes from False→True on a completed job, auto-delete existing outputs (call existing delete-outputs service logic)
|
||||
|
||||
### Phase 3: Distribution Pipeline
|
||||
|
||||
9. [ ] **Update orchestrator config creation** (`backend/workers/video_worker_orchestrator.py`)
|
||||
- In `create_orchestrator_config_from_job()`: Use `get_effective_distribution_for_job()` helper to determine dropbox_path, brand_prefix, enable_youtube_upload, gdrive_folder_id instead of reading directly from job
|
||||
|
||||
10. [ ] **Update native distribution fallback** (`backend/workers/video_worker.py`)
|
||||
- In `_handle_native_distribution()`: Use `get_effective_distribution_for_job()` helper instead of reading directly from job fields
|
||||
|
||||
### Phase 4: Email Template
|
||||
|
||||
11. [ ] **Add YouTube section conditional removal** (`backend/services/template_service.py`)
|
||||
- In `render_template()`: Add regex to remove YouTube paragraph when `youtube_url` is empty (matching existing `feedback_url` pattern)
|
||||
- In `render_job_completion()`: Pass `None` for youtube_url when empty (instead of `"[YouTube URL not available]"`)
|
||||
|
||||
### Phase 5: Frontend
|
||||
|
||||
12. [ ] **Add private checkbox to job creation form** (`frontend/components/job/JobSubmission.tsx`)
|
||||
- Add "Private (Non-Published)" checkbox below the existing "Skip lyrics review" checkbox
|
||||
- Show for all users (not just admin)
|
||||
- Include brief description text: "Private tracks go to Dropbox only, not YouTube or Google Drive"
|
||||
|
||||
13. [ ] **Update API interfaces** (`frontend/lib/api.ts`)
|
||||
- Add `is_private?: boolean` to all job creation option interfaces
|
||||
- Add `is_private` to `JobUpdateRequest` interface
|
||||
- Pass through in `uploadJob()`, `createJobFromUrl()`, `searchAudio()` methods
|
||||
|
||||
14. [ ] **Add private toggle to admin job detail** (`frontend/app/admin/jobs/page.tsx`)
|
||||
- Add `is_private` as an inline-editable field in the job overview section (use Switch component)
|
||||
- Show current state with visual indicator (e.g., lock icon for private jobs)
|
||||
- When toggling to private on a completed job, show confirmation dialog about auto-deleting outputs
|
||||
|
||||
### Phase 6: Environment Configuration
|
||||
|
||||
15. [ ] **Update CI/deployment config** (`.github/workflows/ci.yml` or Cloud Run env)
|
||||
- Add `DEFAULT_PRIVATE_DROPBOX_PATH` environment variable (e.g., `/Karaoke/Tracks-NonPublished`)
|
||||
- Add `DEFAULT_PRIVATE_BRAND_PREFIX` environment variable (e.g., `NOMADNP`)
|
||||
- These should be configured in Cloud Run service and CI test environment
|
||||
|
||||
### Phase 7: Testing
|
||||
|
||||
16. [ ] **Unit tests for private distribution logic** (`backend/tests/test_private_tracks.py`)
|
||||
- Test `get_effective_distribution_for_job()` with private and non-private jobs
|
||||
- Test `create_orchestrator_config_from_job()` applies private overrides correctly
|
||||
- Test `_run_distribution()` skips YouTube and GDrive when private config applied
|
||||
- Test `_upload_to_dropbox()` uses private path and brand prefix
|
||||
- Test brand code generation with NOMADNP prefix in Tracks-NonPublished
|
||||
- Test `_handle_native_distribution()` respects private overrides
|
||||
- Test non-private jobs are completely unaffected (regression tests)
|
||||
|
||||
17. [ ] **Unit tests for email changes** (add to `backend/tests/test_email_service.py` or `test_template_service.py`)
|
||||
- Test YouTube section removed from email when youtube_url is None
|
||||
- Test YouTube section present when youtube_url is provided
|
||||
- Test Dropbox section still present for private jobs
|
||||
- Test full email rendering for private job scenario
|
||||
|
||||
18. [ ] **Unit tests for admin toggle** (add to `backend/tests/test_admin.py` or new file)
|
||||
- Test admin can update is_private field
|
||||
- Test toggling is_private to True on completed job triggers output deletion
|
||||
- Test toggling is_private to True on non-completed job does NOT delete outputs
|
||||
- Test toggling is_private to False does nothing special
|
||||
|
||||
19. [ ] **Integration test** (`backend/tests/emulator/` or `test_distribution_services.py`)
|
||||
- Test full distribution pipeline with is_private=True: verify Dropbox path, brand prefix, YouTube skip, GDrive skip
|
||||
|
||||
20. [ ] **Frontend E2E regression test** (`frontend/e2e/regression/`)
|
||||
- Test private checkbox appears in job creation form
|
||||
- Test private toggle in admin dashboard
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/models/job.py` | Modify | Add `is_private: bool = False` to Job and JobCreate |
|
||||
| `backend/config.py` | Modify | Add `default_private_dropbox_path` and `default_private_brand_prefix` |
|
||||
| `backend/services/job_defaults_service.py` | Modify | Add `get_effective_distribution_for_job()` helper |
|
||||
| `backend/models/requests.py` | Modify | Add `is_private` to URL and AudioSearch request models |
|
||||
| `backend/api/routes/jobs.py` | Modify | Accept and pass `is_private` |
|
||||
| `backend/api/routes/file_upload.py` | Modify | Accept and pass `is_private` |
|
||||
| `backend/api/routes/audio_search.py` | Modify | Accept and pass `is_private` |
|
||||
| `backend/api/routes/admin.py` | Modify | Add `is_private` to editable fields + auto-delete logic |
|
||||
| `backend/workers/video_worker_orchestrator.py` | Modify | Use helper in `create_orchestrator_config_from_job()` |
|
||||
| `backend/workers/video_worker.py` | Modify | Use helper in `_handle_native_distribution()` |
|
||||
| `backend/services/template_service.py` | Modify | Conditional YouTube section removal |
|
||||
| `frontend/components/job/JobSubmission.tsx` | Modify | Add private checkbox |
|
||||
| `frontend/lib/api.ts` | Modify | Add `is_private` to interfaces and API calls |
|
||||
| `frontend/app/admin/jobs/page.tsx` | Modify | Add private toggle to admin detail |
|
||||
| `backend/tests/test_private_tracks.py` | Create | Comprehensive unit tests for private track logic |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests (~25-30 tests in `test_private_tracks.py`)
|
||||
- `get_effective_distribution_for_job()` with private=True and False
|
||||
- `create_orchestrator_config_from_job()` private overrides (YouTube=False, GDrive=None, private Dropbox path, NOMADNP brand)
|
||||
- Distribution stage skips: YouTube not called, GDrive not called, Dropbox IS called with correct path
|
||||
- Brand code generation uses NOMADNP prefix and Tracks-NonPublished path
|
||||
- Native distribution fallback applies same overrides
|
||||
- **Regression tests**: Non-private jobs have unchanged behavior (same paths, same brand code, YouTube+GDrive+Dropbox all fire)
|
||||
|
||||
### Email Template Tests (~5 tests)
|
||||
- YouTube section stripped when youtube_url is None
|
||||
- YouTube section preserved when youtube_url has value
|
||||
- Dropbox section always present
|
||||
- Full private job email rendering (Dropbox + no YouTube)
|
||||
- Full non-private job email rendering (both present) - regression
|
||||
|
||||
### Admin Toggle Tests (~5 tests)
|
||||
- is_private editable via PATCH
|
||||
- Toggle to private on completed job deletes outputs
|
||||
- Toggle to private on pending/in-progress job does NOT delete
|
||||
- Toggle to non-private does nothing special
|
||||
|
||||
### Frontend Tests
|
||||
- E2E: Private checkbox visible and functional in job creation
|
||||
- E2E: Admin toggle visible and includes confirmation dialog
|
||||
|
||||
### Manual Verification
|
||||
- Create a private job end-to-end, verify Dropbox folder in Tracks-NonPublished with NOMADNP code
|
||||
- Verify completion email has Dropbox link but no YouTube section
|
||||
- Toggle existing completed job to private, verify outputs deleted
|
||||
|
||||
## Regression Risk Analysis
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|-----------|
|
||||
| Non-private jobs affected | `is_private` defaults to `False`; helper returns unchanged values for non-private. Explicit regression tests. |
|
||||
| Dual code paths (orchestrator vs native) | Both paths use same helper function. Tests cover both paths. (Lesson: "Fix Both Sides of Dual Code Paths") |
|
||||
| Email template regex breaks other content | Regex targets specific YouTube paragraph text. Tests verify non-YouTube content untouched. |
|
||||
| Brand code namespace collision | NOMADNP codes are in a completely separate Dropbox folder (Tracks-NonPublished), no overlap with NOMAD codes in Tracks-Organized |
|
||||
| Admin auto-delete on wrong job | Only triggers when `is_private` changes from False→True AND job has terminal status (complete). Confirmation dialog in frontend. |
|
||||
| Made-for-you orders | MFY webhook doesn't set is_private (defaults False). Admin can toggle after. No change to MFY flow. |
|
||||
| Existing Firestore documents | Missing `is_private` field defaults to `False` via model default. No migration needed. |
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [x] Who sees private toggle? → **Everyone** (all users at creation, admin on existing)
|
||||
- [x] Auto-delete on toggle? → **Yes**, auto-delete all outputs when toggling to private on completed job
|
||||
- [x] Email format? → **Remove YouTube section** when no YouTube URL (improves all edge cases)
|
||||
- [x] Discord? → **Still notify** (useful for internal tracking)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
1. **Feature flag**: The `is_private` field defaults to `False`, so setting `DEFAULT_PRIVATE_DROPBOX_PATH` to empty/None effectively disables private distribution
|
||||
2. **No schema migration needed**: Missing `is_private` field on existing Firestore documents defaults to `False`
|
||||
3. **Email change is backward-compatible**: The YouTube section removal only happens when youtube_url is None, which is already an edge case showing "[YouTube URL not available]"
|
||||
4. **Frontend**: Private checkbox is additive UI, removing it just means users can't create new private jobs
|
||||
@@ -1,239 +0,0 @@
|
||||
# Plan: Song Lookup & Autocomplete + Community Version Detection
|
||||
|
||||
**Created:** 2026-03-02
|
||||
**Branch:** feat/sess-20260302-2324-song-lookup-autocomplete
|
||||
**Status:** Implementation Complete
|
||||
|
||||
## Overview
|
||||
|
||||
Add two features to the karaoke-gen job creation flow:
|
||||
|
||||
1. **Artist/title autocomplete** using karaoke-decide's MusicBrainz + Spotify catalog data, so users get properly-styled artist/title text (e.g. "Fleetwood Mac" instead of "fleetwood mac")
|
||||
2. **Community karaoke version detection** that warns users when a high-quality community karaoke version already exists on YouTube (via karaokenerds data), saving them credits and time
|
||||
|
||||
Both features are **optional and non-blocking** — users can still type whatever they want and proceed even if a community version exists.
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Artist field autocomplete across all 3 job creation tabs (Search, Upload, URL)
|
||||
- [ ] Title field autocomplete (optionally filtered by selected artist) across all 3 tabs
|
||||
- [ ] Autocomplete uses canonical MusicBrainz/Spotify text styling
|
||||
- [ ] Autocomplete is optional — users can ignore suggestions and type freely
|
||||
- [ ] Community version check triggers when both artist and title are filled
|
||||
- [ ] If community karaoke version exists, show a dismissible banner with YouTube link(s)
|
||||
- [ ] Community check does not block job submission — just informs the user
|
||||
- [ ] Graceful degradation if karaoke-decide API or karaokenerds.com is down
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
### How to access karaoke-decide catalog data
|
||||
|
||||
**Decision: Proxy through karaoke-gen backend**
|
||||
|
||||
Both services share the same GCP project (`nomadkaraoke`), but the frontend at `gen.nomadkaraoke.com` can't directly call `decide.nomadkaraoke.com/api/` due to CORS (different origins). Options considered:
|
||||
|
||||
| Option | Pros | Cons |
|
||||
|--------|------|------|
|
||||
| **Proxy via karaoke-gen backend** | No CORS issues, no changes to karaoke-decide, frontend already calls api.nomadkaraoke.com | Added latency (extra hop), karaoke-decide dependency |
|
||||
| Direct frontend calls + CORS | Simpler, no proxy code | Requires karaoke-decide CORS changes, cross-project coupling |
|
||||
| Query BigQuery directly from karaoke-gen | No dependency on karaoke-decide service | Duplicates query logic, BigQuery setup needed, higher latency |
|
||||
|
||||
The proxy approach is cleanest: karaoke-gen frontend → karaoke-gen backend → karaoke-decide API. Response caching in the proxy minimizes latency impact.
|
||||
|
||||
### How to detect community karaoke versions
|
||||
|
||||
**Decision: Scrape karaokenerds.com from karaoke-gen backend** (same approach as kjbox)
|
||||
|
||||
The `karaokenerds_raw` BigQuery table has the catalog but NOT community status. Community status is determined by an `<img class="check">` badge in karaokenerds.com's HTML, only available via web scraping. The kjbox codebase has proven, well-tested scraping logic we can port directly.
|
||||
|
||||
Search URL: `https://karaokenerds.com/Search?query={artist}+{title}&webFilter=OnlyWeb`
|
||||
|
||||
Returns: songs with tracks, each track having `brand_name`, `brand_code`, `youtube_url`, `is_community`.
|
||||
|
||||
### Autocomplete UI component
|
||||
|
||||
**Decision: Use existing shadcn Command (cmdk) + Popover components**
|
||||
|
||||
The frontend already has `command.tsx` and `popover.tsx` from shadcn/ui. The standard combobox pattern (Popover + Command) provides:
|
||||
- Keyboard navigation (arrow keys, enter to select)
|
||||
- Debounced search-as-you-type
|
||||
- Clean dropdown with loading states
|
||||
- Works inline within forms (not modal)
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Data flow
|
||||
|
||||
```
|
||||
User types in artist field
|
||||
→ debounced (300ms) API call to GET /api/catalog/artists?q=fle
|
||||
→ karaoke-gen backend proxies to decide.nomadkaraoke.com/api/catalog/artists?q=fle
|
||||
→ returns [{ name: "Fleetwood Mac", mbid: "...", popularity: 85 }, ...]
|
||||
→ user selects "Fleetwood Mac" → field populated with canonical name
|
||||
|
||||
User types in title field
|
||||
→ debounced (300ms) API call to GET /api/catalog/tracks?q=dreams&artist=Fleetwood+Mac
|
||||
→ returns [{ track_name: "Dreams", artist_name: "Fleetwood Mac", popularity: 82 }, ...]
|
||||
→ user selects "Dreams" → field populated with canonical title
|
||||
|
||||
Both fields filled → community check fires
|
||||
→ POST /api/catalog/community-check { artist: "Fleetwood Mac", title: "Dreams" }
|
||||
→ backend scrapes karaokenerds.com for "Fleetwood Mac Dreams" with webFilter=OnlyWeb
|
||||
→ if community tracks found with YouTube URLs, return them
|
||||
→ frontend shows banner: "A community karaoke version already exists! [Watch on YouTube →]"
|
||||
```
|
||||
|
||||
### Caching strategy
|
||||
|
||||
| Endpoint | Cache TTL | Scope |
|
||||
|----------|-----------|-------|
|
||||
| Artist search proxy | 5 min | In-memory (backend) |
|
||||
| Track search proxy | 5 min | In-memory (backend) |
|
||||
| Community check | 1 hour | In-memory (backend) |
|
||||
|
||||
### karaoke-decide API endpoints used
|
||||
|
||||
These are all **public, no auth required**:
|
||||
|
||||
- `GET /api/catalog/artists?q={query}&limit=10` — MBID-first artist search
|
||||
- Returns: `[{ mbid, name, disambiguation, artist_type, tags, spotify_id, popularity, genres }]`
|
||||
- `GET /api/catalog/tracks?q={query}&limit=10` — Track search (Spotify data)
|
||||
- Returns: `[{ track_id, track_name, artist_name, artist_id, popularity, duration_ms, explicit }]`
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Backend — Catalog proxy + community check endpoints
|
||||
|
||||
1. [ ] **Add catalog proxy service** — `backend/services/catalog_proxy_service.py`
|
||||
- HTTP client (httpx async) calling karaoke-decide API
|
||||
- In-memory TTL cache for responses (5 min)
|
||||
- Configurable karaoke-decide base URL
|
||||
- Graceful error handling (return empty results on failure)
|
||||
|
||||
2. [ ] **Port karaokenerds scraping logic** — `backend/services/karaokenerds_service.py`
|
||||
- Port `search()`, `parse_results()`, `_parse_tracks()`, `_parse_single_track()`, `_clean_youtube_url()` from `kjbox/kj-controller/karaoke_nerds.py`
|
||||
- Add async support (httpx instead of requests)
|
||||
- In-memory TTL cache (1 hour)
|
||||
- Return only community tracks with YouTube URLs
|
||||
|
||||
3. [ ] **Add catalog routes** — `backend/api/routes/catalog.py`
|
||||
- `GET /api/catalog/artists?q=&limit=10` — proxy to karaoke-decide
|
||||
- `GET /api/catalog/tracks?q=&artist=&limit=10` — proxy to karaoke-decide
|
||||
- `POST /api/catalog/community-check` — scrape karaokenerds.com
|
||||
- All endpoints require auth (same as job creation)
|
||||
- Pydantic request/response models
|
||||
|
||||
4. [ ] **Register routes in main.py** — add `catalog.router` to app
|
||||
|
||||
5. [ ] **Add config** — `backend/config.py`
|
||||
- `karaoke_decide_api_url` setting (default: `https://decide.nomadkaraoke.com`)
|
||||
|
||||
6. [ ] **Add `beautifulsoup4` + `httpx` dependencies** to `pyproject.toml` (if not already present)
|
||||
|
||||
### Phase 2: Frontend — Autocomplete component
|
||||
|
||||
7. [ ] **Create `AutocompleteInput` component** — `frontend/components/ui/autocomplete-input.tsx`
|
||||
- Wraps an Input field with a Popover + Command dropdown
|
||||
- Props: `value`, `onChange`, `onSelect`, `fetchSuggestions(query) => Promise<Suggestion[]>`, `placeholder`, `disabled`, `renderItem`
|
||||
- Debounced search (300ms) triggered on input change
|
||||
- Shows loading spinner while fetching
|
||||
- Shows "No results" when search returns empty
|
||||
- Keyboard navigation (up/down arrows, enter to select, escape to close)
|
||||
- Clicking outside closes dropdown
|
||||
- When user selects a suggestion, calls `onSelect(suggestion)` and populates input
|
||||
- When user types without selecting, uses their raw text (autocomplete is optional)
|
||||
|
||||
8. [ ] **Add catalog API functions** — `frontend/lib/api.ts`
|
||||
- `searchArtists(query: string, limit?: number)` → `GET /api/catalog/artists`
|
||||
- `searchTracks(query: string, artist?: string, limit?: number)` → `GET /api/catalog/tracks`
|
||||
- `checkCommunityVersions(artist: string, title: string)` → `POST /api/catalog/community-check`
|
||||
|
||||
### Phase 3: Frontend — Integrate autocomplete into job creation
|
||||
|
||||
9. [ ] **Replace artist Input fields with AutocompleteInput** in `JobSubmission.tsx`
|
||||
- All 3 tabs: `searchArtist`, `uploadArtist`, `youtubeArtist`
|
||||
- Fetch suggestions from `api.searchArtists(query)`
|
||||
- On select: populate artist field with canonical name
|
||||
- Show artist name + optional disambiguation in dropdown items
|
||||
|
||||
10. [ ] **Replace title Input fields with AutocompleteInput** in `JobSubmission.tsx`
|
||||
- All 3 tabs: `searchTitle`, `uploadTitle`, `youtubeTitle`
|
||||
- Fetch suggestions from `api.searchTracks(query, selectedArtist)`
|
||||
- On select: populate title field with canonical name
|
||||
- Show track name + artist name + duration in dropdown items
|
||||
|
||||
### Phase 4: Frontend — Community version detection
|
||||
|
||||
11. [ ] **Create `CommunityVersionBanner` component** — `frontend/components/job/CommunityVersionBanner.tsx`
|
||||
- Shows when community karaoke version(s) found
|
||||
- Displays: "A karaoke version of this song already exists!"
|
||||
- Lists community tracks with brand name and YouTube link
|
||||
- "Watch on YouTube" button for top community version
|
||||
- Dismissible (X button or "Continue anyway" link)
|
||||
- Styled with green border (matching kjbox community track styling)
|
||||
|
||||
12. [ ] **Add community check logic to `JobSubmission.tsx`** (Search tab only)
|
||||
- Debounced check (500ms) when both artist AND title fields have values
|
||||
- Only triggers when values change (not on every keystroke)
|
||||
- Shows `CommunityVersionBanner` between the form fields and the submit button
|
||||
- Does NOT block form submission
|
||||
- Clears when artist or title changes
|
||||
|
||||
### Phase 5: Testing
|
||||
|
||||
13. [ ] **Backend unit tests** — `backend/tests/unit/test_catalog_routes.py`
|
||||
- Test proxy endpoints with mocked karaoke-decide responses
|
||||
- Test community check with mocked karaokenerds HTML
|
||||
- Test error handling (karaoke-decide down, karaokenerds down)
|
||||
- Test caching behavior
|
||||
|
||||
14. [ ] **Backend unit tests** — `backend/tests/unit/test_karaokenerds_service.py`
|
||||
- Port relevant tests from `kjbox/kj-controller/tests/unit/test_karaoke_nerds.py`
|
||||
- Test HTML parsing, community detection, YouTube URL cleanup
|
||||
|
||||
15. [ ] **Frontend component tests** — `frontend/components/ui/__tests__/autocomplete-input.test.tsx`
|
||||
- Test suggestion fetching and display
|
||||
- Test keyboard navigation
|
||||
- Test selection behavior
|
||||
- Test free-text input (no selection)
|
||||
|
||||
16. [ ] **E2E tests** — `frontend/e2e/job-creation-autocomplete.spec.ts`
|
||||
- Test autocomplete appears on typing
|
||||
- Test selecting from autocomplete populates field
|
||||
- Test community banner appears for known songs
|
||||
- Test form submission works with and without autocomplete selection
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/services/catalog_proxy_service.py` | Create | HTTP client for karaoke-decide API with caching |
|
||||
| `backend/services/karaokenerds_service.py` | Create | Karaokenerds.com scraper (ported from kjbox) |
|
||||
| `backend/api/routes/catalog.py` | Create | Proxy endpoints for artist/track search + community check |
|
||||
| `backend/main.py` | Modify | Register catalog router |
|
||||
| `backend/config.py` | Modify | Add karaoke_decide_api_url setting |
|
||||
| `pyproject.toml` | Modify | Add beautifulsoup4 dependency (if missing) |
|
||||
| `frontend/components/ui/autocomplete-input.tsx` | Create | Reusable autocomplete input component |
|
||||
| `frontend/components/job/CommunityVersionBanner.tsx` | Create | Community version warning banner |
|
||||
| `frontend/components/job/JobSubmission.tsx` | Modify | Replace Input with AutocompleteInput, add community check |
|
||||
| `frontend/lib/api.ts` | Modify | Add catalog API functions |
|
||||
| `backend/tests/unit/test_catalog_routes.py` | Create | Backend route tests |
|
||||
| `backend/tests/unit/test_karaokenerds_service.py` | Create | Scraper unit tests |
|
||||
| `frontend/components/ui/__tests__/autocomplete-input.test.tsx` | Create | Component tests |
|
||||
| `frontend/e2e/job-creation-autocomplete.spec.ts` | Create | E2E tests |
|
||||
|
||||
## Decisions (Resolved)
|
||||
|
||||
- **Track search scope**: All Spotify tracks (256M) — better coverage for new/obscure songs
|
||||
- **Community check scope**: Search tab only (Upload/URL users already have their audio)
|
||||
- **Rate limiting**: 20 requests/min per user on catalog proxy endpoints (prevents abuse of karaokenerds scraping). All endpoints require auth.
|
||||
- **"Display As" fields**: No autocomplete — they're for deliberate overrides like soundtrack names
|
||||
- **CORS**: Proxy approach (no changes needed to karaoke-decide)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Feature is entirely additive — no existing functionality is modified
|
||||
- Autocomplete fields fall back to plain text Input if API calls fail
|
||||
- Community check is non-blocking — if it fails, form works normally
|
||||
- All new endpoints are behind the existing auth middleware
|
||||
- Can disable by reverting the frontend changes (backend proxy is harmless if unused)
|
||||
@@ -1,329 +0,0 @@
|
||||
# Plan: Unified Combined Review for Local CLI
|
||||
|
||||
**Created:** 2026-01-24
|
||||
**Branch:** feat/sess-20260124-1444-combined-review-flow
|
||||
**Status:** Draft
|
||||
|
||||
## Problem Statement
|
||||
|
||||
The combined lyrics + instrumental review flow was implemented for the cloud web app, but the local CLI is broken in two ways:
|
||||
|
||||
1. **Bug: Lyrics review is skipped when `SKIP_CORRECTION=true`** (the default)
|
||||
- Review code lives inside `correct_lyrics()` method in controller.py
|
||||
- When auto-correction is disabled, `correct_lyrics()` is never called
|
||||
- Users never get a chance to review lyrics
|
||||
|
||||
2. **Standalone instrumental UI still exists for CLI**
|
||||
- `InstrumentalReviewServer` in `instrumental_review/server.py` is a separate server
|
||||
- CLI launches this standalone server after lyrics review
|
||||
- The combined review flow we built only works for the web app
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Fix the skip bug** - Review should happen even when auto-correction is disabled
|
||||
2. **Unify all review UIs** - One combined review flow for CLI, cloud CLI, and web app
|
||||
3. **Remove dead code** - Delete standalone `InstrumentalReviewServer` and related code
|
||||
4. **Keep it simple** - Minimal changes to achieve the goal
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### Current State (Broken)
|
||||
|
||||
```
|
||||
CLI Flow:
|
||||
controller.py::process()
|
||||
→ correct_lyrics() [SKIPPED if SKIP_CORRECTION=true]
|
||||
→ ReviewServer starts (lyrics only)
|
||||
→ User reviews
|
||||
→ ReviewServer stops
|
||||
→ gen_cli.py::run_instrumental_review()
|
||||
→ InstrumentalReviewServer starts (instrumental only)
|
||||
→ User selects instrumental
|
||||
→ InstrumentalReviewServer stops
|
||||
|
||||
Cloud Web App Flow:
|
||||
Job enters AWAITING_REVIEW
|
||||
→ User visits /app/jobs/{id}/review
|
||||
→ Combined UI: lyrics + instrumental
|
||||
→ POST /api/jobs/{id}/complete-review (includes instrumental_selection)
|
||||
```
|
||||
|
||||
### Target State
|
||||
|
||||
```
|
||||
CLI Flow (and Cloud CLI):
|
||||
controller.py::process()
|
||||
→ _run_human_review() [NEW - always called when review enabled]
|
||||
→ ReviewServer starts (combined: lyrics + instrumental)
|
||||
→ User reviews lyrics AND selects instrumental
|
||||
→ ReviewServer stops, returns both results
|
||||
→ Continue with selected instrumental
|
||||
|
||||
Cloud Web App Flow: (unchanged)
|
||||
Same as before
|
||||
```
|
||||
|
||||
## Key Insight
|
||||
|
||||
The ReviewServer already serves the bundled Next.js frontend. That frontend already has the combined review UI with `InstrumentalSelectorEmbedded`. We just need to:
|
||||
|
||||
1. Make `ReviewServer` serve instrumental options in its `/correction-data` endpoint
|
||||
2. Make `ReviewServer` accept instrumental selection in its `/complete-review` endpoint
|
||||
3. Call the review flow from the right place (not inside `correct_lyrics()`)
|
||||
4. Delete `InstrumentalReviewServer` entirely
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Fix ReviewServer to Support Instrumental Selection
|
||||
|
||||
**1.1. Add instrumental data to ReviewServer's correction-data endpoint**
|
||||
|
||||
File: `karaoke_gen/lyrics_transcriber/review/server.py`
|
||||
|
||||
The `ReviewServer.__init__()` accepts a `CorrectionResult`. We need to also accept instrumental options:
|
||||
|
||||
```python
|
||||
def __init__(
|
||||
self,
|
||||
correction_result: CorrectionResult,
|
||||
instrumental_options: list[dict] | None = None, # NEW
|
||||
backing_vocals_analysis: dict | None = None, # NEW
|
||||
...
|
||||
):
|
||||
```
|
||||
|
||||
Update `_correction_data()` endpoint to include these in response:
|
||||
|
||||
```python
|
||||
@app.get("/api/review/{job_id}/correction-data")
|
||||
def _correction_data(job_id: str):
|
||||
return {
|
||||
"lyrics_data": self.correction_result.to_dict(),
|
||||
"instrumental_options": self.instrumental_options, # NEW
|
||||
"backing_vocals_analysis": self.backing_vocals_analysis # NEW
|
||||
}
|
||||
```
|
||||
|
||||
**1.2. Update ReviewServer's complete-review endpoint to accept instrumental selection**
|
||||
|
||||
File: `karaoke_gen/lyrics_transcriber/review/server.py`
|
||||
|
||||
The existing endpoint accepts `corrected_lyrics`. Add `instrumental_selection`:
|
||||
|
||||
```python
|
||||
@app.post("/api/review/{job_id}/complete-review")
|
||||
def _complete_review(job_id: str, request: ReviewCompleteRequest):
|
||||
# Existing: store corrected lyrics
|
||||
self.corrected_lyrics = request.corrected_lyrics
|
||||
|
||||
# NEW: store instrumental selection
|
||||
self.instrumental_selection = request.instrumental_selection # "clean" | "with_backing"
|
||||
|
||||
self.review_completed = True
|
||||
```
|
||||
|
||||
**1.3. Expose instrumental selection after review completes**
|
||||
|
||||
The calling code needs to get the selection. Update the return value or add an attribute:
|
||||
|
||||
```python
|
||||
# After review loop completes:
|
||||
return {
|
||||
"corrected_lyrics": self.corrected_lyrics,
|
||||
"instrumental_selection": self.instrumental_selection
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 2: Fix controller.py to Call Review at the Right Time
|
||||
|
||||
**2.1. Extract review logic from `correct_lyrics()` into standalone method**
|
||||
|
||||
File: `karaoke_gen/lyrics_transcriber/core/controller.py`
|
||||
|
||||
Create new method `_run_human_review()` that can be called independently:
|
||||
|
||||
```python
|
||||
def _run_human_review(
|
||||
self,
|
||||
correction_result: CorrectionResult,
|
||||
instrumental_options: list[dict] | None = None,
|
||||
backing_vocals_analysis: dict | None = None
|
||||
) -> tuple[CorrectionResult, str | None]:
|
||||
"""Run human review server and return corrected result + instrumental selection."""
|
||||
|
||||
if not self.output_config.review_enabled:
|
||||
return correction_result, None
|
||||
|
||||
server = ReviewServer(
|
||||
correction_result=correction_result,
|
||||
instrumental_options=instrumental_options,
|
||||
backing_vocals_analysis=backing_vocals_analysis,
|
||||
...
|
||||
)
|
||||
|
||||
result = server.start() # Blocks until review complete
|
||||
|
||||
return result["corrected_lyrics"], result.get("instrumental_selection")
|
||||
```
|
||||
|
||||
**2.2. Update `process()` to always call review when appropriate**
|
||||
|
||||
File: `karaoke_gen/lyrics_transcriber/core/controller.py`
|
||||
|
||||
Current flow (simplified):
|
||||
```python
|
||||
def process(self):
|
||||
self.transcribe()
|
||||
self.separate_audio()
|
||||
if self.output_config.run_correction:
|
||||
self.correct_lyrics() # Review is inside here!
|
||||
# ...
|
||||
```
|
||||
|
||||
New flow:
|
||||
```python
|
||||
def process(self):
|
||||
self.transcribe()
|
||||
self.separate_audio()
|
||||
|
||||
# Build correction result (with or without auto-correction)
|
||||
if self.output_config.run_correction:
|
||||
correction_result = self._run_auto_correction()
|
||||
else:
|
||||
correction_result = self._create_uncorrected_result()
|
||||
|
||||
# Human review is separate from auto-correction
|
||||
if self.output_config.review_enabled:
|
||||
instrumental_options = self._get_instrumental_options()
|
||||
backing_vocals_analysis = self._analyze_backing_vocals()
|
||||
|
||||
corrected, instrumental_selection = self._run_human_review(
|
||||
correction_result,
|
||||
instrumental_options,
|
||||
backing_vocals_analysis
|
||||
)
|
||||
|
||||
self.results.correction_result = corrected
|
||||
self.results.instrumental_selection = instrumental_selection
|
||||
```
|
||||
|
||||
### Phase 3: Update gen_cli.py to Use Combined Review
|
||||
|
||||
**3.1. Remove standalone instrumental review call**
|
||||
|
||||
File: `karaoke_gen/utils/gen_cli.py`
|
||||
|
||||
Remove the `run_instrumental_review()` function call from main flow. The instrumental selection now comes from the combined review.
|
||||
|
||||
Before:
|
||||
```python
|
||||
# After lyrics processing
|
||||
if not args.non_interactive:
|
||||
instrumental_selection = run_instrumental_review(...)
|
||||
```
|
||||
|
||||
After:
|
||||
```python
|
||||
# Instrumental selection comes from controller.results.instrumental_selection
|
||||
instrumental_selection = controller.results.instrumental_selection
|
||||
```
|
||||
|
||||
**3.2. Pass instrumental options to controller**
|
||||
|
||||
The controller needs instrumental options to display in review. These come from the separated audio stems:
|
||||
|
||||
```python
|
||||
controller = LyricsTranscriber(
|
||||
# ... existing params ...
|
||||
)
|
||||
|
||||
# Before calling process(), set up instrumental options
|
||||
# These are typically discovered during audio separation
|
||||
```
|
||||
|
||||
### Phase 4: Delete Standalone InstrumentalReviewServer
|
||||
|
||||
**4.1. Delete files**
|
||||
|
||||
- Delete `karaoke_gen/instrumental_review/server.py`
|
||||
- Delete `karaoke_gen/instrumental_review/__init__.py` (if empty after)
|
||||
- Remove `run_instrumental_review()` from `karaoke_gen/utils/gen_cli.py`
|
||||
|
||||
**4.2. Clean up imports**
|
||||
|
||||
Remove any imports of `InstrumentalReviewServer` throughout the codebase.
|
||||
|
||||
### Phase 5: Update Frontend for Local Mode
|
||||
|
||||
**5.1. Verify local mode detection works**
|
||||
|
||||
File: `frontend/lib/api.ts`
|
||||
|
||||
The frontend already has local mode detection based on hostname and port. Verify it works:
|
||||
|
||||
```typescript
|
||||
const isLocalMode = () => {
|
||||
if (typeof window === 'undefined') return false;
|
||||
const hostname = window.location.hostname;
|
||||
const port = parseInt(window.location.port, 10);
|
||||
return hostname === 'localhost' && port >= 8000 && port <= 8770;
|
||||
};
|
||||
```
|
||||
|
||||
**5.2. Verify correction-data endpoint parsing**
|
||||
|
||||
Ensure the frontend correctly parses instrumental_options and backing_vocals_analysis from the local server's response.
|
||||
|
||||
### Phase 6: Testing
|
||||
|
||||
**6.1. Manual testing checklist**
|
||||
|
||||
- [ ] Run CLI with `SKIP_CORRECTION=true` - review should still appear
|
||||
- [ ] Run CLI with `SKIP_CORRECTION=false` - review should appear after correction
|
||||
- [ ] Combined UI shows both lyrics editor and instrumental selector
|
||||
- [ ] Selecting instrumental and completing review works
|
||||
- [ ] No standalone instrumental review page appears
|
||||
- [ ] Cloud web app still works (no regression)
|
||||
|
||||
**6.2. Update unit tests**
|
||||
|
||||
- Remove tests for `InstrumentalReviewServer`
|
||||
- Add tests for `ReviewServer` with instrumental options
|
||||
- Add tests for `controller._run_human_review()`
|
||||
|
||||
## Files to Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `lyrics_transcriber/review/server.py` | Modify | Add instrumental options/selection support |
|
||||
| `lyrics_transcriber/core/controller.py` | Modify | Extract review into standalone method, call at right time |
|
||||
| `utils/gen_cli.py` | Modify | Remove `run_instrumental_review()`, use combined result |
|
||||
| `instrumental_review/server.py` | Delete | Standalone server no longer needed |
|
||||
| `instrumental_review/__init__.py` | Modify/Delete | Clean up imports |
|
||||
|
||||
## Risks & Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Breaking cloud flow | Cloud doesn't use ReviewServer, uses backend API - no risk |
|
||||
| Missing instrumental options in local mode | Fail clearly if options not provided |
|
||||
| Review server port conflicts | Keep existing port allocation logic |
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Where does backing vocals analysis run for local CLI?**
|
||||
- Currently runs in `render_video_worker.py` for cloud
|
||||
- For local, need to run it after audio separation, before review
|
||||
- May need to call analysis function from controller
|
||||
|
||||
2. **How are instrumental stems exposed to local review?**
|
||||
- Need to serve audio files from ReviewServer
|
||||
- Or use file:// URLs (may have CORS issues)
|
||||
- Existing approach: ReviewServer already serves static files
|
||||
|
||||
## Success Criteria
|
||||
|
||||
1. `SKIP_CORRECTION=true` no longer skips human review
|
||||
2. Single combined review UI appears (no separate instrumental step)
|
||||
3. All platforms (CLI, cloud CLI, web) use same review flow
|
||||
4. No dead code remaining for standalone instrumental review
|
||||
+150
-239
@@ -2,7 +2,6 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
@@ -10,6 +9,7 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
@@ -245,23 +245,12 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Production Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
|
||||
E2E_TEST_TOKEN: ${{ secrets.E2E_TEST_TOKEN }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
@@ -546,14 +535,6 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-backend-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
@@ -608,23 +589,12 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-backend-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-backend-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Set up Java 21 (required by Firestore emulator)
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "21"
|
||||
|
||||
- name: Install Firestore emulator
|
||||
run: sudo apt-get install -y google-cloud-cli-firestore-emulator
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
@@ -646,10 +616,27 @@ jobs:
|
||||
|
||||
backend-lint:
|
||||
name: "Backend - Code Quality"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true')
|
||||
steps:
|
||||
- name: Check disk space
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -660,10 +647,27 @@ jobs:
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-lint-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-lint-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
- name: Run validation (syntax check only)
|
||||
run: |
|
||||
python -m py_compile backend/main.py backend/config.py
|
||||
echo "Basic syntax validation passed"
|
||||
poetry run python -m py_compile backend/main.py backend/config.py
|
||||
echo "✅ Basic syntax validation passed"
|
||||
|
||||
# ============================================
|
||||
# CI GATE - Required status check for PRs
|
||||
@@ -673,16 +677,14 @@ jobs:
|
||||
ci-gate:
|
||||
name: "CI Gate"
|
||||
runs-on: ubuntu-latest
|
||||
# Note: frontend-e2e-full is optional (requires 'e2e' label) so not included here
|
||||
# frontend-e2e-smoke IS required - fast smoke tests catch critical regressions
|
||||
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
|
||||
# frontend-e2e-happy-path is required ONLY when 'e2e-happy-path' label is present
|
||||
# frontend-e2e-full is optional (requires 'e2e' label) so not enforced here
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path]
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
run: |
|
||||
# Check all always-required jobs
|
||||
results=(
|
||||
"${{ needs.frontend-lint.result }}"
|
||||
"${{ needs.frontend-unit-tests.result }}"
|
||||
@@ -700,20 +702,6 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# E2E Happy Path: enforced when 'e2e-happy-path' label is on the PR
|
||||
e2e_result="${{ needs.frontend-e2e-happy-path.result }}"
|
||||
has_label="${{ contains(github.event.pull_request.labels.*.name, 'e2e-happy-path') }}"
|
||||
if [[ "$has_label" == "true" ]]; then
|
||||
if [[ "$e2e_result" != "success" ]]; then
|
||||
echo "❌ E2E Happy Path is required (label present) but result is: $e2e_result"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ E2E Happy Path passed (required by label)"
|
||||
else
|
||||
echo "ℹ️ E2E Happy Path skipped (no label)"
|
||||
fi
|
||||
|
||||
echo "✅ CI passed"
|
||||
|
||||
# ============================================
|
||||
@@ -854,7 +842,7 @@ jobs:
|
||||
|
||||
### Assets
|
||||
- Python package published to PyPI
|
||||
- Frontend deployed to Cloudflare Pages at gen.nomadkaraoke.com
|
||||
- Frontend deployed to GitHub Pages at gen.nomadkaraoke.com
|
||||
|
||||
For detailed changes, see the commit history.
|
||||
draft: false
|
||||
@@ -864,7 +852,7 @@ jobs:
|
||||
dist/*.tar.gz
|
||||
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (Cloudflare Pages)"
|
||||
name: "Deploy - Frontend (GitHub Pages)"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
steps:
|
||||
@@ -889,38 +877,23 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
# ===== Consumer Build (gen.nomadkaraoke.com) =====
|
||||
- name: Build frontend (consumer)
|
||||
- name: Build frontend (Next.js static export)
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy consumer to Cloudflare Pages
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
command: pages deploy frontend/out --project-name=karaoke-gen --branch=main
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
|
||||
# ===== Tenant Portal Build (vocalstar.nomadkaraoke.com, singa.nomadkaraoke.com, etc.) =====
|
||||
# Separate build with NEXT_PUBLIC_TENANT_PORTAL=true which tree-shakes
|
||||
# consumer marketing content and renders TenantLandingPage at root.
|
||||
# The Cloudflare Pages Function (frontend/functions/) injects tenant config at the edge.
|
||||
- name: Build frontend (tenant portal)
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
NEXT_PUBLIC_TENANT_PORTAL: "true"
|
||||
run: npm run build
|
||||
|
||||
- name: Deploy tenant portal to Cloudflare Pages
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
workingDirectory: frontend
|
||||
command: pages deploy out --project-name=karaoke-gen-tenant --branch=main
|
||||
path: "frontend/out"
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
|
||||
# NOTE: buy-site was consolidated into the main frontend (PR #122, Dec 2024)
|
||||
# Landing page and payment flow are now at gen.nomadkaraoke.com (root)
|
||||
@@ -929,7 +902,7 @@ jobs:
|
||||
deploy-backend:
|
||||
name: "Deploy - Backend (Cloud Run)"
|
||||
needs: [package-build]
|
||||
runs-on: [self-hosted, linux, gcp, docker-build]
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -943,22 +916,17 @@ jobs:
|
||||
BASE_IMAGE_NAME: karaoke-backend-base
|
||||
APP_IMAGE_NAME: karaoke-backend
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
- name: Check disk space
|
||||
run: |
|
||||
echo "Checking disk space..."
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "Current disk usage: ${USAGE}%"
|
||||
if [ "$USAGE" -gt 50 ]; then
|
||||
echo "Disk usage above 50%, cleaning unused images..."
|
||||
docker system prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After image cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 70 ]; then
|
||||
echo "Still above 70%, clearing build cache..."
|
||||
echo "Disk usage high, running cleanup..."
|
||||
docker system prune -af || true
|
||||
docker builder prune -af || true
|
||||
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||
echo "After build cache cleanup: ${USAGE}%"
|
||||
echo "After cleanup: ${USAGE}%"
|
||||
fi
|
||||
if [ "$USAGE" -gt 85 ]; then
|
||||
echo "::error::Disk usage ${USAGE}% exceeds 85% even after cleanup. Runner needs maintenance."
|
||||
@@ -999,16 +967,8 @@ jobs:
|
||||
version: "latest"
|
||||
|
||||
# ============================================
|
||||
# Deploy to GCE Encoding Worker (Immutable Deployment Pattern)
|
||||
#
|
||||
# This pattern ensures version consistency:
|
||||
# 1. Upload wheel to FIXED path (no version sorting)
|
||||
# 2. Upload startup.sh (logic can change without image rebuild)
|
||||
# 3. Write version manifest for verification
|
||||
# 4. Restart service (triggers bootstrap.sh -> startup.sh)
|
||||
# 5. STRICTLY verify deployed version (fail CI on mismatch)
|
||||
#
|
||||
# See infrastructure/encoding-worker/README.md for details
|
||||
# Upload wheel to GCS for GCE encoding worker
|
||||
# The GCE worker installs this wheel at job start for hot code updates
|
||||
# ============================================
|
||||
|
||||
- name: Download wheel artifact
|
||||
@@ -1017,155 +977,52 @@ jobs:
|
||||
name: package-dist
|
||||
path: dist/
|
||||
|
||||
- name: Deploy to GCE Encoding Worker
|
||||
- name: Upload wheel to GCS for GCE worker
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
BUCKET="gs://karaoke-gen-storage-${{ env.PROJECT_ID }}"
|
||||
|
||||
echo "🚀 Deploying encoding worker v${VERSION}..."
|
||||
|
||||
# 1. Find the wheel file
|
||||
echo "📦 Uploading wheel to GCS for GCE encoding worker..."
|
||||
WHEEL_FILE=$(ls dist/*.whl | head -1)
|
||||
if [ -z "$WHEEL_FILE" ]; then
|
||||
echo "::error::No wheel file found in dist/"
|
||||
exit 1
|
||||
fi
|
||||
echo "📦 Found wheel: $WHEEL_FILE"
|
||||
echo "Found wheel: $WHEEL_FILE"
|
||||
|
||||
# 2. Upload wheel to FIXED path (atomic via temp file)
|
||||
# This eliminates version sorting - always use karaoke_gen-current.whl
|
||||
echo "📤 Uploading wheel to fixed path..."
|
||||
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/karaoke_gen-current.whl.tmp"
|
||||
gsutil mv "${BUCKET}/wheels/karaoke_gen-current.whl.tmp" \
|
||||
"${BUCKET}/wheels/karaoke_gen-current.whl"
|
||||
# Upload to GCS (GCE worker downloads latest at job start)
|
||||
gsutil cp "$WHEEL_FILE" gs://karaoke-gen-storage-${{ env.PROJECT_ID }}/wheels/
|
||||
|
||||
# Also keep versioned copy for rollback/debugging
|
||||
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/"
|
||||
|
||||
# 3. Upload startup.sh (allows logic changes without image rebuild)
|
||||
echo "📤 Uploading startup.sh..."
|
||||
gsutil cp infrastructure/encoding-worker/startup.sh \
|
||||
"${BUCKET}/encoding-worker/startup.sh"
|
||||
|
||||
# 4. Write version manifest for verification
|
||||
echo "📝 Writing version manifest..."
|
||||
echo "${VERSION}" | gsutil cp - "${BUCKET}/encoding-worker/version.txt"
|
||||
|
||||
echo "✅ GCS deployment complete"
|
||||
|
||||
- name: Drain active encoding jobs before restart
|
||||
run: |
|
||||
# Graceful drain: wait for any active encoding jobs to finish before
|
||||
# restarting the worker. This prevents killing in-flight FFmpeg encodes.
|
||||
#
|
||||
# The /health endpoint returns active_jobs count. We poll until it's 0
|
||||
# or until the drain timeout expires (10 minutes — well within the
|
||||
# longest encoding time of ~5 min for a full 4-format encode).
|
||||
|
||||
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
|
||||
DRAIN_TIMEOUT=600 # 10 minutes
|
||||
POLL_INTERVAL=15
|
||||
ELAPSED=0
|
||||
|
||||
echo "🔍 Checking for active encoding jobs before restart..."
|
||||
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
HEALTH=$(curl -sf -H "X-API-Key: $WORKER_KEY" "$WORKER_URL/health" 2>/dev/null || echo '{"active_jobs": -1}')
|
||||
ACTIVE=$(echo "$HEALTH" | grep -o '"active_jobs":[0-9]*' | cut -d: -f2)
|
||||
|
||||
if [ -z "$ACTIVE" ] || [ "$ACTIVE" = "-1" ]; then
|
||||
echo "⚠️ Could not reach health endpoint (worker may already be down). Proceeding with restart."
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$ACTIVE" = "0" ]; then
|
||||
echo "✅ No active encoding jobs. Safe to restart."
|
||||
break
|
||||
fi
|
||||
|
||||
echo "⏳ $ACTIVE active encoding job(s) running. Waiting ${POLL_INTERVAL}s... (${ELAPSED}s/${DRAIN_TIMEOUT}s)"
|
||||
sleep $POLL_INTERVAL
|
||||
ELAPSED=$((ELAPSED + POLL_INTERVAL))
|
||||
done
|
||||
|
||||
if [ $ELAPSED -ge $DRAIN_TIMEOUT ]; then
|
||||
echo "⚠️ Drain timeout reached (${DRAIN_TIMEOUT}s) with jobs still active. Proceeding with restart."
|
||||
echo " Active jobs will be recoverable via idempotent /encode endpoint (PR #413)."
|
||||
fi
|
||||
echo "✅ Wheel uploaded to GCS"
|
||||
|
||||
- name: Restart GCE Encoding Worker
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
echo "🔄 Restarting encoding worker..."
|
||||
echo "🔄 Restarting encoding worker to pick up new wheel..."
|
||||
|
||||
# Use IAP tunneling - works directly with service account credentials
|
||||
# (avoids SSH key propagation delays that cause silent failures)
|
||||
gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
|
||||
echo "⏳ Waiting for service to start (up to 60s)..."
|
||||
sleep 20
|
||||
echo "⏳ Waiting for service to start..."
|
||||
sleep 15
|
||||
|
||||
- name: Verify Encoding Worker Version
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
# Verify the restart worked by checking the wheel version
|
||||
NEW_VERSION=$(gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="curl -s http://localhost:8080/health | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4")
|
||||
|
||||
echo "🔍 Verifying encoding worker version..."
|
||||
EXPECTED_VERSION=$(cat pyproject.toml | grep 'version = ' | head -1 | cut -d'"' -f2)
|
||||
|
||||
# Retry loop - service may take time to fully start
|
||||
MAX_RETRIES=6
|
||||
RETRY_DELAY=10
|
||||
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Attempt $i/$MAX_RETRIES..."
|
||||
|
||||
NEW_VERSION=$(gcloud compute ssh encoding-worker \
|
||||
--zone=us-central1-c \
|
||||
--project=nomadkaraoke \
|
||||
--tunnel-through-iap \
|
||||
--command="curl -s http://localhost:8080/health 2>/dev/null | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4" 2>/dev/null || echo "")
|
||||
|
||||
if [ "$NEW_VERSION" = "$VERSION" ]; then
|
||||
echo "✅ Encoding worker version verified: v$NEW_VERSION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -n "$NEW_VERSION" ]; then
|
||||
echo "⚠️ Version: $NEW_VERSION (expected: $VERSION)"
|
||||
else
|
||||
echo "⚠️ Health endpoint not responding yet"
|
||||
fi
|
||||
|
||||
if [ $i -lt $MAX_RETRIES ]; then
|
||||
echo " Retrying in ${RETRY_DELAY}s..."
|
||||
sleep $RETRY_DELAY
|
||||
fi
|
||||
done
|
||||
|
||||
# STRICT VERIFICATION: Fail CI on version mismatch
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo "❌ ENCODING WORKER DEPLOYMENT FAILED"
|
||||
echo "=============================================="
|
||||
echo "Expected version: $VERSION"
|
||||
echo "Deployed version: $NEW_VERSION"
|
||||
echo ""
|
||||
echo "Possible causes:"
|
||||
echo " - GCS upload failed (check 'Deploy to GCE' step)"
|
||||
echo " - startup.sh download failed (check VM logs)"
|
||||
echo " - Wheel installation failed (check VM logs)"
|
||||
echo ""
|
||||
echo "To debug, SSH to VM and check logs:"
|
||||
echo " gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke --tunnel-through-iap"
|
||||
echo " sudo journalctl -u encoding-worker -n 100"
|
||||
echo " cat /var/log/encoding-worker-startup.log"
|
||||
echo "=============================================="
|
||||
|
||||
exit 1
|
||||
if [ "$NEW_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Encoding worker restarted successfully (v$NEW_VERSION)"
|
||||
else
|
||||
echo "⚠️ Version mismatch: encoder has v$NEW_VERSION, expected v$EXPECTED_VERSION"
|
||||
echo " This may indicate the restart failed or the wheel wasn't downloaded"
|
||||
# Don't fail the build - the encoder will still work, just with old version
|
||||
fi
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
@@ -1226,7 +1083,6 @@ jobs:
|
||||
|
||||
- name: Build and push base image (if needed)
|
||||
if: steps.check-base.outputs.needs_rebuild == 'true'
|
||||
timeout-minutes: 20
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
@@ -1316,8 +1172,8 @@ jobs:
|
||||
--min-instances 4 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest"
|
||||
|
||||
- name: Verify deployment and version
|
||||
run: |
|
||||
@@ -1373,11 +1229,11 @@ jobs:
|
||||
|
||||
# ============================================
|
||||
# PROPAGATE BASE IMAGE TO ALL RUNNERS
|
||||
# When base image is rebuilt, pull it to all 3 runners
|
||||
# When base image is rebuilt, pull it to all 20 runners
|
||||
# so subsequent app builds don't wait 8 min for the pull
|
||||
#
|
||||
# NOTE: This is best-effort distribution. GitHub Actions doesn't
|
||||
# support targeting specific runners by name, so we spawn 3 jobs
|
||||
# support targeting specific runners by name, so we spawn 20 jobs
|
||||
# and rely on the scheduler to distribute them across idle runners.
|
||||
# In practice, with all runners idle after deploy-backend, distribution
|
||||
# is good. Runners that miss this pull will get the image on their
|
||||
@@ -1394,9 +1250,9 @@ jobs:
|
||||
id-token: write
|
||||
strategy:
|
||||
matrix:
|
||||
# 3 parallel jobs - one per self-hosted runner
|
||||
runner_index: [1, 2, 3]
|
||||
max-parallel: 3
|
||||
# 20 parallel jobs - GitHub distributes across available runners
|
||||
runner_index: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
|
||||
max-parallel: 20
|
||||
fail-fast: false # Don't cancel other runners if one fails
|
||||
env:
|
||||
REGISTRY: us-central1-docker.pkg.dev
|
||||
@@ -1426,7 +1282,62 @@ jobs:
|
||||
docker pull $BASE_IMAGE
|
||||
echo "✅ Base image cached on $RUNNER_NAME"
|
||||
|
||||
# NOTE: Pulumi infrastructure deploys are done locally, not in CI.
|
||||
# CI runners run on the infrastructure Pulumi manages, creating a circular
|
||||
# dependency. Always run `pulumi up` locally before merging infra PRs.
|
||||
# See docs/LESSONS-LEARNED.md for details.
|
||||
deploy-infrastructure:
|
||||
name: "Deploy - Infrastructure (Pulumi)"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Authenticate to Google Cloud (Workload Identity)
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Set up Cloud SDK
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
with:
|
||||
version: "latest"
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.13'
|
||||
|
||||
- name: Install Pulumi
|
||||
run: |
|
||||
curl -fsSL https://get.pulumi.com | sh
|
||||
echo "$HOME/.pulumi/bin" >> $GITHUB_PATH
|
||||
|
||||
- name: Install Python dependencies
|
||||
working-directory: infrastructure
|
||||
run: |
|
||||
pip install pulumi pulumi-gcp pulumi-docker
|
||||
|
||||
- name: Configure Pulumi
|
||||
env:
|
||||
PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}
|
||||
run: |
|
||||
pulumi login
|
||||
|
||||
- name: Deploy Infrastructure
|
||||
working-directory: infrastructure
|
||||
env:
|
||||
PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}
|
||||
run: |
|
||||
echo "🚀 Deploying infrastructure changes..."
|
||||
# Skip preview to avoid needing broad read permissions on all GCP resources
|
||||
# Pulumi state is authoritative since infrastructure is only managed via Pulumi
|
||||
pulumi up --yes --skip-preview --stack nomadkaraoke/karaoke-gen-infrastructure/prod
|
||||
|
||||
- name: Summary
|
||||
if: success()
|
||||
run: |
|
||||
echo "🎉 Infrastructure deployment successful!"
|
||||
echo "Commit: ${{ github.sha }}"
|
||||
echo "Branch: ${{ github.ref_name }}"
|
||||
@@ -67,24 +67,12 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run E2E Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || '' }}
|
||||
E2E_TEST_TOKEN: ${{ inputs.use_test_token && secrets.E2E_TEST_TOKEN || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
.vscode
|
||||
*.csv
|
||||
*.mp3
|
||||
ABBA*
|
||||
|
||||
# Andrew functional adds
|
||||
/audio/
|
||||
|
||||
@@ -19,8 +19,6 @@
|
||||
| **Testing & code quality** | `docs/TESTING.md` |
|
||||
| API reference | `docs/API.md` |
|
||||
| Past learnings | `docs/LESSONS-LEARNED.md` |
|
||||
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
|
||||
| GDrive validator & gaps | `docs/GDRIVE-VALIDATOR.md` |
|
||||
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
|
||||
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
|
||||
|
||||
@@ -62,39 +60,15 @@ This single command:
|
||||
|
||||
**All tests must pass.** Don't dismiss failures as "pre-existing" - investigate and fix them.
|
||||
|
||||
### Testing in Production (for Agents)
|
||||
|
||||
When asked to "test it yourself in prod" or verify a fix in production:
|
||||
|
||||
```bash
|
||||
# Get admin token
|
||||
export KARAOKE_ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)
|
||||
|
||||
# Option 1: Use the debug template directly
|
||||
cd frontend && node e2e/helpers/debug-prod-template.mjs
|
||||
|
||||
# Option 2: Copy template for customization (gitignored)
|
||||
cp frontend/e2e/helpers/debug-prod-template.mjs frontend/test-my-issue.local.mjs
|
||||
# Edit the script, then run it
|
||||
node test-my-issue.local.mjs
|
||||
|
||||
# Option 3: Run existing production E2E tests
|
||||
KARAOKE_ADMIN_TOKEN=$KARAOKE_ADMIN_TOKEN npx playwright test e2e/production/admin-dashboard.spec.ts
|
||||
```
|
||||
|
||||
Files matching `test-*.local.*` and `debug-*.local.*` are gitignored - you can hardcode tokens in them safely.
|
||||
|
||||
See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
|
||||
### Version Bumping
|
||||
- Bump `tool.poetry.version` in `pyproject.toml` for code changes
|
||||
- Skip for docs-only changes
|
||||
|
||||
### Infrastructure
|
||||
- **All GCP changes via Pulumi PRs** - changes in `infrastructure/` deploy automatically on merge to main
|
||||
- **Always run `pulumi up` locally BEFORE merging PRs** - CI deploys run on spot VMs that can be preempted mid-apply, causing partial state. Apply locally first, then merge (CI re-runs as no-op)
|
||||
- Never modify GCP resources directly via console or `gcloud` CLI
|
||||
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
|
||||
- Local `pulumi preview` works but `pulumi up` requires broader permissions than CI
|
||||
- Stop and notify user on auth issues
|
||||
|
||||
## API Authentication (for Agents)
|
||||
@@ -130,16 +104,14 @@ EOF
|
||||
|
||||
### GCE Encoding Worker
|
||||
```bash
|
||||
# Check health (includes wheel_version)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health"
|
||||
|
||||
# Restart service (pick up new wheel after a deploy)
|
||||
# SSH to restart service (clears in-memory job queue)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
```
|
||||
|
||||
For job stuck at `encoding` status, see [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
|
||||
# Check health
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health"
|
||||
```
|
||||
|
||||
### What Doesn't Work
|
||||
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
# Makefile for karaoke-gen project
|
||||
# Run `make help` to see available commands
|
||||
|
||||
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
|
||||
|
||||
# Per-stage timeout in seconds (default: 10 minutes)
|
||||
# Prevents hangs from stale dev servers, broken emulators, etc.
|
||||
# Override with: make test TEST_TIMEOUT=300
|
||||
TEST_TIMEOUT ?= 600
|
||||
.PHONY: help install install-backend install-frontend test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@@ -17,8 +12,6 @@ help:
|
||||
@echo " make test-unit - Run unit tests only (karaoke_gen package)"
|
||||
@echo " make test-e2e - Run emulator tests with auto-start/stop"
|
||||
@echo " make install - Install all dependencies (backend + frontend)"
|
||||
@echo " make build-frontend - Build frontend and copy to Python package"
|
||||
@echo " make dev-install - Build frontend + pip install -e . (for local CLI testing)"
|
||||
@echo " make lint - Run linter checks"
|
||||
@echo " make emulators-start - Start GCP emulators for local development"
|
||||
@echo " make emulators-stop - Stop GCP emulators"
|
||||
@@ -40,34 +33,15 @@ install-frontend:
|
||||
|
||||
install: install-backend install-frontend
|
||||
|
||||
# Build frontend and copy to Python package
|
||||
build-frontend: install-frontend
|
||||
@echo "=== Building frontend ==="
|
||||
cd frontend && npm run build
|
||||
@echo "=== Copying build to Python package ==="
|
||||
rm -rf karaoke_gen/nextjs_frontend/out
|
||||
mkdir -p karaoke_gen/nextjs_frontend/out
|
||||
cp -r frontend/out/* karaoke_gen/nextjs_frontend/out/
|
||||
@echo "✅ Frontend built and copied to karaoke_gen/nextjs_frontend/out/"
|
||||
|
||||
# Build frontend + install package in editable mode for local CLI testing
|
||||
# After running this, `karaoke-gen` CLI will use the freshly built frontend.
|
||||
dev-install: build-frontend
|
||||
@echo "=== Installing package in editable mode ==="
|
||||
pip install -e .
|
||||
@echo ""
|
||||
@echo "✅ Ready! You can now run karaoke-gen with the updated frontend."
|
||||
@echo " Example: karaoke-gen input.flac \"Artist\" \"Title\""
|
||||
|
||||
# Run unit tests for karaoke_gen package
|
||||
test-unit: install-backend
|
||||
@echo "=== Running karaoke_gen unit tests ==="
|
||||
timeout $(TEST_TIMEOUT) poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
|
||||
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
|
||||
|
||||
# Run backend unit tests (excludes emulator tests)
|
||||
test-backend-unit: install-backend
|
||||
@echo "=== Running backend unit tests ==="
|
||||
timeout $(TEST_TIMEOUT) poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
|
||||
poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
|
||||
|
||||
# Run E2E integration tests with emulators
|
||||
test-e2e: install-backend
|
||||
@@ -79,7 +53,7 @@ test-e2e: install-backend
|
||||
export GCS_BUCKET_NAME=test-bucket && \
|
||||
export ADMIN_TOKENS=test-admin-token && \
|
||||
export ENVIRONMENT=test && \
|
||||
timeout $(TEST_TIMEOUT) poetry run pytest backend/tests/emulator/ -v; \
|
||||
poetry run pytest backend/tests/emulator/ -v; \
|
||||
TEST_RESULT=$$?; \
|
||||
./scripts/stop-emulators.sh; \
|
||||
exit $$TEST_RESULT
|
||||
@@ -92,7 +66,7 @@ test-backend: test-unit test-backend-unit test-e2e
|
||||
# Run frontend tests (unit + E2E)
|
||||
test-frontend: install-frontend
|
||||
@echo "=== Running frontend tests ==="
|
||||
cd frontend && timeout $(TEST_TIMEOUT) npm run test:all
|
||||
cd frontend && npm run test:all
|
||||
|
||||
# Run ALL tests (backend + frontend) - use this before committing!
|
||||
test: test-backend test-frontend
|
||||
|
||||
@@ -159,9 +159,6 @@ karaoke-gen --style_params_json="./styles.json" "Artist" "Title"
|
||||
# Generate CDG and TXT packages
|
||||
karaoke-gen --enable_cdg --enable_txt "Artist" "Title"
|
||||
|
||||
# Skip video encoding (CDG/TXT only, faster)
|
||||
karaoke-gen --no-video --enable_cdg "Artist" "Title"
|
||||
|
||||
# YouTube upload
|
||||
karaoke-gen --enable_youtube_upload --youtube_description_file="./desc.txt" "Artist" "Title"
|
||||
|
||||
@@ -406,8 +403,26 @@ gcloud secrets versions add gdrive-service-account --data-file=./gdrive-sa.json
|
||||
|
||||
### Deploy Cloud Run
|
||||
|
||||
Deployments happen automatically via GitHub Actions CI when pushing to `main`.
|
||||
See `.github/workflows/ci.yml` for the full deployment workflow.
|
||||
```bash
|
||||
# Build and deploy
|
||||
gcloud builds submit --config=cloudbuild.yaml
|
||||
|
||||
# Get outputs from Pulumi
|
||||
SA_EMAIL=$(pulumi stack output service_account_email)
|
||||
BUCKET_NAME=$(pulumi stack output bucket_name)
|
||||
|
||||
# Deploy Cloud Run service
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image us-central1-docker.pkg.dev/YOUR-PROJECT/karaoke-repo/karaoke-backend:latest \
|
||||
--platform managed \
|
||||
--region us-central1 \
|
||||
--allow-unauthenticated \
|
||||
--service-account $SA_EMAIL \
|
||||
--memory 2Gi \
|
||||
--cpu 2 \
|
||||
--timeout 600 \
|
||||
--set-env-vars="GOOGLE_CLOUD_PROJECT=YOUR-PROJECT,GCS_BUCKET_NAME=$BUCKET_NAME"
|
||||
```
|
||||
|
||||
### Point CLI to Your Backend
|
||||
|
||||
|
||||
+3
-2
@@ -22,9 +22,10 @@ WORKDIR /app
|
||||
COPY backend /app/backend
|
||||
|
||||
# Copy and reinstall karaoke_gen from local source
|
||||
# This ensures new modules are included without rebuilding base image
|
||||
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
|
||||
# This ensures new modules (like style_loader.py) are included without rebuilding base image
|
||||
# Note: lyrics_transcriber is vendored in libs/lyrics_transcriber/ and bundled via pyproject.toml
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY libs /app/libs
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
RUN pip install --no-cache-dir -e .
|
||||
|
||||
|
||||
+7
-25
@@ -1,15 +1,8 @@
|
||||
# Base image with all Python dependencies pre-installed
|
||||
# This image is rebuilt only when poetry.lock or this Dockerfile changes
|
||||
#
|
||||
# This image is rebuilt only when poetry.lock changes
|
||||
#
|
||||
# Build with: gcloud builds submit --config=cloudbuild-base.yaml
|
||||
# Or manually: docker build -f backend/Dockerfile.base -t karaoke-backend-base .
|
||||
#
|
||||
# Layer caching strategy:
|
||||
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
|
||||
# 2. pyproject.toml + package stubs (changes with dep updates)
|
||||
# 3. pip install (the slow part - cached unless pyproject.toml changes)
|
||||
# 4. Source code copy (changes every rebuild, but AFTER deps are installed)
|
||||
# 5. spaCy model download (cached unless pip install layer changes)
|
||||
|
||||
FROM python:3.11-slim
|
||||
|
||||
@@ -57,27 +50,16 @@ RUN curl -L https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-stati
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy ONLY dependency specification files first (changes less often than source code)
|
||||
# Copy dependency files and source code needed for pip install
|
||||
COPY pyproject.toml README.md LICENSE /app/
|
||||
|
||||
# Create minimal package stubs so pip can resolve the editable install
|
||||
# pip install -e . needs package directories to exist but doesn't validate content
|
||||
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
|
||||
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
|
||||
|
||||
# Install all Python dependencies (the slow part)
|
||||
# BuildKit cache mount preserves downloaded wheels across builds, so partial
|
||||
# dependency updates only download changed packages instead of everything
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install --upgrade pip && \
|
||||
pip install -e .
|
||||
|
||||
# Now copy actual source code (AFTER deps installed, so code changes don't
|
||||
# invalidate the expensive pip install layer in registry cache)
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
|
||||
COPY backend /app/backend
|
||||
|
||||
# Install all Python dependencies (the slow part - cached in base image)
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -e .
|
||||
|
||||
# Download spaCy language model for lyrics transcription
|
||||
# This must be done at build time, not runtime (Cloud Run network restrictions)
|
||||
RUN python -m spacy download en_core_web_sm
|
||||
|
||||
+114
-14
@@ -113,19 +113,6 @@ async def require_auth(
|
||||
detail=f"Authentication failed: {auth_result.message}"
|
||||
)
|
||||
|
||||
# If token has a tenant_id, override the hostname-based tenant detection.
|
||||
# This allows tenant-scoped tokens to enforce tenant context regardless of domain.
|
||||
# We must also load tenant_config so downstream handlers (e.g. job creation)
|
||||
# that rely on tenant_config for setting tenant_id on jobs work correctly.
|
||||
if auth_result.tenant_id:
|
||||
request.state.tenant_id = auth_result.tenant_id
|
||||
if not getattr(request.state, "tenant_config", None):
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
tenant_service = get_tenant_service()
|
||||
tenant_config = tenant_service.get_tenant_config(auth_result.tenant_id)
|
||||
if tenant_config and tenant_config.is_active:
|
||||
request.state.tenant_config = tenant_config
|
||||
|
||||
# Log successful auth with request_id for correlation with request audit
|
||||
logger.info(
|
||||
"auth_success",
|
||||
@@ -135,7 +122,6 @@ async def require_auth(
|
||||
"user_type": auth_result.user_type.value if auth_result.user_type else None,
|
||||
"is_admin": auth_result.is_admin,
|
||||
"remaining_uses": auth_result.remaining_uses,
|
||||
"tenant_id": auth_result.tenant_id,
|
||||
"audit_type": "auth_event",
|
||||
}
|
||||
)
|
||||
@@ -355,3 +341,117 @@ def require_review_auth_factory(job_id_param: str = "job_id"):
|
||||
require_review_auth = require_review_auth_factory()
|
||||
|
||||
|
||||
def require_instrumental_auth_factory(job_id_param: str = "job_id"):
|
||||
"""
|
||||
Factory to create an instrumental review authentication dependency.
|
||||
|
||||
Accepts either:
|
||||
1. Full user authentication (admin/user token) - also validates job ownership
|
||||
2. Job-specific instrumental token (only valid for the specific job)
|
||||
|
||||
Args:
|
||||
job_id_param: Name of the path parameter containing the job ID
|
||||
|
||||
Returns:
|
||||
Dependency function that validates instrumental review access
|
||||
"""
|
||||
async def require_instrumental_auth(
|
||||
request: Request,
|
||||
job_id: str = Path(...),
|
||||
instrumental_token: Optional[str] = Query(None, description="Job-specific instrumental review token"),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
token: Optional[str] = Query(None, alias="token", description="Full access token")
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Validate instrumental review access for a job.
|
||||
|
||||
Returns:
|
||||
(job_id, auth_type) where auth_type is "full" or "instrumental_token"
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if authentication fails
|
||||
HTTPException: 403 if user doesn't own the job (for full auth)
|
||||
"""
|
||||
# Import here to avoid circular dependency
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
# Try full authentication first
|
||||
full_token = None
|
||||
if credentials:
|
||||
full_token = credentials.credentials
|
||||
elif token:
|
||||
full_token = token
|
||||
|
||||
if full_token:
|
||||
auth_result = auth_service.validate_token_full(full_token)
|
||||
if auth_result.is_valid:
|
||||
# For full auth, also verify job ownership
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Check ownership: admin can access all, users only their own jobs
|
||||
if not auth_result.is_admin:
|
||||
if auth_result.user_email and job.user_email:
|
||||
if auth_result.user_email.lower() != job.user_email.lower():
|
||||
logger.warning(
|
||||
f"Instrumental access denied: user {auth_result.user_email} "
|
||||
f"tried to access job {job_id} owned by {job.user_email}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You don't have permission to access this job's instrumental review"
|
||||
)
|
||||
elif job.user_email:
|
||||
# Token auth without email trying to access a job with owner
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You don't have permission to access this job's instrumental review"
|
||||
)
|
||||
|
||||
logger.info(f"Instrumental access granted via full auth ({auth_result.user_type}) for job {job_id}")
|
||||
return job_id, "full"
|
||||
|
||||
# Try instrumental token
|
||||
if instrumental_token:
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Validate instrumental token matches
|
||||
if job.instrumental_token and secrets.compare_digest(job.instrumental_token, instrumental_token):
|
||||
# Check expiry if set
|
||||
if job.instrumental_token_expires_at:
|
||||
now = datetime.now(UTC)
|
||||
# Handle timezone-naive datetimes from Firestore
|
||||
expiry = job.instrumental_token_expires_at
|
||||
if expiry.tzinfo is None:
|
||||
expiry = expiry.replace(tzinfo=UTC)
|
||||
|
||||
if now > expiry:
|
||||
logger.warning(f"Instrumental token expired for job {job_id}")
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Instrumental review token has expired. Please request a new review link."
|
||||
)
|
||||
|
||||
logger.info(f"Instrumental access granted via instrumental_token for job {job_id}")
|
||||
return job_id, "instrumental_token"
|
||||
else:
|
||||
logger.warning(f"Invalid instrumental token for job {job_id}")
|
||||
|
||||
# No valid authentication
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Authentication required. Provide either a full access token or a valid instrumental_token for this job."
|
||||
)
|
||||
|
||||
return require_instrumental_auth
|
||||
|
||||
|
||||
# Default instance for most instrumental review endpoints
|
||||
require_instrumental_auth = require_instrumental_auth_factory()
|
||||
+60
-1743
File diff suppressed because it is too large.
Load diff
+160
-445
@@ -13,12 +13,8 @@ The flow is:
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request, Depends
|
||||
@@ -37,11 +33,6 @@ from backend.services.audio_search_service import (
|
||||
NoResultsError,
|
||||
DownloadError,
|
||||
)
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
from backend.config import get_settings
|
||||
@@ -49,9 +40,6 @@ from backend.version import VERSION
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -140,9 +128,6 @@ class AudioSearchRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
@validator('artist', 'title', 'lyrics_artist', 'lyrics_title', 'display_artist', 'display_title')
|
||||
def normalize_text_fields(cls, v):
|
||||
"""Normalize text fields to standardize Unicode characters."""
|
||||
@@ -201,32 +186,9 @@ class AudioSearchResponse(BaseModel):
|
||||
style_upload_urls: Optional[List[StyleUploadUrl]] = None
|
||||
|
||||
|
||||
class StandaloneSearchRequest(BaseModel):
|
||||
"""Request for standalone audio search (no job created)."""
|
||||
artist: str = Field(..., description="Artist name to search for")
|
||||
title: str = Field(..., description="Song title to search for")
|
||||
|
||||
@validator('artist', 'title')
|
||||
def normalize_text_fields(cls, v):
|
||||
if v is not None and isinstance(v, str):
|
||||
return normalize_text(v)
|
||||
return v
|
||||
|
||||
|
||||
class StandaloneSearchResponse(BaseModel):
|
||||
"""Response from standalone audio search."""
|
||||
search_session_id: str
|
||||
results: List[AudioSearchResultResponse]
|
||||
results_count: int
|
||||
|
||||
|
||||
class AudioSelectRequest(BaseModel):
|
||||
"""Request to select an audio source."""
|
||||
selection_index: int = Field(..., description="Index of the selected audio source from search results")
|
||||
# Optional overrides — sent from the guided flow's Customize step (Step 3)
|
||||
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
|
||||
display_artist: Optional[str] = Field(None, description="Override display artist name")
|
||||
display_title: Optional[str] = Field(None, description="Override display title")
|
||||
|
||||
|
||||
class AudioSelectResponse(BaseModel):
|
||||
@@ -268,38 +230,35 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
|
||||
}
|
||||
|
||||
|
||||
def _extract_gcs_path(filepath: str) -> str:
|
||||
"""
|
||||
Extract the path portion from a GCS path or gs:// URL.
|
||||
|
||||
Args:
|
||||
filepath: Either a gs:// URL or a plain path
|
||||
|
||||
Returns:
|
||||
The path portion (e.g., "uploads/job123/audio/file.flac")
|
||||
"""
|
||||
if filepath.startswith("gs://"):
|
||||
# Format: gs://bucket/path/to/file
|
||||
parts = filepath.replace("gs://", "").split("/", 1)
|
||||
if len(parts) == 2:
|
||||
return parts[1]
|
||||
return filepath
|
||||
async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
"""Trigger both audio and lyrics workers in parallel."""
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
|
||||
def _validate_and_prepare_selection(
|
||||
async def _download_and_start_processing(
|
||||
job_id: str,
|
||||
selection_index: int,
|
||||
audio_search_service,
|
||||
background_tasks: BackgroundTasks,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate selection and transition job to DOWNLOADING_AUDIO state.
|
||||
|
||||
Returns selection info dict with the selected result details.
|
||||
Raises HTTPException on validation errors.
|
||||
Download selected audio and start job processing.
|
||||
|
||||
This is called either:
|
||||
- Immediately after search if auto_download=True
|
||||
- When user calls the select endpoint
|
||||
|
||||
For remote flacfetch downloads (torrent sources), the file is downloaded
|
||||
on the flacfetch VM and uploaded directly to GCS. For local downloads
|
||||
(YouTube), the file is downloaded locally and then uploaded to GCS.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
|
||||
# Get search results from state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
@@ -313,6 +272,9 @@ def _validate_and_prepare_selection(
|
||||
|
||||
selected = search_results[selection_index]
|
||||
|
||||
# Get remote_search_id from state_data (stored during initial search)
|
||||
remote_search_id = job.state_data.get('remote_search_id')
|
||||
|
||||
# Transition to downloading state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
@@ -324,243 +286,161 @@ def _validate_and_prepare_selection(
|
||||
'selected_audio_provider': selected['provider'],
|
||||
}
|
||||
)
|
||||
|
||||
# Save download params to job BEFORE attempting download
|
||||
# This enables retry even if download fails
|
||||
source_name = selected.get('provider')
|
||||
source_id = selected.get('source_id')
|
||||
target_file = selected.get('target_file')
|
||||
download_url = selected.get('url')
|
||||
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_source_type': 'audio_search',
|
||||
'source_name': source_name,
|
||||
'source_id': source_id,
|
||||
'target_file': target_file,
|
||||
'download_url': download_url,
|
||||
})
|
||||
logger.info(
|
||||
f"Job {job_id}: Saved download params before attempt: "
|
||||
f"source_name={source_name}, source_id={source_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
'selected_index': selection_index,
|
||||
'selected_title': selected['title'],
|
||||
'selected_artist': selected['artist'],
|
||||
'selected_provider': selected['provider'],
|
||||
}
|
||||
|
||||
|
||||
async def _download_audio_and_trigger_workers(
|
||||
job_id: str,
|
||||
selection_index: int,
|
||||
audio_search_service,
|
||||
) -> None:
|
||||
"""
|
||||
Download audio and trigger processing workers.
|
||||
|
||||
This runs as a background task after the select endpoint returns.
|
||||
Also called synchronously from the auto_download path during search.
|
||||
|
||||
For remote flacfetch downloads (torrent sources), the file is downloaded
|
||||
on the flacfetch VM and uploaded directly to GCS. For local downloads
|
||||
(YouTube), the file is downloaded locally and then uploaded to GCS.
|
||||
"""
|
||||
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"Job {job_id} not found during background download")
|
||||
return
|
||||
# Determine if this is a remote torrent download
|
||||
is_torrent_source = selected.get('provider') in ['RED', 'OPS']
|
||||
is_remote_enabled = audio_search_service.is_remote_enabled()
|
||||
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
selected = search_results[selection_index]
|
||||
remote_search_id = job.state_data.get('remote_search_id')
|
||||
|
||||
# Get source info from selected result
|
||||
source_name = selected.get('provider')
|
||||
# Check if we can use download_by_id (preferred - avoids re-searching)
|
||||
source_id = selected.get('source_id')
|
||||
source_name = selected.get('provider')
|
||||
target_file = selected.get('target_file')
|
||||
download_url = selected.get('url')
|
||||
|
||||
# Route to appropriate download handler based on source type
|
||||
if source_name == 'YouTube':
|
||||
# Use YouTubeDownloadService for all YouTube downloads
|
||||
# This ensures consistent handling whether remote is configured or not
|
||||
youtube_service = get_youtube_download_service()
|
||||
|
||||
if not source_id and download_url:
|
||||
# Extract video ID from URL if not in source_id
|
||||
source_id = youtube_service._extract_video_id(download_url)
|
||||
|
||||
if not source_id:
|
||||
raise DownloadError(f"No video ID available for YouTube download")
|
||||
|
||||
logger.info(f"YouTube download via YouTubeDownloadService: video_id={source_id}")
|
||||
|
||||
try:
|
||||
audio_gcs_path = await youtube_service.download_by_id(
|
||||
video_id=source_id,
|
||||
job_id=job_id,
|
||||
artist=selected.get('artist'),
|
||||
title=selected.get('title'),
|
||||
)
|
||||
filename = os.path.basename(audio_gcs_path)
|
||||
except YouTubeDownloadError as e:
|
||||
raise DownloadError(f"YouTube download failed: {e}")
|
||||
|
||||
elif source_name in ['RED', 'OPS']:
|
||||
# Torrent sources - must use remote flacfetch (async, no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from {source_name} without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
)
|
||||
|
||||
# For remote torrent downloads, have flacfetch VM upload directly to GCS
|
||||
if is_torrent_source and is_remote_enabled:
|
||||
# Generate GCS path for remote upload
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
if source_id:
|
||||
logger.info(f"Torrent download via download_by_id: {source_name} ID={source_id}")
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
# Use download_by_id if we have source_id (preferred - no re-search needed)
|
||||
if source_id and source_name:
|
||||
logger.info(f"Using download_by_id for {source_name} ID={source_id} with GCS upload to: {gcs_destination}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="", # Not used for remote
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
if not remote_search_id:
|
||||
raise DownloadError(
|
||||
f"No source_id or remote_search_id available for {source_name} download"
|
||||
)
|
||||
logger.info(f"Torrent download via search-based download")
|
||||
download_id = await flacfetch_client.download(
|
||||
search_id=remote_search_id,
|
||||
# Fallback to search-based download (requires re-search)
|
||||
logger.info(f"No source_id available, falling back to search-based download to: {gcs_destination}")
|
||||
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir="", # Not used for remote
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"Torrent download complete: {audio_gcs_path}")
|
||||
|
||||
elif source_name == 'Spotify':
|
||||
# Spotify downloads - use async FlacfetchClient directly (no event loop blocking)
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from Spotify without remote flacfetch service. "
|
||||
"Configure FLACFETCH_API_URL."
|
||||
)
|
||||
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
logger.info(f"Spotify download: source_id={source_id}")
|
||||
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
audio_gcs_path = _extract_gcs_path(filepath)
|
||||
filename = os.path.basename(filepath)
|
||||
logger.info(f"Spotify download complete: {audio_gcs_path}")
|
||||
|
||||
else:
|
||||
# Unknown source - try generic download (run sync code in thread to avoid blocking)
|
||||
logger.warning(f"Unknown source type: {source_name}, attempting generic download")
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
audio_search_service.download,
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
# For remote downloads, filepath is already the GCS path
|
||||
if result.filepath.startswith("gs://"):
|
||||
# Extract the path portion after the bucket name
|
||||
# Format: gs://bucket/uploads/job_id/audio/filename.flac
|
||||
parts = result.filepath.replace("gs://", "").split("/", 1)
|
||||
if len(parts) == 2:
|
||||
audio_gcs_path = parts[1]
|
||||
else:
|
||||
audio_gcs_path = result.filepath
|
||||
filename = os.path.basename(result.filepath)
|
||||
else:
|
||||
# Fallback: treat as local path (shouldn't happen for remote)
|
||||
filename = os.path.basename(result.filepath)
|
||||
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
|
||||
content_type, _ = mimetypes.guess_type(result.filepath)
|
||||
logger.warning(f"Remote download returned local path: {result.filepath}, uploading manually")
|
||||
with open(result.filepath, 'rb') as f:
|
||||
storage_service.upload_fileobj(
|
||||
f,
|
||||
audio_gcs_path,
|
||||
content_type=content_type or 'application/octet-stream'
|
||||
)
|
||||
storage_service.upload_fileobj(f, audio_gcs_path, content_type='audio/flac')
|
||||
|
||||
logger.info(f"Generic download uploaded to GCS: {audio_gcs_path}")
|
||||
finally:
|
||||
# Clean up temp files
|
||||
try:
|
||||
if os.path.exists(temp_dir):
|
||||
import shutil
|
||||
shutil.rmtree(temp_dir)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to clean up temp files: {e}")
|
||||
logger.info(f"Remote download complete, GCS path: {audio_gcs_path}")
|
||||
else:
|
||||
# Local download (YouTube or fallback)
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
|
||||
# Update job with GCS path
|
||||
# Use download_by_id if we have source_id and remote is enabled
|
||||
if source_id and source_name and is_remote_enabled:
|
||||
logger.info(f"Using download_by_id for local download: {source_name} ID={source_id}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir=temp_dir,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
)
|
||||
elif source_name == 'YouTube' and download_url:
|
||||
# For YouTube without remote, download directly using URL from state_data
|
||||
# This avoids relying on in-memory cache which doesn't persist across instances
|
||||
logger.info(f"Downloading YouTube audio directly from URL: {download_url}")
|
||||
from backend.workers.audio_worker import download_from_url
|
||||
|
||||
local_path = await download_from_url(
|
||||
download_url,
|
||||
temp_dir,
|
||||
selected.get('artist'),
|
||||
selected.get('title')
|
||||
)
|
||||
|
||||
if not local_path or not os.path.exists(local_path):
|
||||
raise DownloadError(f"Failed to download from YouTube: {download_url}")
|
||||
|
||||
# Create a result-like object
|
||||
class DownloadResult:
|
||||
def __init__(self, filepath):
|
||||
self.filepath = filepath
|
||||
|
||||
result = DownloadResult(local_path)
|
||||
else:
|
||||
# Fallback to search-based download (may fail if cache is empty)
|
||||
logger.warning(f"Falling back to cache-based download for {source_name} - this may fail on multi-instance deployments")
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id, # Pass for potential fallback scenarios
|
||||
)
|
||||
|
||||
# Upload to GCS
|
||||
filename = os.path.basename(result.filepath)
|
||||
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
|
||||
with open(result.filepath, 'rb') as f:
|
||||
storage_service.upload_fileobj(
|
||||
f,
|
||||
audio_gcs_path,
|
||||
content_type='audio/flac' # flacfetch typically returns FLAC
|
||||
)
|
||||
|
||||
logger.info(f"Uploaded audio to GCS: {audio_gcs_path}")
|
||||
|
||||
# Clean up temp file
|
||||
try:
|
||||
os.remove(result.filepath)
|
||||
os.rmdir(temp_dir)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to clean up temp files: {e}")
|
||||
|
||||
# Update job with GCS path and transition to DOWNLOADING
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': filename,
|
||||
})
|
||||
|
||||
# Transition from DOWNLOADING_AUDIO to DOWNLOADING and trigger workers
|
||||
# Note: Can't use start_job_processing() here because that expects PENDING status,
|
||||
# but we're in DOWNLOADING_AUDIO state from the audio search flow.
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
# Trigger workers directly
|
||||
worker_service = get_worker_service()
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
except (DownloadError, FlacfetchServiceError) as e:
|
||||
logger.error(f"Download failed for job {job_id}: {e}")
|
||||
|
||||
# Trigger workers
|
||||
background_tasks.add_task(_trigger_workers_parallel, job_id)
|
||||
|
||||
return {
|
||||
'selected_index': selection_index,
|
||||
'selected_title': selected['title'],
|
||||
'selected_artist': selected['artist'],
|
||||
'selected_provider': selected['provider'],
|
||||
}
|
||||
|
||||
except DownloadError as e:
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Download failed for job {job_id}: {e}", exc_info=True)
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Download failed: {e}")
|
||||
|
||||
|
||||
@router.post("/audio-search/search", response_model=AudioSearchResponse)
|
||||
@@ -686,18 +566,12 @@ async def search_audio(
|
||||
auto_download=body.auto_download,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "audio_search")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
logger.info(f"Created job {job_id} for audio search: {body.artist} - {body.title}")
|
||||
|
||||
# Update job with audio search fields
|
||||
@@ -800,7 +674,7 @@ async def search_audio(
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
search_results = audio_search_service.search(body.artist, body.title)
|
||||
except NoResultsError as e:
|
||||
job_manager.fail_job(job_id, f"No audio sources found for: {body.artist} - {body.title}")
|
||||
raise HTTPException(
|
||||
@@ -831,21 +705,16 @@ async def search_audio(
|
||||
# If auto_download, select best and start processing
|
||||
if body.auto_download:
|
||||
best_index = audio_search_service.select_best(search_results)
|
||||
|
||||
|
||||
logger.info(f"Auto-download enabled, selecting result {best_index}")
|
||||
|
||||
selection_info = _validate_and_prepare_selection(
|
||||
|
||||
selection_info = await _download_and_start_processing(
|
||||
job_id=job_id,
|
||||
selection_index=best_index,
|
||||
audio_search_service=audio_search_service,
|
||||
background_tasks=background_tasks,
|
||||
)
|
||||
|
||||
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
|
||||
|
||||
|
||||
return AudioSearchResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
@@ -933,145 +802,10 @@ async def search_audio(
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
if isinstance(e, InsufficientCreditsError):
|
||||
raise
|
||||
logger.error(f"Error in audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/audio-search/search-standalone", response_model=StandaloneSearchResponse)
|
||||
async def search_audio_standalone(
|
||||
request: Request,
|
||||
body: StandaloneSearchRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Search for audio by artist and title WITHOUT creating a job.
|
||||
|
||||
Returns a search session ID and results. Call POST /api/jobs/create-from-search
|
||||
with the session ID and selected result index to create the actual job.
|
||||
|
||||
Credits are checked here (early feedback) but NOT deducted — deduction
|
||||
happens when the job is created via create-from-search.
|
||||
"""
|
||||
# Check tenant feature flag
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.audio_search:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Audio search is not available for this portal"
|
||||
)
|
||||
|
||||
try:
|
||||
user_email = auth_result.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Credit check — give early feedback but do NOT deduct here
|
||||
if not auth_result.is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
if not user_service.has_credits(user_email):
|
||||
credits_available = user_service.check_credits(user_email)
|
||||
raise InsufficientCreditsError(
|
||||
message="You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
credits_available=credits_available,
|
||||
credits_required=1,
|
||||
)
|
||||
|
||||
# Perform the search (runs in thread to avoid blocking the event loop)
|
||||
audio_search_service = get_audio_search_service()
|
||||
try:
|
||||
search_results = await audio_search_service.search_async(body.artist, body.title)
|
||||
except NoResultsError:
|
||||
# No results is a normal outcome — return empty list, not an error
|
||||
search_results = []
|
||||
except AudioSearchError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
|
||||
|
||||
# Build result response objects
|
||||
result_responses: List[AudioSearchResultResponse] = []
|
||||
results_dicts: List[Dict[str, Any]] = []
|
||||
for r in search_results:
|
||||
raw_dict: Dict[str, Any] = {}
|
||||
if r.raw_result:
|
||||
if isinstance(r.raw_result, dict):
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
result_responses.append(
|
||||
AudioSearchResultResponse(
|
||||
index=r.index,
|
||||
title=r.title,
|
||||
artist=r.artist,
|
||||
provider=r.provider,
|
||||
url=r.url,
|
||||
duration=r.duration,
|
||||
quality=r.quality,
|
||||
source_id=r.source_id,
|
||||
seeders=raw_dict.get('seeders') or r.seeders,
|
||||
target_file=raw_dict.get('target_file') or r.target_file,
|
||||
year=raw_dict.get('year'),
|
||||
label=raw_dict.get('label'),
|
||||
edition_info=raw_dict.get('edition_info'),
|
||||
release_type=raw_dict.get('release_type'),
|
||||
channel=raw_dict.get('channel'),
|
||||
view_count=raw_dict.get('view_count'),
|
||||
size_bytes=raw_dict.get('size_bytes'),
|
||||
target_file_size=raw_dict.get('target_file_size'),
|
||||
track_pattern=raw_dict.get('track_pattern'),
|
||||
match_score=raw_dict.get('match_score'),
|
||||
formatted_size=raw_dict.get('formatted_size'),
|
||||
formatted_duration=raw_dict.get('formatted_duration'),
|
||||
formatted_views=raw_dict.get('formatted_views'),
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
)
|
||||
results_dicts.append(r.to_dict())
|
||||
|
||||
# Store session in Firestore (TTL: 30 minutes)
|
||||
session_id = str(uuid.uuid4())
|
||||
now = datetime.utcnow()
|
||||
session_data = {
|
||||
'session_id': session_id,
|
||||
'user_email': user_email,
|
||||
'tenant_id': tenant_config.id if tenant_config else None,
|
||||
'artist': body.artist,
|
||||
'title': body.title,
|
||||
'results': results_dicts,
|
||||
'remote_search_id': audio_search_service.last_remote_search_id,
|
||||
'created_at': now.isoformat(),
|
||||
'ttl_expiry': now + timedelta(minutes=30),
|
||||
}
|
||||
firestore_service = FirestoreService()
|
||||
firestore_service.create_search_session(session_data)
|
||||
|
||||
logger.info(
|
||||
f"Standalone search complete for {body.artist} - {body.title}: "
|
||||
f"{len(search_results)} results, session={session_id}"
|
||||
)
|
||||
|
||||
return StandaloneSearchResponse(
|
||||
search_session_id=session_id,
|
||||
results=result_responses,
|
||||
results_count=len(result_responses),
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error in standalone audio search: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/audio-search/{job_id}/results")
|
||||
async def get_audio_search_results(
|
||||
job_id: str,
|
||||
@@ -1114,64 +848,45 @@ async def select_audio_source(
|
||||
):
|
||||
"""
|
||||
Select an audio source and start job processing.
|
||||
|
||||
This endpoint returns immediately after validating the selection and
|
||||
transitioning the job to DOWNLOADING_AUDIO state. The actual download
|
||||
runs as a background task so the UI can close the selection dialog
|
||||
without waiting for the download to complete.
|
||||
|
||||
This endpoint:
|
||||
1. Validates the job is awaiting selection
|
||||
2. Downloads the selected audio
|
||||
3. Uploads to GCS
|
||||
4. Triggers audio and lyrics workers
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
|
||||
# Verify job is awaiting selection
|
||||
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job is not awaiting audio selection (status: {job.status})"
|
||||
)
|
||||
|
||||
|
||||
# Get search service instance
|
||||
# Note: With download_by_id, we no longer need to re-search to populate the cache.
|
||||
# The source_id stored in job.state_data['audio_search_results'] is sufficient.
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
# Apply optional overrides from guided flow Step 3 (Customize)
|
||||
# These fields are set AFTER the job is created (Step 2), so they must be
|
||||
# patched here before the pipeline starts.
|
||||
overrides = {}
|
||||
if body.is_private is not None:
|
||||
overrides["is_private"] = body.is_private
|
||||
if body.display_artist is not None:
|
||||
overrides["display_artist"] = body.display_artist
|
||||
if body.display_title is not None:
|
||||
overrides["display_title"] = body.display_title
|
||||
if overrides:
|
||||
job_manager.update_job(job_id, overrides)
|
||||
logger.info(f"[job:{job_id}] Applied selection overrides: {list(overrides.keys())}")
|
||||
|
||||
# Validate search results exist in job state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results cached for this job")
|
||||
|
||||
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
|
||||
selection_info = _validate_and_prepare_selection(
|
||||
|
||||
selection_info = await _download_and_start_processing(
|
||||
job_id=job_id,
|
||||
selection_index=body.selection_index,
|
||||
audio_search_service=audio_search_service,
|
||||
background_tasks=background_tasks,
|
||||
)
|
||||
|
||||
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
|
||||
|
||||
|
||||
return AudioSelectResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
message="Audio selected, download starting",
|
||||
message="Audio selected and download started",
|
||||
selected_index=selection_info['selected_index'],
|
||||
selected_title=selection_info['selected_title'],
|
||||
selected_artist=selection_info['selected_artist'],
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
"""
|
||||
Catalog API routes for song/artist lookup and community version detection.
|
||||
|
||||
Provides autocomplete data from karaoke-decide's MusicBrainz + Spotify catalog,
|
||||
and checks karaokenerds.com for existing community karaoke versions.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/catalog", tags=["catalog"])
|
||||
|
||||
# Simple per-user rate limiting: 20 requests/minute
|
||||
# { user_email: [timestamp, timestamp, ...] }
|
||||
_rate_limit_windows: dict[str, list[float]] = {}
|
||||
RATE_LIMIT_MAX_REQUESTS = 20
|
||||
RATE_LIMIT_WINDOW_SECONDS = 60
|
||||
|
||||
|
||||
def _check_rate_limit(user_email: str) -> None:
|
||||
"""Check per-user rate limit. Raises 429 if exceeded."""
|
||||
now = time.monotonic()
|
||||
window_start = now - RATE_LIMIT_WINDOW_SECONDS
|
||||
|
||||
# Get or create window for this user
|
||||
if user_email not in _rate_limit_windows:
|
||||
_rate_limit_windows[user_email] = []
|
||||
|
||||
# Remove expired entries
|
||||
timestamps = _rate_limit_windows[user_email]
|
||||
_rate_limit_windows[user_email] = [t for t in timestamps if t > window_start]
|
||||
|
||||
if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.",
|
||||
)
|
||||
|
||||
_rate_limit_windows[user_email].append(now)
|
||||
|
||||
|
||||
# --- Response Models ---
|
||||
|
||||
|
||||
class ArtistResult(BaseModel):
|
||||
"""Artist search result from MusicBrainz/Spotify catalog."""
|
||||
name: str
|
||||
mbid: Optional[str] = None
|
||||
disambiguation: Optional[str] = None
|
||||
artist_type: Optional[str] = None
|
||||
spotify_id: Optional[str] = None
|
||||
popularity: Optional[int] = None
|
||||
genres: Optional[list[str]] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
class TrackResult(BaseModel):
|
||||
"""Track search result from Spotify catalog."""
|
||||
track_name: str
|
||||
artist_name: str
|
||||
track_id: Optional[str] = None
|
||||
artist_id: Optional[str] = None
|
||||
popularity: Optional[int] = None
|
||||
duration_ms: Optional[int] = None
|
||||
explicit: Optional[bool] = None
|
||||
|
||||
|
||||
class CommunityTrack(BaseModel):
|
||||
"""A community-approved karaoke track from karaokenerds."""
|
||||
brand_name: str
|
||||
brand_code: str
|
||||
youtube_url: str
|
||||
is_community: bool = True
|
||||
|
||||
|
||||
class CommunityCheckSong(BaseModel):
|
||||
"""A song with community karaoke tracks."""
|
||||
title: str
|
||||
artist: str
|
||||
community_tracks: list[CommunityTrack]
|
||||
|
||||
|
||||
class CommunityCheckRequest(BaseModel):
|
||||
"""Request body for community version check."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class CommunityCheckResponse(BaseModel):
|
||||
"""Response for community version check."""
|
||||
has_community: bool
|
||||
songs: list[CommunityCheckSong]
|
||||
best_youtube_url: Optional[str] = None
|
||||
|
||||
|
||||
# --- Routes ---
|
||||
|
||||
|
||||
@router.get("/artists", response_model=list[ArtistResult])
|
||||
async def search_artists(
|
||||
q: str = Query(..., min_length=2, description="Artist name search query"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Search for artists by name. Returns canonical MusicBrainz/Spotify artist data
|
||||
for autocomplete in job creation forms.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
|
||||
from backend.services.catalog_proxy_service import search_artists
|
||||
results = await search_artists(q, limit)
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/tracks", response_model=list[TrackResult])
|
||||
async def search_tracks(
|
||||
q: str = Query(..., min_length=2, description="Track name search query"),
|
||||
artist: Optional[str] = Query(None, description="Filter by artist name"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Maximum results"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Search for tracks by name, optionally filtered by artist.
|
||||
Returns canonical Spotify track data for autocomplete in job creation forms.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
|
||||
from backend.services.catalog_proxy_service import search_tracks
|
||||
results = await search_tracks(q, artist, limit)
|
||||
return results
|
||||
|
||||
|
||||
@router.post("/community-check", response_model=CommunityCheckResponse)
|
||||
async def check_community_versions(
|
||||
body: CommunityCheckRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Check if a song already has community-approved karaoke versions on YouTube
|
||||
via karaokenerds.com. Non-blocking — just informs the user.
|
||||
"""
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown")
|
||||
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
return result
|
||||
@@ -39,70 +39,11 @@ from backend.services.metrics import metrics
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _is_youtube_url(url: str) -> bool:
|
||||
"""Check if a URL is a YouTube URL."""
|
||||
return any(domain in url.lower() for domain in [
|
||||
'youtube.com', 'youtu.be', 'youtube-nocookie.com'
|
||||
])
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
effective_theme_id: str | None,
|
||||
is_private: bool,
|
||||
enable_youtube_upload: bool,
|
||||
) -> tuple:
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
For tenant jobs:
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
"""
|
||||
if not tenant_config:
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
|
||||
# Apply locked_theme (overrides any user selection)
|
||||
if defaults.locked_theme:
|
||||
effective_theme_id = defaults.locked_theme
|
||||
|
||||
# Disable YouTube upload for tenants
|
||||
enable_youtube_upload = False
|
||||
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Pydantic models for signed URL upload flow
|
||||
# ============================================================================
|
||||
@@ -159,9 +100,6 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
"""Response from creating a job from URL."""
|
||||
@@ -223,9 +161,6 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
|
||||
class SignedUploadUrl(BaseModel):
|
||||
"""Signed URL for uploading a file."""
|
||||
@@ -248,17 +183,6 @@ class UploadsCompleteRequest(BaseModel):
|
||||
"""Request to mark uploads as complete and start processing."""
|
||||
uploaded_files: List[str] = Field(..., description="List of file_types that were successfully uploaded")
|
||||
|
||||
|
||||
class StyleUploadUrlsRequest(BaseModel):
|
||||
"""Request to get signed upload URLs for style assets on an existing job."""
|
||||
files: List[FileUploadRequest] = Field(..., description="List of style files to upload")
|
||||
|
||||
|
||||
class StyleUploadsCompleteRequest(BaseModel):
|
||||
"""Request to finalize style asset uploads on an existing job."""
|
||||
uploaded_files: List[str] = Field(..., description="List of style file_types that were successfully uploaded (e.g. 'style_karaoke_background')")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color (hex #RRGGBB)")
|
||||
|
||||
# Initialize services
|
||||
job_manager = JobManager()
|
||||
storage_service = StorageService()
|
||||
@@ -321,6 +245,19 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
|
||||
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
|
||||
|
||||
|
||||
async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
"""
|
||||
Trigger both audio and lyrics workers in parallel.
|
||||
|
||||
FastAPI's BackgroundTasks runs async tasks sequentially, so we use
|
||||
asyncio.gather to ensure both workers start at the same time.
|
||||
"""
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
|
||||
async def _trigger_audio_worker_only(job_id: str) -> None:
|
||||
"""
|
||||
Trigger only the audio worker.
|
||||
@@ -426,8 +363,6 @@ async def upload_and_create_job(
|
||||
other_stems_models: Optional[str] = Form(None, description="Comma-separated list of models for other stems (bass, drums, guitar, etc.)"),
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
|
||||
):
|
||||
"""
|
||||
Upload an audio file and create a karaoke generation job with full style configuration.
|
||||
@@ -528,11 +463,10 @@ async def upload_and_create_job(
|
||||
|
||||
# Validate credentials for requested distribution services (including defaults)
|
||||
# This prevents accepting jobs that will fail later due to missing credentials
|
||||
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not is_private:
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -542,7 +476,7 @@ async def upload_and_create_job(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not is_private:
|
||||
if dist.gdrive_folder_id:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -557,7 +491,7 @@ async def upload_and_create_job(
|
||||
"auth_url": "/api/auth/status"
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# Extract request metadata for tracking and filtering
|
||||
request_metadata = extract_request_metadata(request, created_from="upload")
|
||||
|
||||
@@ -581,14 +515,6 @@ async def upload_and_create_job(
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Apply tenant-specific overrides (brand, paths, privacy, theme)
|
||||
dist, effective_theme_id, is_private, effective_enable_youtube_upload = _apply_tenant_overrides(
|
||||
dist, tenant_config, effective_theme_id, is_private, effective_enable_youtube_upload,
|
||||
)
|
||||
if tenant_config:
|
||||
logger.info(f"Applied tenant overrides for '{tenant_config.id}': "
|
||||
f"brand={dist.brand_prefix}, private={is_private}, theme={effective_theme_id}")
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(
|
||||
effective_theme_id, enable_cdg, enable_txt
|
||||
@@ -650,19 +576,12 @@ async def upload_and_create_job(
|
||||
request_metadata=request_metadata,
|
||||
# Non-interactive mode
|
||||
non_interactive=non_interactive,
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "upload")
|
||||
add_span_attribute("job.is_private", is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
@@ -825,17 +744,18 @@ async def upload_and_create_job(
|
||||
if style_assets:
|
||||
logger.info(f"Style assets: {list(style_assets.keys())}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions to DOWNLOADING (raises InvalidStateTransitionError if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
5, # progress
|
||||
"Files uploaded, preparing to process"
|
||||
# Transition job to DOWNLOADING state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Files uploaded, preparing to process"
|
||||
)
|
||||
|
||||
# Trigger workers in parallel using asyncio.gather
|
||||
# (FastAPI's BackgroundTasks runs async tasks sequentially)
|
||||
background_tasks.add_task(_trigger_workers_parallel, job_id)
|
||||
|
||||
# Build distribution services info for response
|
||||
distribution_services: Dict[str, Any] = {}
|
||||
|
||||
@@ -883,8 +803,6 @@ async def upload_and_create_job(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error uploading files: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -909,35 +827,6 @@ VALID_FILE_TYPES = {
|
||||
'existing_instrumental': ALLOWED_AUDIO_EXTENSIONS, # Batch 3: user-provided instrumental
|
||||
}
|
||||
|
||||
# Style-only file types (subset allowed for post-creation style uploads)
|
||||
STYLE_FILE_TYPES = {
|
||||
'style_intro_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_karaoke_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
'style_end_background': ALLOWED_IMAGE_EXTENSIONS,
|
||||
}
|
||||
|
||||
# Statuses at or past which style uploads are no longer accepted
|
||||
# (style assets must be uploaded before screen generation begins)
|
||||
STYLE_UPLOAD_CUTOFF_STATUSES = {
|
||||
JobStatus.GENERATING_SCREENS,
|
||||
JobStatus.APPLYING_PADDING,
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.IN_REVIEW,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.GENERATING_VIDEO,
|
||||
JobStatus.ENCODING,
|
||||
JobStatus.PACKAGING,
|
||||
JobStatus.UPLOADING,
|
||||
JobStatus.NOTIFYING,
|
||||
JobStatus.COMPLETE,
|
||||
JobStatus.PREP_COMPLETE,
|
||||
JobStatus.FAILED,
|
||||
JobStatus.CANCELLED,
|
||||
}
|
||||
|
||||
# Valid file types for finalise-only mode (Batch 6)
|
||||
ALLOWED_VIDEO_EXTENSIONS = {'.mkv', '.mov', '.mp4'}
|
||||
FINALISE_ONLY_FILE_TYPES = {
|
||||
@@ -990,8 +879,6 @@ class CreateFinaliseOnlyJobRequest(BaseModel):
|
||||
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
|
||||
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
|
||||
|
||||
|
||||
@@ -1137,29 +1024,11 @@ async def create_job_with_upload_urls(
|
||||
settings = get_settings()
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Apply default theme if none specified
|
||||
effective_theme_id = body.theme_id
|
||||
if effective_theme_id is None:
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Apply tenant-specific overrides (brand, paths, privacy, theme)
|
||||
effective_is_private = body.is_private
|
||||
dist, effective_theme_id, effective_is_private, effective_enable_youtube_upload = _apply_tenant_overrides(
|
||||
dist, tenant_config, effective_theme_id, effective_is_private, effective_enable_youtube_upload,
|
||||
)
|
||||
if tenant_config:
|
||||
logger.info(f"Applied tenant overrides for '{tenant_config.id}': "
|
||||
f"brand={dist.brand_prefix}, private={effective_is_private}, theme={effective_theme_id}")
|
||||
|
||||
# Validate credentials for requested distribution services
|
||||
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not effective_is_private:
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1169,7 +1038,7 @@ async def create_job_with_upload_urls(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not effective_is_private:
|
||||
if dist.gdrive_folder_id:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1191,6 +1060,15 @@ async def create_job_with_upload_urls(
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
|
||||
# Apply default theme if none specified
|
||||
# This ensures all karaoke videos use the Nomad theme by default
|
||||
effective_theme_id = body.theme_id
|
||||
if effective_theme_id is None:
|
||||
theme_service = get_theme_service()
|
||||
effective_theme_id = theme_service.get_default_theme_id()
|
||||
if effective_theme_id:
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(
|
||||
effective_theme_id, body.enable_cdg, body.enable_txt
|
||||
@@ -1229,18 +1107,12 @@ async def create_job_with_upload_urls(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "signed_url_upload")
|
||||
add_span_attribute("job.is_private", effective_is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
@@ -1292,8 +1164,6 @@ async def create_job_with_upload_urls(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job with upload URLs: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -1424,17 +1294,17 @@ async def mark_uploads_complete(
|
||||
|
||||
logger.info(f"Validated uploads for job {job_id}: {body.uploaded_files}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions to DOWNLOADING (raises InvalidStateTransitionError if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
5, # progress
|
||||
"Files uploaded, preparing to process"
|
||||
# Transition job to DOWNLOADING state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Files uploaded, preparing to process"
|
||||
)
|
||||
|
||||
# Trigger workers in parallel
|
||||
background_tasks.add_task(_trigger_workers_parallel, job_id)
|
||||
|
||||
# Get distribution services info for response
|
||||
credential_manager = get_credential_manager()
|
||||
distribution_services: Dict[str, Any] = {}
|
||||
@@ -1583,32 +1453,6 @@ async def create_job_from_url(
|
||||
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL."
|
||||
)
|
||||
|
||||
# For YouTube URLs, check availability before creating the job
|
||||
# This catches geo-restricted, private, and removed videos early
|
||||
if _is_youtube_url(body.url):
|
||||
youtube_service = get_youtube_download_service()
|
||||
availability = await youtube_service.check_availability(body.url)
|
||||
|
||||
if availability and not availability.get("available"):
|
||||
error_msg = availability.get("error", "This video is not available")
|
||||
|
||||
if availability.get("is_geo_restricted"):
|
||||
detail = (
|
||||
"This YouTube video is not available in our server's region. "
|
||||
"Videos that are restricted to certain countries cannot be downloaded. "
|
||||
"Try using a different source for this song."
|
||||
)
|
||||
elif availability.get("is_private"):
|
||||
detail = "This YouTube video is private and cannot be downloaded."
|
||||
elif availability.get("is_removed"):
|
||||
detail = "This YouTube video has been removed and cannot be downloaded."
|
||||
elif availability.get("is_age_restricted"):
|
||||
detail = "This YouTube video is age-restricted and cannot be downloaded."
|
||||
else:
|
||||
detail = f"This YouTube video is unavailable: {error_msg}"
|
||||
|
||||
raise HTTPException(status_code=400, detail=detail)
|
||||
|
||||
# Apply default distribution settings from environment if not provided
|
||||
dist = get_effective_distribution_settings(
|
||||
dropbox_path=body.dropbox_path,
|
||||
@@ -1623,11 +1467,10 @@ async def create_job_from_url(
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Validate credentials for requested distribution services
|
||||
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1637,7 +1480,7 @@ async def create_job_from_url(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
if dist.gdrive_folder_id:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -1704,18 +1547,12 @@ async def create_job_from_url(
|
||||
other_stems_models=body.other_stems_models,
|
||||
request_metadata=request_metadata,
|
||||
non_interactive=body.non_interactive,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "url")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="url")
|
||||
|
||||
@@ -1739,57 +1576,20 @@ async def create_job_from_url(
|
||||
logger.info(f" Artist: {artist}")
|
||||
if title:
|
||||
logger.info(f" Title: {title}")
|
||||
|
||||
# Transition job to DOWNLOADING state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Starting audio download from URL"
|
||||
)
|
||||
|
||||
# For YouTube URLs, download audio NOW using YouTubeDownloadService
|
||||
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
|
||||
if _is_youtube_url(body.url):
|
||||
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
|
||||
try:
|
||||
youtube_service = get_youtube_download_service()
|
||||
audio_gcs_path = await youtube_service.download(
|
||||
url=body.url,
|
||||
job_id=job_id,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
# Update job with the downloaded audio path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
10, # progress
|
||||
"Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
except YouTubeDownloadError as e:
|
||||
logger.error(f"YouTube download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"YouTube download failed: {e}"
|
||||
)
|
||||
else:
|
||||
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
|
||||
# The audio worker will download the URL and trigger lyrics worker after
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Starting audio download from URL"
|
||||
)
|
||||
background_tasks.add_task(_trigger_audio_worker_only, job_id)
|
||||
|
||||
# For URL jobs, trigger ONLY audio worker first
|
||||
# The audio worker will trigger lyrics worker after download completes
|
||||
# This prevents race condition where lyrics worker times out waiting for audio
|
||||
background_tasks.add_task(_trigger_audio_worker_only, job_id)
|
||||
|
||||
return CreateJobFromUrlResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
@@ -1801,8 +1601,6 @@ async def create_job_from_url(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job from URL: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -1939,11 +1737,10 @@ async def create_finalise_only_job(
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload
|
||||
|
||||
# Validate distribution credentials if services are requested
|
||||
# Skip YouTube/GDrive checks for private jobs (they won't use those services)
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -1953,7 +1750,7 @@ async def create_finalise_only_job(
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
if dist.gdrive_folder_id:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
@@ -2011,18 +1808,12 @@ async def create_finalise_only_job(
|
||||
finalise_only=True,
|
||||
keep_brand_code=body.keep_brand_code,
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
tenant_id=tenant_config.id if tenant_config else None,
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("job.source", "finalise")
|
||||
add_span_attribute("job.is_private", body.is_private)
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="finalise")
|
||||
|
||||
@@ -2074,8 +1865,6 @@ async def create_finalise_only_job(
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating finalise-only job: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -2090,13 +1879,9 @@ async def mark_finalise_uploads_complete(
|
||||
):
|
||||
"""
|
||||
Mark finalise-only file uploads as complete and start video generation.
|
||||
|
||||
|
||||
This is called after uploading prep outputs for a finalise-only job.
|
||||
The job will transition directly to AWAITING_INSTRUMENTAL_SELECTION.
|
||||
|
||||
Note: Finalise-only jobs are a special case where users upload pre-rendered
|
||||
video and only need to select instrumental. For normal jobs, instrumental
|
||||
selection is combined with lyrics review in a single step.
|
||||
"""
|
||||
try:
|
||||
# Get job and verify it exists
|
||||
@@ -2301,192 +2086,3 @@ async def mark_finalise_uploads_complete(
|
||||
except Exception as e:
|
||||
logger.error(f"Error completing finalise-only uploads for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Post-creation style asset upload endpoints (for private/custom branding)
|
||||
# ============================================================================
|
||||
|
||||
@router.post("/jobs/{job_id}/style-upload-urls")
|
||||
async def get_style_upload_urls(
|
||||
job_id: str,
|
||||
body: StyleUploadUrlsRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Get signed GCS upload URLs for style assets on an already-created job.
|
||||
|
||||
Used by the guided flow to upload custom backgrounds/images after job creation.
|
||||
Only accepts style file types (backgrounds). The job must not have progressed
|
||||
past the screen generation stage.
|
||||
"""
|
||||
try:
|
||||
# Get job and verify it exists
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Verify ownership (non-admin users can only modify their own jobs)
|
||||
if auth_result.user_type != UserType.ADMIN:
|
||||
if job.user_email != auth_result.user_email:
|
||||
raise HTTPException(status_code=403, detail="Not authorized to modify this job")
|
||||
|
||||
# Check cutoff - reject if job is too far along
|
||||
try:
|
||||
current_status = JobStatus(job.status)
|
||||
except ValueError:
|
||||
current_status = None
|
||||
if current_status in STYLE_UPLOAD_CUTOFF_STATUSES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job {job_id} is past the style upload cutoff (status: {job.status}). "
|
||||
"Style assets must be uploaded before screen generation begins."
|
||||
)
|
||||
|
||||
# Validate file types - only style files allowed
|
||||
upload_urls = []
|
||||
for file_info in body.files:
|
||||
if file_info.file_type not in STYLE_FILE_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid file_type for style upload: '{file_info.file_type}'. "
|
||||
f"Allowed: {list(STYLE_FILE_TYPES.keys())}"
|
||||
)
|
||||
|
||||
ext = Path(file_info.filename).suffix.lower()
|
||||
allowed_extensions = STYLE_FILE_TYPES[file_info.file_type]
|
||||
if ext not in allowed_extensions:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid extension '{ext}' for {file_info.file_type}. Allowed: {allowed_extensions}"
|
||||
)
|
||||
|
||||
gcs_path = _get_gcs_path_for_file(job_id, file_info.file_type, file_info.filename)
|
||||
signed_url = storage_service.generate_signed_upload_url(
|
||||
gcs_path, file_info.content_type
|
||||
)
|
||||
|
||||
upload_urls.append({
|
||||
"file_type": file_info.file_type,
|
||||
"gcs_path": gcs_path,
|
||||
"upload_url": signed_url,
|
||||
"content_type": file_info.content_type,
|
||||
})
|
||||
|
||||
logger.info(f"Generated {len(upload_urls)} style upload URLs for job {job_id}")
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"upload_urls": upload_urls,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating style upload URLs for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/style-uploads-complete")
|
||||
async def complete_style_uploads(
|
||||
job_id: str,
|
||||
body: StyleUploadsCompleteRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Finalize style asset uploads on an existing job.
|
||||
|
||||
Verifies uploaded files exist in GCS, merges them into the job's style_assets,
|
||||
and re-generates style_params.json with any color overrides applied.
|
||||
"""
|
||||
try:
|
||||
# Get job and verify it exists
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Verify ownership
|
||||
if auth_result.user_type != UserType.ADMIN:
|
||||
if job.user_email != auth_result.user_email:
|
||||
raise HTTPException(status_code=403, detail="Not authorized to modify this job")
|
||||
|
||||
# Check cutoff
|
||||
try:
|
||||
current_status = JobStatus(job.status)
|
||||
except ValueError:
|
||||
current_status = None
|
||||
if current_status in STYLE_UPLOAD_CUTOFF_STATUSES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job {job_id} is past the style upload cutoff (status: {job.status})."
|
||||
)
|
||||
|
||||
# Verify uploaded files exist in GCS and build asset mapping
|
||||
new_style_assets = {}
|
||||
for file_type in body.uploaded_files:
|
||||
if file_type not in STYLE_FILE_TYPES:
|
||||
logger.warning(f"Unknown style file_type: {file_type}")
|
||||
continue
|
||||
|
||||
asset_key = file_type.replace('style_', '')
|
||||
prefix = f"uploads/{job_id}/style/{asset_key}"
|
||||
files = storage_service.list_files(prefix)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
|
||||
)
|
||||
new_style_assets[asset_key] = files[0]
|
||||
|
||||
# Merge with existing style_assets (preserve font, other theme assets)
|
||||
existing_assets = dict(job.style_assets) if job.style_assets else {}
|
||||
existing_assets.update(new_style_assets)
|
||||
|
||||
update_data: Dict[str, Any] = {"style_assets": existing_assets}
|
||||
|
||||
# If the job has a theme, reload its style_params, apply overrides + custom paths
|
||||
theme_id = getattr(job, 'theme_id', None)
|
||||
if theme_id:
|
||||
theme_service = get_theme_service()
|
||||
style_params = theme_service.get_theme_style_params(theme_id)
|
||||
if style_params:
|
||||
# Apply color overrides if provided
|
||||
if body.color_overrides:
|
||||
color_overrides_model = ColorOverrides(**body.color_overrides)
|
||||
style_params = theme_service.apply_color_overrides(style_params, color_overrides_model)
|
||||
|
||||
# Update asset paths in style_params to use theme paths first
|
||||
style_params = theme_service._update_asset_paths_in_style(theme_id, style_params)
|
||||
|
||||
# Overwrite background paths with custom uploads
|
||||
for asset_key, gcs_path in new_style_assets.items():
|
||||
bucket_name = storage_service.bucket_name
|
||||
gcs_uri = f"gs://{bucket_name}/{gcs_path}"
|
||||
if asset_key == "intro_background" and "intro" in style_params:
|
||||
style_params["intro"]["background_image"] = gcs_uri
|
||||
elif asset_key == "karaoke_background" and "karaoke" in style_params:
|
||||
style_params["karaoke"]["background_image"] = gcs_uri
|
||||
elif asset_key == "end_background" and "end" in style_params:
|
||||
style_params["end"]["background_image"] = gcs_uri
|
||||
|
||||
# Upload updated style_params.json
|
||||
style_params_path = f"uploads/{job_id}/style/style_params.json"
|
||||
storage_service.upload_json(style_params_path, style_params)
|
||||
update_data["style_params_gcs_path"] = style_params_path
|
||||
|
||||
# Update job in Firestore
|
||||
job_manager.update_job(job_id, update_data)
|
||||
|
||||
logger.info(f"Completed style uploads for job {job_id}: {list(new_style_assets.keys())}")
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"message": "Style assets applied successfully.",
|
||||
"assets_updated": list(new_style_assets.keys()),
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error completing style uploads for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e)) from e
|
||||
@@ -16,9 +16,6 @@ from backend.services.encoding_service import get_encoding_service
|
||||
from backend.services.spacy_preloader import get_preloaded_model, is_model_preloaded
|
||||
from backend.services.nltk_preloader import get_preloaded_cmudict, is_cmudict_preloaded
|
||||
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler, is_langfuse_preloaded, is_langfuse_configured
|
||||
from backend.services.job_health_service import check_job_consistency_detailed
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -277,37 +274,6 @@ async def encoding_worker_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/flacfetch")
|
||||
async def flacfetch_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Lightweight endpoint to check flacfetch service status.
|
||||
|
||||
Returns minimal info for frontend footer display.
|
||||
No authentication required.
|
||||
"""
|
||||
status = await check_flacfetch_service_status()
|
||||
|
||||
# Return simplified response for frontend
|
||||
if not status.get("configured"):
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
if not status.get("available"):
|
||||
return {
|
||||
"available": False,
|
||||
"status": "offline",
|
||||
"error": status.get("error"),
|
||||
}
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": status.get("version"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
@@ -433,69 +399,6 @@ async def preload_status() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/job-consistency")
|
||||
async def job_consistency_check(
|
||||
status: Optional[str] = None,
|
||||
limit: int = 50
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Check job consistency across the system.
|
||||
|
||||
This endpoint identifies jobs with state inconsistencies that may indicate
|
||||
bugs in the state machine or trigger logic. Use this to find stuck jobs
|
||||
or jobs in invalid states.
|
||||
|
||||
Args:
|
||||
status: Optional filter by job status (e.g., "pending", "downloading")
|
||||
limit: Maximum number of jobs to check (default 50)
|
||||
|
||||
Returns:
|
||||
Dictionary with:
|
||||
- total_checked: Number of jobs checked
|
||||
- inconsistent_count: Number of jobs with issues
|
||||
- inconsistent_jobs: List of job details with their issues
|
||||
- summary: Summary of issue types found
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
|
||||
# Query jobs to check
|
||||
query_params = {}
|
||||
if status:
|
||||
try:
|
||||
job_status = JobStatus(status)
|
||||
query_params['status'] = job_status
|
||||
except ValueError:
|
||||
return {
|
||||
"error": f"Invalid status: {status}",
|
||||
"valid_statuses": [s.value for s in JobStatus]
|
||||
}
|
||||
|
||||
# Get jobs from Firestore
|
||||
jobs = job_manager.list_jobs(limit=limit, **query_params)
|
||||
|
||||
# Check each job for consistency
|
||||
inconsistent_jobs = []
|
||||
issue_summary = {}
|
||||
|
||||
for job in jobs:
|
||||
result = check_job_consistency_detailed(job)
|
||||
if not result['is_healthy']:
|
||||
inconsistent_jobs.append(result)
|
||||
# Count issue types
|
||||
for issue in result['issues']:
|
||||
issue_type = issue.split(':')[0] if ':' in issue else issue
|
||||
issue_summary[issue_type] = issue_summary.get(issue_type, 0) + 1
|
||||
|
||||
return {
|
||||
"total_checked": len(jobs),
|
||||
"inconsistent_count": len(inconsistent_jobs),
|
||||
"inconsistent_jobs": inconsistent_jobs,
|
||||
"summary": issue_summary,
|
||||
"status_filter": status,
|
||||
"limit": limit,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/readiness")
|
||||
async def readiness_check() -> Dict[str, str]:
|
||||
"""Readiness check endpoint for Cloud Run."""
|
||||
|
||||
@@ -288,7 +288,7 @@ async def trigger_render_video_worker(
|
||||
Idempotency: If worker is already running or complete, returns early.
|
||||
|
||||
Output: with_vocals.mkv in GCS
|
||||
Next state: INSTRUMENTAL_SELECTED (instrumental is now selected during review)
|
||||
Next state: AWAITING_INSTRUMENTAL_SELECTION
|
||||
"""
|
||||
job_id = request.job_id
|
||||
|
||||
@@ -326,7 +326,7 @@ async def check_idle_reminder(
|
||||
Check if a job needs an idle reminder email.
|
||||
|
||||
This endpoint is called by a Cloud Tasks scheduled task 5 minutes after
|
||||
a job enters AWAITING_REVIEW state.
|
||||
a job enters a blocking state (AWAITING_REVIEW or AWAITING_INSTRUMENTAL_SELECTION).
|
||||
|
||||
If the job is still in the blocking state and no reminder has been sent yet,
|
||||
sends a reminder email to the user.
|
||||
@@ -352,7 +352,6 @@ async def check_idle_reminder(
|
||||
return {"status": "not_found", "job_id": job_id, "message": "Job not found"}
|
||||
|
||||
# Check if job is still in a blocking state
|
||||
# Note: AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs only
|
||||
blocking_states = [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]
|
||||
if job.status not in [s.value for s in blocking_states]:
|
||||
logger.info(f"[job:{job_id}] Job no longer in blocking state ({job.status}), skipping reminder")
|
||||
@@ -428,137 +427,6 @@ async def check_idle_reminder(
|
||||
return {"status": "error", "job_id": job_id, "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/youtube-queue/process")
|
||||
async def process_youtube_upload_queue(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Process queued YouTube uploads.
|
||||
|
||||
Called by Cloud Scheduler (hourly) to retry uploads that were deferred
|
||||
due to YouTube API quota exhaustion. Can also be triggered manually
|
||||
from the admin dashboard.
|
||||
|
||||
Processes queued uploads one at a time, stopping if quota is exhausted.
|
||||
"""
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue as process_queue
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("YOUTUBE_QUEUE_PROCESS starting")
|
||||
add_span_attribute("operation", "youtube_queue_process")
|
||||
|
||||
# Run in background so the HTTP response returns quickly
|
||||
# (Cloud Scheduler has a 30min timeout but we don't want to block)
|
||||
async def _process():
|
||||
try:
|
||||
result = await process_queue()
|
||||
logger.info(f"YOUTUBE_QUEUE_PROCESS complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"YOUTUBE_QUEUE_PROCESS failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
|
||||
add_span_event("queue_processing_started")
|
||||
return {
|
||||
"status": "started",
|
||||
"message": "YouTube upload queue processing started in background"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-gdrive-validation")
|
||||
async def trigger_gdrive_validation_endpoint(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Trigger GDrive validation via the Cloud Function.
|
||||
|
||||
Called by a Cloud Tasks delayed task after a job completes and uploads
|
||||
to the public GDrive share. The 5-minute delay ensures E2E test cleanup
|
||||
finishes before the validator checks for sequence gaps.
|
||||
"""
|
||||
from backend.services.gdrive_validator_client import trigger_gdrive_validation
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info("GDRIVE_VALIDATION_TRIGGER starting (delayed post-job)")
|
||||
add_span_attribute("operation", "gdrive_validation_trigger")
|
||||
|
||||
try:
|
||||
result = trigger_gdrive_validation()
|
||||
if result is None:
|
||||
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
|
||||
|
||||
status = result.get("status", "unknown")
|
||||
add_span_event("validation_complete", {"result_status": status})
|
||||
return {"status": status, "message": "GDrive validation completed", "result": result}
|
||||
except Exception as e:
|
||||
logger.exception(f"GDrive validation trigger failed: {e}")
|
||||
add_span_event("error", {"error": str(e)})
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/recover-stuck-jobs")
|
||||
async def recover_stuck_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Detect and recover jobs stuck in downloading_audio status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
Finds jobs stuck in DOWNLOADING_AUDIO for >10 minutes and fails them
|
||||
so they can be retried.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
logger.info("RECOVER_STUCK_JOBS starting")
|
||||
add_span_attribute("operation", "recover_stuck_jobs")
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
# Query jobs in downloading_audio status
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
stuck_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", "downloading_audio")
|
||||
).stream()
|
||||
|
||||
recovered = []
|
||||
for doc in stuck_query:
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
# Use the health service to check if actually stuck
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
|
||||
issues = check_job_consistency(job)
|
||||
stuck_issues = [i for i in issues if "downloading_audio_stuck" in i]
|
||||
|
||||
if stuck_issues:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download: {stuck_issues[0]}")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
"Audio download timed out (stuck >10 minutes). Use retry to re-attempt."
|
||||
)
|
||||
recovered.append(job_id)
|
||||
|
||||
logger.info(f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} jobs")
|
||||
add_span_event("recovery_complete", {"recovered_count": len(recovered)})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"recovered_jobs": recovered,
|
||||
"recovered_count": len(recovered),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
@@ -571,197 +439,3 @@ async def internal_health(
|
||||
"""
|
||||
return {"status": "healthy", "service": "karaoke-backend-internal"}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Webhook Endpoint (for E2E testing)
|
||||
# =============================================================================
|
||||
|
||||
class TestWebhookRequest(BaseModel):
|
||||
"""
|
||||
Request to simulate a Stripe webhook event for E2E testing.
|
||||
|
||||
This allows E2E tests to trigger payment flow logic without requiring
|
||||
actual Stripe checkout sessions or valid webhook signatures.
|
||||
"""
|
||||
event_type: str # e.g., "checkout.session.completed"
|
||||
session_id: str # Must start with "e2e-test-" prefix
|
||||
customer_email: str
|
||||
metadata: dict # order_type, package_id, credits, artist, title, etc.
|
||||
|
||||
|
||||
class TestWebhookResponse(BaseModel):
|
||||
"""Response from test webhook processing."""
|
||||
status: str # "processed", "already_processed", "error"
|
||||
job_id: Optional[str] = None # For made-for-you orders
|
||||
credits_added: Optional[int] = None # For credit purchases
|
||||
new_balance: Optional[int] = None # For credit purchases
|
||||
message: str
|
||||
|
||||
|
||||
@router.post("/test-webhook", response_model=TestWebhookResponse)
|
||||
async def test_webhook(
|
||||
request: TestWebhookRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Test endpoint that simulates Stripe webhook events for E2E testing.
|
||||
|
||||
SECURITY:
|
||||
- Protected by admin authentication (X-Admin-Token header)
|
||||
- Session IDs must start with "e2e-test-" prefix to prevent collision
|
||||
with real Stripe sessions
|
||||
- Only for E2E testing - bypasses Stripe signature verification
|
||||
|
||||
This endpoint reuses the same handler logic as the real webhook endpoint,
|
||||
ensuring E2E tests validate actual business logic.
|
||||
|
||||
Supported event types:
|
||||
- checkout.session.completed: Handles credit purchases and made-for-you orders
|
||||
|
||||
For credit purchases, metadata must include:
|
||||
- package_id: e.g., "1_credit"
|
||||
- credits: e.g., "1"
|
||||
- user_email: Email of user to credit
|
||||
|
||||
For made-for-you orders, metadata must include:
|
||||
- order_type: "made_for_you"
|
||||
- customer_email: Customer email for delivery
|
||||
- artist: Song artist
|
||||
- title: Song title
|
||||
- source_type: "search" or "youtube"
|
||||
- youtube_url: (optional) If source_type is "youtube"
|
||||
- notes: (optional) Customer notes
|
||||
"""
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
# Validate session_id prefix for safety
|
||||
if not request.session_id.startswith("e2e-test-"):
|
||||
logger.warning(f"Test webhook rejected: session_id '{request.session_id}' missing required prefix")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Session ID must start with 'e2e-test-' prefix for test webhooks"
|
||||
)
|
||||
|
||||
logger.info(f"TEST_WEBHOOK event_type={request.event_type} session_id={request.session_id}")
|
||||
add_span_attribute("event_type", request.event_type)
|
||||
add_span_attribute("session_id", request.session_id)
|
||||
add_span_attribute("is_test_webhook", True)
|
||||
|
||||
user_service = get_user_service()
|
||||
email_service = get_email_service()
|
||||
stripe_service = get_stripe_service()
|
||||
|
||||
if request.event_type == "checkout.session.completed":
|
||||
session_id = request.session_id
|
||||
metadata = request.metadata
|
||||
|
||||
# Idempotency check: Skip if this session was already processed
|
||||
if user_service.is_stripe_session_processed(session_id):
|
||||
logger.info(f"Test webhook: session {session_id} already processed")
|
||||
return TestWebhookResponse(
|
||||
status="already_processed",
|
||||
message=f"Session {session_id} was already processed"
|
||||
)
|
||||
|
||||
# Check if this is a made-for-you order
|
||||
if metadata.get("order_type") == "made_for_you":
|
||||
try:
|
||||
# Call the same handler used by the real webhook
|
||||
await _handle_made_for_you_order(
|
||||
session_id=session_id,
|
||||
metadata=metadata,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
)
|
||||
|
||||
# Get the job ID from the most recent job for this customer
|
||||
# The handler creates a job, so we need to find it
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
db = user_service.db
|
||||
# Look for the job by session_id pattern in state_data or by customer_email
|
||||
# Since the job was just created, query by customer_email and made_for_you flag
|
||||
customer_email = metadata.get("customer_email", "")
|
||||
jobs_query = db.collection("jobs").where(
|
||||
filter=FieldFilter("customer_email", "==", customer_email)
|
||||
).where(
|
||||
filter=FieldFilter("made_for_you", "==", True)
|
||||
).order_by("created_at", direction=firestore.Query.DESCENDING).limit(1)
|
||||
|
||||
jobs = list(jobs_query.stream())
|
||||
job_id = jobs[0].to_dict().get("job_id") if jobs else None
|
||||
|
||||
logger.info(f"Test webhook: made-for-you order processed, job_id={job_id}")
|
||||
return TestWebhookResponse(
|
||||
status="processed",
|
||||
job_id=job_id,
|
||||
message=f"Made-for-you order created successfully"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(f"Test webhook: error processing made-for-you order: {e}")
|
||||
return TestWebhookResponse(
|
||||
status="error",
|
||||
message=f"Error processing made-for-you order: {str(e)}"
|
||||
)
|
||||
else:
|
||||
# Handle regular credit purchase
|
||||
# Build a synthetic session object that matches Stripe's format
|
||||
synthetic_session = {
|
||||
"id": session_id,
|
||||
"customer_email": request.customer_email,
|
||||
"metadata": metadata,
|
||||
}
|
||||
|
||||
success, user_email, credits, msg = stripe_service.handle_checkout_completed(
|
||||
synthetic_session
|
||||
)
|
||||
|
||||
if not success:
|
||||
logger.warning(f"Test webhook: credit purchase validation failed: {msg}")
|
||||
return TestWebhookResponse(
|
||||
status="error",
|
||||
message=msg
|
||||
)
|
||||
|
||||
if user_email and credits > 0:
|
||||
# Add credits to user account
|
||||
ok, new_balance, credit_msg = user_service.add_credits(
|
||||
email=user_email,
|
||||
amount=credits,
|
||||
reason="stripe_purchase",
|
||||
stripe_session_id=session_id,
|
||||
)
|
||||
|
||||
if ok:
|
||||
# Send confirmation email (same as real webhook)
|
||||
email_service.send_credits_added(user_email, credits, new_balance)
|
||||
logger.info(f"Test webhook: added {credits} credits to {user_email}, new balance: {new_balance}")
|
||||
return TestWebhookResponse(
|
||||
status="processed",
|
||||
credits_added=credits,
|
||||
new_balance=new_balance,
|
||||
message=f"Added {credits} credits to {user_email}"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Test webhook: failed to add credits: {credit_msg}")
|
||||
return TestWebhookResponse(
|
||||
status="error",
|
||||
message=f"Failed to add credits: {credit_msg}"
|
||||
)
|
||||
|
||||
return TestWebhookResponse(
|
||||
status="error",
|
||||
message="Invalid credit purchase data"
|
||||
)
|
||||
else:
|
||||
# Unsupported event type
|
||||
logger.warning(f"Test webhook: unsupported event type '{request.event_type}'")
|
||||
return TestWebhookResponse(
|
||||
status="error",
|
||||
message=f"Unsupported event type: {request.event_type}"
|
||||
)
|
||||
|
||||
+446
-871
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,7 @@ Provides endpoints for managing Web Push notification subscriptions:
|
||||
import logging
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.config import get_settings
|
||||
@@ -37,7 +37,6 @@ class SubscribeRequest(BaseModel):
|
||||
endpoint: str
|
||||
keys: Dict[str, str] # p256dh and auth
|
||||
device_name: Optional[str] = None
|
||||
tenant_id: Optional[str] = None # Tenant scope for notification isolation
|
||||
|
||||
|
||||
class SubscribeResponse(BaseModel):
|
||||
@@ -112,8 +111,7 @@ async def get_vapid_public_key():
|
||||
|
||||
@router.post("/subscribe", response_model=SubscribeResponse)
|
||||
async def subscribe_push(
|
||||
subscribe_request: SubscribeRequest,
|
||||
http_request: Request,
|
||||
request: SubscribeRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -121,11 +119,6 @@ async def subscribe_push(
|
||||
|
||||
Requires authentication. Users can have up to 5 subscriptions
|
||||
(configurable via MAX_PUSH_SUBSCRIPTIONS_PER_USER).
|
||||
|
||||
Subscriptions are scoped by tenant_id to prevent cross-tenant
|
||||
notification leakage. The tenant is resolved from:
|
||||
1. Request body tenant_id field (explicit from frontend)
|
||||
2. Tenant middleware (X-Tenant-ID header or subdomain detection)
|
||||
"""
|
||||
settings = get_settings()
|
||||
if not settings.enable_push_notifications:
|
||||
@@ -137,20 +130,14 @@ async def subscribe_push(
|
||||
push_service = get_push_notification_service()
|
||||
|
||||
# Validate keys
|
||||
if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys:
|
||||
if "p256dh" not in request.keys or "auth" not in request.keys:
|
||||
raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)")
|
||||
|
||||
# Resolve tenant_id: prefer explicit from body, fall back to middleware
|
||||
tenant_id = subscribe_request.tenant_id
|
||||
if tenant_id is None:
|
||||
tenant_id = getattr(http_request.state, "tenant_id", None)
|
||||
|
||||
success = await push_service.add_subscription(
|
||||
user_email=auth_result.user_email,
|
||||
endpoint=subscribe_request.endpoint,
|
||||
keys=subscribe_request.keys,
|
||||
device_name=subscribe_request.device_name,
|
||||
tenant_id=tenant_id or None,
|
||||
endpoint=request.endpoint,
|
||||
keys=request.keys,
|
||||
device_name=request.device_name
|
||||
)
|
||||
|
||||
if not success:
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
"""
|
||||
Admin API routes for blocklist and YouTube queue management.
|
||||
Admin API routes for rate limit management.
|
||||
|
||||
Handles:
|
||||
- Rate limit statistics and monitoring
|
||||
- Blocklist management (disposable domains, blocked emails, blocked IPs)
|
||||
- YouTube upload queue management
|
||||
- User override management (whitelist/bypass permissions)
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.rate_limit_service import get_rate_limit_service, RateLimitService
|
||||
from backend.services.email_validation_service import get_email_validation_service, EmailValidationService
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"])
|
||||
@@ -25,27 +28,36 @@ router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"])
|
||||
# Response Models
|
||||
# =============================================================================
|
||||
|
||||
class YouTubeQueueEntry(BaseModel):
|
||||
"""A queued YouTube upload entry."""
|
||||
job_id: str
|
||||
status: str
|
||||
reason: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
brand_code: Optional[str] = None
|
||||
queued_at: Optional[datetime] = None
|
||||
attempts: int = 0
|
||||
max_attempts: int = 5
|
||||
last_error: Optional[str] = None
|
||||
youtube_url: Optional[str] = None
|
||||
notification_sent: bool = False
|
||||
class RateLimitStatsResponse(BaseModel):
|
||||
"""Current rate limit statistics."""
|
||||
# Configuration
|
||||
jobs_per_day_limit: int
|
||||
youtube_uploads_per_day_limit: int
|
||||
beta_ip_per_day_limit: int
|
||||
rate_limiting_enabled: bool
|
||||
|
||||
# Current usage
|
||||
youtube_uploads_today: int
|
||||
youtube_uploads_remaining: int
|
||||
|
||||
# Blocklist stats
|
||||
disposable_domains_count: int
|
||||
blocked_emails_count: int
|
||||
blocked_ips_count: int
|
||||
|
||||
# User override stats
|
||||
total_overrides: int
|
||||
|
||||
|
||||
class YouTubeQueueListResponse(BaseModel):
|
||||
"""List of YouTube upload queue entries."""
|
||||
entries: List[YouTubeQueueEntry]
|
||||
stats: dict
|
||||
class UserRateLimitStatusResponse(BaseModel):
|
||||
"""Rate limit status for a specific user."""
|
||||
email: str
|
||||
jobs_today: int
|
||||
jobs_limit: int
|
||||
jobs_remaining: int
|
||||
has_bypass: bool
|
||||
custom_limit: Optional[int]
|
||||
bypass_reason: Optional[str]
|
||||
|
||||
|
||||
class BlocklistsResponse(BaseModel):
|
||||
@@ -72,12 +84,115 @@ class IPRequest(BaseModel):
|
||||
ip_address: str
|
||||
|
||||
|
||||
class UserOverride(BaseModel):
|
||||
"""User override configuration."""
|
||||
email: str
|
||||
bypass_job_limit: bool
|
||||
custom_daily_job_limit: Optional[int]
|
||||
reason: str
|
||||
created_by: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class UserOverrideRequest(BaseModel):
|
||||
"""Request to set/update a user override."""
|
||||
bypass_job_limit: bool = False
|
||||
custom_daily_job_limit: Optional[int] = None
|
||||
reason: str
|
||||
|
||||
|
||||
class UserOverridesListResponse(BaseModel):
|
||||
"""List of all user overrides."""
|
||||
overrides: List[UserOverride]
|
||||
total: int
|
||||
|
||||
|
||||
class SuccessResponse(BaseModel):
|
||||
"""Generic success response."""
|
||||
success: bool
|
||||
message: str
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Statistics Endpoints
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/stats", response_model=RateLimitStatsResponse)
|
||||
async def get_rate_limit_stats(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get current rate limit statistics.
|
||||
|
||||
Returns configuration values, current usage counts, and blocklist stats.
|
||||
"""
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
email_validation = get_email_validation_service()
|
||||
|
||||
# Get YouTube uploads today
|
||||
youtube_today = rate_limit_service.get_youtube_uploads_today()
|
||||
youtube_limit = settings.rate_limit_youtube_uploads_per_day
|
||||
youtube_remaining = max(0, youtube_limit - youtube_today) if youtube_limit > 0 else -1
|
||||
|
||||
# Get blocklist stats
|
||||
blocklist_stats = email_validation.get_blocklist_stats()
|
||||
|
||||
# Get override count
|
||||
overrides = rate_limit_service.get_all_overrides()
|
||||
|
||||
return RateLimitStatsResponse(
|
||||
jobs_per_day_limit=settings.rate_limit_jobs_per_day,
|
||||
youtube_uploads_per_day_limit=settings.rate_limit_youtube_uploads_per_day,
|
||||
beta_ip_per_day_limit=settings.rate_limit_beta_ip_per_day,
|
||||
rate_limiting_enabled=settings.enable_rate_limiting,
|
||||
youtube_uploads_today=youtube_today,
|
||||
youtube_uploads_remaining=youtube_remaining,
|
||||
disposable_domains_count=blocklist_stats["disposable_domains_count"],
|
||||
blocked_emails_count=blocklist_stats["blocked_emails_count"],
|
||||
blocked_ips_count=blocklist_stats["blocked_ips_count"],
|
||||
total_overrides=len(overrides),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/users/{email}", response_model=UserRateLimitStatusResponse)
|
||||
async def get_user_rate_limit_status(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get rate limit status for a specific user.
|
||||
|
||||
Returns their current usage and any override settings.
|
||||
"""
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
|
||||
jobs_today = rate_limit_service.get_user_job_count_today(email)
|
||||
override = rate_limit_service.get_user_override(email)
|
||||
|
||||
if override:
|
||||
has_bypass = override.get("bypass_job_limit", False)
|
||||
custom_limit = override.get("custom_daily_job_limit")
|
||||
bypass_reason = override.get("reason")
|
||||
jobs_limit = custom_limit if custom_limit is not None else settings.rate_limit_jobs_per_day
|
||||
else:
|
||||
has_bypass = False
|
||||
custom_limit = None
|
||||
bypass_reason = None
|
||||
jobs_limit = settings.rate_limit_jobs_per_day
|
||||
|
||||
jobs_remaining = max(0, jobs_limit - jobs_today) if not has_bypass else -1
|
||||
|
||||
return UserRateLimitStatusResponse(
|
||||
email=email,
|
||||
jobs_today=jobs_today,
|
||||
jobs_limit=jobs_limit,
|
||||
jobs_remaining=jobs_remaining,
|
||||
has_bypass=has_bypass,
|
||||
custom_limit=custom_limit,
|
||||
bypass_reason=bypass_reason,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Blocklist Management Endpoints
|
||||
# =============================================================================
|
||||
@@ -235,84 +350,79 @@ async def remove_blocked_ip(
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# YouTube Upload Queue Management Endpoints
|
||||
# User Override Management Endpoints
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/youtube-queue", response_model=YouTubeQueueListResponse)
|
||||
async def get_youtube_queue(
|
||||
@router.get("/overrides", response_model=UserOverridesListResponse)
|
||||
async def get_all_overrides(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get YouTube upload queue entries and stats.
|
||||
"""Get all user overrides."""
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
|
||||
Returns all queue entries (any status) and aggregate statistics.
|
||||
"""
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
overrides_data = rate_limit_service.get_all_overrides()
|
||||
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
entries = queue_service.get_all_queue_entries(limit=50)
|
||||
stats = queue_service.get_queue_stats()
|
||||
|
||||
return YouTubeQueueListResponse(
|
||||
entries=[YouTubeQueueEntry(**entry) for entry in entries],
|
||||
stats=stats,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/youtube-queue/{job_id}/retry", response_model=SuccessResponse)
|
||||
async def retry_youtube_upload(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Manually retry a failed YouTube upload.
|
||||
|
||||
Resets the entry back to 'queued' status with 0 attempts.
|
||||
"""
|
||||
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
|
||||
|
||||
queue_service = get_youtube_upload_queue_service()
|
||||
|
||||
if not queue_service.retry_upload(job_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Upload not found or not in retryable state for job {job_id}"
|
||||
overrides = [
|
||||
UserOverride(
|
||||
email=email,
|
||||
bypass_job_limit=data.get("bypass_job_limit", False),
|
||||
custom_daily_job_limit=data.get("custom_daily_job_limit"),
|
||||
reason=data.get("reason", ""),
|
||||
created_by=data.get("created_by", "unknown"),
|
||||
created_at=data.get("created_at", datetime.now(timezone.utc)),
|
||||
)
|
||||
for email, data in overrides_data.items()
|
||||
]
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"YouTube upload for job {job_id} queued for retry"
|
||||
return UserOverridesListResponse(
|
||||
overrides=overrides,
|
||||
total=len(overrides),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/youtube-queue/process", response_model=SuccessResponse)
|
||||
async def trigger_youtube_queue_processing(
|
||||
@router.put("/overrides/{email}", response_model=SuccessResponse)
|
||||
async def set_user_override(
|
||||
email: str,
|
||||
request: UserOverrideRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Manually trigger YouTube upload queue processing.
|
||||
"""Set or update a user override."""
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
|
||||
Same as the scheduled processor but triggered from the admin dashboard.
|
||||
Runs in the background and returns immediately.
|
||||
"""
|
||||
from backend.workers.youtube_queue_processor import process_youtube_upload_queue
|
||||
import asyncio
|
||||
email = email.lower().strip()
|
||||
if not email or "@" not in email:
|
||||
raise HTTPException(status_code=400, detail="Invalid email format")
|
||||
|
||||
async def _process():
|
||||
try:
|
||||
result = await process_youtube_upload_queue()
|
||||
logger.info(f"Manual YouTube queue processing complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"Manual YouTube queue processing failed: {e}")
|
||||
if not request.reason or len(request.reason.strip()) < 3:
|
||||
raise HTTPException(status_code=400, detail="Reason is required (min 3 characters)")
|
||||
|
||||
# Fire and forget
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.create_task(_process())
|
||||
except RuntimeError:
|
||||
pass
|
||||
rate_limit_service.set_user_override(
|
||||
user_email=email,
|
||||
bypass_job_limit=request.bypass_job_limit,
|
||||
custom_daily_job_limit=request.custom_daily_job_limit,
|
||||
reason=request.reason,
|
||||
admin_email=auth_result.user_email,
|
||||
)
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message="YouTube queue processing started in background"
|
||||
message=f"Override set for user '{email}'"
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/overrides/{email}", response_model=SuccessResponse)
|
||||
async def remove_user_override(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Remove a user override."""
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
|
||||
email = email.lower().strip()
|
||||
if not rate_limit_service.remove_user_override(email, auth_result.user_email):
|
||||
raise HTTPException(status_code=404, detail="Override not found for user")
|
||||
|
||||
return SuccessResponse(
|
||||
success=True,
|
||||
message=f"Override removed for user '{email}'"
|
||||
)
|
||||
+94
-342
@@ -1,15 +1,12 @@
|
||||
"""
|
||||
Review API routes - Combined lyrics + instrumental review.
|
||||
Review API routes - Compatible with LyricsTranscriber frontend.
|
||||
|
||||
These endpoints support the combined review flow where users review lyrics
|
||||
AND select their instrumental in a single session.
|
||||
|
||||
The correction-data endpoint now includes instrumental options and backing
|
||||
vocals analysis, and the complete endpoint requires instrumental selection.
|
||||
These endpoints match the API that the LyricsTranscriber review frontend expects,
|
||||
allowing us to use the existing React review UI with our cloud backend.
|
||||
|
||||
Usage:
|
||||
Frontend URL: http://localhost:5173/?baseApiUrl=http://localhost:8000/api/review/{job_id}
|
||||
|
||||
|
||||
The baseApiUrl includes the job_id, and all endpoints are relative to that.
|
||||
"""
|
||||
import asyncio
|
||||
@@ -22,7 +19,7 @@ from pathlib import Path
|
||||
from typing import Dict, Any, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends
|
||||
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
@@ -36,9 +33,9 @@ from backend.services.auth_service import UserType
|
||||
from backend.config import get_settings
|
||||
|
||||
# LyricsTranscriber imports for preview generation
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from lyrics_transcriber.types import CorrectionResult
|
||||
from lyrics_transcriber.core.config import OutputConfig
|
||||
from lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
|
||||
# Import from the unified style loader
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
@@ -75,54 +72,39 @@ async def get_correction_data(
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get correction data for the combined review interface.
|
||||
|
||||
Returns the CorrectionResult data plus instrumental options and analysis
|
||||
for the combined lyrics + instrumental review UI.
|
||||
|
||||
Response includes:
|
||||
- All lyrics correction data (segments, reference lyrics, anchors, etc.)
|
||||
- instrumental_options: List of available instrumental tracks with audio URLs
|
||||
- backing_vocals_analysis: Analysis data to help users choose instrumental
|
||||
Get correction data for the review interface.
|
||||
|
||||
Returns the CorrectionResult data that the frontend needs to render
|
||||
the lyrics review UI.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not ready for review (current status: {job.status})"
|
||||
)
|
||||
|
||||
# Check for updated corrections first (from previous review sessions where user edited lyrics)
|
||||
# This mirrors the logic in render_video_worker.py to ensure consistency
|
||||
corrections_updated_gcs = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
if not corrections_updated_gcs:
|
||||
# Try direct path for updated corrections
|
||||
corrections_updated_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if corrections_updated_gcs and storage.file_exists(corrections_updated_gcs):
|
||||
corrections_gcs = corrections_updated_gcs
|
||||
logger.info(f"Job {job_id}: Using updated corrections from previous review")
|
||||
else:
|
||||
# Fall back to original corrections
|
||||
corrections_gcs = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
if not corrections_gcs:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
if not storage.file_exists(corrections_gcs):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Corrections data not found. Lyrics processing may not be complete."
|
||||
)
|
||||
|
||||
|
||||
# Get corrections URL from file_urls
|
||||
corrections_gcs = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
if not corrections_gcs:
|
||||
# Try direct path
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
if not storage.file_exists(corrections_gcs):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="Corrections data not found. Lyrics processing may not be complete."
|
||||
)
|
||||
|
||||
# Download and return corrections data
|
||||
try:
|
||||
corrections_data = storage.download_json(corrections_gcs)
|
||||
|
||||
|
||||
# Add audio hash for the frontend
|
||||
audio_hash = _get_audio_hash(job_id)
|
||||
if 'metadata' not in corrections_data:
|
||||
@@ -130,75 +112,24 @@ async def get_correction_data(
|
||||
corrections_data['metadata']['audio_hash'] = audio_hash
|
||||
corrections_data['metadata']['artist'] = job.artist
|
||||
corrections_data['metadata']['title'] = job.title
|
||||
|
||||
|
||||
# Store context for audio serving
|
||||
_job_contexts[job_id] = {
|
||||
'audio_hash': audio_hash,
|
||||
'audio_gcs_path': job.input_media_gcs_path
|
||||
}
|
||||
|
||||
# === Add instrumental data for combined review ===
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
# Get instrumental stem URLs
|
||||
stems = job.file_urls.get('stems', {})
|
||||
clean_url = stems.get('instrumental_clean')
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
|
||||
# Build instrumental options with transcoded signed URLs (OGG Opus)
|
||||
instrumental_options = []
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
|
||||
signed_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
if clean_url:
|
||||
instrumental_options.append({
|
||||
"id": "clean",
|
||||
"label": "Clean Instrumental",
|
||||
"description": "No backing vocals - just the music",
|
||||
"audio_url": signed_urls['clean'],
|
||||
})
|
||||
if backing_url:
|
||||
instrumental_options.append({
|
||||
"id": "with_backing",
|
||||
"label": "Instrumental with Backing Vocals",
|
||||
"description": "Includes harmonies and background vocals",
|
||||
"audio_url": signed_urls['with_backing'],
|
||||
})
|
||||
|
||||
corrections_data['instrumental_options'] = instrumental_options
|
||||
|
||||
# Get backing vocals analysis from state_data (populated by screens_worker)
|
||||
backing_vocals_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
corrections_data['backing_vocals_analysis'] = backing_vocals_analysis
|
||||
|
||||
# Get waveform URL if available
|
||||
analysis_files = job.file_urls.get('analysis', {})
|
||||
waveform_url = analysis_files.get('backing_vocals_waveform')
|
||||
if waveform_url:
|
||||
corrections_data['backing_vocals_waveform_url'] = storage.generate_signed_url(
|
||||
waveform_url, expiration_minutes=120
|
||||
)
|
||||
|
||||
|
||||
# Transition to IN_REVIEW if not already
|
||||
if job.status == JobStatus.AWAITING_REVIEW:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User opened combined review interface"
|
||||
message="User opened review interface"
|
||||
)
|
||||
|
||||
logger.info(f"Job {job_id}: Serving correction data with instrumental options for combined review")
|
||||
|
||||
logger.info(f"Job {job_id}: Serving correction data for review")
|
||||
return corrections_data
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error loading corrections: {str(e)}")
|
||||
@@ -226,32 +157,49 @@ async def get_audio_no_hash(
|
||||
|
||||
async def _stream_audio(job_id: str):
|
||||
"""
|
||||
Redirect to a signed GCS URL for audio playback in the review interface.
|
||||
|
||||
Serves transcoded OGG Opus (~3 MB) instead of raw FLAC (~35 MB).
|
||||
Falls back to FLAC if transcoded version is not available.
|
||||
Stream the audio file for playback in the review interface.
|
||||
"""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
if not audio_gcs_path:
|
||||
raise HTTPException(status_code=404, detail="Audio file not found")
|
||||
|
||||
|
||||
# Download to temp file and stream
|
||||
try:
|
||||
transcoding = AudioTranscodingService()
|
||||
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
|
||||
# Create temp file
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".flac") as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
storage.download_file(audio_gcs_path, tmp_path)
|
||||
|
||||
# Determine content type
|
||||
if audio_gcs_path.endswith('.flac'):
|
||||
media_type = "audio/flac"
|
||||
elif audio_gcs_path.endswith('.wav'):
|
||||
media_type = "audio/wav"
|
||||
elif audio_gcs_path.endswith('.mp3'):
|
||||
media_type = "audio/mpeg"
|
||||
else:
|
||||
media_type = "audio/mpeg"
|
||||
|
||||
logger.info(f"Job {job_id}: Streaming audio for review")
|
||||
|
||||
return FileResponse(
|
||||
tmp_path,
|
||||
media_type=media_type,
|
||||
filename=os.path.basename(audio_gcs_path),
|
||||
background=BackgroundTask(os.unlink, tmp_path),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}")
|
||||
logger.error(f"Job {job_id}: Error streaming audio: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error streaming audio: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
@@ -261,100 +209,53 @@ async def complete_review(
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Complete the combined review - save corrected lyrics AND instrumental selection.
|
||||
|
||||
This endpoint receives:
|
||||
- Updated correction data (lyrics corrections)
|
||||
- instrumental_selection: "clean" or "with_backing" (REQUIRED)
|
||||
|
||||
After saving, triggers the render video worker which will use the
|
||||
pre-selected instrumental (no separate instrumental selection step).
|
||||
Complete the review and save corrected lyrics.
|
||||
|
||||
This endpoint receives the updated correction data from the frontend
|
||||
and saves it, then triggers the render video worker.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
|
||||
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job not in review state (current status: {job.status})"
|
||||
)
|
||||
|
||||
# === Require instrumental selection ===
|
||||
instrumental_selection = updated_data.get("instrumental_selection")
|
||||
if not instrumental_selection:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="instrumental_selection is required. Must be 'clean' or 'with_backing'."
|
||||
)
|
||||
|
||||
valid_selections = ["clean", "with_backing"]
|
||||
# Allow "custom" for mute-region instrumentals or user-uploaded instrumentals
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
if job.existing_instrumental_gcs_path or stems.get("custom_instrumental"):
|
||||
valid_selections.append("custom")
|
||||
|
||||
if instrumental_selection not in valid_selections:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid instrumental_selection. Must be one of: {valid_selections}"
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
# Remove instrumental_selection from updated_data before saving to corrections
|
||||
# (it's stored separately in state_data)
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Save updated corrections to GCS
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, corrections_to_save)
|
||||
storage.upload_json(corrections_gcs_path, updated_data)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
|
||||
|
||||
logger.info(f"Job {job_id}: Saved updated corrections")
|
||||
|
||||
# === Store instrumental selection in state_data ===
|
||||
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
|
||||
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
|
||||
|
||||
# Clear worker progress keys to ensure workers will run fresh (not skip due to idempotency)
|
||||
# This handles cases where a job is re-reviewed after completion or where state was inconsistent.
|
||||
# The idempotency check in workers looks at {worker}_progress.stage == 'complete' to skip,
|
||||
# so we must clear these before triggering the render-video worker.
|
||||
progress_keys = ['render_progress', 'screens_progress', 'video_progress', 'encoding_progress']
|
||||
cleared = job_manager.delete_state_data_keys(job_id, progress_keys)
|
||||
if cleared:
|
||||
logger.info(f"Job {job_id}: Cleared worker progress keys for re-processing: {cleared}")
|
||||
|
||||
|
||||
# Transition to REVIEW_COMPLETE
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.REVIEW_COMPLETE,
|
||||
progress=70,
|
||||
message=f"Review complete (instrumental: {instrumental_selection}), rendering video"
|
||||
message="Review complete, rendering video with corrected lyrics"
|
||||
)
|
||||
|
||||
|
||||
# Trigger render video worker
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
|
||||
|
||||
# Run in background, keep reference to prevent garbage collection
|
||||
task = asyncio.create_task(worker_service.trigger_render_video_worker(job_id))
|
||||
_background_tasks.add(task)
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
logger.info(f"Job {job_id}: Combined review complete, triggered render video worker")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"instrumental_selection": instrumental_selection,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
|
||||
logger.info(f"Job {job_id}: Review complete, triggered render video worker")
|
||||
|
||||
return {"status": "success"}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error completing review: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error completing review: {str(e)}")
|
||||
@@ -732,41 +633,17 @@ async def get_preview_video(
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
payload: Dict[str, Any],
|
||||
annotation: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Submit correction annotations for ML training data.
|
||||
|
||||
Accepts either a single annotation dict or {"annotations": [...]} batch.
|
||||
Stores to GCS at jobs/{job_id}/lyrics/annotations.json.
|
||||
Submit a correction annotation for ML training data.
|
||||
|
||||
For now, just log and acknowledge - full annotation support
|
||||
would require a database.
|
||||
"""
|
||||
annotations = payload.get("annotations", [payload]) if isinstance(payload, dict) else [payload]
|
||||
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
|
||||
# Merge with any existing annotations
|
||||
existing: list = []
|
||||
try:
|
||||
existing_data = storage.download_json(gcs_path)
|
||||
if isinstance(existing_data, list):
|
||||
existing = existing_data
|
||||
elif isinstance(existing_data, dict) and "annotations" in existing_data:
|
||||
existing = existing_data["annotations"]
|
||||
except Exception:
|
||||
pass # No existing file, start fresh
|
||||
|
||||
merged = existing + annotations
|
||||
storage.upload_json(gcs_path, {"annotations": merged})
|
||||
|
||||
logger.info(f"Job {job_id}: {len(annotations)} annotation(s) saved ({len(merged)} total)")
|
||||
return {"status": "success", "saved_count": len(annotations), "total_count": len(merged)}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
logger.info(f"Job {job_id}: Annotation submitted (logged but not stored)")
|
||||
return {"status": "success", "annotation_id": "stub"}
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
@@ -775,133 +652,8 @@ async def get_annotation_stats(
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Get annotation statistics."""
|
||||
try:
|
||||
storage = StorageService()
|
||||
gcs_path = f"jobs/{job_id}/lyrics/annotations.json"
|
||||
data = storage.download_json(gcs_path)
|
||||
annotations = data.get("annotations", []) if isinstance(data, dict) else data
|
||||
by_type: Dict[str, int] = {}
|
||||
for a in annotations:
|
||||
atype = a.get("annotation_type", "unknown")
|
||||
by_type[atype] = by_type.get(atype, 0) + 1
|
||||
return {"total_annotations": len(annotations), "by_type": by_type}
|
||||
except Exception:
|
||||
return {"total_annotations": 0, "by_type": {}}
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
async def get_instrumental_analysis(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get instrumental analysis data for the review interface.
|
||||
|
||||
Returns analysis data in the format expected by InstrumentalSelector component:
|
||||
- analysis: backing vocals analysis with audible segments
|
||||
- audio_urls: signed URLs for instrumental stems
|
||||
- has_original: whether original audio is available
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
# Get backing vocals analysis from state_data
|
||||
backing_analysis = job.state_data.get('backing_vocals_analysis', {})
|
||||
|
||||
# Get stem URLs
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
stems = job.file_urls.get('stems', {})
|
||||
clean_url = stems.get('instrumental_clean')
|
||||
backing_url = stems.get('instrumental_with_backing')
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
|
||||
# Build audio URLs with transcoded signed access (OGG Opus, parallel)
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks['clean'] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks['with_backing'] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if job.input_media_gcs_path:
|
||||
url_tasks['original'] = transcoding.get_review_audio_url_async(job.input_media_gcs_path, expiration_minutes=120)
|
||||
if backing_vocals_path:
|
||||
url_tasks['backing_vocals'] = transcoding.get_review_audio_url_async(backing_vocals_path, expiration_minutes=120)
|
||||
|
||||
audio_urls = {}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
|
||||
# Format response to match InstrumentalAnalysis type
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"duration_seconds": backing_analysis.get('total_duration_seconds'),
|
||||
"analysis": {
|
||||
"has_audible_content": backing_analysis.get('has_audible_content', False),
|
||||
"total_duration_seconds": backing_analysis.get('total_duration_seconds', 0),
|
||||
"audible_segments": backing_analysis.get('audible_segments', []),
|
||||
"recommended_selection": backing_analysis.get('recommended_selection', 'with_backing'),
|
||||
"total_audible_duration_seconds": backing_analysis.get('total_audible_duration_seconds', 0),
|
||||
"audible_percentage": backing_analysis.get('audible_percentage', 0),
|
||||
"silence_threshold_db": backing_analysis.get('silence_threshold_db', -40),
|
||||
},
|
||||
"audio_urls": audio_urls,
|
||||
"has_original": bool(job.input_media_gcs_path),
|
||||
"has_uploaded_instrumental": bool(job.existing_instrumental_gcs_path),
|
||||
"total_annotations": 0,
|
||||
"by_type": {},
|
||||
"message": "Annotation stats not yet implemented"
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{job_id}/waveform-data")
|
||||
async def get_waveform_data(
|
||||
job_id: str,
|
||||
num_points: int = 1000,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get waveform amplitude data for client-side rendering.
|
||||
|
||||
Returns amplitude values for drawing the waveform in the frontend.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
# Get backing vocals path
|
||||
stems = job.file_urls.get('stems', {})
|
||||
backing_vocals_path = stems.get('backing_vocals')
|
||||
|
||||
if not backing_vocals_path:
|
||||
# Fallback to input audio if no backing vocals
|
||||
backing_vocals_path = job.input_media_gcs_path
|
||||
|
||||
if not backing_vocals_path:
|
||||
raise HTTPException(status_code=404, detail="No audio available for waveform")
|
||||
|
||||
try:
|
||||
analysis_service = AudioAnalysisService()
|
||||
amplitudes, duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=backing_vocals_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
|
||||
return {
|
||||
"amplitudes": amplitudes,
|
||||
"duration_seconds": duration,
|
||||
"duration": duration, # Legacy field name
|
||||
"sample_rate": num_points,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
|
||||
+412
-401
File diff suppressed because it is too large.
Load diff
+10
-28
@@ -41,15 +41,7 @@ class Settings(BaseSettings):
|
||||
max_concurrent_jobs: int = int(os.getenv("MAX_CONCURRENT_JOBS", "5"))
|
||||
job_timeout_seconds: int = int(os.getenv("JOB_TIMEOUT_SECONDS", "3600"))
|
||||
|
||||
# Lyrics Correction Settings
|
||||
# Skip all auto-correction (both agentic AI and heuristic handlers).
|
||||
# When true, raw transcription goes directly to human review without any automatic fixes.
|
||||
# This is the default because auto-correction currently creates more work for reviewers.
|
||||
# Set SKIP_CORRECTION=false to re-enable auto-correction if quality improves.
|
||||
skip_correction: bool = os.getenv("SKIP_CORRECTION", "true").lower() in ("true", "1", "yes")
|
||||
|
||||
# Agentic AI Correction (for lyrics correction via LLM)
|
||||
# Only used when skip_correction=false
|
||||
# When enabled, uses Gemini via Vertex AI for intelligent lyrics correction
|
||||
use_agentic_ai: bool = os.getenv("USE_AGENTIC_AI", "true").lower() in ("true", "1", "yes")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3-flash-preview")
|
||||
@@ -83,9 +75,6 @@ class Settings(BaseSettings):
|
||||
# Requires use_gce_encoding to be enabled and the GCE worker to support /encode-preview endpoint.
|
||||
use_gce_preview_encoding: bool = os.getenv("USE_GCE_PREVIEW_ENCODING", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# Karaoke-Decide catalog API (for song/artist autocomplete)
|
||||
karaoke_decide_api_url: str = os.getenv("KARAOKE_DECIDE_API_URL", "https://decide.nomadkaraoke.com")
|
||||
|
||||
# Storage paths
|
||||
temp_dir: str = os.getenv("TEMP_DIR", "/tmp/karaoke-gen")
|
||||
|
||||
@@ -100,13 +89,7 @@ class Settings(BaseSettings):
|
||||
# This is required for torrent downloads since Cloud Run doesn't support BitTorrent.
|
||||
flacfetch_api_url: Optional[str] = os.getenv("FLACFETCH_API_URL") # e.g., http://10.0.0.5:8080
|
||||
flacfetch_api_key: Optional[str] = os.getenv("FLACFETCH_API_KEY")
|
||||
|
||||
# Flacfetch client retry settings
|
||||
# Retries help handle transient network failures when calling the flacfetch service
|
||||
flacfetch_retry_max_attempts: int = int(os.getenv("FLACFETCH_RETRY_MAX_ATTEMPTS", "9")) # Total attempts (1 initial + 8 retries)
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
|
||||
|
||||
# Default distribution settings (can be overridden per-request)
|
||||
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
|
||||
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
|
||||
@@ -119,17 +102,16 @@ class Settings(BaseSettings):
|
||||
default_enable_youtube_upload: bool = os.getenv("DEFAULT_ENABLE_YOUTUBE_UPLOAD", "false").lower() in ("true", "1", "yes")
|
||||
default_brand_prefix: Optional[str] = os.getenv("DEFAULT_BRAND_PREFIX")
|
||||
|
||||
# Private (non-published) track distribution settings
|
||||
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
|
||||
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
|
||||
# Rate Limiting Configuration
|
||||
# Enable/disable rate limiting system-wide (useful for development)
|
||||
enable_rate_limiting: bool = os.getenv("ENABLE_RATE_LIMITING", "true").lower() in ("true", "1", "yes")
|
||||
# Maximum jobs a user can create per day (0 = unlimited)
|
||||
rate_limit_jobs_per_day: int = int(os.getenv("RATE_LIMIT_JOBS_PER_DAY", "5"))
|
||||
# Maximum YouTube uploads system-wide per day (0 = unlimited)
|
||||
rate_limit_youtube_uploads_per_day: int = int(os.getenv("RATE_LIMIT_YOUTUBE_UPLOADS_PER_DAY", "10"))
|
||||
# Maximum beta enrollments from same IP per day (0 = unlimited)
|
||||
rate_limit_beta_ip_per_day: int = int(os.getenv("RATE_LIMIT_BETA_IP_PER_DAY", "1"))
|
||||
|
||||
# YouTube Data API v3 Quota Configuration
|
||||
# Daily quota limit (YouTube grants 10,000 units/day by default)
|
||||
youtube_quota_daily_limit: int = int(os.getenv("YOUTUBE_QUOTA_DAILY_LIMIT", "10000"))
|
||||
# Estimated units consumed per upload (videos.insert=100 + search.list=100 + thumbnails.set=50 + buffer)
|
||||
youtube_quota_upload_cost: int = int(os.getenv("YOUTUBE_QUOTA_UPLOAD_COST", "300"))
|
||||
# Safety margin to reserve (avoid hitting exact limit)
|
||||
youtube_quota_safety_margin: int = int(os.getenv("YOUTUBE_QUOTA_SAFETY_MARGIN", "500"))
|
||||
# E2E test bypass key for rate limiting (set via secret in production)
|
||||
e2e_bypass_key: str = os.getenv("E2E_BYPASS_KEY", "")
|
||||
default_youtube_description: str = os.getenv(
|
||||
|
||||
+31
-59
@@ -2,10 +2,40 @@
|
||||
Custom exceptions for the karaoke generation backend.
|
||||
|
||||
These exceptions are used for structured error handling across the application,
|
||||
particularly for validation errors and credit checks.
|
||||
particularly for rate limiting and validation errors.
|
||||
"""
|
||||
|
||||
|
||||
class RateLimitExceededError(Exception):
|
||||
"""
|
||||
Raised when a rate limit is exceeded.
|
||||
|
||||
Includes information about when the limit will reset for client retry logic.
|
||||
|
||||
Attributes:
|
||||
message: Human-readable error message
|
||||
limit_type: Type of limit exceeded (e.g., "jobs_per_day", "youtube_uploads")
|
||||
remaining_seconds: Seconds until the limit resets (for Retry-After header)
|
||||
current_count: Current usage count
|
||||
limit_value: The limit that was exceeded
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
limit_type: str = "unknown",
|
||||
remaining_seconds: int = 0,
|
||||
current_count: int = 0,
|
||||
limit_value: int = 0
|
||||
):
|
||||
self.message = message
|
||||
self.limit_type = limit_type
|
||||
self.remaining_seconds = remaining_seconds
|
||||
self.current_count = current_count
|
||||
self.limit_value = limit_value
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class EmailValidationError(Exception):
|
||||
"""
|
||||
Raised when email validation fails.
|
||||
@@ -34,61 +64,3 @@ class IPBlockedError(Exception):
|
||||
self.message = message
|
||||
self.ip_address = ip_address
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class InsufficientCreditsError(Exception):
|
||||
"""
|
||||
Raised when a user attempts to create a job without sufficient credits.
|
||||
|
||||
Attributes:
|
||||
message: Human-readable error message
|
||||
credits_available: Number of credits the user currently has
|
||||
credits_required: Number of credits required (always 1 for now)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
credits_available: int = 0,
|
||||
credits_required: int = 1
|
||||
):
|
||||
self.message = message
|
||||
self.credits_available = credits_available
|
||||
self.credits_required = credits_required
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class InvalidStateTransitionError(Exception):
|
||||
"""
|
||||
Raised when an invalid job state transition is attempted.
|
||||
|
||||
This exception is raised by JobManager.transition_to_state() when the
|
||||
requested transition is not allowed by the state machine defined in
|
||||
STATE_TRANSITIONS.
|
||||
|
||||
Example: Trying to transition from PENDING to GENERATING_SCREENS is invalid
|
||||
because PENDING can only transition to DOWNLOADING, SEARCHING_AUDIO, FAILED,
|
||||
or CANCELLED.
|
||||
|
||||
Attributes:
|
||||
message: Human-readable error message
|
||||
job_id: The job ID that failed to transition
|
||||
from_status: Current status of the job
|
||||
to_status: Attempted target status
|
||||
valid_transitions: List of valid transitions from current status
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
job_id: str = "",
|
||||
from_status: str = "",
|
||||
to_status: str = "",
|
||||
valid_transitions: list = None
|
||||
):
|
||||
self.message = message
|
||||
self.job_id = job_id
|
||||
self.from_status = from_status
|
||||
self.to_status = to_status
|
||||
self.valid_transitions = valid_transitions or []
|
||||
super().__init__(message)
|
||||
+17
-31
@@ -7,7 +7,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -15,7 +15,6 @@ from backend.services.nltk_preloader import preload_all_nltk_resources
|
||||
from backend.services.langfuse_preloader import preload_langfuse_handler
|
||||
from backend.middleware.audit_logging import AuditLoggingMiddleware
|
||||
from backend.middleware.tenant import TenantMiddleware
|
||||
from backend.workers.registry import worker_registry
|
||||
|
||||
|
||||
from backend.version import VERSION
|
||||
@@ -101,23 +100,8 @@ async def lifespan(app: FastAPI):
|
||||
logger.error(f"Credential validation failed: {e}")
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown - wait for any active workers to complete before terminating
|
||||
# This prevents Cloud Run from killing workers mid-processing
|
||||
logger.info("Shutdown requested, checking for active workers...")
|
||||
if worker_registry.has_active_workers():
|
||||
active = worker_registry.get_active_workers()
|
||||
logger.info(f"Active workers found: {active}")
|
||||
logger.info("Waiting for workers to complete (timeout: 600s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=600) # 10 min max
|
||||
if not completed:
|
||||
logger.error(
|
||||
"Shutdown timeout - some workers may not have completed cleanly. "
|
||||
f"Remaining workers: {worker_registry.get_active_workers()}"
|
||||
)
|
||||
else:
|
||||
logger.info("No active workers, proceeding with shutdown")
|
||||
|
||||
|
||||
# Shutdown
|
||||
logger.info("Shutting down karaoke generation backend")
|
||||
|
||||
|
||||
@@ -136,8 +120,8 @@ if tracing_enabled:
|
||||
# Configure CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=False,
|
||||
allow_origins=["*"], # Configure this properly for production
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -161,27 +145,29 @@ app.include_router(users.router, prefix="/api") # User auth, credits, and Strip
|
||||
app.include_router(admin.router, prefix="/api") # Admin dashboard and management
|
||||
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
|
||||
app.include_router(push.router, prefix="/api") # Push notification subscription management
|
||||
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
|
||||
|
||||
# Exception handlers
|
||||
# Exception handler for rate limiting
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.exceptions import RateLimitExceededError
|
||||
|
||||
|
||||
@app.exception_handler(InsufficientCreditsError)
|
||||
async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError):
|
||||
"""Handle insufficient credits errors with 402 Payment Required status."""
|
||||
@app.exception_handler(RateLimitExceededError)
|
||||
async def rate_limit_exception_handler(request: Request, exc: RateLimitExceededError):
|
||||
"""Handle rate limit exceeded errors with 429 status."""
|
||||
return JSONResponse(
|
||||
status_code=402,
|
||||
status_code=429,
|
||||
content={
|
||||
"detail": exc.message,
|
||||
"credits_available": exc.credits_available,
|
||||
"credits_required": exc.credits_required,
|
||||
"buy_url": "/#pricing",
|
||||
"limit_type": exc.limit_type,
|
||||
"current_count": exc.current_count,
|
||||
"limit_value": exc.limit_value,
|
||||
},
|
||||
headers={
|
||||
"Retry-After": str(exc.remaining_seconds),
|
||||
} if exc.remaining_seconds > 0 else None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+53
-82
@@ -15,58 +15,54 @@ from karaoke_gen.utils import normalize_text
|
||||
class JobStatus(str, Enum):
|
||||
"""
|
||||
Job status enumeration - Complete state machine.
|
||||
|
||||
The workflow has 7 main stages with 2 human interaction points:
|
||||
|
||||
The workflow has 8 main stages with 3 human interaction points:
|
||||
1. Input & Setup (may include audio source selection)
|
||||
2. Parallel Processing (audio + lyrics)
|
||||
3. Title/End Screen Generation + Backing Vocals Analysis
|
||||
3. Title/End Screen Generation
|
||||
4. Countdown Padding Synchronization
|
||||
5. Combined Human Review (BLOCKING) - lyrics review + instrumental selection
|
||||
6. Video Finalization
|
||||
7. Distribution
|
||||
|
||||
Note: As of 2026-01, lyrics review and instrumental selection are combined
|
||||
into a single human review step. The user selects their instrumental
|
||||
during the lyrics review phase, before the video is rendered.
|
||||
5. Human Review (BLOCKING)
|
||||
6. Instrumental Selection (BLOCKING)
|
||||
7. Video Finalization
|
||||
8. Distribution
|
||||
"""
|
||||
# Initial states
|
||||
PENDING = "pending" # Job created, queued for processing
|
||||
|
||||
|
||||
# Audio search states (for artist+title search mode)
|
||||
SEARCHING_AUDIO = "searching_audio" # Searching for audio sources via flacfetch
|
||||
AWAITING_AUDIO_SELECTION = "awaiting_audio_selection" # ⚠️ WAITING FOR USER - select audio source
|
||||
DOWNLOADING_AUDIO = "downloading_audio" # Downloading selected audio from source
|
||||
|
||||
|
||||
DOWNLOADING = "downloading" # Downloading from URL or processing upload
|
||||
|
||||
|
||||
# Stage 2a: Audio separation (parallel track 1)
|
||||
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
|
||||
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
|
||||
AUDIO_COMPLETE = "audio_complete" # All audio stems ready
|
||||
|
||||
|
||||
# Stage 2b: Lyrics processing (parallel track 2)
|
||||
TRANSCRIBING = "transcribing" # AudioShake API transcription
|
||||
CORRECTING = "correcting" # Automatic lyrics correction
|
||||
LYRICS_COMPLETE = "lyrics_complete" # Corrections JSON ready
|
||||
|
||||
# Stage 3: Title/End screens + Backing Vocals Analysis
|
||||
|
||||
# Stage 3: Title/End screens
|
||||
GENERATING_SCREENS = "generating_screens" # Creating title and end screen videos
|
||||
|
||||
|
||||
# Stage 4: Countdown padding (automatic)
|
||||
APPLYING_PADDING = "applying_padding" # Synchronizing countdown padding
|
||||
|
||||
# Stage 5: Combined Human Review (BLOCKING) - lyrics + instrumental selection
|
||||
AWAITING_REVIEW = "awaiting_review" # ⚠️ WAITING FOR USER - combined review needed
|
||||
IN_REVIEW = "in_review" # User is actively reviewing
|
||||
REVIEW_COMPLETE = "review_complete" # User submitted lyrics + instrumental selection
|
||||
|
||||
|
||||
# Stage 5: Human review (BLOCKING)
|
||||
AWAITING_REVIEW = "awaiting_review" # ⚠️ WAITING FOR USER - lyrics review needed
|
||||
IN_REVIEW = "in_review" # User is actively reviewing lyrics
|
||||
REVIEW_COMPLETE = "review_complete" # User submitted corrected lyrics
|
||||
|
||||
# Stage 5.5: Render video with corrected lyrics (post-review)
|
||||
RENDERING_VIDEO = "rendering_video" # Using OutputGenerator to create with_vocals.mkv
|
||||
|
||||
# Stage 6: Instrumental already selected (during combined review)
|
||||
# Note: AWAITING_INSTRUMENTAL_SELECTION kept for DB compatibility with historical jobs only
|
||||
AWAITING_INSTRUMENTAL_SELECTION = "awaiting_instrumental_selection" # LEGACY - no longer used
|
||||
INSTRUMENTAL_SELECTED = "instrumental_selected" # Instrumental was selected during combined review
|
||||
|
||||
# Stage 6: Instrumental selection (BLOCKING)
|
||||
AWAITING_INSTRUMENTAL_SELECTION = "awaiting_instrumental_selection" # ⚠️ WAITING FOR USER
|
||||
INSTRUMENTAL_SELECTED = "instrumental_selected" # User made selection
|
||||
|
||||
# Stage 7: Video generation and finalization
|
||||
GENERATING_VIDEO = "generating_video" # Creating initial karaoke video
|
||||
@@ -93,77 +89,71 @@ class JobStatus(str, Enum):
|
||||
|
||||
# Valid state transitions
|
||||
STATE_TRANSITIONS = {
|
||||
# PENDING can go to DOWNLOADING (file upload), SEARCHING_AUDIO (artist+title search),
|
||||
# or DOWNLOADING_AUDIO (create-from-search where audio is pre-selected)
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
|
||||
# PENDING can go to DOWNLOADING (file upload), SEARCHING_AUDIO (artist+title search), or AWAITING_INSTRUMENTAL_SELECTION (finalise-only)
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
|
||||
# Audio search flow (for artist+title search mode)
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
|
||||
|
||||
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
|
||||
# Audio separation flow
|
||||
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
|
||||
JobStatus.SEPARATING_STAGE2: [JobStatus.AUDIO_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.AUDIO_COMPLETE: [JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
|
||||
# Lyrics flow
|
||||
JobStatus.TRANSCRIBING: [JobStatus.CORRECTING, JobStatus.FAILED],
|
||||
JobStatus.CORRECTING: [JobStatus.LYRICS_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.LYRICS_COMPLETE: [JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
# Post-parallel processing (screens + backing vocals analysis)
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
|
||||
# Post-parallel processing
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.FAILED],
|
||||
JobStatus.APPLYING_PADDING: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
|
||||
# Combined human review flow (lyrics + instrumental selection)
|
||||
|
||||
# Human review flow
|
||||
# AWAITING_REVIEW can go directly to REVIEW_COMPLETE (quick review) or to IN_REVIEW (editing)
|
||||
JobStatus.AWAITING_REVIEW: [JobStatus.IN_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_REVIEW: [JobStatus.REVIEW_COMPLETE, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
JobStatus.REVIEW_COMPLETE: [JobStatus.RENDERING_VIDEO, JobStatus.PREP_COMPLETE, JobStatus.FAILED], # PREP_COMPLETE for prep-only jobs
|
||||
|
||||
# Video rendering (post-review) - instrumental was already selected during combined review
|
||||
JobStatus.RENDERING_VIDEO: [JobStatus.INSTRUMENTAL_SELECTED, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs in DB
|
||||
# New jobs never enter this state; they go directly to INSTRUMENTAL_SELECTED after render
|
||||
|
||||
# Video rendering (post-review)
|
||||
JobStatus.RENDERING_VIDEO: [JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Instrumental selection flow
|
||||
JobStatus.AWAITING_INSTRUMENTAL_SELECTION: [JobStatus.INSTRUMENTAL_SELECTED, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.INSTRUMENTAL_SELECTED: [JobStatus.GENERATING_VIDEO, JobStatus.FAILED],
|
||||
|
||||
|
||||
# Video generation flow
|
||||
JobStatus.GENERATING_VIDEO: [JobStatus.ENCODING, JobStatus.FAILED],
|
||||
JobStatus.ENCODING: [JobStatus.PACKAGING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.PACKAGING: [JobStatus.UPLOADING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
|
||||
# Distribution flow
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states - COMPLETE allows visibility change re-processing
|
||||
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE have no transitions
|
||||
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
|
||||
# PREP_COMPLETE allows continuation from combined review
|
||||
JobStatus.COMPLETE: [JobStatus.LYRICS_COMPLETE], # Visibility change: private->public re-processing
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED], # Continue from combined review
|
||||
# PREP_COMPLETE allows finalise-only continuation
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.FAILED], # Finalise-only continues from here
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.DOWNLOADING_AUDIO, # Retry audio download (audio search flow)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
JobStatus.AWAITING_REVIEW, # Retry from combined review
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.DOWNLOADING_AUDIO, # Retry audio download (audio search flow)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
JobStatus.AWAITING_REVIEW, # Retry from combined review
|
||||
],
|
||||
|
||||
|
||||
# Legacy states (for backward compatibility)
|
||||
JobStatus.QUEUED: [JobStatus.PENDING],
|
||||
JobStatus.PROCESSING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING],
|
||||
@@ -208,14 +198,7 @@ class Job(BaseModel):
|
||||
title: Optional[str] = None
|
||||
filename: Optional[str] = None # Original uploaded filename
|
||||
input_media_gcs_path: Optional[str] = None # GCS path to uploaded file
|
||||
|
||||
# Audio source tracking (for retry capability)
|
||||
audio_source_type: Optional[str] = None # Source type: 'audio_search', 'youtube_url', 'file_upload'
|
||||
source_name: Optional[str] = None # Provider name (RED, OPS, YouTube, Spotify) - for audio_search
|
||||
source_id: Optional[str] = None # Source-specific ID (torrent ID, video ID, track ID) - for audio_search
|
||||
target_file: Optional[str] = None # For torrents, specific file to extract - for audio_search
|
||||
download_url: Optional[str] = None # Direct download URL if available - for audio_search
|
||||
|
||||
|
||||
# User preferences
|
||||
enable_cdg: bool = False # Generate CDG+MP3 package (requires style config)
|
||||
enable_txt: bool = False # Generate TXT+MP3 package (requires style config)
|
||||
@@ -225,8 +208,8 @@ class Job(BaseModel):
|
||||
user_email: Optional[str] = None # Email for notifications
|
||||
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
|
||||
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
# Multi-tenant support (None = default Nomad Karaoke)
|
||||
tenant_id: Optional[str] = None # Tenant ID for white-label portal scoping
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
@@ -302,19 +285,10 @@ class Job(BaseModel):
|
||||
customer_email: Optional[str] = None # Customer email for final delivery (job owned by admin during processing)
|
||||
customer_notes: Optional[str] = None # Notes provided by customer with their order
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Creation-time decision params (for observability — what did the user actually choose?)
|
||||
creation_params: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
# Output deletion tracking (for admin cleanup without deleting job)
|
||||
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
|
||||
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
|
||||
|
||||
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
|
||||
credit_refunded: bool = False
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
@@ -518,9 +492,6 @@ class JobCreate(BaseModel):
|
||||
customer_email: Optional[str] = None # Customer email for final delivery (job owned by admin during processing)
|
||||
customer_notes: Optional[str] = None # Notes provided by customer with their order
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Request metadata (set by API endpoint from request headers)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
@@ -533,8 +504,8 @@ class JobCreate(BaseModel):
|
||||
- custom_headers: All X-* headers
|
||||
"""
|
||||
|
||||
# Tenant scoping for white-label portals ("" = consumer, "vocalstar"/etc = tenant)
|
||||
tenant_id: str = "" # Tenant ID for job scoping
|
||||
# Tenant scoping for white-label portals
|
||||
tenant_id: Optional[str] = None # Tenant ID for job scoping
|
||||
|
||||
@validator('url')
|
||||
def validate_url(cls, v):
|
||||
|
||||
@@ -10,7 +10,7 @@ class URLSubmissionRequest(BaseModel):
|
||||
url: HttpUrl
|
||||
artist: Optional[str] = None # Auto-detected if not provided
|
||||
title: Optional[str] = None # Auto-detected if not provided
|
||||
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
@@ -18,7 +18,6 @@ class URLSubmissionRequest(BaseModel):
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
is_private: Optional[bool] = None # Private (non-published) track mode
|
||||
|
||||
|
||||
class UploadSubmissionRequest(BaseModel):
|
||||
@@ -58,13 +57,13 @@ class CorrectionsSubmission(BaseModel):
|
||||
class InstrumentalSelection(BaseModel):
|
||||
"""
|
||||
Request to select instrumental audio option.
|
||||
|
||||
|
||||
This is the second critical human-in-the-loop interaction point.
|
||||
User chooses between clean instrumental, instrumental with backing vocals,
|
||||
or a custom instrumental (created via create-custom-instrumental endpoint).
|
||||
"""
|
||||
selection: str # "clean", "with_backing", or "custom"
|
||||
|
||||
|
||||
@validator('selection')
|
||||
def validate_selection(cls, v):
|
||||
"""Validate selection is a valid option."""
|
||||
@@ -74,26 +73,6 @@ class InstrumentalSelection(BaseModel):
|
||||
return v
|
||||
|
||||
|
||||
class CompleteReviewRequest(BaseModel):
|
||||
"""
|
||||
Request to complete the review with optional instrumental selection.
|
||||
|
||||
For the combined review flow, this includes the instrumental selection.
|
||||
For legacy flows, the instrumental_selection can be omitted.
|
||||
"""
|
||||
instrumental_selection: Optional[str] = None # "clean", "with_backing", or "custom"
|
||||
|
||||
@validator('instrumental_selection')
|
||||
def validate_instrumental_selection(cls, v):
|
||||
"""Validate instrumental selection if provided."""
|
||||
if v is None:
|
||||
return v
|
||||
valid_options = ['clean', 'with_backing', 'custom']
|
||||
if v not in valid_options:
|
||||
raise ValueError(f"instrumental_selection must be one of: {valid_options}")
|
||||
return v
|
||||
|
||||
|
||||
class MuteRegionRequest(BaseModel):
|
||||
"""A region to mute in the backing vocals."""
|
||||
start_seconds: float
|
||||
@@ -142,24 +121,3 @@ class RetryJobRequest(BaseModel):
|
||||
"""Request to retry a failed job."""
|
||||
from_stage: Optional[str] = None # Optional: restart from specific stage
|
||||
|
||||
|
||||
class ChangeVisibilityRequest(BaseModel):
|
||||
"""Request to change job visibility (public/private)."""
|
||||
target_visibility: str # "public" or "private"
|
||||
|
||||
@validator('target_visibility')
|
||||
def validate_target(cls, v):
|
||||
if v not in ('public', 'private'):
|
||||
raise ValueError("target_visibility must be 'public' or 'private'")
|
||||
return v
|
||||
|
||||
|
||||
class ChangeVisibilityResponse(BaseModel):
|
||||
"""Response from change visibility endpoint."""
|
||||
status: str # "success", "processing", "error"
|
||||
job_id: str
|
||||
message: str
|
||||
previous_visibility: str # "public" or "private"
|
||||
new_visibility: str # "public" or "private"
|
||||
reprocessing_required: bool
|
||||
|
||||
@@ -95,12 +95,6 @@ class TenantDefaults(BaseModel):
|
||||
brand_prefix: Optional[str] = Field(
|
||||
None, description="Prefix for output filenames (e.g., 'VSTAR')"
|
||||
)
|
||||
dropbox_path: Optional[str] = Field(
|
||||
None, description="Tenant-specific Dropbox folder path (e.g., '/Karaoke/Vocal-Star')"
|
||||
)
|
||||
gdrive_folder_id: Optional[str] = Field(
|
||||
None, description="Tenant-specific Google Drive folder ID for output uploads"
|
||||
)
|
||||
youtube_description_template: Optional[str] = Field(
|
||||
None, description="Default YouTube description template"
|
||||
)
|
||||
@@ -145,10 +139,6 @@ class TenantConfig(BaseModel):
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
def get_frontend_url(self) -> str:
|
||||
"""Get the frontend URL for this tenant's portal."""
|
||||
return f"https://{self.subdomain}"
|
||||
|
||||
def get_sender_email(self) -> str:
|
||||
"""Get the email sender address for this tenant."""
|
||||
if self.auth.sender_email:
|
||||
|
||||
+51
-36
@@ -6,6 +6,7 @@ Supports:
|
||||
- Credit system for karaoke generation
|
||||
- Role-based access control (user/admin)
|
||||
- Stripe integration for payments
|
||||
- Beta tester program with feedback collection
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
@@ -19,6 +20,14 @@ class UserRole(str, Enum):
|
||||
ADMIN = "admin"
|
||||
|
||||
|
||||
class BetaTesterStatus(str, Enum):
|
||||
"""Status of beta tester participation."""
|
||||
ACTIVE = "active" # Enrolled, free credits available
|
||||
PENDING_FEEDBACK = "pending_feedback" # Job completed, awaiting feedback
|
||||
COMPLETED = "completed" # Feedback submitted
|
||||
EXPIRED = "expired" # 24hr deadline passed without feedback
|
||||
|
||||
|
||||
class CreditTransaction(BaseModel):
|
||||
"""Record of a credit transaction."""
|
||||
id: str
|
||||
@@ -36,15 +45,10 @@ class PushSubscription(BaseModel):
|
||||
|
||||
Stores the push subscription endpoint and encryption keys needed
|
||||
to send push notifications to the user's browser/device.
|
||||
|
||||
Subscriptions are scoped by tenant_id to prevent cross-tenant
|
||||
notification leakage (e.g., a consumer job notification appearing
|
||||
on a tenant portal's service worker).
|
||||
"""
|
||||
endpoint: str # Push service endpoint URL
|
||||
keys: Dict[str, str] # p256dh and auth keys for encryption
|
||||
device_name: Optional[str] = None # e.g., "iPhone", "Chrome on Windows"
|
||||
tenant_id: Optional[str] = None # Tenant scope (None = consumer/default portal)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_used_at: Optional[datetime] = None # Last time a notification was sent
|
||||
|
||||
@@ -85,19 +89,21 @@ class User(BaseModel):
|
||||
total_jobs_created: int = 0
|
||||
total_jobs_completed: int = 0
|
||||
|
||||
# Payment tracking (cached from stripe_payments, in cents)
|
||||
total_spent: int = 0
|
||||
|
||||
# Optional profile fields for future use
|
||||
display_name: Optional[str] = None
|
||||
|
||||
# Beta tester program
|
||||
is_beta_tester: bool = False
|
||||
beta_tester_status: Optional[BetaTesterStatus] = None
|
||||
beta_enrolled_at: Optional[datetime] = None
|
||||
beta_promise_text: Optional[str] = None # User's promise statement
|
||||
beta_feedback_due_at: Optional[datetime] = None # 24hr after job completion
|
||||
beta_feedback_email_sent: bool = False
|
||||
|
||||
# Push notification subscriptions (Web Push API)
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
|
||||
# Feedback-for-credits program
|
||||
has_submitted_feedback: bool = False
|
||||
|
||||
|
||||
class MagicLinkToken(BaseModel):
|
||||
"""
|
||||
@@ -168,7 +174,6 @@ class VerifyMagicLinkResponse(BaseModel):
|
||||
session_token: str
|
||||
user: "UserPublic"
|
||||
message: str
|
||||
tenant_subdomain: Optional[str] = None
|
||||
|
||||
|
||||
class UserPublic(BaseModel):
|
||||
@@ -180,10 +185,6 @@ class UserPublic(BaseModel):
|
||||
total_jobs_created: int = 0
|
||||
total_jobs_completed: int = 0
|
||||
tenant_id: Optional[str] = None
|
||||
feedback_eligible: bool = False
|
||||
total_spent: int = 0
|
||||
created_at: Optional[str] = None
|
||||
last_login_at: Optional[str] = None
|
||||
|
||||
|
||||
class AddCreditsRequest(BaseModel):
|
||||
@@ -209,18 +210,18 @@ class UserListResponse(BaseModel):
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# User Feedback-for-Credits Models
|
||||
# Beta Tester Program Models
|
||||
# ============================================================================
|
||||
|
||||
class UserFeedback(BaseModel):
|
||||
class BetaTesterFeedback(BaseModel):
|
||||
"""
|
||||
Feedback from any user (not just beta testers).
|
||||
Feedback from a beta tester after using the service.
|
||||
|
||||
Stored in Firestore 'user_feedback' collection.
|
||||
Users earn 2 free credits for submitting detailed feedback.
|
||||
Stored in Firestore 'beta_feedback' collection.
|
||||
"""
|
||||
id: str
|
||||
id: str # Unique feedback ID
|
||||
user_email: str
|
||||
job_id: Optional[str] = None # The job they're providing feedback on
|
||||
|
||||
# Ratings (1-5 scale)
|
||||
overall_rating: int = Field(ge=1, le=5)
|
||||
@@ -239,11 +240,33 @@ class UserFeedback(BaseModel):
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
submitted_via: str = "web"
|
||||
submitted_via: str = "web" # 'web' or 'email'
|
||||
|
||||
|
||||
class UserFeedbackRequest(BaseModel):
|
||||
"""Request to submit user feedback for credits."""
|
||||
class BetaTesterEnrollRequest(BaseModel):
|
||||
"""Request to enroll as a beta tester."""
|
||||
email: str
|
||||
promise_text: str = Field(
|
||||
min_length=10,
|
||||
description="User's promise to provide feedback (min 10 chars)"
|
||||
)
|
||||
accept_corrections_work: bool = Field(
|
||||
description="User accepts they may need to review/correct lyrics"
|
||||
)
|
||||
|
||||
|
||||
class BetaTesterEnrollResponse(BaseModel):
|
||||
"""Response after enrolling as beta tester."""
|
||||
status: str
|
||||
message: str
|
||||
credits_granted: int
|
||||
session_token: Optional[str] = None # If new user, provide session
|
||||
|
||||
|
||||
class BetaFeedbackRequest(BaseModel):
|
||||
"""Request to submit beta tester feedback."""
|
||||
job_id: Optional[str] = None
|
||||
|
||||
# Ratings (1-5 scale)
|
||||
overall_rating: int = Field(ge=1, le=5)
|
||||
ease_of_use_rating: int = Field(ge=1, le=5)
|
||||
@@ -260,16 +283,8 @@ class UserFeedbackRequest(BaseModel):
|
||||
would_use_again: bool = True
|
||||
|
||||
|
||||
class UserFeedbackResponse(BaseModel):
|
||||
"""Response after submitting user feedback."""
|
||||
class BetaFeedbackResponse(BaseModel):
|
||||
"""Response after submitting feedback."""
|
||||
status: str
|
||||
message: str
|
||||
credits_granted: int = 0
|
||||
|
||||
|
||||
class FeedbackEligibilityResponse(BaseModel):
|
||||
"""Response for feedback eligibility check."""
|
||||
eligible: bool
|
||||
has_submitted: bool
|
||||
jobs_completed: int
|
||||
credits_reward: int = 2
|
||||
bonus_credits: int = 0 # Bonus credits for great feedback
|
||||
@@ -1,265 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate a Mermaid state diagram from the job state machine.
|
||||
|
||||
This script reads the STATE_TRANSITIONS dictionary from models/job.py
|
||||
and generates a Mermaid diagram that can be embedded in documentation.
|
||||
|
||||
Usage:
|
||||
python scripts/generate_state_diagram.py > docs/state-machine.mmd
|
||||
# Or to update ARCHITECTURE.md directly:
|
||||
python scripts/generate_state_diagram.py --update-docs
|
||||
|
||||
Created as part of state machine robustness improvements (2026-02-02).
|
||||
"""
|
||||
import sys
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
# Add backend to path for imports
|
||||
backend_dir = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(backend_dir))
|
||||
|
||||
# Import the state machine data
|
||||
# Note: Must be run from an environment where karaoke_gen is installed
|
||||
try:
|
||||
from models.job import STATE_TRANSITIONS, JobStatus
|
||||
except ImportError:
|
||||
# Fallback: define the state machine inline for documentation purposes
|
||||
from enum import Enum
|
||||
|
||||
class JobStatus(str, Enum):
|
||||
PENDING = "pending"
|
||||
SEARCHING_AUDIO = "searching_audio"
|
||||
AWAITING_AUDIO_SELECTION = "awaiting_audio_selection"
|
||||
DOWNLOADING_AUDIO = "downloading_audio"
|
||||
DOWNLOADING = "downloading"
|
||||
SEPARATING_STAGE1 = "separating_stage1"
|
||||
SEPARATING_STAGE2 = "separating_stage2"
|
||||
AUDIO_COMPLETE = "audio_complete"
|
||||
TRANSCRIBING = "transcribing"
|
||||
CORRECTING = "correcting"
|
||||
LYRICS_COMPLETE = "lyrics_complete"
|
||||
GENERATING_SCREENS = "generating_screens"
|
||||
APPLYING_PADDING = "applying_padding"
|
||||
AWAITING_REVIEW = "awaiting_review"
|
||||
IN_REVIEW = "in_review"
|
||||
REVIEW_COMPLETE = "review_complete"
|
||||
RENDERING_VIDEO = "rendering_video"
|
||||
AWAITING_INSTRUMENTAL_SELECTION = "awaiting_instrumental_selection"
|
||||
INSTRUMENTAL_SELECTED = "instrumental_selected"
|
||||
GENERATING_VIDEO = "generating_video"
|
||||
ENCODING = "encoding"
|
||||
PACKAGING = "packaging"
|
||||
UPLOADING = "uploading"
|
||||
NOTIFYING = "notifying"
|
||||
COMPLETE = "complete"
|
||||
PREP_COMPLETE = "prep_complete"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
ERROR = "error"
|
||||
READY_FOR_FINALIZATION = "ready_for_finalization"
|
||||
FINALIZING = "finalizing"
|
||||
|
||||
STATE_TRANSITIONS = {
|
||||
JobStatus.PENDING: [JobStatus.DOWNLOADING, JobStatus.SEARCHING_AUDIO, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
|
||||
JobStatus.SEPARATING_STAGE2: [JobStatus.AUDIO_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.AUDIO_COMPLETE: [JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
JobStatus.TRANSCRIBING: [JobStatus.CORRECTING, JobStatus.FAILED],
|
||||
JobStatus.CORRECTING: [JobStatus.LYRICS_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.LYRICS_COMPLETE: [JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
JobStatus.GENERATING_SCREENS: [JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
JobStatus.APPLYING_PADDING: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_REVIEW: [JobStatus.IN_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_REVIEW: [JobStatus.REVIEW_COMPLETE, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
JobStatus.REVIEW_COMPLETE: [JobStatus.RENDERING_VIDEO, JobStatus.FAILED],
|
||||
JobStatus.RENDERING_VIDEO: [JobStatus.INSTRUMENTAL_SELECTED, JobStatus.FAILED],
|
||||
JobStatus.INSTRUMENTAL_SELECTED: [JobStatus.GENERATING_VIDEO, JobStatus.FAILED],
|
||||
JobStatus.GENERATING_VIDEO: [JobStatus.ENCODING, JobStatus.FAILED],
|
||||
JobStatus.ENCODING: [JobStatus.PACKAGING, JobStatus.COMPLETE, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.PACKAGING: [JobStatus.UPLOADING, JobStatus.COMPLETE, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
}
|
||||
|
||||
|
||||
def generate_mermaid() -> str:
|
||||
"""
|
||||
Generate a Mermaid state diagram from STATE_TRANSITIONS.
|
||||
|
||||
Returns:
|
||||
Mermaid diagram as a string
|
||||
"""
|
||||
lines = ["stateDiagram-v2"]
|
||||
lines.append(" direction TB")
|
||||
lines.append("")
|
||||
|
||||
# Group states by category for better visualization
|
||||
categories = {
|
||||
"Initial": [JobStatus.PENDING],
|
||||
"Audio Search": [
|
||||
JobStatus.SEARCHING_AUDIO,
|
||||
JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
JobStatus.DOWNLOADING_AUDIO,
|
||||
],
|
||||
"Processing": [
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.SEPARATING_STAGE1,
|
||||
JobStatus.SEPARATING_STAGE2,
|
||||
JobStatus.AUDIO_COMPLETE,
|
||||
JobStatus.TRANSCRIBING,
|
||||
JobStatus.CORRECTING,
|
||||
JobStatus.LYRICS_COMPLETE,
|
||||
],
|
||||
"Screens": [
|
||||
JobStatus.GENERATING_SCREENS,
|
||||
JobStatus.APPLYING_PADDING,
|
||||
],
|
||||
"Review": [
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.IN_REVIEW,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
],
|
||||
"Video": [
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.GENERATING_VIDEO,
|
||||
JobStatus.ENCODING,
|
||||
JobStatus.PACKAGING,
|
||||
],
|
||||
"Distribution": [
|
||||
JobStatus.UPLOADING,
|
||||
JobStatus.NOTIFYING,
|
||||
],
|
||||
"Terminal": [
|
||||
JobStatus.COMPLETE,
|
||||
JobStatus.PREP_COMPLETE,
|
||||
JobStatus.FAILED,
|
||||
JobStatus.CANCELLED,
|
||||
],
|
||||
}
|
||||
|
||||
# Add state definitions with notes for key states
|
||||
lines.append(" %% State definitions")
|
||||
key_states = {
|
||||
JobStatus.PENDING: "Job created",
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: "⚠️ USER ACTION",
|
||||
JobStatus.AWAITING_REVIEW: "⚠️ USER ACTION",
|
||||
JobStatus.COMPLETE: "✅ Success",
|
||||
JobStatus.FAILED: "❌ Error",
|
||||
}
|
||||
|
||||
for status, note in key_states.items():
|
||||
lines.append(f" {status.value}: {status.value}")
|
||||
lines.append(f" note right of {status.value}: {note}")
|
||||
|
||||
lines.append("")
|
||||
lines.append(" %% Transitions")
|
||||
|
||||
# Generate transitions
|
||||
for from_status, to_statuses in STATE_TRANSITIONS.items():
|
||||
for to_status in to_statuses:
|
||||
# Skip deprecated statuses
|
||||
if to_status in [JobStatus.QUEUED, JobStatus.PROCESSING, JobStatus.ERROR,
|
||||
JobStatus.READY_FOR_FINALIZATION, JobStatus.FINALIZING]:
|
||||
continue
|
||||
if from_status in [JobStatus.QUEUED, JobStatus.PROCESSING, JobStatus.ERROR,
|
||||
JobStatus.READY_FOR_FINALIZATION, JobStatus.FINALIZING]:
|
||||
continue
|
||||
|
||||
lines.append(f" {from_status.value} --> {to_status.value}")
|
||||
|
||||
# Add start and end markers
|
||||
lines.append("")
|
||||
lines.append(" %% Start and end")
|
||||
lines.append(" [*] --> pending")
|
||||
lines.append(" complete --> [*]")
|
||||
lines.append(" prep_complete --> [*]")
|
||||
lines.append(" failed --> [*]")
|
||||
lines.append(" cancelled --> [*]")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_markdown_section() -> str:
|
||||
"""
|
||||
Generate a markdown section with the state diagram.
|
||||
|
||||
Returns:
|
||||
Markdown string with the diagram
|
||||
"""
|
||||
diagram = generate_mermaid()
|
||||
|
||||
return f"""## Job State Machine
|
||||
|
||||
The following diagram shows all valid state transitions for a karaoke generation job.
|
||||
|
||||
Key states:
|
||||
- **PENDING**: Initial state when job is created
|
||||
- **AWAITING_AUDIO_SELECTION**: Human selects audio source (for artist+title search)
|
||||
- **AWAITING_REVIEW**: Human reviews lyrics and selects instrumental
|
||||
- **COMPLETE**: All processing finished successfully
|
||||
|
||||
```mermaid
|
||||
{diagram}
|
||||
```
|
||||
|
||||
### Parallel Processing
|
||||
|
||||
Jobs use parallel processing for audio separation and lyrics transcription:
|
||||
|
||||
1. **DOWNLOADING** triggers both:
|
||||
- Audio worker → SEPARATING_STAGE1 → SEPARATING_STAGE2 → AUDIO_COMPLETE
|
||||
- Lyrics worker → TRANSCRIBING → CORRECTING → LYRICS_COMPLETE
|
||||
|
||||
2. When BOTH complete, the screens worker is triggered automatically.
|
||||
|
||||
### Human Review Points
|
||||
|
||||
Jobs wait for human input at these points:
|
||||
- **AWAITING_AUDIO_SELECTION**: User selects audio source from search results
|
||||
- **AWAITING_REVIEW**: User reviews/corrects lyrics AND selects instrumental
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Any state can transition to **FAILED** on unrecoverable errors
|
||||
- **CANCELLED** is set when user cancels the job
|
||||
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate state machine diagram")
|
||||
parser.add_argument(
|
||||
"--update-docs",
|
||||
action="store_true",
|
||||
help="Update ARCHITECTURE.md with the diagram"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--markdown",
|
||||
action="store_true",
|
||||
help="Output markdown section instead of raw Mermaid"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.update_docs:
|
||||
# TODO: Implement auto-update of ARCHITECTURE.md
|
||||
print("Auto-update of ARCHITECTURE.md not yet implemented")
|
||||
print("Please copy the output below to the appropriate section:")
|
||||
print()
|
||||
print(generate_markdown_section())
|
||||
elif args.markdown:
|
||||
print(generate_markdown_section())
|
||||
else:
|
||||
print(generate_mermaid())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -204,9 +204,7 @@ class AudioSearchService:
|
||||
provider=item.get("provider", "Unknown"),
|
||||
duration=item.get("duration_seconds"),
|
||||
quality=item.get("quality", ""),
|
||||
# source_id: use explicit source_id field first (YouTube video ID, Spotify track ID),
|
||||
# fall back to info_hash for torrent sources (RED/OPS)
|
||||
source_id=item.get("source_id") or item.get("info_hash"),
|
||||
source_id=item.get("info_hash"),
|
||||
index=item.get("index", 0),
|
||||
seeders=item.get("seeders"),
|
||||
target_file=item.get("target_file"),
|
||||
@@ -612,13 +610,13 @@ class AudioSearchService:
|
||||
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
|
||||
"""
|
||||
Async version of search for use in async routes.
|
||||
|
||||
Runs the sync search in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
|
||||
Note: Currently wraps sync search in executor. Future optimization
|
||||
could make this fully async.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(None, self.search, artist, title)
|
||||
|
||||
|
||||
async def download_async(
|
||||
self,
|
||||
result_index: int,
|
||||
@@ -630,10 +628,10 @@ class AudioSearchService:
|
||||
"""
|
||||
Async version of download for use in async routes.
|
||||
|
||||
Runs the sync download in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
Note: Currently wraps sync download in executor. Future optimization
|
||||
could make this fully async.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
|
||||
@@ -651,11 +649,8 @@ class AudioSearchService:
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Async version of download_by_id for use in async routes.
|
||||
|
||||
Runs the sync download_by_id in a thread executor to avoid blocking
|
||||
the event loop.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download_by_id(
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
"""
|
||||
Audio transcoding service for review UI optimization.
|
||||
|
||||
Transcodes FLAC audio files to OGG Opus for efficient browser playback.
|
||||
Original FLAC files are never modified — transcoded versions are cached
|
||||
in GCS at jobs/{job_id}/review-audio/{filename}.ogg.
|
||||
|
||||
Eager transcoding: called from screens_worker before AWAITING_REVIEW
|
||||
so all files are cached before the user opens the review UI.
|
||||
Falls back to original FLAC signed URLs if transcoded version is missing.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AudioTranscodingService:
|
||||
"""
|
||||
Transcodes audio files to OGG Opus and caches them in GCS.
|
||||
|
||||
Used by the review UI to serve ~3 MB OGG files instead of 35+ MB FLACs.
|
||||
"""
|
||||
|
||||
def __init__(self, storage_service: Optional[StorageService] = None):
|
||||
self.storage = storage_service or StorageService()
|
||||
|
||||
def _get_cache_path(self, source_gcs_path: str) -> str:
|
||||
"""
|
||||
Derive the cache path for a transcoded file.
|
||||
|
||||
Examples:
|
||||
jobs/abc123/input/song.flac -> jobs/abc123/review-audio/song.ogg
|
||||
jobs/abc123/stems/instrumental_clean.flac -> jobs/abc123/review-audio/instrumental_clean.ogg
|
||||
"""
|
||||
parts = Path(source_gcs_path).parts
|
||||
# Find "jobs/{job_id}" prefix
|
||||
try:
|
||||
jobs_idx = list(parts).index("jobs")
|
||||
job_id = parts[jobs_idx + 1]
|
||||
except (ValueError, IndexError):
|
||||
# Fallback: use a hash of the full path to avoid collisions
|
||||
job_id = "_" + hashlib.sha256(source_gcs_path.encode()).hexdigest()[:12]
|
||||
|
||||
filename = Path(source_gcs_path).stem + ".ogg"
|
||||
return f"jobs/{job_id}/review-audio/{filename}"
|
||||
|
||||
def _transcode_and_upload(self, source_gcs_path: str, cache_path: str) -> str:
|
||||
"""
|
||||
Download FLAC from GCS, transcode to OGG Opus, upload to cache path.
|
||||
|
||||
Returns the cache GCS path on success.
|
||||
Raises on failure.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_input = os.path.join(temp_dir, "input.flac")
|
||||
local_output = os.path.join(temp_dir, "output.ogg")
|
||||
|
||||
# Download source
|
||||
self.storage.download_file(source_gcs_path, local_input)
|
||||
|
||||
# Transcode: FLAC -> OGG Opus 128kbps
|
||||
cmd = [
|
||||
"ffmpeg", "-hide_banner", "-loglevel", "error",
|
||||
"-y",
|
||||
"-i", local_input,
|
||||
"-c:a", "libopus",
|
||||
"-b:a", "128k",
|
||||
"-vn",
|
||||
local_output,
|
||||
]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"ffmpeg transcoding failed (exit {result.returncode}): {result.stderr}"
|
||||
)
|
||||
|
||||
# Upload transcoded file
|
||||
self.storage.upload_file(local_output, cache_path)
|
||||
|
||||
return cache_path
|
||||
|
||||
def transcode_if_needed(self, source_gcs_path: str) -> str:
|
||||
"""
|
||||
Return the GCS path of the transcoded OGG file, transcoding if not cached.
|
||||
|
||||
Returns the cache path (always an OGG file in review-audio/).
|
||||
Raises if transcoding fails.
|
||||
"""
|
||||
cache_path = self._get_cache_path(source_gcs_path)
|
||||
|
||||
if self.storage.file_exists(cache_path):
|
||||
logger.debug(f"Cache hit: {cache_path}")
|
||||
return cache_path
|
||||
|
||||
logger.info(f"Cache miss, transcoding: {source_gcs_path} -> {cache_path}")
|
||||
return self._transcode_and_upload(source_gcs_path, cache_path)
|
||||
|
||||
def get_review_audio_url(
|
||||
self, source_gcs_path: str, expiration_minutes: int = 120
|
||||
) -> str:
|
||||
"""
|
||||
Get a signed URL for the transcoded audio, falling back to original FLAC.
|
||||
"""
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_gcs_path)
|
||||
return self.storage.generate_signed_url(cache_path, expiration_minutes)
|
||||
except Exception as e:
|
||||
# Source may be deleted but cache from earlier transcode persists
|
||||
try:
|
||||
cache_path = self._get_cache_path(source_gcs_path)
|
||||
if self.storage.file_exists(cache_path):
|
||||
logger.info(f"Source gone but cache exists, serving: {cache_path}")
|
||||
return self.storage.generate_signed_url(cache_path, expiration_minutes)
|
||||
except Exception:
|
||||
pass # Fall through to FLAC fallback below
|
||||
logger.warning(
|
||||
f"Transcoding failed for {source_gcs_path}, falling back to FLAC: {e}"
|
||||
)
|
||||
return self.storage.generate_signed_url(source_gcs_path, expiration_minutes)
|
||||
|
||||
async def get_review_audio_url_async(
|
||||
self, source_gcs_path: str, expiration_minutes: int = 120
|
||||
) -> str:
|
||||
"""Async wrapper around get_review_audio_url via asyncio.to_thread."""
|
||||
return await asyncio.to_thread(
|
||||
self.get_review_audio_url, source_gcs_path, expiration_minutes
|
||||
)
|
||||
|
||||
def prepare_review_audio_for_job(self, job) -> list[str]:
|
||||
"""
|
||||
Transcode all review audio files for a job (eager transcoding).
|
||||
|
||||
Called from screens_worker before AWAITING_REVIEW transition
|
||||
and from the admin backfill endpoint.
|
||||
|
||||
Returns list of cache paths that were transcoded.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
transcoded = []
|
||||
|
||||
# Collect all audio paths to transcode
|
||||
paths_to_transcode = []
|
||||
|
||||
# Main input audio
|
||||
if job.input_media_gcs_path:
|
||||
paths_to_transcode.append(("input", job.input_media_gcs_path))
|
||||
|
||||
# Stems
|
||||
stems = job.file_urls.get("stems", {})
|
||||
for stem_key in ["instrumental_clean", "instrumental_with_backing", "backing_vocals"]:
|
||||
path = stems.get(stem_key)
|
||||
if path:
|
||||
paths_to_transcode.append((stem_key, path))
|
||||
|
||||
for label, source_path in paths_to_transcode:
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_path)
|
||||
transcoded.append(cache_path)
|
||||
logger.info(f"[{job_id}] Transcoded {label}: {cache_path}")
|
||||
except Exception as e:
|
||||
# Non-fatal: review UI will fall back to FLAC
|
||||
logger.warning(
|
||||
f"[{job_id}] Failed to transcode {label} ({source_path}): {e}"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[{job_id}] Review audio preparation complete: "
|
||||
f"{len(transcoded)}/{len(paths_to_transcode)} files transcoded"
|
||||
)
|
||||
return transcoded
|
||||
@@ -49,7 +49,6 @@ class AuthResult:
|
||||
user_email: Optional[str] = None # Email if authenticated via session/API key
|
||||
is_admin: bool = False # True if admin token or admin email domain
|
||||
api_key_id: Optional[str] = None # API key ID if authenticated via API key
|
||||
tenant_id: Optional[str] = None # Tenant scope from token or session
|
||||
|
||||
def __iter__(self):
|
||||
"""Allow unpacking as tuple for backward compatibility."""
|
||||
@@ -285,7 +284,6 @@ class AuthService:
|
||||
# All auth_tokens must have an associated user_email for job ownership
|
||||
token_user_email = token_data.get("user_email")
|
||||
api_key_id = token_data.get("api_key_id")
|
||||
token_tenant_id = token_data.get("tenant_id")
|
||||
|
||||
# Require user_email on all auth_tokens (no anonymous token auth)
|
||||
if not token_user_email:
|
||||
@@ -309,8 +307,7 @@ class AuthService:
|
||||
message="Unlimited access granted",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
# LIMITED tokens: check usage count
|
||||
@@ -323,8 +320,7 @@ class AuthService:
|
||||
message="Limited token with unlimited uses",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
current_uses = token_data.get("usage_count", 0)
|
||||
@@ -337,8 +333,7 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="Token usage limit exceeded",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -348,8 +343,7 @@ class AuthService:
|
||||
message=f"Limited token: {remaining} uses remaining",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
# STRIPE tokens: check expiration and usage
|
||||
@@ -363,8 +357,7 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="Token has expired",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
if max_uses > 0:
|
||||
@@ -378,8 +371,7 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="Token usage limit exceeded",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -389,8 +381,7 @@ class AuthService:
|
||||
message=f"Stripe token: {remaining} uses remaining",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -400,8 +391,7 @@ class AuthService:
|
||||
message="Stripe access granted",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
# API_KEY tokens
|
||||
@@ -416,8 +406,7 @@ class AuthService:
|
||||
remaining_uses=0,
|
||||
message="API key usage limit exceeded",
|
||||
user_email=token_user_email,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
@@ -426,8 +415,7 @@ class AuthService:
|
||||
message=f"API key valid: {remaining} uses remaining",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -437,8 +425,7 @@ class AuthService:
|
||||
message="API key access granted",
|
||||
user_email=token_user_email,
|
||||
is_admin=token_is_admin,
|
||||
api_key_id=api_key_id,
|
||||
tenant_id=token_tenant_id
|
||||
api_key_id=api_key_id
|
||||
)
|
||||
|
||||
return AuthResult(
|
||||
@@ -450,11 +437,10 @@ class AuthService:
|
||||
|
||||
def increment_token_usage(self, token: str, job_id: str) -> bool:
|
||||
"""
|
||||
Increment usage count for an auth_token and track the job.
|
||||
Increment usage count for a token and track the job.
|
||||
|
||||
Note: Credit deduction for session-based users is handled in
|
||||
JobManager.create_job(), not here. This method only tracks usage
|
||||
for legacy auth_tokens stored in Firestore.
|
||||
For session tokens (magic link auth), this deducts a credit from the user.
|
||||
For auth_tokens, this increments the usage count.
|
||||
|
||||
Args:
|
||||
token: The access token
|
||||
@@ -479,11 +465,32 @@ class AuthService:
|
||||
if token in self.admin_tokens:
|
||||
return True
|
||||
|
||||
# Only increment usage for auth_tokens in Firestore
|
||||
# Session tokens (magic link auth) have credits managed by JobManager.create_job()
|
||||
# Check if this is a session token (STRIPE type from validate_token means it's a session)
|
||||
# Session tokens are not in auth_tokens collection
|
||||
token_data = self.firestore.get_token(token)
|
||||
|
||||
if not token_data:
|
||||
return True
|
||||
# This is a session token - deduct credit from user
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
|
||||
# Get the user email from the session
|
||||
is_valid, user, _ = user_service.validate_session(token)
|
||||
if not is_valid or not user:
|
||||
logger.error(f"Session token validation failed during usage increment")
|
||||
return False
|
||||
|
||||
# Deduct one credit
|
||||
success, new_balance, deduct_message = user_service.deduct_credit(
|
||||
user.email, job_id, reason="job_creation"
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info(f"Deducted credit for user {user.email} (remaining: {new_balance})")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Failed to deduct credit for user {user.email}: {deduct_message}")
|
||||
return False
|
||||
|
||||
# Regular auth_token - increment usage in Firestore
|
||||
try:
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
"""
|
||||
Brand code allocation service using Firestore atomic counters.
|
||||
|
||||
Replaces the previous Dropbox folder-scanning approach which was susceptible to
|
||||
TOCTOU race conditions when concurrent jobs read the same folder state.
|
||||
|
||||
Uses Firestore transactions to atomically allocate unique brand codes.
|
||||
Supports recycling numbers when E2E cleanup deletes test brand codes.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BRAND_CODE_COUNTERS_COLLECTION = "brand_code_counters"
|
||||
|
||||
# Singleton instance
|
||||
_brand_code_service: Optional["BrandCodeService"] = None
|
||||
|
||||
|
||||
class BrandCodeService:
|
||||
"""Atomic brand code allocation using Firestore counters."""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def allocate_brand_code(self, prefix: str, dropbox_path: str) -> str:
|
||||
"""
|
||||
Atomically allocate the next brand code for a given prefix.
|
||||
|
||||
Uses a Firestore transaction to ensure no two concurrent callers
|
||||
receive the same number. If recycled numbers are available (from
|
||||
E2E cleanup), the smallest recycled number is reused first.
|
||||
|
||||
On first use for a prefix, initializes the counter by scanning
|
||||
Dropbox to find the current max number.
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix (e.g., "NOMAD" or "NOMADNP")
|
||||
dropbox_path: Dropbox path for one-time initialization scan
|
||||
|
||||
Returns:
|
||||
Brand code string (e.g., "NOMAD-1264")
|
||||
"""
|
||||
doc_ref = self.db.collection(BRAND_CODE_COUNTERS_COLLECTION).document(prefix)
|
||||
|
||||
@firestore.transactional
|
||||
def allocate_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
# First use — initialize from Dropbox scan
|
||||
next_number = self._get_initial_next_number(prefix, dropbox_path)
|
||||
allocated = next_number
|
||||
transaction.set(doc_ref, {
|
||||
"prefix": prefix,
|
||||
"next_number": next_number + 1,
|
||||
"recycled": [],
|
||||
"initialized_at": datetime.now(timezone.utc),
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
return allocated
|
||||
|
||||
data = doc.to_dict()
|
||||
recycled = data.get("recycled", [])
|
||||
|
||||
if recycled:
|
||||
# Reuse smallest recycled number
|
||||
recycled.sort()
|
||||
allocated = recycled.pop(0)
|
||||
transaction.update(doc_ref, {
|
||||
"recycled": recycled,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
else:
|
||||
# Allocate next sequential number
|
||||
allocated = data["next_number"]
|
||||
transaction.update(doc_ref, {
|
||||
"next_number": allocated + 1,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
return allocated
|
||||
|
||||
transaction = self.db.transaction()
|
||||
number = allocate_in_transaction(transaction)
|
||||
brand_code = f"{prefix}-{number:04d}"
|
||||
logger.info(f"Allocated brand code: {brand_code}")
|
||||
return brand_code
|
||||
|
||||
def recycle_brand_code(self, prefix: str, number: int) -> None:
|
||||
"""
|
||||
Return a brand code number to the recycled pool.
|
||||
|
||||
Called when E2E cleanup deletes a brand code's distribution.
|
||||
The number will be reused on the next allocation for this prefix.
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix (e.g., "NOMAD")
|
||||
number: The numeric portion to recycle (e.g., 1234)
|
||||
"""
|
||||
doc_ref = self.db.collection(BRAND_CODE_COUNTERS_COLLECTION).document(prefix)
|
||||
|
||||
@firestore.transactional
|
||||
def recycle_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
# Counter doesn't exist yet — nothing to recycle into.
|
||||
# The number will naturally be below next_number when
|
||||
# the counter is initialized, so it would create a gap.
|
||||
# Just log and skip.
|
||||
logger.warning(
|
||||
f"Cannot recycle {prefix}-{number:04d}: counter doc doesn't exist"
|
||||
)
|
||||
return
|
||||
|
||||
data = doc.to_dict()
|
||||
next_number = data.get("next_number", 0)
|
||||
|
||||
if number <= 0 or number >= next_number:
|
||||
logger.warning(
|
||||
f"Cannot recycle {prefix}-{number:04d}: "
|
||||
f"invalid (next_number={next_number})"
|
||||
)
|
||||
return
|
||||
|
||||
recycled = data.get("recycled", [])
|
||||
|
||||
if number not in recycled:
|
||||
recycled.append(number)
|
||||
transaction.update(doc_ref, {
|
||||
"recycled": recycled,
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
})
|
||||
logger.info(f"Recycled brand code number: {prefix}-{number:04d}")
|
||||
else:
|
||||
logger.warning(f"Number {number} already in recycled pool for {prefix}")
|
||||
|
||||
transaction = self.db.transaction()
|
||||
recycle_in_transaction(transaction)
|
||||
|
||||
def _get_initial_next_number(self, prefix: str, dropbox_path: str) -> int:
|
||||
"""
|
||||
Scan Dropbox once to determine the starting next_number.
|
||||
|
||||
This is only called when the counter document doesn't exist yet
|
||||
(one-time migration from the old Dropbox-scanning approach).
|
||||
|
||||
Args:
|
||||
prefix: Brand prefix to scan for
|
||||
dropbox_path: Dropbox path containing organized folders
|
||||
|
||||
Returns:
|
||||
The next number to allocate (max existing + 1, minimum 1)
|
||||
"""
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
logger.warning(
|
||||
f"Dropbox not configured for initialization of {prefix} counter, starting at 1"
|
||||
)
|
||||
return 1
|
||||
|
||||
folders = dropbox.list_folders(dropbox_path)
|
||||
pattern = re.compile(rf"^{re.escape(prefix)}-(\d{{4}})")
|
||||
|
||||
existing_nums: set[int] = set()
|
||||
for folder in folders:
|
||||
match = pattern.match(folder)
|
||||
if match:
|
||||
existing_nums.add(int(match.group(1)))
|
||||
|
||||
if existing_nums:
|
||||
next_num = max(existing_nums) + 1
|
||||
logger.info(
|
||||
f"Initialized {prefix} counter from Dropbox: "
|
||||
f"max existing={max(existing_nums)}, next_number={next_num}"
|
||||
)
|
||||
return next_num
|
||||
|
||||
logger.info(f"No existing {prefix} codes found in Dropbox, starting at 1")
|
||||
return 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize {prefix} counter from Dropbox: {e}")
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def parse_brand_code(brand_code: str) -> tuple[str, int]:
|
||||
"""
|
||||
Parse a brand code string into prefix and number.
|
||||
|
||||
Args:
|
||||
brand_code: e.g., "NOMAD-1234" or "NOMADNP-0012"
|
||||
|
||||
Returns:
|
||||
Tuple of (prefix, number), e.g., ("NOMAD", 1234)
|
||||
|
||||
Raises:
|
||||
ValueError: If brand_code doesn't match expected format
|
||||
"""
|
||||
match = re.match(r"^([A-Z]+)-(\d+)$", brand_code)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid brand code format: {brand_code}")
|
||||
return match.group(1), int(match.group(2))
|
||||
|
||||
|
||||
def get_brand_code_service() -> BrandCodeService:
|
||||
"""Get or create the singleton BrandCodeService instance."""
|
||||
global _brand_code_service
|
||||
if _brand_code_service is None:
|
||||
_brand_code_service = BrandCodeService()
|
||||
return _brand_code_service
|
||||
@@ -1,105 +0,0 @@
|
||||
"""
|
||||
Proxy service for karaoke-decide catalog API.
|
||||
|
||||
Forwards artist and track search requests to the karaoke-decide backend,
|
||||
providing autocomplete data from MusicBrainz + Spotify catalogs.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 300 # 5 minutes
|
||||
|
||||
KARAOKE_DECIDE_BASE_URL = "https://decide.nomadkaraoke.com"
|
||||
REQUEST_TIMEOUT = 10 # seconds
|
||||
|
||||
|
||||
def _get_base_url() -> str:
|
||||
"""Get the karaoke-decide API base URL from config or default."""
|
||||
return getattr(settings, "karaoke_decide_api_url", None) or KARAOKE_DECIDE_BASE_URL
|
||||
|
||||
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
|
||||
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
|
||||
|
||||
async def search_artists(query: str, limit: int = 10) -> list[dict]:
|
||||
"""
|
||||
Search for artists via karaoke-decide catalog API.
|
||||
|
||||
Returns list of artist dicts with canonical MusicBrainz names.
|
||||
Falls back to empty list on any error.
|
||||
"""
|
||||
cache_key = f"artists:{query.lower()}:{limit}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
base_url = _get_base_url()
|
||||
url = f"{base_url}/api/catalog/artists"
|
||||
params = {"q": query, "limit": limit}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
# karaoke-decide wraps results: {"artists": [...], "total": N}
|
||||
results = data.get("artists", data) if isinstance(data, dict) else data
|
||||
_cache_set(cache_key, results)
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to search artists from karaoke-decide: {e}")
|
||||
return []
|
||||
|
||||
|
||||
async def search_tracks(query: str, artist: str | None = None, limit: int = 10) -> list[dict]:
|
||||
"""
|
||||
Search for tracks via karaoke-decide catalog API.
|
||||
|
||||
Returns list of track dicts with canonical Spotify/MusicBrainz names.
|
||||
Falls back to empty list on any error.
|
||||
"""
|
||||
cache_key = f"tracks:{query.lower()}:{(artist or '').lower()}:{limit}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
base_url = _get_base_url()
|
||||
url = f"{base_url}/api/catalog/tracks"
|
||||
params: dict[str, Any] = {"q": query, "limit": limit}
|
||||
if artist:
|
||||
params["artist"] = artist
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
# karaoke-decide wraps results: {"tracks": [...], "total": N}
|
||||
results = data.get("tracks", data) if isinstance(data, dict) else data
|
||||
_cache_set(cache_key, results)
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to search tracks from karaoke-decide: {e}")
|
||||
return []
|
||||
@@ -109,46 +109,30 @@ class DropboxService:
|
||||
|
||||
def get_next_brand_code(self, path: str, brand_prefix: str) -> str:
|
||||
"""
|
||||
Calculate next brand code from existing folders, filling gaps in the sequence.
|
||||
|
||||
NOTE: This method is only used for one-time initialization of the Firestore
|
||||
counter (see brand_code_service.py). All runtime brand code allocation now
|
||||
goes through BrandCodeService.allocate_brand_code() for atomic safety.
|
||||
Calculate next brand code from existing folders.
|
||||
|
||||
Scans the folder for existing brand codes like "NOMAD-0001" and
|
||||
returns the first available code, filling any gaps left by deleted outputs.
|
||||
returns the next sequential code.
|
||||
|
||||
Args:
|
||||
path: Dropbox path containing organized folders
|
||||
brand_prefix: Brand prefix (e.g., "NOMAD")
|
||||
|
||||
Returns:
|
||||
Next brand code (e.g., "NOMAD-0003" if 0003 is the first gap)
|
||||
Next brand code (e.g., "NOMAD-1164")
|
||||
"""
|
||||
folders = self.list_folders(path)
|
||||
pattern = re.compile(rf"^{re.escape(brand_prefix)}-(\d{{4}})")
|
||||
|
||||
existing_nums: set[int] = set()
|
||||
max_num = 0
|
||||
for folder in folders:
|
||||
match = pattern.match(folder)
|
||||
if match:
|
||||
existing_nums.add(int(match.group(1)))
|
||||
num = int(match.group(1))
|
||||
max_num = max(max_num, num)
|
||||
|
||||
max_existing = max(existing_nums) if existing_nums else 0
|
||||
|
||||
# Only fill gaps for numbers >= 1001 (preserve legacy gaps below 1000)
|
||||
if max_existing >= 1000:
|
||||
next_num = 1001
|
||||
while next_num in existing_nums:
|
||||
next_num += 1
|
||||
else:
|
||||
next_num = max_existing + 1
|
||||
|
||||
next_code = f"{brand_prefix}-{next_num:04d}"
|
||||
if max_existing >= 1000 and next_num <= max_existing:
|
||||
logger.info(f"Next brand code for {brand_prefix}: {next_code} (filling gap, max existing: {max_existing})")
|
||||
else:
|
||||
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
|
||||
next_code = f"{brand_prefix}-{max_num + 1:04d}"
|
||||
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_num})")
|
||||
return next_code
|
||||
|
||||
def upload_file(self, local_path: str, remote_path: str) -> None:
|
||||
|
||||
+207
-107
@@ -247,8 +247,6 @@ class EmailService:
|
||||
email: str,
|
||||
token: str,
|
||||
sender_email: Optional[str] = None,
|
||||
tenant_frontend_url: Optional[str] = None,
|
||||
tenant_name: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send a magic link email for authentication.
|
||||
@@ -257,17 +255,13 @@ class EmailService:
|
||||
email: User's email address
|
||||
token: Magic link token
|
||||
sender_email: Override sender email address (for multi-tenant)
|
||||
tenant_frontend_url: Override frontend URL for tenant portals (e.g., https://vocalstar.nomadkaraoke.com)
|
||||
tenant_name: Override brand name for tenant portals (e.g., "Vocal Star")
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
base_url = tenant_frontend_url or self.frontend_url
|
||||
magic_link_url = f"{base_url}/auth/verify?token={token}"
|
||||
magic_link_url = f"{self.frontend_url}/auth/verify?token={token}"
|
||||
|
||||
brand_name = tenant_name or "Nomad Karaoke"
|
||||
subject = f"Sign in to {brand_name}"
|
||||
subject = "Sign in to Nomad Karaoke"
|
||||
|
||||
extra_styles = """
|
||||
.warning {
|
||||
@@ -283,7 +277,7 @@ class EmailService:
|
||||
content = f"""
|
||||
<p>Hi there,</p>
|
||||
|
||||
<p>Click the button below to sign in to {html.escape(brand_name)}:</p>
|
||||
<p>Click the button below to sign in to Nomad Karaoke:</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{magic_link_url}" class="button">Sign In</a>
|
||||
@@ -304,7 +298,7 @@ class EmailService:
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = f"""
|
||||
Sign in to {brand_name}
|
||||
Sign in to Nomad Karaoke
|
||||
========================
|
||||
|
||||
Click this link to sign in:
|
||||
@@ -315,7 +309,7 @@ This link expires in 15 minutes and can only be used once.
|
||||
If you didn't request this email, you can safely ignore it.
|
||||
|
||||
---
|
||||
© {self._get_year()} {brand_name}
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self.provider.send_email(
|
||||
@@ -406,31 +400,9 @@ Start creating: {self.frontend_url}
|
||||
"""
|
||||
subject = "Welcome to Nomad Karaoke! 🎤"
|
||||
|
||||
credits_text = f"You have <strong>{credits} credits</strong> to get started!" if credits > 0 else ""
|
||||
|
||||
extra_styles = """
|
||||
.credits-box {
|
||||
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
|
||||
border: 2px solid #e2b714;
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
margin: 24px 0;
|
||||
}
|
||||
.credits-box .credits-number {
|
||||
font-size: 48px;
|
||||
font-weight: bold;
|
||||
color: #e2b714;
|
||||
line-height: 1;
|
||||
}
|
||||
.credits-box .credits-label {
|
||||
font-size: 16px;
|
||||
color: #ccc;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.credits-box .credits-note {
|
||||
font-size: 13px;
|
||||
color: #999;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.feature {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
@@ -442,22 +414,10 @@ Start creating: {self.frontend_url}
|
||||
}
|
||||
"""
|
||||
|
||||
credits_box = ""
|
||||
if credits > 0:
|
||||
credits_box = f"""
|
||||
<div class="credits-box">
|
||||
<div class="credits-number">{credits}</div>
|
||||
<div class="credits-label">Free Credits</div>
|
||||
<div class="credits-note">Each credit creates one professional karaoke video</div>
|
||||
</div>
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Welcome to Nomad Karaoke!</p>
|
||||
|
||||
<p>Turn any song into a professional karaoke video in minutes.</p>
|
||||
|
||||
{credits_box}
|
||||
<p>Turn any song into a professional karaoke video in minutes. {credits_text}</p>
|
||||
|
||||
<p><strong>Here's how it works:</strong></p>
|
||||
|
||||
@@ -493,10 +453,6 @@ Start creating: {self.frontend_url}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p style="text-align: center; font-size: 14px; color: #999; margin-top: 20px;">
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.frontend_url}" class="button">Get Started</a>
|
||||
</p>
|
||||
@@ -504,13 +460,11 @@ Start creating: {self.frontend_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
credits_text = f"\nYou have {credits} free credits to get started!\nEach credit creates one professional karaoke video.\n" if credits > 0 else ""
|
||||
|
||||
text_content = f"""
|
||||
Welcome to Nomad Karaoke!
|
||||
|
||||
Turn any song into a professional karaoke video in minutes.
|
||||
{credits_text}
|
||||
|
||||
Here's how it works:
|
||||
|
||||
1. Search for a song
|
||||
@@ -525,10 +479,206 @@ Here's how it works:
|
||||
4. Get your video
|
||||
Download your 4K karaoke video or upload directly to YouTube.
|
||||
|
||||
Complete 2 videos and earn 2 more free credits by sharing your feedback!
|
||||
|
||||
Get started: {self.frontend_url}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
|
||||
def send_beta_welcome_email(self, email: str, credits: int = 1) -> bool:
|
||||
"""
|
||||
Send welcome email to new beta testers.
|
||||
|
||||
Args:
|
||||
email: User's email address
|
||||
credits: Initial free credits granted
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
subject = "Welcome Beta Tester! Free Karaoke Credits Inside 🎤"
|
||||
|
||||
extra_styles = f"""
|
||||
.beta-badge {{
|
||||
display: inline-block;
|
||||
background: linear-gradient(135deg, {self.BRAND_PRIMARY}, {self.BRAND_SECONDARY});
|
||||
color: #333;
|
||||
padding: 4px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}}
|
||||
.credits-box {{
|
||||
background-color: #ecfdf5;
|
||||
border: 2px solid {self.BRAND_SUCCESS};
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
}}
|
||||
.credits-number {{
|
||||
font-size: 48px;
|
||||
font-weight: bold;
|
||||
color: {self.BRAND_SUCCESS};
|
||||
}}
|
||||
.reminder {{
|
||||
background-color: #fef3c7;
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
}}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Thank you for joining our beta program!</p>
|
||||
|
||||
<p>As promised, here's your free credit to create a karaoke video:</p>
|
||||
|
||||
<div class="credits-box">
|
||||
<div>Your balance:</div>
|
||||
<div class="credits-number">{credits}</div>
|
||||
<div>free credit{'' if credits == 1 else 's'}</div>
|
||||
</div>
|
||||
|
||||
<div class="reminder">
|
||||
<strong>📝 Your Promise:</strong><br>
|
||||
Remember, as a beta tester you agreed to:
|
||||
<ul style="margin: 10px 0; padding-left: 20px;">
|
||||
<li>Review and correct any lyrics transcription errors</li>
|
||||
<li>Share your honest feedback after trying the tool</li>
|
||||
</ul>
|
||||
We'll send you a quick feedback form after your job completes!
|
||||
</div>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{self.frontend_url}" class="button">Create Your Karaoke Video</a>
|
||||
</p>
|
||||
|
||||
<p>Thanks for helping us make Nomad Karaoke better!</p>
|
||||
"""
|
||||
|
||||
extra_header = '<div><span class="beta-badge">BETA TESTER</span></div>'
|
||||
html_content = self._build_email_html(content, extra_styles, extra_header)
|
||||
|
||||
text_content = f"""
|
||||
Welcome Beta Tester!
|
||||
|
||||
Thank you for joining our beta program!
|
||||
|
||||
You've been granted {credits} free credit{'' if credits == 1 else 's'} to create karaoke videos.
|
||||
|
||||
YOUR PROMISE:
|
||||
As a beta tester, you agreed to:
|
||||
- Review and correct any lyrics transcription errors
|
||||
- Share your honest feedback after trying the tool
|
||||
|
||||
We'll send you a quick feedback form after your job completes!
|
||||
|
||||
Create your karaoke video: {self.frontend_url}
|
||||
|
||||
Thanks for helping us make Nomad Karaoke better!
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
|
||||
def send_feedback_request_email(self, email: str, feedback_url: str, job_title: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Send feedback request email to beta testers.
|
||||
|
||||
Args:
|
||||
email: User's email address
|
||||
feedback_url: URL to the feedback form
|
||||
job_title: Optional title of the completed job
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
subject = "Quick feedback on your karaoke experience? 🎤"
|
||||
|
||||
# Escape job_title to prevent XSS in email clients that render HTML
|
||||
safe_job_title = html.escape(job_title) if job_title else ""
|
||||
job_context = f" for <strong>{safe_job_title}</strong>" if job_title else ""
|
||||
|
||||
extra_styles = f"""
|
||||
.feedback-box {{
|
||||
background: linear-gradient(135deg, #fff0f9, #ffe0f2);
|
||||
border: 2px solid {self.BRAND_PRIMARY};
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
}}
|
||||
.stars {{
|
||||
font-size: 36px;
|
||||
margin: 10px 0;
|
||||
}}
|
||||
.time-note {{
|
||||
background-color: #fef3c7;
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
margin: 20px 0;
|
||||
font-size: 14px;
|
||||
}}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>Hi there!</p>
|
||||
|
||||
<p>Hope you enjoyed creating your karaoke video{job_context}! As a beta tester, your feedback is super valuable to us.</p>
|
||||
|
||||
<div class="feedback-box">
|
||||
<div class="stars">⭐⭐⭐⭐⭐</div>
|
||||
<p><strong>How was your experience?</strong></p>
|
||||
<p>Quick 2-minute survey - we'd love to hear your thoughts!</p>
|
||||
</div>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{feedback_url}" class="button">Share Your Feedback</a>
|
||||
</p>
|
||||
|
||||
<div class="time-note">
|
||||
⏱️ This takes less than 2 minutes and helps us improve the tool for everyone!
|
||||
</div>
|
||||
|
||||
<p>Specifically, we'd love to know:</p>
|
||||
<ul>
|
||||
<li>How easy was it to use?</li>
|
||||
<li>Were the lyrics accurate?</li>
|
||||
<li>How was the correction experience?</li>
|
||||
<li>What could we improve?</li>
|
||||
</ul>
|
||||
|
||||
<p>Thanks for being part of making Nomad Karaoke better!</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
text_content = f"""
|
||||
Quick feedback on your karaoke experience?
|
||||
|
||||
Hi there!
|
||||
|
||||
Hope you enjoyed creating your karaoke video{' for ' + safe_job_title if safe_job_title else ''}!
|
||||
|
||||
As a beta tester, your feedback is super valuable to us.
|
||||
|
||||
Share your feedback (2-minute survey): {feedback_url}
|
||||
|
||||
We'd love to know:
|
||||
- How easy was it to use?
|
||||
- Were the lyrics accurate?
|
||||
- How was the correction experience?
|
||||
- What could we improve?
|
||||
|
||||
Thanks for being part of making Nomad Karaoke better!
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
@@ -981,56 +1131,6 @@ Get started: {self.frontend_url}
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_youtube_upload_complete(
|
||||
self,
|
||||
to_email: str,
|
||||
message_content: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send follow-up email when a deferred YouTube upload completes.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
message_content: Pre-rendered message content (plain text)
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
brand_code: Release ID for subject line
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if brand_code and safe_artist and safe_title:
|
||||
subject = f"{brand_code}: {safe_artist} - {safe_title} (YouTube upload ready!)"
|
||||
elif safe_artist and safe_title:
|
||||
subject = f"{safe_artist} - {safe_title} (YouTube upload ready!)"
|
||||
else:
|
||||
subject = "Your YouTube upload is ready!"
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=message_content,
|
||||
cc_emails=["gen@nomadkaraoke.com"],
|
||||
)
|
||||
|
||||
def send_made_for_you_order_confirmation(
|
||||
self,
|
||||
to_email: str,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Email Validation Service.
|
||||
|
||||
Provides email validation, normalization, and blocklist checking
|
||||
to prevent abuse during enrollment and other flows.
|
||||
to prevent abuse during beta enrollment and other flows.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
@@ -369,6 +369,36 @@ class EmailValidationService:
|
||||
config = self.get_blocklist_config()
|
||||
return ip_address in config["blocked_ips"]
|
||||
|
||||
def validate_email_for_beta(self, email: str) -> Tuple[bool, str]:
|
||||
"""
|
||||
Validate an email for beta enrollment.
|
||||
|
||||
Performs all validation checks:
|
||||
1. Basic format validation
|
||||
2. Disposable domain check
|
||||
3. Blocked email check
|
||||
|
||||
Args:
|
||||
email: Email address to validate
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, error_message)
|
||||
"""
|
||||
if not email or "@" not in email:
|
||||
return False, "Invalid email format"
|
||||
|
||||
# Check disposable domain
|
||||
if self.is_disposable_domain(email):
|
||||
logger.warning(f"Beta enrollment blocked - disposable domain: {_mask_email(email)}")
|
||||
return False, "Disposable email addresses are not allowed"
|
||||
|
||||
# Check blocked email
|
||||
if self.is_email_blocked(email):
|
||||
logger.warning(f"Beta enrollment blocked - email blocked: {_mask_email(email)}")
|
||||
return False, "This email address is not allowed"
|
||||
|
||||
return True, ""
|
||||
|
||||
def hash_ip(self, ip_address: str) -> str:
|
||||
"""
|
||||
Hash an IP address for privacy-preserving storage.
|
||||
|
||||
@@ -200,7 +200,6 @@ class LocalEncodingBackend(EncodingBackend):
|
||||
output_lossy_4k_mp4=os.path.join(output_dir, f"{base_name} (Final Karaoke Lossy 4k).mp4"),
|
||||
output_lossless_mkv=os.path.join(output_dir, f"{base_name} (Final Karaoke Lossless 4k).mkv"),
|
||||
output_720p_mp4=os.path.join(output_dir, f"{base_name} (Final Karaoke Lossy 720p).mp4"),
|
||||
countdown_padding_seconds=input_config.options.get("countdown_padding_seconds"),
|
||||
)
|
||||
|
||||
# Run encoding in thread pool to avoid blocking
|
||||
@@ -335,12 +334,6 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
"instrumental_selection": input_config.instrumental_selection,
|
||||
}
|
||||
|
||||
# Add countdown padding if present (for audio sync with countdown-padded vocals)
|
||||
countdown_padding = input_config.options.get("countdown_padding_seconds")
|
||||
if countdown_padding:
|
||||
encoding_config["countdown_padding_seconds"] = countdown_padding
|
||||
self.logger.info(f"GCE encoding with countdown_padding_seconds={countdown_padding}")
|
||||
|
||||
# Submit and wait for completion
|
||||
result = await service.encode_videos(
|
||||
job_id=job_id,
|
||||
|
||||
@@ -25,23 +25,10 @@ from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Retry configuration for handling transient failures (e.g., worker restarts during deployments).
|
||||
#
|
||||
# During a CI deployment, the encoding worker is restarted via systemctl. The restart
|
||||
# involves downloading a new wheel from GCS, installing it, and starting uvicorn —
|
||||
# which can take 30-90 seconds. The retry window must exceed this to avoid failing
|
||||
# jobs that happen to hit the encoding stage during a deploy.
|
||||
#
|
||||
# With 7 retries and exponential backoff (5s, 10s, 15s, 15s, 15s, 15s, 15s),
|
||||
# total retry window is ~90s, sufficient to survive a full worker restart.
|
||||
MAX_RETRIES = 7
|
||||
INITIAL_BACKOFF_SECONDS = 5.0
|
||||
MAX_BACKOFF_SECONDS = 15.0
|
||||
|
||||
# Poll failure tolerance: number of consecutive poll failures allowed before giving up.
|
||||
# This prevents a single transient network blip during status polling from killing a
|
||||
# long-running encoding job. Similar pattern to flacfetch status polling (PR #446).
|
||||
MAX_CONSECUTIVE_POLL_FAILURES = 5
|
||||
# Retry configuration for handling transient failures (e.g., worker restarts)
|
||||
MAX_RETRIES = 3
|
||||
INITIAL_BACKOFF_SECONDS = 2.0
|
||||
MAX_BACKOFF_SECONDS = 10.0
|
||||
|
||||
|
||||
class EncodingService:
|
||||
@@ -211,24 +198,7 @@ class EncodingService:
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 409:
|
||||
# Job already exists on worker — check if it already completed
|
||||
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
job_status = status.get("status", "unknown")
|
||||
if job_status == "complete":
|
||||
logger.info(f"[job:{job_id}] Job already complete on GCE worker, returning cached result")
|
||||
return {"status": "cached", "job_id": job_id, "output_files": status.get("output_files")}
|
||||
elif job_status in ("pending", "running"):
|
||||
logger.info(f"[job:{job_id}] Job still in progress on GCE worker")
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
else:
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists with status: {job_status}")
|
||||
except RuntimeError as e:
|
||||
if "not found" in str(e).lower():
|
||||
# Job was in worker memory but got cleared (restart) — safe to raise original error
|
||||
raise RuntimeError(f"Encoding job {job_id} conflict: 409 but job not found on status check")
|
||||
raise
|
||||
raise RuntimeError(f"Encoding job {job_id} already exists")
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to submit encoding job: {resp['status']} - {resp['text']}")
|
||||
|
||||
@@ -277,12 +247,7 @@ class EncodingService:
|
||||
progress_callback=None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Poll for encoding job completion with tolerance for transient failures.
|
||||
|
||||
During a deployment, the encoding worker may restart while we're polling.
|
||||
Rather than failing the entire job on a single poll error, we tolerate up to
|
||||
MAX_CONSECUTIVE_POLL_FAILURES consecutive failures before giving up. This is
|
||||
the same pattern used in flacfetch status polling (PR #446).
|
||||
Poll for encoding job completion.
|
||||
|
||||
Args:
|
||||
job_id: Job identifier
|
||||
@@ -295,40 +260,19 @@ class EncodingService:
|
||||
|
||||
Raises:
|
||||
TimeoutError: If job doesn't complete within timeout
|
||||
RuntimeError: If job fails or too many consecutive poll failures
|
||||
RuntimeError: If job fails
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Waiting for GCE encoding to complete...")
|
||||
|
||||
start_time = asyncio.get_event_loop().time()
|
||||
last_progress = 0
|
||||
consecutive_failures = 0
|
||||
|
||||
while True:
|
||||
elapsed = asyncio.get_event_loop().time() - start_time
|
||||
if elapsed > timeout:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
|
||||
try:
|
||||
status = await self.get_job_status(job_id)
|
||||
# Reset failure counter on successful poll
|
||||
consecutive_failures = 0
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
|
||||
asyncio.TimeoutError, RuntimeError) as e:
|
||||
consecutive_failures += 1
|
||||
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
|
||||
logger.error(
|
||||
f"[job:{job_id}] Status polling failed {consecutive_failures} consecutive times, giving up: {e}"
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"Encoding job {job_id} lost contact with worker after "
|
||||
f"{consecutive_failures} consecutive poll failures: {e}"
|
||||
)
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Status poll failed ({consecutive_failures}/{MAX_CONSECUTIVE_POLL_FAILURES}): {e}. "
|
||||
f"Worker may be restarting, will retry..."
|
||||
)
|
||||
await asyncio.sleep(poll_interval)
|
||||
continue
|
||||
status = await self.get_job_status(job_id)
|
||||
|
||||
# Handle case where GCE worker returns a list instead of dict
|
||||
if isinstance(status, list):
|
||||
@@ -387,17 +331,7 @@ class EncodingService:
|
||||
config = encoding_config or {"formats": ["mp4_4k", "mp4_720p"]}
|
||||
|
||||
# Submit the job
|
||||
submit_result = await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
|
||||
@@ -153,8 +153,7 @@ class FirestoreService:
|
||||
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
|
||||
|
||||
# Filter by tenant_id (white-label portal scoping)
|
||||
# Always filter: "" for consumer jobs, "vocalstar"/etc for tenant jobs
|
||||
if tenant_id is not None:
|
||||
if tenant_id:
|
||||
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
|
||||
|
||||
# Date range filters
|
||||
@@ -174,83 +173,6 @@ class FirestoreService:
|
||||
logger.error(f"Error listing jobs: {e}")
|
||||
raise
|
||||
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
'state_data.audio_progress', 'state_data.lyrics_progress',
|
||||
'state_data.audio_complete', 'state_data.lyrics_complete',
|
||||
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
]
|
||||
|
||||
def list_jobs_summary(
|
||||
self,
|
||||
status: Optional[JobStatus] = None,
|
||||
exclude_statuses: Optional[List[str]] = None,
|
||||
environment: Optional[str] = None,
|
||||
client_id: Optional[str] = None,
|
||||
created_after: Optional[datetime] = None,
|
||||
created_before: Optional[datetime] = None,
|
||||
user_email: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
List jobs with Firestore field projection for reduced payload.
|
||||
|
||||
Uses ``query.select()`` so Firestore only reads the requested fields,
|
||||
drastically cutting bandwidth and deserialization cost.
|
||||
|
||||
Returns raw dicts (not Job models) because projected documents would
|
||||
fail Pydantic validation for missing required fields.
|
||||
"""
|
||||
try:
|
||||
query = self.db.collection(self.collection)
|
||||
|
||||
if status:
|
||||
query = query.where(filter=FieldFilter('status', '==', status.value))
|
||||
|
||||
# NOTE: exclude_statuses is filtered in Python after the query
|
||||
# because Firestore's not-in filter combined with order_by(created_at)
|
||||
# requires a composite index. Since documents are tiny after select(),
|
||||
# Python filtering is fast and avoids the index requirement.
|
||||
|
||||
if environment:
|
||||
query = query.where(filter=FieldFilter('request_metadata.environment', '==', environment))
|
||||
|
||||
if client_id:
|
||||
query = query.where(filter=FieldFilter('request_metadata.client_id', '==', client_id))
|
||||
|
||||
if user_email:
|
||||
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
|
||||
|
||||
# Always filter: "" for consumer jobs, "vocalstar"/etc for tenant jobs
|
||||
if tenant_id is not None:
|
||||
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
|
||||
|
||||
if created_after:
|
||||
query = query.where(filter=FieldFilter('created_at', '>=', created_after))
|
||||
|
||||
if created_before:
|
||||
query = query.where(filter=FieldFilter('created_at', '<=', created_before))
|
||||
|
||||
query = query.order_by('created_at', direction=firestore.Query.DESCENDING).limit(limit)
|
||||
query = query.select(self.SUMMARY_FIELD_PATHS)
|
||||
|
||||
docs = query.stream()
|
||||
results = [doc.to_dict() for doc in docs]
|
||||
|
||||
# Apply exclude_statuses filter in Python (see note above)
|
||||
if exclude_statuses:
|
||||
results = [r for r in results if r.get('status') not in exclude_statuses]
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing jobs summary: {e}")
|
||||
raise
|
||||
|
||||
def delete_jobs_by_filter(
|
||||
self,
|
||||
environment: Optional[str] = None,
|
||||
@@ -594,101 +516,6 @@ class FirestoreService:
|
||||
logger.error(f"Error listing tokens: {e}")
|
||||
return []
|
||||
|
||||
# ============================================
|
||||
# Search Session Methods
|
||||
# ============================================
|
||||
|
||||
def create_search_session(self, session_data: dict) -> str:
|
||||
"""Store a search session for the guided job creation flow.
|
||||
|
||||
Sessions are short-lived (TTL enforced via Firestore TTL policy) and
|
||||
represent a completed audio search that hasn't yet been converted into
|
||||
a job. The document is consumed (deleted) when create-from-search runs.
|
||||
|
||||
Args:
|
||||
session_data: Dict with session_id, user_email, tenant_id, artist,
|
||||
title, results, remote_search_id, ttl_expiry.
|
||||
|
||||
Returns:
|
||||
session_id from session_data.
|
||||
"""
|
||||
try:
|
||||
session_id = session_data['session_id']
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc_ref.set(session_data)
|
||||
logger.info(f"Created search session {session_id}")
|
||||
return session_id
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating search session: {e}")
|
||||
raise
|
||||
|
||||
def get_search_session(self, session_id: str) -> Optional[dict]:
|
||||
"""Retrieve a search session by ID.
|
||||
|
||||
Returns None only if the document does not exist.
|
||||
Raises on Firestore errors so callers can distinguish a missing session
|
||||
from a transient datastore failure.
|
||||
|
||||
TTL-expired documents may still appear briefly; callers should check
|
||||
ttl_expiry and treat expired sessions as missing.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
|
||||
Returns:
|
||||
Session dict or None.
|
||||
"""
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
return doc.to_dict()
|
||||
|
||||
def consume_search_session(self, session_id: str) -> Optional[dict]:
|
||||
"""Atomically read and delete a search session.
|
||||
|
||||
Uses a Firestore transaction to prevent two concurrent job-creation
|
||||
requests from both reading the same session and creating duplicate jobs.
|
||||
|
||||
Returns the session dict if it existed, None if it did not exist.
|
||||
Raises on Firestore errors.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
|
||||
Returns:
|
||||
Session dict or None.
|
||||
"""
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
|
||||
@firestore.transactional
|
||||
def _read_and_delete(transaction, ref):
|
||||
doc = ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return None
|
||||
session_data = doc.to_dict()
|
||||
transaction.delete(ref)
|
||||
return session_data
|
||||
|
||||
transaction = self.db.transaction()
|
||||
return _read_and_delete(transaction, doc_ref)
|
||||
|
||||
def delete_search_session(self, session_id: str) -> None:
|
||||
"""Delete a search session after it has been consumed by job creation.
|
||||
|
||||
Errors are logged but not re-raised — a missing or already-deleted
|
||||
session is a no-op.
|
||||
|
||||
Args:
|
||||
session_id: UUID string identifying the session.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection('search_sessions').document(session_id)
|
||||
doc_ref.delete()
|
||||
logger.debug(f"Deleted search session {session_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting search session {session_id}: {e}")
|
||||
|
||||
|
||||
# Singleton client instance
|
||||
_firestore_client: Optional[firestore.Client] = None
|
||||
|
||||
@@ -34,8 +34,6 @@ from typing import Any, Dict, List, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -44,104 +42,6 @@ class FlacfetchServiceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _format_httpx_error(e: Exception) -> str:
|
||||
"""
|
||||
Format an httpx exception into a descriptive error string.
|
||||
|
||||
httpx.RequestError subclasses (ConnectError, ReadError, etc.) often have
|
||||
empty str() representations, which produces useless messages like
|
||||
"Status request failed: ". This helper always returns something meaningful.
|
||||
"""
|
||||
error_str = str(e)
|
||||
error_type = type(e).__name__
|
||||
|
||||
if error_str:
|
||||
return f"{error_type}: {error_str}"
|
||||
|
||||
# str(e) is empty - try to include request URL for context
|
||||
if isinstance(e, httpx.RequestError):
|
||||
try:
|
||||
request = e.request
|
||||
if request:
|
||||
return f"{error_type} for {request.method} {request.url}"
|
||||
except RuntimeError:
|
||||
pass # .request not set
|
||||
return error_type
|
||||
|
||||
|
||||
def should_retry_flacfetch_error(exception: Exception) -> bool:
|
||||
"""
|
||||
Determine if a flacfetch exception should be retried.
|
||||
|
||||
Retry on:
|
||||
- httpx.RequestError (network failures: timeout, connection refused, etc.)
|
||||
- httpx.HTTPStatusError with 5xx status (server errors)
|
||||
|
||||
Don't retry on:
|
||||
- httpx.HTTPStatusError with 4xx status (client errors: bad request, auth, not found)
|
||||
"""
|
||||
if isinstance(exception, httpx.RequestError):
|
||||
# Network-level failures - always retry
|
||||
return True
|
||||
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
# HTTP errors - only retry on 5xx (server errors)
|
||||
return exception.response.status_code >= 500
|
||||
|
||||
# Don't retry on other exceptions (e.g., FlacfetchServiceError after wrapping)
|
||||
return False
|
||||
|
||||
|
||||
async def with_retry(func, *args, **kwargs):
|
||||
"""
|
||||
Execute an async function with retry logic using exponential backoff.
|
||||
|
||||
This implementation uses manual retry logic instead of tenacity decorators
|
||||
for better testability and runtime configuration.
|
||||
"""
|
||||
settings = get_settings()
|
||||
max_attempts = settings.flacfetch_retry_max_attempts
|
||||
min_wait = settings.flacfetch_retry_min_wait
|
||||
max_wait = settings.flacfetch_retry_max_wait
|
||||
|
||||
last_exception = None
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return await func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
last_exception = e
|
||||
|
||||
# Check if we should retry this exception
|
||||
if not should_retry_flacfetch_error(e):
|
||||
# Don't retry - raise immediately
|
||||
raise
|
||||
|
||||
# Check if we have more attempts left
|
||||
if attempt >= max_attempts:
|
||||
# No more attempts - raise the last exception
|
||||
logger.warning(
|
||||
f"Flacfetch request failed after {max_attempts} attempts: "
|
||||
f"{_format_httpx_error(e) if isinstance(e, httpx.RequestError) else e}"
|
||||
)
|
||||
raise
|
||||
|
||||
# Calculate wait time with exponential backoff
|
||||
wait_time = min(min_wait * (2 ** (attempt - 1)), max_wait)
|
||||
|
||||
logger.warning(
|
||||
f"Flacfetch request failed (attempt {attempt}/{max_attempts}): "
|
||||
f"{_format_httpx_error(e) if isinstance(e, httpx.RequestError) else e}. "
|
||||
f"Retrying in {wait_time:.1f}s..."
|
||||
)
|
||||
|
||||
# Wait before next attempt
|
||||
await asyncio.sleep(wait_time)
|
||||
|
||||
# Should never reach here, but just in case
|
||||
raise last_exception
|
||||
|
||||
|
||||
class FlacfetchClient:
|
||||
"""
|
||||
Client for remote flacfetch HTTP API.
|
||||
@@ -200,7 +100,7 @@ class FlacfetchClient:
|
||||
|
||||
return data
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Cannot reach flacfetch service: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Cannot reach flacfetch service: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Health check failed: {e.response.status_code}")
|
||||
|
||||
@@ -245,10 +145,10 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Search request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
|
||||
async def download(
|
||||
self,
|
||||
search_id: str,
|
||||
@@ -258,59 +158,47 @@ class FlacfetchClient:
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading an audio file.
|
||||
|
||||
Retries automatically on network errors and server errors (5xx) using
|
||||
exponential backoff. Configured via FLACFETCH_RETRY_* environment variables.
|
||||
|
||||
|
||||
Args:
|
||||
search_id: Search ID from previous search
|
||||
result_index: Index of result to download
|
||||
output_filename: Optional custom filename (without extension)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download start failure (after all retries exhausted)
|
||||
FlacfetchServiceError: On download start failure
|
||||
"""
|
||||
try:
|
||||
return await with_retry(self._download_impl, search_id, result_index, output_filename, gcs_path)
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"search_id": search_id,
|
||||
"result_index": result_index,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Download request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download start failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _download_impl(
|
||||
self,
|
||||
search_id: str,
|
||||
result_index: int,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Implementation of download without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"search_id": search_id,
|
||||
"result_index": result_index,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
|
||||
async def download_by_id(
|
||||
self,
|
||||
source_name: str,
|
||||
@@ -326,9 +214,6 @@ class FlacfetchClient:
|
||||
This is useful when you have stored the source_id from a previous search
|
||||
and want to download later without re-searching.
|
||||
|
||||
Retries automatically on network errors and server errors (5xx) using
|
||||
exponential backoff. Configured via FLACFETCH_RETRY_* environment variables.
|
||||
|
||||
Args:
|
||||
source_name: Provider name (RED, OPS, YouTube, Spotify)
|
||||
source_id: Source-specific ID (torrent ID, video ID, track ID)
|
||||
@@ -341,68 +226,52 @@ class FlacfetchClient:
|
||||
Download ID for tracking progress
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download start failure (after all retries exhausted)
|
||||
FlacfetchServiceError: On download start failure
|
||||
"""
|
||||
try:
|
||||
return await with_retry(
|
||||
self._download_by_id_impl,
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path
|
||||
)
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"source_name": source_name,
|
||||
"source_id": source_id,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if target_file:
|
||||
payload["target_file"] = target_file
|
||||
if download_url:
|
||||
payload["download_url"] = download_url
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _download_by_id_impl(
|
||||
self,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
output_filename: Optional[str] = None,
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Implementation of download_by_id without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"source_name": source_name,
|
||||
"source_id": source_id,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if target_file:
|
||||
payload["target_file"] = target_file
|
||||
if download_url:
|
||||
payload["download_url"] = download_url
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
async def get_download_status(self, download_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the current status of a download.
|
||||
|
||||
|
||||
Args:
|
||||
download_id: Download ID from start_download
|
||||
|
||||
|
||||
Returns:
|
||||
Status dict with progress, speed, path info
|
||||
|
||||
|
||||
Raises:
|
||||
httpx.RequestError: On network-level failures (connection refused, timeout, etc.)
|
||||
These are NOT wrapped so wait_for_download can handle retries.
|
||||
FlacfetchServiceError: On application-level failures (404, other HTTP errors)
|
||||
FlacfetchServiceError: On status check failure
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -413,10 +282,9 @@ class FlacfetchClient:
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError:
|
||||
# Let network errors bubble up so wait_for_download can handle retries
|
||||
raise
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Status request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
raise FlacfetchServiceError(f"Download not found: {download_id}")
|
||||
@@ -428,59 +296,35 @@ class FlacfetchClient:
|
||||
timeout: int = 600,
|
||||
poll_interval: float = 2.0,
|
||||
progress_callback: Optional[callable] = None,
|
||||
max_consecutive_errors: int = 3,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Wait for a download to complete.
|
||||
|
||||
Tolerates transient network errors during status polling. A single
|
||||
connection hiccup won't fail the entire download -- only N consecutive
|
||||
poll failures will.
|
||||
|
||||
|
||||
Args:
|
||||
download_id: Download ID to wait for
|
||||
timeout: Maximum wait time in seconds
|
||||
poll_interval: Time between status checks
|
||||
progress_callback: Optional callback(status_dict) for progress updates
|
||||
max_consecutive_errors: Number of consecutive poll failures before giving up
|
||||
|
||||
|
||||
Returns:
|
||||
Final status dict with output_path or gcs_path
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download failure, timeout, or too many consecutive poll errors
|
||||
FlacfetchServiceError: On download failure or timeout
|
||||
"""
|
||||
elapsed = 0.0
|
||||
consecutive_errors = 0
|
||||
|
||||
|
||||
while elapsed < timeout:
|
||||
try:
|
||||
status = await self.get_download_status(download_id)
|
||||
consecutive_errors = 0 # Reset on success
|
||||
except httpx.RequestError as e:
|
||||
consecutive_errors += 1
|
||||
error_desc = _format_httpx_error(e)
|
||||
logger.warning(
|
||||
f"Status poll failed for download {download_id} "
|
||||
f"({consecutive_errors}/{max_consecutive_errors}): {error_desc}"
|
||||
)
|
||||
if consecutive_errors >= max_consecutive_errors:
|
||||
raise FlacfetchServiceError(
|
||||
f"Status polling failed after {consecutive_errors} consecutive "
|
||||
f"network errors (last: {error_desc})"
|
||||
)
|
||||
await asyncio.sleep(poll_interval)
|
||||
elapsed += poll_interval
|
||||
continue
|
||||
|
||||
status = await self.get_download_status(download_id)
|
||||
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback(status)
|
||||
except Exception as e:
|
||||
logger.warning(f"Progress callback error: {e}")
|
||||
|
||||
|
||||
download_status = status.get("status")
|
||||
|
||||
|
||||
if download_status in ["complete", "seeding"]:
|
||||
logger.info(f"Download {download_id} complete: {status.get('gcs_path') or status.get('output_path')}")
|
||||
return status
|
||||
@@ -489,7 +333,7 @@ class FlacfetchClient:
|
||||
raise FlacfetchServiceError(f"Download failed: {error}")
|
||||
elif download_status == "cancelled":
|
||||
raise FlacfetchServiceError("Download was cancelled")
|
||||
|
||||
|
||||
# Log progress
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
@@ -498,10 +342,10 @@ class FlacfetchClient:
|
||||
f"Download {download_id}: {progress:.1f}% "
|
||||
f"({speed:.1f} KB/s, {peers} peers)"
|
||||
)
|
||||
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
elapsed += poll_interval
|
||||
|
||||
|
||||
raise FlacfetchServiceError(f"Download timed out after {timeout}s")
|
||||
|
||||
async def list_torrents(self) -> Dict[str, Any]:
|
||||
@@ -522,7 +366,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"List torrents failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"List torrents failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"List torrents failed: {e.response.status_code}")
|
||||
|
||||
@@ -553,7 +397,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Delete torrent failed: {e.response.status_code}")
|
||||
|
||||
@@ -587,7 +431,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Cleanup failed: {e.response.status_code}")
|
||||
|
||||
@@ -628,7 +472,7 @@ class FlacfetchClient:
|
||||
return deleted
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Clear search cache request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Clear search cache request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Clear search cache failed: {e.response.status_code} - {e.response.text}"
|
||||
@@ -658,55 +502,12 @@ class FlacfetchClient:
|
||||
return deleted_count
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Clear all cache request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Clear all cache request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Clear all cache failed: {e.response.status_code} - {e.response.text}"
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# YouTube Availability Check
|
||||
# =========================================================================
|
||||
|
||||
async def check_youtube(self, url: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Check if a YouTube video is available for download from this server's location.
|
||||
|
||||
Calls the flacfetch /check-youtube endpoint which uses yt-dlp to detect
|
||||
geo-restrictions, private/removed videos, and other unavailability reasons.
|
||||
|
||||
Args:
|
||||
url: YouTube video URL or video ID
|
||||
|
||||
Returns:
|
||||
Dict with keys: available, video_id, title, error,
|
||||
is_geo_restricted, is_age_restricted, is_private, is_removed
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On request failure
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/check-youtube",
|
||||
headers=self._headers(),
|
||||
json={"url": url},
|
||||
timeout=15,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"YouTube availability check failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"YouTube availability check failed: {e.response.status_code} - {e.response.text}"
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Cache Management
|
||||
# =========================================================================
|
||||
|
||||
async def get_cache_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get statistics about the cache.
|
||||
@@ -728,7 +529,7 @@ class FlacfetchClient:
|
||||
return resp.json()
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Get cache stats request failed: {_format_httpx_error(e)}")
|
||||
raise FlacfetchServiceError(f"Get cache stats request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(
|
||||
f"Get cache stats failed: {e.response.status_code} - {e.response.text}"
|
||||
|
||||
@@ -3,7 +3,6 @@ import glob as glob_module
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -14,7 +13,6 @@ from typing import Optional
|
||||
|
||||
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
|
||||
from google.cloud import storage
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
@@ -256,23 +254,12 @@ def ensure_latest_wheel():
|
||||
|
||||
# Find the downloaded wheel (get the latest by version sorting)
|
||||
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
|
||||
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
|
||||
wheels = [w for w in wheels if '-current' not in w]
|
||||
|
||||
if not wheels:
|
||||
logger.warning("No wheel found in GCS, using fallback encoding logic")
|
||||
return False
|
||||
|
||||
# Sort to get latest version (by semantic version, not alphabetically)
|
||||
def extract_version(wheel_path):
|
||||
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
|
||||
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
|
||||
if match:
|
||||
return Version(match.group(1))
|
||||
return Version("0.0.0") # Fallback for unparseable filenames
|
||||
|
||||
wheels.sort(key=extract_version, reverse=True)
|
||||
wheel_path = wheels[0]
|
||||
# Sort to get latest version
|
||||
wheel_path = sorted(wheels)[-1]
|
||||
logger.info(f"Installing wheel: {wheel_path}")
|
||||
|
||||
# Install (or upgrade) the wheel
|
||||
@@ -338,58 +325,24 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
|
||||
|
||||
# Karaoke video - search for With Vocals or main karaoke video
|
||||
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
|
||||
# old encoding outputs from finals/ directory when re-encoding after reset
|
||||
karaoke_video = find_file(
|
||||
work_dir,
|
||||
# First: Look in videos/ subdirectory (where render_video_worker puts output)
|
||||
"videos/with_vocals.mkv", "videos/with_vocals.mov",
|
||||
"videos/*With Vocals*.mkv", "videos/*With Vocals*.mov",
|
||||
# Second: Look for specific filename patterns (case-insensitive variants)
|
||||
"*with_vocals*.mkv", "*with_vocals*.mov",
|
||||
"*With Vocals*.mov", "*With Vocals*.mkv",
|
||||
"*vocals*.mkv", "*vocals*.mov",
|
||||
"*Vocals*.mov", "*Vocals*.mkv",
|
||||
# Last resort: any video file (but excluding finals/outputs)
|
||||
"*.mkv", "*.mov"
|
||||
)
|
||||
# Exclude title/end/output/finals videos to avoid re-encoding old outputs
|
||||
# Exclude title/end/output videos
|
||||
if karaoke_video:
|
||||
path_str = str(karaoke_video).lower()
|
||||
name_lower = karaoke_video.name.lower()
|
||||
if ("title" in name_lower or "end" in name_lower or
|
||||
"outputs" in path_str or "finals" in path_str or
|
||||
"final karaoke" in name_lower or "lossless" in name_lower or
|
||||
"lossy" in name_lower or "720p" in name_lower):
|
||||
# Search more specifically for karaoke video in videos/ directory only
|
||||
karaoke_video = find_file(
|
||||
work_dir,
|
||||
"videos/with_vocals.mkv", "videos/with_vocals.mov",
|
||||
"videos/*vocals*.mkv", "videos/*vocals*.mov"
|
||||
)
|
||||
if "title" in name_lower or "end" in name_lower or "outputs" in str(karaoke_video):
|
||||
# Search more specifically for karaoke video
|
||||
karaoke_video = find_file(work_dir, "*Karaoke*.mkv", "*Karaoke*.mov", "*vocals*.mkv")
|
||||
|
||||
# Instrumental audio - respect user's selection from encoding config
|
||||
instrumental_selection = config.get("instrumental_selection", "clean")
|
||||
existing_instrumental = config.get("existing_instrumental")
|
||||
logger.info(f"Instrumental selection from config: {instrumental_selection}")
|
||||
if existing_instrumental:
|
||||
logger.info(f"Existing instrumental from config: {existing_instrumental}")
|
||||
|
||||
if existing_instrumental:
|
||||
# User-provided instrumental uploaded at job creation
|
||||
# Downloaded to work_dir by process_job before run_encoding is called
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*existing_instrumental*", "*Instrumental User*",
|
||||
)
|
||||
elif instrumental_selection == "custom":
|
||||
# Custom instrumental created via mute-region editing in review UI
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*custom_instrumental*.flac", "*Instrumental Custom*.flac",
|
||||
"*custom_instrumental*.mp3",
|
||||
)
|
||||
elif instrumental_selection == "with_backing":
|
||||
if instrumental_selection == "with_backing":
|
||||
# User selected instrumental with backing vocals
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
@@ -413,11 +366,6 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
logger.info(f" End video: {end_video}")
|
||||
logger.info(f" Instrumental ({instrumental_selection}): {instrumental}")
|
||||
|
||||
# Check for countdown padding - if vocals were padded, instrumental must match
|
||||
countdown_padding_seconds = config.get("countdown_padding_seconds")
|
||||
if countdown_padding_seconds:
|
||||
logger.info(f" Countdown padding: {countdown_padding_seconds}s - will be handled by LocalEncodingService")
|
||||
|
||||
# Validate required files
|
||||
if not title_video:
|
||||
raise ValueError(f"No title video found in {work_dir}. Check screens/ subdirectory.")
|
||||
@@ -432,7 +380,6 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
jobs[job_id]["progress"] = 20
|
||||
|
||||
# Build encoding config with proper file names
|
||||
# Note: countdown_padding_seconds is passed to LocalEncodingService which handles padding
|
||||
encoding_config = EncodingConfig(
|
||||
title_video=str(title_video),
|
||||
karaoke_video=str(karaoke_video),
|
||||
@@ -444,7 +391,6 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
output_lossy_4k_mp4=str(output_dir / f"{base_name} (Final Karaoke Lossy 4k).mp4"),
|
||||
output_lossless_mkv=str(output_dir / f"{base_name} (Final Karaoke Lossless 4k).mkv"),
|
||||
output_720p_mp4=str(output_dir / f"{base_name} (Final Karaoke Lossy 720p).mp4"),
|
||||
countdown_padding_seconds=countdown_padding_seconds,
|
||||
)
|
||||
|
||||
# Create service and run encoding
|
||||
@@ -502,17 +448,6 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
logger.info(f"Downloading from {request.input_gcs_path}")
|
||||
download_from_gcs(request.input_gcs_path, work_dir)
|
||||
|
||||
# Download existing instrumental if present (stored under uploads/, not jobs/)
|
||||
existing_instrumental = request.encoding_config.get("existing_instrumental") if request.encoding_config else None
|
||||
if existing_instrumental:
|
||||
# Extract bucket name from input_gcs_path (gs://bucket/jobs/...)
|
||||
bucket_name = request.input_gcs_path.replace("gs://", "").split("/", 1)[0]
|
||||
ext = Path(existing_instrumental).suffix.lower()
|
||||
dest = work_dir / f"existing_instrumental{ext}"
|
||||
gcs_uri = f"gs://{bucket_name}/{existing_instrumental}"
|
||||
logger.info(f"Downloading existing instrumental: {gcs_uri} -> {dest}")
|
||||
download_single_file_from_gcs(gcs_uri, dest)
|
||||
|
||||
# Run encoding in thread pool (CPU-bound)
|
||||
loop = asyncio.get_event_loop()
|
||||
output_dir = await loop.run_in_executor(
|
||||
@@ -617,18 +552,8 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
|
||||
# Submit an encoding job
|
||||
job_id = request.job_id
|
||||
|
||||
# If job already exists, return cached result or current status
|
||||
if job_id in jobs:
|
||||
existing_job = jobs[job_id]
|
||||
if existing_job["status"] == "complete":
|
||||
# Return cached result - encoding already done
|
||||
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files")}
|
||||
elif existing_job["status"] == "failed":
|
||||
# Previous attempt failed, allow retry by replacing the job
|
||||
pass
|
||||
else:
|
||||
# Job is still in progress
|
||||
return {"status": "in_progress", "job_id": job_id}
|
||||
raise HTTPException(status_code=409, detail=f"Job {job_id} already exists")
|
||||
|
||||
jobs[job_id] = {
|
||||
"job_id": job_id,
|
||||
|
||||
@@ -12,19 +12,13 @@ shared with YouTube credentials if scopes include drive.file.
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from tenacity import Retrying, stop_after_attempt, wait_exponential, retry_if_exception_type
|
||||
|
||||
from backend.config import get_settings
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Transient errors that indicate a stale HTTP connection (Cloud Run idle containers)
|
||||
TRANSIENT_ERRORS = (BrokenPipeError, ConnectionResetError, ConnectionError, ssl.SSLError)
|
||||
|
||||
|
||||
class GoogleDriveService:
|
||||
"""Google Drive operations using native API."""
|
||||
@@ -39,11 +33,6 @@ class GoogleDriveService:
|
||||
self._credentials_data: Optional[Dict[str, Any]] = None
|
||||
self._loaded = False
|
||||
|
||||
def _reset_service(self):
|
||||
"""Reset the cached Drive service to force a fresh connection on next use."""
|
||||
logger.info("Resetting Google Drive service connection")
|
||||
self._service = None
|
||||
|
||||
def _load_credentials(self) -> Optional[Dict[str, Any]]:
|
||||
"""Load OAuth credentials from Secret Manager."""
|
||||
if self._loaded:
|
||||
@@ -138,9 +127,6 @@ class GoogleDriveService:
|
||||
"""
|
||||
Get existing folder or create new one, return folder ID.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
parent_id: Parent folder ID
|
||||
folder_name: Name of folder to find or create
|
||||
@@ -148,41 +134,33 @@ class GoogleDriveService:
|
||||
Returns:
|
||||
Folder ID
|
||||
"""
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
logger.info(f"Looking for folder '{folder_name}' in parent {parent_id}")
|
||||
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
# Search for existing folder
|
||||
# Escape single quotes in folder name for Google Drive API query syntax
|
||||
escaped_folder_name = folder_name.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_folder_name}' and '{parent_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id, name)").execute()
|
||||
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
if results.get("files"):
|
||||
folder_id = results["files"][0]["id"]
|
||||
logger.info(f"Found existing folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
# Create folder
|
||||
logger.info(f"Creating new folder '{folder_name}'")
|
||||
metadata = {
|
||||
"name": folder_name,
|
||||
"mimeType": "application/vnd.google-apps.folder",
|
||||
"parents": [parent_id],
|
||||
}
|
||||
folder = self.service.files().create(body=metadata, fields="id").execute()
|
||||
folder_id = folder["id"]
|
||||
logger.info(f"Created folder '{folder_name}': {folder_id}")
|
||||
return folder_id
|
||||
|
||||
def upload_file(
|
||||
self,
|
||||
@@ -194,9 +172,6 @@ class GoogleDriveService:
|
||||
"""
|
||||
Upload a file to a specific Drive folder.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
local_path: Local file path
|
||||
parent_id: Parent folder ID in Google Drive
|
||||
@@ -208,57 +183,49 @@ class GoogleDriveService:
|
||||
"""
|
||||
from googleapiclient.http import MediaFileUpload
|
||||
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
file_size = os.path.getsize(local_path)
|
||||
logger.info(
|
||||
f"Uploading {local_path} ({file_size / 1024 / 1024:.1f} MB) "
|
||||
f"as '{filename}' to folder {parent_id}"
|
||||
)
|
||||
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
# Determine MIME type
|
||||
ext = os.path.splitext(local_path)[1].lower()
|
||||
mime_types = {
|
||||
".mp4": "video/mp4",
|
||||
".mkv": "video/x-matroska",
|
||||
".zip": "application/zip",
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
}
|
||||
mime_type = mime_types.get(ext, "application/octet-stream")
|
||||
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
# Check for existing file with same name
|
||||
if replace_existing:
|
||||
# Escape single quotes in filename for Google Drive API query syntax
|
||||
escaped_filename = filename.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_filename}' and '{parent_id}' in parents and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(q=query, fields="files(id)").execute()
|
||||
for existing_file in results.get("files", []):
|
||||
logger.info(f"Deleting existing file: {existing_file['id']}")
|
||||
self.service.files().delete(fileId=existing_file["id"]).execute()
|
||||
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
# Upload file
|
||||
metadata = {"name": filename, "parents": [parent_id]}
|
||||
media = MediaFileUpload(local_path, mimetype=mime_type, resumable=True)
|
||||
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
file_result = (
|
||||
self.service.files().create(body=metadata, media_body=media, fields="id").execute()
|
||||
)
|
||||
file_id = file_result["id"]
|
||||
logger.info(f"Successfully uploaded '{filename}': {file_id}")
|
||||
return file_id
|
||||
|
||||
def upload_to_public_share(
|
||||
self,
|
||||
@@ -341,9 +308,6 @@ class GoogleDriveService:
|
||||
"""
|
||||
Delete a file from Google Drive.
|
||||
|
||||
Retries on transient connection errors (BrokenPipeError, SSLError)
|
||||
that occur when Cloud Run containers sit idle between jobs.
|
||||
|
||||
Args:
|
||||
file_id: Google Drive file ID to delete
|
||||
|
||||
@@ -353,17 +317,9 @@ class GoogleDriveService:
|
||||
logger.info(f"Deleting Google Drive file: {file_id}")
|
||||
|
||||
try:
|
||||
for attempt in Retrying(
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=8),
|
||||
retry=retry_if_exception_type(TRANSIENT_ERRORS),
|
||||
before_sleep=lambda retry_state: self._reset_service(),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
self.service.files().delete(fileId=file_id).execute()
|
||||
logger.info(f"Successfully deleted file: {file_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# Check if it's a 404 (already deleted)
|
||||
if hasattr(e, 'resp') and e.resp.status == 404:
|
||||
@@ -387,85 +343,6 @@ class GoogleDriveService:
|
||||
results[file_id] = self.delete_file(file_id)
|
||||
return results
|
||||
|
||||
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
|
||||
"""
|
||||
Search for files in public share subfolders matching a brand code prefix.
|
||||
|
||||
Used as a fallback when gdrive_files is not tracked in state_data (e.g., old
|
||||
jobs uploaded before file ID tracking was implemented, or jobs where GDrive
|
||||
upload succeeded but file IDs were not saved due to a bug).
|
||||
|
||||
Searches CDG/, MP4/, MP4-720p/ subfolders for files whose name starts with
|
||||
'{brand_code} - '.
|
||||
|
||||
Args:
|
||||
root_folder_id: Root Google Drive folder ID for the public share
|
||||
brand_code: Brand code prefix to search for (e.g., "NOMAD-1271")
|
||||
|
||||
Returns:
|
||||
List of file IDs found matching the brand code
|
||||
"""
|
||||
found_ids = []
|
||||
subfolders = ["CDG", "MP4", "MP4-720p"]
|
||||
search_errors: list[Exception] = []
|
||||
|
||||
for subfolder in subfolders:
|
||||
try:
|
||||
# Find the subfolder
|
||||
escaped_subfolder = subfolder.replace("'", "\\'")
|
||||
query = (
|
||||
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
|
||||
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
|
||||
)
|
||||
results = self.service.files().list(
|
||||
q=query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
if not results.get("files"):
|
||||
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
|
||||
continue
|
||||
|
||||
subfolder_id = results["files"][0]["id"]
|
||||
|
||||
# Search for files whose name starts with the brand code
|
||||
# Use contains for efficiency, then filter by exact prefix
|
||||
escaped_brand = brand_code.replace("'", "\\'")
|
||||
file_query = (
|
||||
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
|
||||
f"and trashed=false"
|
||||
)
|
||||
file_results = self.service.files().list(
|
||||
q=file_query, fields="files(id, name)", supportsAllDrives=True,
|
||||
includeItemsFromAllDrives=True
|
||||
).execute()
|
||||
|
||||
for f in file_results.get("files", []):
|
||||
if f["name"].startswith(f"{brand_code} - "):
|
||||
found_ids.append(f["id"])
|
||||
logger.info(
|
||||
f"Found GDrive file to clean up in {subfolder}/: "
|
||||
f"{f['name']} ({f['id']})"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
search_errors.append(e)
|
||||
|
||||
if search_errors:
|
||||
# Raise so the caller knows the search was incomplete.
|
||||
# This prevents the cleanup endpoint from treating an uncertain result
|
||||
# as "GDrive is clean" and incorrectly recycling the brand code.
|
||||
raise RuntimeError(
|
||||
f"GDrive brand_code search incomplete: "
|
||||
f"{len(search_errors)}/{len(subfolders)} subfolder(s) failed"
|
||||
)
|
||||
|
||||
return found_ids
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_gdrive_service: Optional[GoogleDriveService] = None
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
"""
|
||||
GDrive Validator Cloud Function client.
|
||||
|
||||
Lightweight HTTP client for invoking the gdrive-validator Cloud Function
|
||||
from the backend (e.g., after job completion). Uses OIDC authentication
|
||||
via the backend's service account.
|
||||
|
||||
Fire-and-forget pattern: never blocks or fails the caller.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
import requests
|
||||
import google.auth.transport.requests
|
||||
import google.oauth2.id_token
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Cloud Function URL - set via environment variable
|
||||
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
|
||||
|
||||
|
||||
def trigger_gdrive_validation() -> dict | None:
|
||||
"""
|
||||
Invoke the GDrive validator Cloud Function.
|
||||
|
||||
Uses the backend service account's OIDC token for authentication.
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from the function, or None on error.
|
||||
"""
|
||||
if not GDRIVE_VALIDATOR_URL:
|
||||
logger.debug("GDRIVE_VALIDATOR_URL not set, skipping GDrive validation trigger")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Get OIDC token for the Cloud Function URL
|
||||
auth_request = google.auth.transport.requests.Request()
|
||||
token = google.oauth2.id_token.fetch_id_token(auth_request, GDRIVE_VALIDATOR_URL)
|
||||
|
||||
response = requests.post(
|
||||
GDRIVE_VALIDATOR_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
status = result.get("status", "unknown")
|
||||
|
||||
if status == "issues_found":
|
||||
logger.warning("GDrive validation found issues (notification sent)")
|
||||
elif status == "ok":
|
||||
logger.info("GDrive validation: all clear")
|
||||
else:
|
||||
logger.info(f"GDrive validation returned status: {status}")
|
||||
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Failed to trigger GDrive validation (non-fatal)")
|
||||
return None
|
||||
@@ -61,56 +61,6 @@ def get_effective_distribution_settings(
|
||||
)
|
||||
|
||||
|
||||
def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings:
|
||||
"""
|
||||
Get effective distribution settings for a job, applying private overrides if is_private=True.
|
||||
|
||||
For private (non-published) jobs, this overrides:
|
||||
- dropbox_path → private Dropbox path (Tracks-NonPublished)
|
||||
- brand_prefix → private brand prefix (NOMADNP)
|
||||
- enable_youtube_upload → False (no YouTube for private)
|
||||
- gdrive_folder_id → None (no Google Drive for private)
|
||||
|
||||
For non-private jobs, returns the job's own distribution settings unchanged.
|
||||
|
||||
Args:
|
||||
job: Job object (or any object with distribution fields)
|
||||
|
||||
Returns:
|
||||
EffectiveDistributionSettings with private overrides applied if needed
|
||||
"""
|
||||
if getattr(job, 'is_private', False):
|
||||
# Tenant jobs: use the job's own distribution fields (set at creation from tenant config)
|
||||
# Non-tenant private jobs: override to NonPublished paths
|
||||
if getattr(job, 'tenant_id', None):
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
settings = get_settings()
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=settings.default_private_dropbox_path,
|
||||
brand_prefix=settings.default_private_brand_prefix,
|
||||
enable_youtube_upload=False,
|
||||
gdrive_folder_id=None,
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=None,
|
||||
)
|
||||
# Non-private: return job's own settings
|
||||
return EffectiveDistributionSettings(
|
||||
dropbox_path=getattr(job, 'dropbox_path', None),
|
||||
brand_prefix=getattr(job, 'brand_prefix', None),
|
||||
enable_youtube_upload=getattr(job, 'enable_youtube_upload', False),
|
||||
gdrive_folder_id=getattr(job, 'gdrive_folder_id', None),
|
||||
discord_webhook_url=getattr(job, 'discord_webhook_url', None),
|
||||
youtube_description=getattr(job, 'youtube_description_template', None),
|
||||
)
|
||||
|
||||
|
||||
def resolve_cdg_txt_defaults(
|
||||
theme_id: Optional[str],
|
||||
enable_cdg: Optional[bool] = None,
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
"""
|
||||
Job health and consistency checking service.
|
||||
|
||||
Provides functions to detect state inconsistencies in jobs that might indicate
|
||||
bugs in the state machine or trigger logic.
|
||||
|
||||
Created as part of state machine robustness improvements (2026-02-02).
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Jobs in these statuses should NOT have audio_complete flag set
|
||||
# (unless they're actively processing or beyond)
|
||||
STATUSES_BEFORE_AUDIO_START = {
|
||||
JobStatus.PENDING,
|
||||
JobStatus.SEARCHING_AUDIO,
|
||||
JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
}
|
||||
|
||||
# Jobs in these statuses should NOT have lyrics_complete flag set
|
||||
STATUSES_BEFORE_LYRICS_START = {
|
||||
JobStatus.PENDING,
|
||||
JobStatus.SEARCHING_AUDIO,
|
||||
JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
}
|
||||
|
||||
# Statuses where screens_progress.stage='complete' is valid
|
||||
STATUSES_AFTER_SCREENS_COMPLETE = {
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.IN_REVIEW,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.AWAITING_INSTRUMENTAL_SELECTION, # Legacy
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.GENERATING_VIDEO,
|
||||
JobStatus.ENCODING,
|
||||
JobStatus.PACKAGING,
|
||||
JobStatus.UPLOADING,
|
||||
JobStatus.NOTIFYING,
|
||||
JobStatus.COMPLETE,
|
||||
JobStatus.PREP_COMPLETE,
|
||||
}
|
||||
|
||||
|
||||
def check_job_consistency(job: Job) -> List[str]:
|
||||
"""
|
||||
Check for state inconsistencies in a job.
|
||||
|
||||
This function detects situations where state_data flags indicate
|
||||
progress that doesn't match the job status - which usually indicates
|
||||
a bug in the state machine or trigger logic.
|
||||
|
||||
Args:
|
||||
job: Job object to check
|
||||
|
||||
Returns:
|
||||
List of issue descriptions found. Empty list means no issues.
|
||||
"""
|
||||
issues = []
|
||||
state_data = job.state_data or {}
|
||||
|
||||
# Normalize status to JobStatus enum if it's a string
|
||||
status = job.status
|
||||
if isinstance(status, str):
|
||||
try:
|
||||
status = JobStatus(status)
|
||||
except ValueError:
|
||||
issues.append(f"invalid_status: '{job.status}' is not a valid JobStatus")
|
||||
return issues
|
||||
|
||||
# Check: audio_complete=True but status still in pre-audio states
|
||||
if state_data.get('audio_complete') and status in STATUSES_BEFORE_AUDIO_START:
|
||||
issues.append(
|
||||
f"audio_complete_status_mismatch: audio_complete=True but status={status.value}"
|
||||
)
|
||||
|
||||
# Check: lyrics_complete=True but status still in pre-lyrics states
|
||||
if state_data.get('lyrics_complete') and status in STATUSES_BEFORE_LYRICS_START:
|
||||
issues.append(
|
||||
f"lyrics_complete_status_mismatch: lyrics_complete=True but status={status.value}"
|
||||
)
|
||||
|
||||
# Check: screens_progress.stage='complete' but status not in post-screens states
|
||||
screens_progress = state_data.get('screens_progress', {})
|
||||
if isinstance(screens_progress, dict) and screens_progress.get('stage') == 'complete':
|
||||
if status not in STATUSES_AFTER_SCREENS_COMPLETE:
|
||||
issues.append(
|
||||
f"screens_complete_status_mismatch: screens_progress.stage=complete but status={status.value}"
|
||||
)
|
||||
|
||||
# Check: job has input_media_gcs_path but is stuck at pending
|
||||
# This was the exact bug that got jobs 06cfea29 and 984da08b stuck
|
||||
if job.input_media_gcs_path and status == JobStatus.PENDING:
|
||||
# This could be legitimate if job was just created and workers haven't started
|
||||
# But if it's been more than a few minutes, it's likely stuck
|
||||
# We flag it as a warning, not an error
|
||||
issues.append(
|
||||
f"pending_with_input_media: has input_media_gcs_path but status=pending (may be stuck)"
|
||||
)
|
||||
|
||||
# Check: job stuck in encoding status beyond 50 minutes
|
||||
# Encoding timeout is 1 hour; if updated_at hasn't advanced in 50 min,
|
||||
# the poller likely died (e.g., Cloud Run deployment killed the instance)
|
||||
if status == JobStatus.ENCODING and job.updated_at:
|
||||
now = datetime.now(timezone.utc)
|
||||
updated_at = job.updated_at
|
||||
if updated_at.tzinfo is None:
|
||||
updated_at = updated_at.replace(tzinfo=timezone.utc)
|
||||
encoding_age = now - updated_at
|
||||
if encoding_age > timedelta(minutes=50):
|
||||
minutes = int(encoding_age.total_seconds() / 60)
|
||||
issues.append(
|
||||
f"encoding_stuck: status=encoding for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
# Check: job stuck in downloading_audio status beyond 10 minutes
|
||||
# Audio downloads typically complete in 30s-5min. If stuck longer,
|
||||
# the Cloud Run Job likely failed silently.
|
||||
if status == JobStatus.DOWNLOADING_AUDIO and job.updated_at:
|
||||
now = datetime.now(timezone.utc)
|
||||
updated_at = job.updated_at
|
||||
if updated_at.tzinfo is None:
|
||||
updated_at = updated_at.replace(tzinfo=timezone.utc)
|
||||
download_age = now - updated_at
|
||||
if download_age > timedelta(minutes=10):
|
||||
minutes = int(download_age.total_seconds() / 60)
|
||||
issues.append(
|
||||
f"downloading_audio_stuck: status=downloading_audio for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def check_job_consistency_detailed(job: Job) -> Dict[str, Any]:
|
||||
"""
|
||||
Check job consistency with detailed information for debugging.
|
||||
|
||||
Returns a dictionary with:
|
||||
- job_id: The job ID
|
||||
- status: Current job status
|
||||
- issues: List of issue descriptions
|
||||
- state_data_summary: Summary of relevant state_data fields
|
||||
- is_healthy: Boolean indicating if no issues were found
|
||||
|
||||
Args:
|
||||
job: Job object to check
|
||||
|
||||
Returns:
|
||||
Dictionary with detailed consistency information
|
||||
"""
|
||||
issues = check_job_consistency(job)
|
||||
state_data = job.state_data or {}
|
||||
|
||||
return {
|
||||
"job_id": job.job_id,
|
||||
"status": job.status.value if hasattr(job.status, 'value') else str(job.status),
|
||||
"issues": issues,
|
||||
"state_data_summary": {
|
||||
"audio_complete": state_data.get('audio_complete', False),
|
||||
"lyrics_complete": state_data.get('lyrics_complete', False),
|
||||
"screens_progress_stage": state_data.get('screens_progress', {}).get('stage'),
|
||||
"has_input_media_gcs_path": bool(job.input_media_gcs_path),
|
||||
},
|
||||
"is_healthy": len(issues) == 0,
|
||||
}
|
||||
|
||||
|
||||
def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
|
||||
"""
|
||||
Get mapping of worker names to their valid job statuses.
|
||||
|
||||
This is used by workers to validate they should run for a given job.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping worker name to list of valid JobStatus values
|
||||
"""
|
||||
return {
|
||||
"audio_worker": [
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.DOWNLOADING_AUDIO,
|
||||
JobStatus.SEPARATING_STAGE1,
|
||||
JobStatus.SEPARATING_STAGE2,
|
||||
],
|
||||
"lyrics_worker": [
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.TRANSCRIBING,
|
||||
JobStatus.CORRECTING,
|
||||
],
|
||||
"screens_worker": [
|
||||
# Screens worker can be triggered when both audio+lyrics complete
|
||||
# which can happen in any of these states
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.AUDIO_COMPLETE,
|
||||
JobStatus.LYRICS_COMPLETE,
|
||||
# Also valid if re-running after a failure
|
||||
JobStatus.GENERATING_SCREENS,
|
||||
],
|
||||
"video_worker": [
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.GENERATING_VIDEO,
|
||||
],
|
||||
"render_video_worker": [
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def validate_worker_can_run(worker_name: str, job: Job) -> Optional[str]:
|
||||
"""
|
||||
Validate that a worker should run for the given job.
|
||||
|
||||
Args:
|
||||
worker_name: Name of the worker (e.g., "screens_worker")
|
||||
job: Job object to validate
|
||||
|
||||
Returns:
|
||||
None if valid, or an error message string if invalid
|
||||
"""
|
||||
valid_statuses_map = get_worker_valid_statuses()
|
||||
|
||||
if worker_name not in valid_statuses_map:
|
||||
# Unknown worker, can't validate
|
||||
return None
|
||||
|
||||
valid_statuses = valid_statuses_map[worker_name]
|
||||
|
||||
# Normalize status
|
||||
status = job.status
|
||||
if isinstance(status, str):
|
||||
try:
|
||||
status = JobStatus(status)
|
||||
except ValueError:
|
||||
return f"Invalid job status: {job.status}"
|
||||
|
||||
if status not in valid_statuses:
|
||||
valid_names = [s.value for s in valid_statuses]
|
||||
return (
|
||||
f"{worker_name} called but job status is {status.value}, "
|
||||
f"expected one of {valid_names}. This may indicate a bug in the trigger logic."
|
||||
)
|
||||
|
||||
return None
|
||||
+79
-325
@@ -14,7 +14,7 @@ from datetime import datetime
|
||||
from typing import Optional, Dict, Any, List
|
||||
|
||||
from backend.config import settings
|
||||
from backend.exceptions import InvalidStateTransitionError, InsufficientCreditsError
|
||||
from backend.exceptions import RateLimitExceededError
|
||||
from backend.models.job import Job, JobStatus, JobCreate, STATE_TRANSITIONS
|
||||
from backend.models.worker_log import WorkerLogEntry
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
@@ -51,21 +51,33 @@ class JobManager:
|
||||
|
||||
Args:
|
||||
job_create: Job creation parameters
|
||||
is_admin: Whether the requesting user is an admin (bypasses credit checks)
|
||||
is_admin: Whether the requesting user is an admin (bypasses rate limits)
|
||||
|
||||
Raises:
|
||||
ValueError: If theme_id is not provided (all jobs require a theme)
|
||||
RateLimitExceededError: If user has exceeded their daily job limit
|
||||
"""
|
||||
# Check credits (skip for admins)
|
||||
if job_create.user_email and not is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
if not user_service.has_credits(job_create.user_email):
|
||||
credits_available = user_service.check_credits(job_create.user_email)
|
||||
raise InsufficientCreditsError(
|
||||
message="You're out of credits. Buy more to continue creating karaoke videos.",
|
||||
credits_available=credits_available,
|
||||
credits_required=1,
|
||||
# Check rate limit FIRST (before any other validation)
|
||||
# This prevents wasted work if user is rate limited
|
||||
if job_create.user_email:
|
||||
from backend.services.rate_limit_service import get_rate_limit_service
|
||||
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
allowed, remaining, message = rate_limit_service.check_user_job_limit(
|
||||
user_email=job_create.user_email,
|
||||
is_admin=is_admin
|
||||
)
|
||||
if not allowed:
|
||||
from backend.services.rate_limit_service import _seconds_until_midnight_utc
|
||||
|
||||
# Get actual current count - remaining is clamped to 0 which loses info
|
||||
current_count = rate_limit_service.get_user_job_count_today(job_create.user_email)
|
||||
raise RateLimitExceededError(
|
||||
message=message,
|
||||
limit_type="jobs_per_day",
|
||||
remaining_seconds=_seconds_until_midnight_utc(),
|
||||
current_count=current_count,
|
||||
limit_value=settings.rate_limit_jobs_per_day
|
||||
)
|
||||
|
||||
# Enforce theme requirement - all jobs must have a theme
|
||||
@@ -118,38 +130,20 @@ class JobManager:
|
||||
made_for_you=job_create.made_for_you,
|
||||
customer_email=job_create.customer_email,
|
||||
customer_notes=job_create.customer_notes,
|
||||
# Private (non-published) track mode
|
||||
is_private=job_create.is_private,
|
||||
# Capture creation-time decision params for observability
|
||||
creation_params={
|
||||
"is_private": job_create.is_private,
|
||||
"is_admin": is_admin,
|
||||
"created_from": job_create.request_metadata.get("created_from", "unknown"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
self.firestore.create_job(job)
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
# Deduct credit atomically (after job is persisted so we have job_id for transaction record)
|
||||
if job_create.user_email and not is_admin:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
success, _remaining, deduct_msg = user_service.deduct_credit(
|
||||
job_create.user_email, job_id, reason="job_creation"
|
||||
)
|
||||
if not success:
|
||||
# Deduction failed (e.g., race condition) - delete the job and raise error
|
||||
logger.error(f"Credit deduction failed for job {job_id}: {deduct_msg}")
|
||||
try:
|
||||
self.firestore.delete_job(job_id)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to delete job {job_id} after credit deduction failure")
|
||||
raise InsufficientCreditsError(
|
||||
message="Failed to deduct credit. Please try again.",
|
||||
credits_available=0,
|
||||
credits_required=1,
|
||||
)
|
||||
# Record job creation for rate limiting (after successful persistence)
|
||||
if job_create.user_email:
|
||||
try:
|
||||
from backend.services.rate_limit_service import get_rate_limit_service
|
||||
rate_limit_service = get_rate_limit_service()
|
||||
rate_limit_service.record_job_creation(job_create.user_email, job_id)
|
||||
except Exception as e:
|
||||
# Don't fail job creation if rate limit recording fails
|
||||
logger.warning(f"Failed to record job creation for rate limiting: {e}")
|
||||
|
||||
return job
|
||||
|
||||
@@ -216,31 +210,6 @@ class JobManager:
|
||||
limit=limit
|
||||
)
|
||||
|
||||
def list_jobs_summary(
|
||||
self,
|
||||
status: Optional[JobStatus] = None,
|
||||
exclude_statuses: Optional[List[str]] = None,
|
||||
environment: Optional[str] = None,
|
||||
client_id: Optional[str] = None,
|
||||
created_after: Optional[datetime] = None,
|
||||
created_before: Optional[datetime] = None,
|
||||
user_email: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""List jobs with field projection (summary mode)."""
|
||||
return self.firestore.list_jobs_summary(
|
||||
status=status,
|
||||
exclude_statuses=exclude_statuses,
|
||||
environment=environment,
|
||||
client_id=client_id,
|
||||
created_after=created_after,
|
||||
created_before=created_before,
|
||||
user_email=user_email,
|
||||
tenant_id=tenant_id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
def delete_jobs_by_filter(
|
||||
self,
|
||||
environment: Optional[str] = None,
|
||||
@@ -327,20 +296,14 @@ class JobManager:
|
||||
|
||||
def delete_job(self, job_id: str, delete_files: bool = True) -> None:
|
||||
"""Delete a job, its files, and its logs subcollection."""
|
||||
job = self.get_job(job_id)
|
||||
|
||||
# Refund credit if job never completed (and wasn't already refunded via fail/cancel)
|
||||
if job:
|
||||
no_refund_statuses = [JobStatus.COMPLETE, JobStatus.PREP_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
if job.status not in no_refund_statuses:
|
||||
self._refund_credit_for_job(job_id, job, reason="job_deleted")
|
||||
|
||||
if delete_files and job and job.output_files:
|
||||
for gcs_path in job.output_files.values():
|
||||
try:
|
||||
self.storage.delete_file(gcs_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting file {gcs_path}: {e}")
|
||||
if delete_files:
|
||||
job = self.get_job(job_id)
|
||||
if job and job.output_files:
|
||||
for gcs_path in job.output_files.values():
|
||||
try:
|
||||
self.storage.delete_file(gcs_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting file {gcs_path}: {e}")
|
||||
|
||||
# Delete logs subcollection first (must be done before deleting parent doc)
|
||||
try:
|
||||
@@ -353,87 +316,53 @@ class JobManager:
|
||||
self.firestore.delete_job(job_id)
|
||||
logger.info(f"Deleted job {job_id}")
|
||||
|
||||
def validate_state_transition(
|
||||
self,
|
||||
job_id: str,
|
||||
new_status: JobStatus,
|
||||
raise_on_invalid: bool = True
|
||||
) -> bool:
|
||||
def validate_state_transition(self, job_id: str, new_status: JobStatus) -> bool:
|
||||
"""
|
||||
Validate that a state transition is legal.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
new_status: Target state
|
||||
raise_on_invalid: If True, raise InvalidStateTransitionError on invalid
|
||||
transitions. If False, return False (legacy behavior).
|
||||
|
||||
|
||||
Returns:
|
||||
True if transition is valid
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If transition is invalid and raise_on_invalid=True
|
||||
ValueError: If job not found and raise_on_invalid=True
|
||||
True if transition is valid, False otherwise
|
||||
"""
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
error_msg = f"Job {job_id} not found"
|
||||
logger.error(error_msg)
|
||||
if raise_on_invalid:
|
||||
raise ValueError(error_msg)
|
||||
logger.error(f"Job {job_id} not found")
|
||||
return False
|
||||
|
||||
|
||||
current_status = job.status
|
||||
valid_transitions = STATE_TRANSITIONS.get(current_status, [])
|
||||
|
||||
|
||||
if new_status not in valid_transitions:
|
||||
error_msg = (
|
||||
logger.error(
|
||||
f"Invalid state transition for job {job_id}: "
|
||||
f"{current_status} -> {new_status}. "
|
||||
f"Valid transitions: {[s.value for s in valid_transitions]}"
|
||||
f"Valid transitions: {valid_transitions}"
|
||||
)
|
||||
logger.error(error_msg)
|
||||
|
||||
if raise_on_invalid:
|
||||
raise InvalidStateTransitionError(
|
||||
message=error_msg,
|
||||
job_id=job_id,
|
||||
from_status=current_status,
|
||||
to_status=new_status.value if hasattr(new_status, 'value') else str(new_status),
|
||||
valid_transitions=[s.value for s in valid_transitions]
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def transition_to_state(
|
||||
self,
|
||||
job_id: str,
|
||||
new_status: JobStatus,
|
||||
progress: Optional[int] = None,
|
||||
message: Optional[str] = None,
|
||||
state_data_updates: Optional[Dict[str, Any]] = None,
|
||||
raise_on_invalid: bool = True
|
||||
state_data_updates: Optional[Dict[str, Any]] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Transition job to new state with validation.
|
||||
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
new_status: Target state
|
||||
progress: Progress percentage (0-100)
|
||||
message: Timeline message
|
||||
state_data_updates: Updates to state_data field
|
||||
raise_on_invalid: If True (default), raise InvalidStateTransitionError
|
||||
on invalid transitions. If False, return False silently.
|
||||
|
||||
|
||||
Returns:
|
||||
True if transition succeeded, False if failed (only when raise_on_invalid=False)
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If transition is invalid and raise_on_invalid=True
|
||||
True if transition succeeded, False otherwise
|
||||
"""
|
||||
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
|
||||
if not self.validate_state_transition(job_id, new_status):
|
||||
return False
|
||||
|
||||
updates = {
|
||||
@@ -452,6 +381,15 @@ class JobManager:
|
||||
updates['review_token'] = review_token
|
||||
updates['review_token_expires_at'] = None # No expiry - token is job-scoped
|
||||
logger.info(f"Generated review token for job {job_id} (no expiry)")
|
||||
|
||||
# Generate instrumental token when entering AWAITING_INSTRUMENTAL_SELECTION state
|
||||
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
|
||||
from backend.api.dependencies import generate_review_token
|
||||
instrumental_token = generate_review_token() # Reuse same token generator
|
||||
updates['instrumental_token'] = instrumental_token
|
||||
updates['instrumental_token_expires_at'] = None # No expiry - token is job-scoped
|
||||
logger.info(f"Generated instrumental token for job {job_id} (no expiry)")
|
||||
|
||||
# If we have state_data_updates, merge them with existing state_data
|
||||
merged_state_data = None
|
||||
@@ -483,20 +421,16 @@ class JobManager:
|
||||
'review_token': updates['review_token'],
|
||||
'review_token_expires_at': updates['review_token_expires_at']
|
||||
})
|
||||
|
||||
# Apply instrumental token update separately if generated
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION and 'instrumental_token' in updates:
|
||||
self.firestore.update_job(job_id, {
|
||||
'instrumental_token': updates['instrumental_token'],
|
||||
'instrumental_token_expires_at': updates['instrumental_token_expires_at']
|
||||
})
|
||||
|
||||
logger.info(f"Job {job_id} transitioned to {new_status}")
|
||||
|
||||
# Increment user's completed jobs counter on terminal success states
|
||||
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
|
||||
try:
|
||||
job = self.get_job(job_id)
|
||||
if job and job.user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
user_service.increment_jobs_completed(job.user_email)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to increment jobs_completed for job {job_id}")
|
||||
|
||||
# Trigger notifications asynchronously (fire-and-forget)
|
||||
self._trigger_state_notifications(job_id, new_status)
|
||||
|
||||
@@ -557,7 +491,6 @@ class JobManager:
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
dropbox_url = state_data.get('dropbox_link')
|
||||
brand_code = state_data.get('brand_code')
|
||||
youtube_queued = state_data.get('youtube_upload_queued', False)
|
||||
|
||||
# For made-for-you orders, send to customer and transfer ownership
|
||||
recipient_email = job.user_email
|
||||
@@ -581,8 +514,6 @@ class JobManager:
|
||||
youtube_url=youtube_url,
|
||||
dropbox_url=dropbox_url,
|
||||
brand_code=brand_code,
|
||||
is_private=getattr(job, 'is_private', False),
|
||||
youtube_queued=youtube_queued,
|
||||
)
|
||||
|
||||
# Try to get existing event loop, create new one if none exists
|
||||
@@ -684,7 +615,6 @@ class JobManager:
|
||||
"user_email": job.user_email,
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
"tenant_id": job.tenant_id or None,
|
||||
}
|
||||
|
||||
async def send_notification():
|
||||
@@ -712,114 +642,20 @@ class JobManager:
|
||||
def update_state_data(self, job_id: str, key: str, value: Any) -> None:
|
||||
"""
|
||||
Update a specific key in the job's state_data field.
|
||||
|
||||
|
||||
This is used by workers to store stage-specific metadata.
|
||||
"""
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"Job {job_id} not found")
|
||||
return
|
||||
|
||||
|
||||
state_data = job.state_data.copy()
|
||||
state_data[key] = value
|
||||
|
||||
|
||||
self.update_job(job_id, {'state_data': state_data})
|
||||
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
|
||||
|
||||
def delete_state_data_key(self, job_id: str, key: str) -> bool:
|
||||
"""
|
||||
Delete a specific key from the job's state_data field.
|
||||
|
||||
Uses Firestore DELETE_FIELD to atomically remove the key.
|
||||
This is used to clear worker progress markers, allowing workers
|
||||
to re-run without skipping due to idempotency checks.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
key: The state_data key to delete (e.g., "render_progress")
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
try:
|
||||
job_ref = self.firestore.db.collection("jobs").document(job_id)
|
||||
job_ref.update({f"state_data.{key}": DELETE_FIELD})
|
||||
logger.debug(f"Job {job_id}: Deleted state_data key '{key}'")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to delete state_data key '{key}': {e}")
|
||||
return False
|
||||
|
||||
def delete_state_data_keys(self, job_id: str, keys: List[str]) -> List[str]:
|
||||
"""
|
||||
Delete multiple keys from the job's state_data field in a single operation.
|
||||
|
||||
Uses Firestore DELETE_FIELD to atomically remove the keys.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
keys: List of state_data keys to delete
|
||||
|
||||
Returns:
|
||||
List of keys that were successfully deleted
|
||||
"""
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
if not keys:
|
||||
return []
|
||||
|
||||
try:
|
||||
job_ref = self.firestore.db.collection("jobs").document(job_id)
|
||||
update_payload = {f"state_data.{key}": DELETE_FIELD for key in keys}
|
||||
job_ref.update(update_payload)
|
||||
logger.info(f"Job {job_id}: Deleted state_data keys: {keys}")
|
||||
return keys
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to delete state_data keys {keys}: {e}")
|
||||
return []
|
||||
|
||||
def _refund_credit_for_job(self, job_id: str, job: Job, reason: str) -> bool:
|
||||
"""
|
||||
Refund one credit for a job if eligible.
|
||||
|
||||
Skips refund if: already refunded, no user email, or admin-owned job.
|
||||
Never raises — refund failure must not block the calling operation.
|
||||
|
||||
Returns:
|
||||
True if credit was refunded, False otherwise.
|
||||
"""
|
||||
try:
|
||||
if job.credit_refunded:
|
||||
logger.info(f"Credit already refunded for job {job_id}, skipping")
|
||||
return False
|
||||
|
||||
if not job.user_email:
|
||||
return False
|
||||
|
||||
from backend.services.auth_service import is_admin_email
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
if is_admin_email(job.user_email):
|
||||
return False
|
||||
|
||||
user_service = get_user_service()
|
||||
refund_ok, new_balance, refund_msg = user_service.refund_credit(
|
||||
job.user_email, job_id, reason=reason
|
||||
)
|
||||
if refund_ok:
|
||||
# Mark job as refunded to prevent double-refund
|
||||
self.update_job(job_id, {'credit_refunded': True})
|
||||
logger.info(f"Refunded credit for {reason} job {job_id} to {_mask_email(job.user_email)} (balance: {new_balance})")
|
||||
return True
|
||||
else:
|
||||
logger.warning(f"Credit refund failed for job {job_id}: {refund_msg}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning(f"Error refunding credit for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
def fail_job(self, job_id: str, error_message: str, error_details: Optional[Dict[str, Any]] = None) -> bool:
|
||||
"""
|
||||
Mark a job as failed with error information.
|
||||
@@ -847,17 +683,11 @@ class JobManager:
|
||||
)
|
||||
|
||||
logger.error(f"Job {job_id} failed: {error_message}")
|
||||
|
||||
# Auto-refund credit on failure
|
||||
job = self.get_job(job_id)
|
||||
if job:
|
||||
self._refund_credit_for_job(job_id, job, reason="job_failed")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Error marking job {job_id} as failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def update_file_url(self, job_id: str, category: str, file_type: str, url: str) -> None:
|
||||
"""
|
||||
Update a file URL in the job's file_urls structure.
|
||||
@@ -900,79 +730,7 @@ class JobManager:
|
||||
lyrics_complete = job.state_data.get('lyrics_complete', False)
|
||||
|
||||
return audio_complete and lyrics_complete
|
||||
|
||||
async def start_job_processing(
|
||||
self,
|
||||
job_id: str,
|
||||
progress: int = 15,
|
||||
message: str = "Starting audio and lyrics processing"
|
||||
) -> None:
|
||||
"""
|
||||
Transition job to DOWNLOADING and trigger audio + lyrics workers.
|
||||
|
||||
This is the single entry point for starting job processing after audio
|
||||
is available. All handlers (file_upload, webhook, audio_search) should
|
||||
use this method to ensure consistent state transitions.
|
||||
|
||||
The method:
|
||||
1. Validates job exists and has input_media_gcs_path
|
||||
2. Transitions to DOWNLOADING status (raises if invalid)
|
||||
3. Triggers audio and lyrics workers in parallel
|
||||
|
||||
Args:
|
||||
job_id: Job ID to start processing
|
||||
progress: Progress percentage to set (default 15)
|
||||
message: Timeline message (default "Starting audio and lyrics processing")
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If job can't transition to DOWNLOADING
|
||||
ValueError: If job not found or missing input_media_gcs_path
|
||||
|
||||
Example:
|
||||
# After downloading audio to GCS:
|
||||
job_manager.update_job(job_id, {'input_media_gcs_path': audio_path})
|
||||
await job_manager.start_job_processing(job_id)
|
||||
"""
|
||||
import asyncio
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
raise ValueError(f"Job {job_id} not found")
|
||||
|
||||
if not job.input_media_gcs_path:
|
||||
raise ValueError(
|
||||
f"Job {job_id} missing input_media_gcs_path. "
|
||||
"Audio must be downloaded to GCS before starting processing."
|
||||
)
|
||||
|
||||
# Transition to DOWNLOADING - this will raise if invalid
|
||||
self.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=progress,
|
||||
message=message
|
||||
)
|
||||
|
||||
# Check if audio separation can be skipped
|
||||
# Jobs with an existing instrumental (e.g. tenant uploads) don't need
|
||||
# GPU-powered audio separation — saves 5-10 minutes of processing time
|
||||
worker_service = get_worker_service()
|
||||
|
||||
if job.existing_instrumental_gcs_path:
|
||||
logger.info(f"Job {job_id}: Skipping audio separation (existing instrumental provided)")
|
||||
# Mark audio as immediately complete and only trigger lyrics worker
|
||||
self.update_state_data(job_id, 'audio_complete', True)
|
||||
await worker_service.trigger_lyrics_worker(job_id)
|
||||
logger.info(f"Job {job_id}: Started processing (lyrics worker only, audio separation skipped)")
|
||||
else:
|
||||
# Trigger both workers in parallel
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
logger.info(f"Job {job_id}: Started processing (audio + lyrics workers triggered)")
|
||||
|
||||
|
||||
def mark_audio_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
Mark audio processing as complete and check if can proceed.
|
||||
@@ -1057,12 +815,8 @@ class JobManager:
|
||||
)
|
||||
|
||||
logger.info(f"Job {job_id} cancelled")
|
||||
|
||||
# Refund credit for cancelled job
|
||||
self._refund_credit_for_job(job_id, job, reason="job_cancelled")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def mark_job_failed(
|
||||
self,
|
||||
job_id: str,
|
||||
|
||||
@@ -53,13 +53,13 @@ class JobNotificationService:
|
||||
|
||||
def _build_review_url(self, job_id: str, audio_hash: Optional[str] = None, review_token: Optional[str] = None) -> str:
|
||||
"""Build the lyrics review URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/review"
|
||||
# Use consolidated frontend route
|
||||
return f"{self.frontend_url}/app/jobs/{job_id}/review"
|
||||
|
||||
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None) -> str:
|
||||
"""Build the instrumental selection URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
|
||||
# Use consolidated frontend route
|
||||
return f"{self.frontend_url}/app/jobs/{job_id}/instrumental"
|
||||
|
||||
async def send_job_completion_email(
|
||||
self,
|
||||
@@ -71,8 +71,6 @@ class JobNotificationService:
|
||||
youtube_url: Optional[str] = None,
|
||||
dropbox_url: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
Send job completion email to user.
|
||||
@@ -86,8 +84,6 @@ class JobNotificationService:
|
||||
youtube_url: YouTube video URL
|
||||
dropbox_url: Dropbox folder URL
|
||||
brand_code: Release ID (e.g., "NOMAD-1178")
|
||||
is_private: If True, omit YouTube section (private/non-published tracks)
|
||||
youtube_queued: If True, YouTube upload was deferred due to quota
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
@@ -110,8 +106,6 @@ class JobNotificationService:
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
feedback_url=FEEDBACK_FORM_URL,
|
||||
is_private=is_private,
|
||||
youtube_queued=youtube_queued,
|
||||
)
|
||||
|
||||
# Send the email with CC to admin
|
||||
@@ -135,63 +129,6 @@ class JobNotificationService:
|
||||
logger.exception(f"Error sending completion email for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_youtube_upload_complete_email(
|
||||
self,
|
||||
job_id: str,
|
||||
user_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send follow-up email when a deferred YouTube upload completes.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
user_email: User's email address
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
youtube_url: YouTube video URL
|
||||
brand_code: Release ID
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
if not ENABLE_AUTO_EMAILS:
|
||||
logger.info(f"Auto emails disabled, skipping YouTube notification for job {job_id}")
|
||||
return False
|
||||
|
||||
if not user_email:
|
||||
logger.warning(f"No user email for job {job_id}, skipping YouTube notification")
|
||||
return False
|
||||
|
||||
try:
|
||||
message_content = self.template_service.render_youtube_upload_complete(
|
||||
artist=artist,
|
||||
title=title,
|
||||
youtube_url=youtube_url,
|
||||
)
|
||||
|
||||
success = self.email_service.send_youtube_upload_complete(
|
||||
to_email=user_email,
|
||||
message_content=message_content,
|
||||
artist=artist,
|
||||
title=title,
|
||||
brand_code=brand_code,
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info(f"Sent YouTube upload notification for job {job_id} to {_mask_email(user_email)}")
|
||||
else:
|
||||
logger.error(f"Failed to send YouTube upload notification for job {job_id}")
|
||||
|
||||
return success
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error sending YouTube upload notification for job {job_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_action_reminder_email(
|
||||
self,
|
||||
job_id: str,
|
||||
@@ -210,15 +147,13 @@ class JobNotificationService:
|
||||
Args:
|
||||
job_id: Job ID
|
||||
user_email: User's email address
|
||||
action_type: Type of action needed:
|
||||
- "lyrics": Combined review (lyrics + instrumental selection) for normal jobs
|
||||
- "instrumental": Instrumental-only selection for finalise-only jobs
|
||||
action_type: Type of action needed ("lyrics" or "instrumental")
|
||||
user_name: User's display name
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
audio_hash: Audio hash for review URL (unused, kept for compatibility)
|
||||
review_token: Review token for URL (unused, kept for compatibility)
|
||||
instrumental_token: Instrumental token for URL (unused, kept for compatibility)
|
||||
audio_hash: Audio hash for review URL
|
||||
review_token: Review token for URL
|
||||
instrumental_token: Instrumental token for URL
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
@@ -281,8 +216,6 @@ class JobNotificationService:
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
dropbox_url: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
Get the rendered completion message for a job (for admin copy functionality).
|
||||
@@ -294,8 +227,6 @@ class JobNotificationService:
|
||||
title: Song title
|
||||
youtube_url: YouTube video URL
|
||||
dropbox_url: Dropbox folder URL
|
||||
is_private: If True, omit YouTube section (private/non-published tracks)
|
||||
youtube_queued: If True, YouTube upload was deferred
|
||||
|
||||
Returns:
|
||||
Rendered message content as plain text
|
||||
@@ -308,8 +239,6 @@ class JobNotificationService:
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
feedback_url=FEEDBACK_FORM_URL,
|
||||
is_private=is_private,
|
||||
youtube_queued=youtube_queued,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
"""
|
||||
KaraokeNerds community version detection service.
|
||||
|
||||
Scrapes karaokenerds.com to check if a song already has community-approved
|
||||
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
|
||||
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
|
||||
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
|
||||
|
||||
def _clean_youtube_url(url: str) -> str:
|
||||
"""Strip playlist params from YouTube URLs, keep just the video URL."""
|
||||
return re.sub(r"&list=[^&]*", "", url)
|
||||
|
||||
|
||||
def _parse_single_track(li) -> dict | None:
|
||||
"""Parse a single track <li> element from karaokenerds search results."""
|
||||
# Brand name: first <a> in the li
|
||||
brand_link = li.find("a")
|
||||
brand_name = brand_link.get_text(strip=True) if brand_link else ""
|
||||
|
||||
# Brand code: text inside .badge span
|
||||
badge = li.find("span", class_="badge")
|
||||
brand_code = ""
|
||||
if badge:
|
||||
brand_code = badge.get_text(strip=True)
|
||||
|
||||
# YouTube URL: link containing youtube.com
|
||||
youtube_url = None
|
||||
for a in li.find_all("a", href=True):
|
||||
href = a["href"]
|
||||
if "youtube.com" in href:
|
||||
youtube_url = _clean_youtube_url(href)
|
||||
break
|
||||
|
||||
# Community: presence of img.check
|
||||
is_community = bool(li.find("img", class_="check"))
|
||||
|
||||
if not youtube_url:
|
||||
return None
|
||||
|
||||
return {
|
||||
"brand_name": brand_name,
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": is_community,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tracks(details_row) -> list[dict]:
|
||||
"""Parse track list items from a details row."""
|
||||
tracks = []
|
||||
for li in details_row.find_all("li", class_="track"):
|
||||
track = _parse_single_track(li)
|
||||
if track:
|
||||
tracks.append(track)
|
||||
return tracks
|
||||
|
||||
|
||||
def parse_results(html: str) -> list[dict]:
|
||||
"""Parse karaokenerds.com search results HTML into structured data."""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
table = soup.find("table")
|
||||
if not table:
|
||||
return []
|
||||
|
||||
tbody = table.find("tbody")
|
||||
if not tbody:
|
||||
return []
|
||||
|
||||
songs = []
|
||||
rows = tbody.find_all("tr", recursive=False)
|
||||
|
||||
i = 0
|
||||
while i < len(rows):
|
||||
row = rows[i]
|
||||
|
||||
# Song rows have class "group"
|
||||
if "group" not in row.get("class", []):
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Extract title and artist from the song row
|
||||
cells = row.find_all("td")
|
||||
if len(cells) < 3:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
title_link = cells[0].find("a")
|
||||
artist_link = cells[1].find("a")
|
||||
title = title_link.get_text(strip=True) if title_link else ""
|
||||
artist = artist_link.get_text(strip=True) if artist_link else ""
|
||||
|
||||
# The next row should be the details row with tracks
|
||||
tracks = []
|
||||
if i + 1 < len(rows):
|
||||
details_row = rows[i + 1]
|
||||
if "details" in details_row.get("class", []):
|
||||
tracks = _parse_tracks(details_row)
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
if title:
|
||||
songs.append({
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": tracks,
|
||||
})
|
||||
|
||||
return songs
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
|
||||
Returns a dict with:
|
||||
- has_community: bool
|
||||
- songs: list of matched songs with community tracks
|
||||
- best_youtube_url: URL of the top community version (if any)
|
||||
"""
|
||||
query = f"{artist} {title}"
|
||||
cache_key = f"community:{query.lower().strip()}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
songs = parse_results(resp.text)
|
||||
|
||||
# Filter to only songs that have community tracks with YouTube URLs
|
||||
community_songs = []
|
||||
best_youtube_url = None
|
||||
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
"songs": community_songs,
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
@@ -5,19 +5,7 @@ slow initialization during request processing. The CallbackHandler()
|
||||
constructor makes blocking network calls to the Langfuse API, which can
|
||||
take 3+ minutes on Cloud Run cold starts.
|
||||
|
||||
IMPORTANT: Langfuse v3 is built on OpenTelemetry. If not configured carefully,
|
||||
it will install itself as the GLOBAL OpenTelemetry tracer provider, capturing
|
||||
ALL spans from every library (FastAPI, HTTP clients, etc.) - not just LLM calls.
|
||||
This caused us to exceed our Langfuse hobby tier monthly event limit with
|
||||
thousands of "(empty)" HTTP request traces.
|
||||
|
||||
The fix: Initialize the Langfuse client with an ISOLATED TracerProvider before
|
||||
creating the CallbackHandler. This ensures only LangChain/LLM traces are sent
|
||||
to Langfuse, while other OTEL instrumentation remains separate.
|
||||
|
||||
See:
|
||||
- docs/archive/2026-01-08-performance-investigation.md for background
|
||||
- https://github.com/orgs/langfuse/discussions/9136 for the OTEL issue
|
||||
See docs/archive/2026-01-08-performance-investigation.md for background.
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -38,10 +26,6 @@ def preload_langfuse_handler() -> Optional[Any]:
|
||||
Only initializes if LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY
|
||||
environment variables are set.
|
||||
|
||||
CRITICAL: We initialize the Langfuse client with an isolated TracerProvider
|
||||
BEFORE creating the CallbackHandler. This prevents Langfuse from hijacking
|
||||
the global OpenTelemetry provider and capturing all HTTP request spans.
|
||||
|
||||
Returns:
|
||||
The preloaded CallbackHandler, or None if not configured
|
||||
"""
|
||||
@@ -56,44 +40,28 @@ def preload_langfuse_handler() -> Optional[Any]:
|
||||
# Check if Langfuse is configured
|
||||
public_key = os.getenv("LANGFUSE_PUBLIC_KEY")
|
||||
secret_key = os.getenv("LANGFUSE_SECRET_KEY")
|
||||
host = os.getenv("LANGFUSE_HOST", "https://us.cloud.langfuse.com")
|
||||
|
||||
if not (public_key and secret_key):
|
||||
logger.info("Langfuse not configured (missing keys), skipping preload")
|
||||
return None
|
||||
|
||||
logger.info("Preloading Langfuse callback handler with isolated tracer...")
|
||||
logger.info("Preloading Langfuse callback handler...")
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
# Import OpenTelemetry TracerProvider for isolation
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from langfuse import Langfuse
|
||||
from langfuse.langchain import CallbackHandler
|
||||
|
||||
# CRITICAL: Initialize Langfuse client with an ISOLATED TracerProvider
|
||||
# This prevents Langfuse from setting itself as the global OTEL provider,
|
||||
# which would cause ALL HTTP requests to be traced (not just LLM calls).
|
||||
# See: https://github.com/orgs/langfuse/discussions/9136
|
||||
Langfuse(
|
||||
public_key=public_key,
|
||||
secret_key=secret_key,
|
||||
host=host,
|
||||
tracer_provider=TracerProvider(), # Isolated - won't touch global OTEL
|
||||
)
|
||||
logger.info("Langfuse client initialized with isolated TracerProvider")
|
||||
|
||||
# Now create the CallbackHandler - it will reuse the existing client
|
||||
# instead of creating a new one that hijacks global OTEL
|
||||
# Initialize the handler - this is the slow part that makes network calls
|
||||
_preloaded_handler = CallbackHandler()
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
host = os.getenv("LANGFUSE_HOST", "cloud.langfuse.com")
|
||||
logger.info(f"Langfuse handler preloaded in {elapsed:.2f}s (host: {host})")
|
||||
|
||||
return _preloaded_handler
|
||||
|
||||
except ImportError as e:
|
||||
logger.warning(f"langfuse or opentelemetry package not installed, skipping preload: {e}")
|
||||
except ImportError:
|
||||
logger.warning("langfuse package not installed, skipping preload")
|
||||
return None
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
@@ -38,9 +38,6 @@ class EncodingConfig:
|
||||
output_lossless_mkv: Optional[str] = None
|
||||
output_720p_mp4: Optional[str] = None
|
||||
|
||||
# Audio synchronization
|
||||
countdown_padding_seconds: Optional[float] = None # Pad instrumental to match countdown-padded vocals
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncodingResult:
|
||||
@@ -263,38 +260,6 @@ class LocalEncodingService:
|
||||
|
||||
return self._execute_command(cpu_command, description)
|
||||
|
||||
def _pad_audio_file(self, input_audio: str, output_audio: str, padding_seconds: float) -> str:
|
||||
"""Pad an audio file by prepending silence at the beginning.
|
||||
|
||||
Uses FFmpeg adelay filter - same approach as KaraokeFinalise._pad_audio_file().
|
||||
This ensures the instrumental audio is synchronized with countdown-padded vocals.
|
||||
|
||||
Args:
|
||||
input_audio: Path to input audio file
|
||||
output_audio: Path for the padded output file
|
||||
padding_seconds: Amount of silence to prepend (in seconds)
|
||||
|
||||
Returns:
|
||||
Path to the output audio file
|
||||
"""
|
||||
delay_ms = int(padding_seconds * 1000)
|
||||
cmd = [
|
||||
"ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
|
||||
"-i", input_audio,
|
||||
"-af", f"adelay={delay_ms}|{delay_ms}",
|
||||
output_audio
|
||||
]
|
||||
self.logger.info(f"Padding audio with {padding_seconds}s silence: {os.path.basename(input_audio)}")
|
||||
|
||||
if self.dry_run:
|
||||
self.logger.info(f"DRY RUN: Would pad audio file")
|
||||
return output_audio
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"FFmpeg padding failed: {result.stderr}")
|
||||
return output_audio
|
||||
|
||||
def remux_with_instrumental(
|
||||
self,
|
||||
input_video: str,
|
||||
@@ -500,27 +465,12 @@ class LocalEncodingService:
|
||||
output_files = {}
|
||||
|
||||
try:
|
||||
# Pad instrumental if countdown padding was applied to vocals
|
||||
actual_instrumental = config.instrumental_audio
|
||||
if config.countdown_padding_seconds and config.countdown_padding_seconds > 0:
|
||||
if "(Padded)" not in config.instrumental_audio:
|
||||
base, ext = os.path.splitext(config.instrumental_audio)
|
||||
padded_path = f"{base} (Padded){ext}"
|
||||
if not os.path.exists(padded_path) or self.dry_run:
|
||||
self._pad_audio_file(config.instrumental_audio, padded_path, config.countdown_padding_seconds)
|
||||
self.logger.info(f"Created padded instrumental: {padded_path}")
|
||||
else:
|
||||
self.logger.info(f"Using existing padded instrumental: {padded_path}")
|
||||
actual_instrumental = padded_path
|
||||
else:
|
||||
self.logger.info(f"Instrumental already padded: {config.instrumental_audio}")
|
||||
|
||||
# Step 1: Remux with instrumental audio
|
||||
if config.output_karaoke_mp4:
|
||||
self.logger.info("[Step 1/6] Remuxing video with instrumental audio...")
|
||||
if not self.remux_with_instrumental(
|
||||
config.karaoke_video,
|
||||
actual_instrumental,
|
||||
config.instrumental_audio,
|
||||
config.output_karaoke_mp4
|
||||
):
|
||||
return EncodingResult(
|
||||
|
||||
@@ -57,8 +57,6 @@ class PackagingService:
|
||||
title: str,
|
||||
output_mp3_path: Optional[str] = None,
|
||||
output_cdg_path: Optional[str] = None,
|
||||
lrc_has_countdown_padding: bool = False,
|
||||
countdown_padding_seconds: float = 3.0,
|
||||
) -> Tuple[str, Optional[str], Optional[str]]:
|
||||
"""
|
||||
Create a CDG package (ZIP containing CDG and MP3 files).
|
||||
@@ -71,9 +69,6 @@ class PackagingService:
|
||||
title: Song title for metadata
|
||||
output_mp3_path: Optional path for the extracted MP3 file
|
||||
output_cdg_path: Optional path for the extracted CDG file
|
||||
lrc_has_countdown_padding: If True, LRC contains countdown-shifted timestamps
|
||||
that need adjustment since CDG uses instrumental audio without padding
|
||||
countdown_padding_seconds: Duration of countdown padding to compensate for
|
||||
|
||||
Returns:
|
||||
Tuple of (zip_path, mp3_path, cdg_path)
|
||||
@@ -125,7 +120,7 @@ class PackagingService:
|
||||
)
|
||||
|
||||
self.logger.info("Generating CDG and MP3 files")
|
||||
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
|
||||
from lyrics_transcriber.output.cdg import CDGGenerator
|
||||
|
||||
output_dir = os.path.dirname(output_zip_path) or os.getcwd()
|
||||
generator = CDGGenerator(output_dir=output_dir, logger=self.logger)
|
||||
@@ -136,8 +131,6 @@ class PackagingService:
|
||||
title=title,
|
||||
artist=artist,
|
||||
cdg_styles=self.cdg_styles,
|
||||
lrc_has_countdown_padding=lrc_has_countdown_padding,
|
||||
countdown_padding_seconds=countdown_padding_seconds,
|
||||
)
|
||||
|
||||
# Rename ZIP to expected output path if different
|
||||
|
||||
@@ -85,14 +85,10 @@ class PushNotificationService:
|
||||
title: str,
|
||||
body: str,
|
||||
url: str = "/app/",
|
||||
tag: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
tag: Optional[str] = None
|
||||
) -> int:
|
||||
"""
|
||||
Send a push notification to a user's subscribed devices for a specific tenant.
|
||||
|
||||
Only sends to subscriptions matching the given tenant_id to prevent
|
||||
cross-tenant notification leakage.
|
||||
Send a push notification to all of a user's subscribed devices.
|
||||
|
||||
Args:
|
||||
user_email: The user's email address
|
||||
@@ -100,8 +96,6 @@ class PushNotificationService:
|
||||
body: Notification body text
|
||||
url: URL to open when notification is clicked
|
||||
tag: Optional tag for notification grouping (replaces notifications with same tag)
|
||||
tenant_id: Tenant scope - only send to subscriptions for this tenant
|
||||
(None or "" = consumer/default portal)
|
||||
|
||||
Returns:
|
||||
Number of notifications successfully sent
|
||||
@@ -117,30 +111,7 @@ class PushNotificationService:
|
||||
return 0
|
||||
|
||||
user_data = user_doc.to_dict()
|
||||
all_subscriptions = user_data.get("push_subscriptions", [])
|
||||
|
||||
# Filter subscriptions to only those matching the target tenant
|
||||
# Normalize: None and "" both mean "consumer/default portal"
|
||||
target_tenant = tenant_id or None
|
||||
subscriptions = [
|
||||
sub for sub in all_subscriptions
|
||||
if (sub.get("tenant_id") or None) == target_tenant
|
||||
]
|
||||
|
||||
if not subscriptions and all_subscriptions:
|
||||
# Migration path: if no subscriptions match and none have tenant_id set,
|
||||
# it means they're legacy subscriptions created before tenant scoping.
|
||||
# Send to legacy subscriptions (those without tenant_id) only if
|
||||
# the target is the consumer portal (no tenant).
|
||||
has_any_tenant_scoped = any(sub.get("tenant_id") for sub in all_subscriptions)
|
||||
if not has_any_tenant_scoped and target_tenant is None:
|
||||
subscriptions = all_subscriptions
|
||||
logger.debug(f"Using legacy unscoped subscriptions for {user_email}")
|
||||
else:
|
||||
logger.debug(
|
||||
f"No matching subscriptions for tenant={target_tenant} "
|
||||
f"(user has {len(all_subscriptions)} total subscriptions)"
|
||||
)
|
||||
subscriptions = user_data.get("push_subscriptions", [])
|
||||
|
||||
if not subscriptions:
|
||||
logger.debug(f"User {user_email} has no push subscriptions")
|
||||
@@ -225,7 +196,7 @@ class PushNotificationService:
|
||||
Send notification when a job enters a blocking state requiring user action.
|
||||
|
||||
Args:
|
||||
job: Job dictionary with job_id, user_email, artist, title, tenant_id
|
||||
job: Job dictionary with job_id, user_email, artist, title
|
||||
action_type: Type of action needed ("lyrics" or "instrumental")
|
||||
|
||||
Returns:
|
||||
@@ -238,7 +209,6 @@ class PushNotificationService:
|
||||
job_id = job.get("job_id", "unknown")
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
tenant_id = job.get("tenant_id") or None
|
||||
|
||||
if action_type == "lyrics":
|
||||
notif_title = "Review Lyrics"
|
||||
@@ -256,8 +226,7 @@ class PushNotificationService:
|
||||
title=notif_title,
|
||||
body=notif_body,
|
||||
url=url,
|
||||
tag=tag,
|
||||
tenant_id=tenant_id,
|
||||
tag=tag
|
||||
)
|
||||
|
||||
async def send_completion_notification(self, job: dict) -> int:
|
||||
@@ -265,7 +234,7 @@ class PushNotificationService:
|
||||
Send notification when a job completes successfully.
|
||||
|
||||
Args:
|
||||
job: Job dictionary with job_id, user_email, artist, title, tenant_id
|
||||
job: Job dictionary with job_id, user_email, artist, title
|
||||
|
||||
Returns:
|
||||
Number of notifications sent
|
||||
@@ -277,15 +246,13 @@ class PushNotificationService:
|
||||
job_id = job.get("job_id", "unknown")
|
||||
artist = job.get("artist", "Unknown Artist")
|
||||
title = job.get("title", "Unknown Title")
|
||||
tenant_id = job.get("tenant_id") or None
|
||||
|
||||
return await self.send_push(
|
||||
user_email=user_email,
|
||||
title="Video Ready!",
|
||||
body=f'Your karaoke video for "{title}" by {artist} is ready to download',
|
||||
url=f"/app/?job={job_id}",
|
||||
tag=f"complete-{job_id}",
|
||||
tenant_id=tenant_id,
|
||||
tag=f"complete-{job_id}"
|
||||
)
|
||||
|
||||
async def add_subscription(
|
||||
@@ -293,11 +260,10 @@ class PushNotificationService:
|
||||
user_email: str,
|
||||
endpoint: str,
|
||||
keys: dict,
|
||||
device_name: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
device_name: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Add a push subscription for a user, scoped to a tenant.
|
||||
Add a push subscription for a user.
|
||||
|
||||
Enforces max subscriptions per user - oldest removed if limit exceeded.
|
||||
|
||||
@@ -306,7 +272,6 @@ class PushNotificationService:
|
||||
endpoint: Push service endpoint URL
|
||||
keys: Encryption keys (p256dh, auth)
|
||||
device_name: Optional device identifier
|
||||
tenant_id: Tenant scope (None = consumer/default portal)
|
||||
|
||||
Returns:
|
||||
True if subscription was added successfully
|
||||
@@ -333,7 +298,6 @@ class PushNotificationService:
|
||||
"endpoint": endpoint,
|
||||
"keys": keys,
|
||||
"device_name": device_name,
|
||||
"tenant_id": tenant_id or None,
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"last_used_at": None
|
||||
}
|
||||
|
||||
@@ -0,0 +1,641 @@
|
||||
"""
|
||||
Rate limiting service for job creation, YouTube uploads, and beta enrollment.
|
||||
|
||||
Uses Firestore for distributed rate limit tracking with date-based document IDs
|
||||
that automatically reset at UTC midnight.
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Tuple, Optional, List, Dict, Any
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Firestore collection names
|
||||
RATE_LIMITS_COLLECTION = "rate_limits"
|
||||
BLOCKLISTS_COLLECTION = "blocklists"
|
||||
OVERRIDES_COLLECTION = "overrides"
|
||||
|
||||
|
||||
def _get_today_date_str() -> str:
|
||||
"""Get today's date in UTC as YYYY-MM-DD string."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _seconds_until_midnight_utc() -> int:
|
||||
"""Calculate seconds until UTC midnight (when rate limits reset)."""
|
||||
now = datetime.now(timezone.utc)
|
||||
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
# Add 1 day to get next midnight
|
||||
from datetime import timedelta
|
||||
next_midnight = midnight + timedelta(days=1)
|
||||
return int((next_midnight - now).total_seconds())
|
||||
|
||||
|
||||
def _hash_ip(ip_address: str) -> str:
|
||||
"""Hash an IP address for storage (privacy-preserving)."""
|
||||
return hashlib.sha256(ip_address.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
class RateLimitService:
|
||||
"""
|
||||
Service for managing rate limits across the platform.
|
||||
|
||||
Rate limits use Firestore for distributed tracking with automatic
|
||||
reset at UTC midnight via date-based document IDs.
|
||||
"""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
"""Initialize rate limit service with Firestore client."""
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
self._blocklist_cache: Optional[Dict[str, Any]] = None
|
||||
self._blocklist_cache_time: Optional[datetime] = None
|
||||
self._cache_ttl_seconds = 300 # 5 minute cache
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Job Rate Limiting
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def check_user_job_limit(self, user_email: str, is_admin: bool = False) -> Tuple[bool, int, str]:
|
||||
"""
|
||||
Check if a user can create a new job.
|
||||
|
||||
Args:
|
||||
user_email: User's email address
|
||||
is_admin: Whether the user is an admin (admins bypass limits)
|
||||
|
||||
Returns:
|
||||
Tuple of (allowed, remaining, message)
|
||||
- allowed: True if user can create job
|
||||
- remaining: Number of jobs remaining today
|
||||
- message: Human-readable status message
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return True, -1, "Rate limiting disabled"
|
||||
|
||||
if is_admin:
|
||||
return True, -1, "Admin users bypass rate limits"
|
||||
|
||||
limit = settings.rate_limit_jobs_per_day
|
||||
if limit == 0:
|
||||
return True, -1, "No job limit configured"
|
||||
|
||||
# Check for user override
|
||||
override = self.get_user_override(user_email)
|
||||
if override and override.get("bypass_job_limit"):
|
||||
return True, -1, "User has rate limit bypass"
|
||||
if override and override.get("custom_daily_job_limit"):
|
||||
limit = override["custom_daily_job_limit"]
|
||||
|
||||
# Get current count
|
||||
current_count = self.get_user_job_count_today(user_email)
|
||||
remaining = max(0, limit - current_count)
|
||||
|
||||
if current_count >= limit:
|
||||
seconds = _seconds_until_midnight_utc()
|
||||
logger.warning(
|
||||
f"Rate limit exceeded for {user_email}: {current_count}/{limit} jobs today"
|
||||
)
|
||||
return (
|
||||
False,
|
||||
0,
|
||||
f"Daily job limit reached ({limit} jobs per day). Resets in {seconds // 3600}h {(seconds % 3600) // 60}m."
|
||||
)
|
||||
|
||||
return True, remaining, f"{remaining} jobs remaining today"
|
||||
|
||||
def get_user_job_count_today(self, user_email: str) -> int:
|
||||
"""Get the number of jobs created by a user today."""
|
||||
date_str = _get_today_date_str()
|
||||
doc_ref = self.db.collection(RATE_LIMITS_COLLECTION).document(
|
||||
f"user_jobs_{user_email}_{date_str}"
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return 0
|
||||
|
||||
return doc.to_dict().get("count", 0)
|
||||
|
||||
def record_job_creation(self, user_email: str, job_id: str) -> None:
|
||||
"""
|
||||
Record a job creation for rate limiting.
|
||||
|
||||
Uses Firestore transactions for atomic increment.
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return
|
||||
|
||||
date_str = _get_today_date_str()
|
||||
doc_ref = self.db.collection(RATE_LIMITS_COLLECTION).document(
|
||||
f"user_jobs_{user_email}_{date_str}"
|
||||
)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
count = data.get("count", 0) + 1
|
||||
job_ids = data.get("job_ids", [])
|
||||
job_ids.append(job_id)
|
||||
else:
|
||||
count = 1
|
||||
job_ids = [job_id]
|
||||
|
||||
transaction.set(doc_ref, {
|
||||
"user_email": user_email,
|
||||
"date": date_str,
|
||||
"count": count,
|
||||
"job_ids": job_ids,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
logger.info(f"Recorded job {job_id} for user {user_email} rate limiting")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# YouTube Upload Rate Limiting
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def check_youtube_upload_limit(self) -> Tuple[bool, int, str]:
|
||||
"""
|
||||
Check if the system can perform a YouTube upload.
|
||||
|
||||
YouTube uploads are limited system-wide due to API quota constraints.
|
||||
|
||||
Returns:
|
||||
Tuple of (allowed, remaining, message)
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return True, -1, "Rate limiting disabled"
|
||||
|
||||
limit = settings.rate_limit_youtube_uploads_per_day
|
||||
if limit == 0:
|
||||
return True, -1, "No YouTube upload limit configured"
|
||||
|
||||
current_count = self.get_youtube_uploads_today()
|
||||
remaining = max(0, limit - current_count)
|
||||
|
||||
if current_count >= limit:
|
||||
seconds = _seconds_until_midnight_utc()
|
||||
logger.warning(
|
||||
f"YouTube upload limit exceeded: {current_count}/{limit} uploads today"
|
||||
)
|
||||
return (
|
||||
False,
|
||||
0,
|
||||
f"Daily YouTube upload limit reached ({limit} uploads per day). Resets in {seconds // 3600}h {(seconds % 3600) // 60}m."
|
||||
)
|
||||
|
||||
return True, remaining, f"{remaining} YouTube uploads remaining today"
|
||||
|
||||
def get_youtube_uploads_today(self) -> int:
|
||||
"""Get the number of YouTube uploads performed today (system-wide)."""
|
||||
date_str = _get_today_date_str()
|
||||
doc_ref = self.db.collection(RATE_LIMITS_COLLECTION).document(
|
||||
f"youtube_uploads_{date_str}"
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return 0
|
||||
|
||||
return doc.to_dict().get("count", 0)
|
||||
|
||||
def record_youtube_upload(self, job_id: str, user_email: str) -> None:
|
||||
"""
|
||||
Record a YouTube upload for rate limiting.
|
||||
|
||||
Uses Firestore transactions for atomic increment.
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return
|
||||
|
||||
date_str = _get_today_date_str()
|
||||
doc_ref = self.db.collection(RATE_LIMITS_COLLECTION).document(
|
||||
f"youtube_uploads_{date_str}"
|
||||
)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
count = data.get("count", 0) + 1
|
||||
uploads = data.get("uploads", [])
|
||||
else:
|
||||
count = 1
|
||||
uploads = []
|
||||
|
||||
uploads.append({
|
||||
"job_id": job_id,
|
||||
"user_email": user_email,
|
||||
"timestamp": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
transaction.set(doc_ref, {
|
||||
"date": date_str,
|
||||
"count": count,
|
||||
"uploads": uploads,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
logger.info(f"Recorded YouTube upload for job {job_id}")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Beta Enrollment IP Rate Limiting
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def check_beta_ip_limit(self, ip_address: str) -> Tuple[bool, int, str]:
|
||||
"""
|
||||
Check if an IP address can enroll in the beta program.
|
||||
|
||||
Args:
|
||||
ip_address: Client IP address
|
||||
|
||||
Returns:
|
||||
Tuple of (allowed, remaining, message)
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return True, -1, "Rate limiting disabled"
|
||||
|
||||
limit = settings.rate_limit_beta_ip_per_day
|
||||
if limit == 0:
|
||||
return True, -1, "No beta IP limit configured"
|
||||
|
||||
# Check today's enrollment count for this IP
|
||||
ip_hash = _hash_ip(ip_address)
|
||||
date_str = _get_today_date_str()
|
||||
|
||||
doc_ref = self.db.collection(RATE_LIMITS_COLLECTION).document(
|
||||
f"beta_ip_{ip_hash}_{date_str}"
|
||||
)
|
||||
doc = doc_ref.get()
|
||||
|
||||
current_count = 0
|
||||
if doc.exists:
|
||||
current_count = doc.to_dict().get("count", 0)
|
||||
|
||||
remaining = max(0, limit - current_count)
|
||||
|
||||
if current_count >= limit:
|
||||
seconds = _seconds_until_midnight_utc()
|
||||
logger.warning(
|
||||
f"Beta enrollment IP limit exceeded for {ip_hash}: {current_count}/{limit} enrollments today"
|
||||
)
|
||||
return (
|
||||
False,
|
||||
0,
|
||||
f"Too many beta enrollments from this network today. Please try again tomorrow."
|
||||
)
|
||||
|
||||
return True, remaining, f"{remaining} beta enrollments remaining from this IP today"
|
||||
|
||||
def record_beta_enrollment(self, ip_address: str, email: str) -> None:
|
||||
"""
|
||||
Record a beta enrollment for IP rate limiting.
|
||||
|
||||
Uses Firestore transactions for atomic increment.
|
||||
"""
|
||||
if not settings.enable_rate_limiting:
|
||||
return
|
||||
|
||||
ip_hash = _hash_ip(ip_address)
|
||||
date_str = _get_today_date_str()
|
||||
doc_ref = self.db.collection(RATE_LIMITS_COLLECTION).document(
|
||||
f"beta_ip_{ip_hash}_{date_str}"
|
||||
)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
count = data.get("count", 0) + 1
|
||||
enrollments = data.get("enrollments", [])
|
||||
else:
|
||||
count = 1
|
||||
enrollments = []
|
||||
|
||||
enrollments.append({
|
||||
"email": email,
|
||||
"timestamp": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
transaction.set(doc_ref, {
|
||||
"ip_hash": ip_hash,
|
||||
"date": date_str,
|
||||
"count": count,
|
||||
"enrollments": enrollments,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
logger.info(f"Recorded beta enrollment from IP {ip_hash} for {email}")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# User Overrides (Whitelist)
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def get_user_override(self, user_email: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get rate limit override settings for a user.
|
||||
|
||||
Returns:
|
||||
Override settings dict or None if no override exists
|
||||
"""
|
||||
doc_ref = self.db.collection(OVERRIDES_COLLECTION).document(user_email.lower())
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
return doc.to_dict()
|
||||
|
||||
def set_user_override(
|
||||
self,
|
||||
user_email: str,
|
||||
bypass_job_limit: bool = False,
|
||||
custom_daily_job_limit: Optional[int] = None,
|
||||
reason: str = "",
|
||||
admin_email: str = ""
|
||||
) -> None:
|
||||
"""
|
||||
Set rate limit override for a user.
|
||||
|
||||
Args:
|
||||
user_email: User to override
|
||||
bypass_job_limit: If True, user bypasses all job limits
|
||||
custom_daily_job_limit: Custom limit (None = use default)
|
||||
reason: Reason for override
|
||||
admin_email: Admin who set the override
|
||||
"""
|
||||
doc_ref = self.db.collection(OVERRIDES_COLLECTION).document(user_email.lower())
|
||||
doc_ref.set({
|
||||
"email": user_email.lower(),
|
||||
"bypass_job_limit": bypass_job_limit,
|
||||
"custom_daily_job_limit": custom_daily_job_limit,
|
||||
"reason": reason,
|
||||
"created_by": admin_email,
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
})
|
||||
logger.info(f"Set rate limit override for {user_email} by {admin_email}")
|
||||
|
||||
def remove_user_override(self, user_email: str, admin_email: str = "") -> bool:
|
||||
"""Remove rate limit override for a user."""
|
||||
doc_ref = self.db.collection(OVERRIDES_COLLECTION).document(user_email.lower())
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return False
|
||||
|
||||
doc_ref.delete()
|
||||
logger.info(f"Removed rate limit override for {user_email} by {admin_email}")
|
||||
return True
|
||||
|
||||
def list_user_overrides(self) -> List[Dict[str, Any]]:
|
||||
"""List all user rate limit overrides."""
|
||||
docs = self.db.collection(OVERRIDES_COLLECTION).stream()
|
||||
return [doc.to_dict() for doc in docs]
|
||||
|
||||
def get_all_overrides(self) -> Dict[str, Dict[str, Any]]:
|
||||
"""Get all user rate limit overrides as a dict keyed by email."""
|
||||
docs = self.db.collection(OVERRIDES_COLLECTION).stream()
|
||||
return {doc.id: doc.to_dict() for doc in docs}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Blocklist Management
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def _load_blocklist(self, force_refresh: bool = False) -> Dict[str, Any]:
|
||||
"""
|
||||
Load blocklist from Firestore with caching.
|
||||
|
||||
Returns:
|
||||
Dict with keys: disposable_domains, blocked_emails, blocked_ips
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Check cache
|
||||
if not force_refresh and self._blocklist_cache and self._blocklist_cache_time:
|
||||
cache_age = (now - self._blocklist_cache_time).total_seconds()
|
||||
if cache_age < self._cache_ttl_seconds:
|
||||
return self._blocklist_cache
|
||||
|
||||
# Load from Firestore
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
# Initialize with empty blocklist
|
||||
self._blocklist_cache = {
|
||||
"disposable_domains": [],
|
||||
"blocked_emails": [],
|
||||
"blocked_ips": [],
|
||||
}
|
||||
else:
|
||||
self._blocklist_cache = doc.to_dict()
|
||||
|
||||
self._blocklist_cache_time = now
|
||||
return self._blocklist_cache
|
||||
|
||||
def is_disposable_domain(self, domain: str) -> bool:
|
||||
"""Check if a domain is in the disposable domains blocklist."""
|
||||
blocklist = self._load_blocklist()
|
||||
return domain.lower() in [d.lower() for d in blocklist.get("disposable_domains", [])]
|
||||
|
||||
def is_blocked_email(self, email: str) -> bool:
|
||||
"""Check if an email is explicitly blocked."""
|
||||
blocklist = self._load_blocklist()
|
||||
return email.lower() in [e.lower() for e in blocklist.get("blocked_emails", [])]
|
||||
|
||||
def is_blocked_ip(self, ip_address: str) -> bool:
|
||||
"""Check if an IP address is blocked."""
|
||||
blocklist = self._load_blocklist()
|
||||
return ip_address in blocklist.get("blocked_ips", [])
|
||||
|
||||
def get_blocklist(self) -> Dict[str, Any]:
|
||||
"""Get all blocklist data."""
|
||||
return self._load_blocklist(force_refresh=True)
|
||||
|
||||
def add_disposable_domain(self, domain: str, admin_email: str) -> None:
|
||||
"""Add a domain to the disposable domains blocklist."""
|
||||
blocklist = self._load_blocklist(force_refresh=True)
|
||||
domains = set(blocklist.get("disposable_domains", []))
|
||||
domains.add(domain.lower())
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc_ref.set({
|
||||
**blocklist,
|
||||
"disposable_domains": list(domains),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"updated_by": admin_email,
|
||||
}, merge=True)
|
||||
|
||||
self._blocklist_cache = None # Invalidate cache
|
||||
logger.info(f"Added disposable domain {domain} by {admin_email}")
|
||||
|
||||
def remove_disposable_domain(self, domain: str) -> bool:
|
||||
"""Remove a domain from the disposable domains blocklist."""
|
||||
blocklist = self._load_blocklist(force_refresh=True)
|
||||
domains = set(blocklist.get("disposable_domains", []))
|
||||
|
||||
if domain.lower() not in [d.lower() for d in domains]:
|
||||
return False
|
||||
|
||||
domains = {d for d in domains if d.lower() != domain.lower()}
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc_ref.set({
|
||||
**blocklist,
|
||||
"disposable_domains": list(domains),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
}, merge=True)
|
||||
|
||||
self._blocklist_cache = None
|
||||
logger.info(f"Removed disposable domain {domain}")
|
||||
return True
|
||||
|
||||
def add_blocked_email(self, email: str, admin_email: str) -> None:
|
||||
"""Add an email to the blocked emails list."""
|
||||
blocklist = self._load_blocklist(force_refresh=True)
|
||||
emails = set(blocklist.get("blocked_emails", []))
|
||||
emails.add(email.lower())
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc_ref.set({
|
||||
**blocklist,
|
||||
"blocked_emails": list(emails),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"updated_by": admin_email,
|
||||
}, merge=True)
|
||||
|
||||
self._blocklist_cache = None
|
||||
logger.info(f"Added blocked email {email} by {admin_email}")
|
||||
|
||||
def remove_blocked_email(self, email: str) -> bool:
|
||||
"""Remove an email from the blocked emails list."""
|
||||
blocklist = self._load_blocklist(force_refresh=True)
|
||||
emails = set(blocklist.get("blocked_emails", []))
|
||||
|
||||
if email.lower() not in [e.lower() for e in emails]:
|
||||
return False
|
||||
|
||||
emails = {e for e in emails if e.lower() != email.lower()}
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc_ref.set({
|
||||
**blocklist,
|
||||
"blocked_emails": list(emails),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
}, merge=True)
|
||||
|
||||
self._blocklist_cache = None
|
||||
logger.info(f"Removed blocked email {email}")
|
||||
return True
|
||||
|
||||
def add_blocked_ip(self, ip_address: str, admin_email: str) -> None:
|
||||
"""Add an IP address to the blocked IPs list."""
|
||||
blocklist = self._load_blocklist(force_refresh=True)
|
||||
ips = set(blocklist.get("blocked_ips", []))
|
||||
ips.add(ip_address)
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc_ref.set({
|
||||
**blocklist,
|
||||
"blocked_ips": list(ips),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"updated_by": admin_email,
|
||||
}, merge=True)
|
||||
|
||||
self._blocklist_cache = None
|
||||
logger.info(f"Added blocked IP {ip_address} by {admin_email}")
|
||||
|
||||
def remove_blocked_ip(self, ip_address: str) -> bool:
|
||||
"""Remove an IP address from the blocked IPs list."""
|
||||
blocklist = self._load_blocklist(force_refresh=True)
|
||||
ips = set(blocklist.get("blocked_ips", []))
|
||||
|
||||
if ip_address not in ips:
|
||||
return False
|
||||
|
||||
ips.discard(ip_address)
|
||||
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document("config")
|
||||
doc_ref.set({
|
||||
**blocklist,
|
||||
"blocked_ips": list(ips),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
}, merge=True)
|
||||
|
||||
self._blocklist_cache = None
|
||||
logger.info(f"Removed blocked IP {ip_address}")
|
||||
return True
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Stats
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def get_rate_limit_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get current rate limit statistics.
|
||||
|
||||
Returns:
|
||||
Dict with current usage stats
|
||||
"""
|
||||
date_str = _get_today_date_str()
|
||||
|
||||
# Get YouTube upload count
|
||||
youtube_count = self.get_youtube_uploads_today()
|
||||
|
||||
# Count unique users with jobs today
|
||||
users_with_jobs = set()
|
||||
total_jobs_today = 0
|
||||
|
||||
# Query all user job documents for today
|
||||
docs = self.db.collection(RATE_LIMITS_COLLECTION).where(
|
||||
"date", "==", date_str
|
||||
).stream()
|
||||
|
||||
for doc in docs:
|
||||
data = doc.to_dict()
|
||||
if data.get("user_email"):
|
||||
users_with_jobs.add(data["user_email"])
|
||||
total_jobs_today += data.get("count", 0)
|
||||
|
||||
return {
|
||||
"date": date_str,
|
||||
"youtube_uploads_today": youtube_count,
|
||||
"youtube_uploads_limit": settings.rate_limit_youtube_uploads_per_day,
|
||||
"total_jobs_today": total_jobs_today,
|
||||
"users_with_jobs_today": len(users_with_jobs),
|
||||
"job_limit_per_user": settings.rate_limit_jobs_per_day,
|
||||
"beta_ip_limit_per_day": settings.rate_limit_beta_ip_per_day,
|
||||
"rate_limiting_enabled": settings.enable_rate_limiting,
|
||||
"seconds_until_reset": _seconds_until_midnight_utc(),
|
||||
}
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_rate_limit_service: Optional[RateLimitService] = None
|
||||
|
||||
|
||||
def get_rate_limit_service() -> RateLimitService:
|
||||
"""Get the singleton RateLimitService instance."""
|
||||
global _rate_limit_service
|
||||
if _rate_limit_service is None:
|
||||
_rate_limit_service = RateLimitService()
|
||||
return _rate_limit_service
|
||||
@@ -1,759 +0,0 @@
|
||||
"""
|
||||
Stripe admin service for payment analytics and management.
|
||||
|
||||
Handles:
|
||||
- Storing enriched payment data from webhooks
|
||||
- Revenue analytics and reporting
|
||||
- Payment listing and detail views
|
||||
- Stripe balance and payout queries
|
||||
- Refund processing
|
||||
- Dispute monitoring
|
||||
- Webhook event logging
|
||||
"""
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any, List, Tuple
|
||||
|
||||
import stripe
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STRIPE_PAYMENTS_COLLECTION = "stripe_payments"
|
||||
STRIPE_WEBHOOK_EVENTS_COLLECTION = "stripe_webhook_events"
|
||||
|
||||
|
||||
class StripeAdminService:
|
||||
"""Service for Stripe admin analytics and payment management."""
|
||||
|
||||
def __init__(self):
|
||||
self.settings = get_settings()
|
||||
self.db = firestore.Client()
|
||||
self._revenue_cache: Optional[Dict[str, Any]] = None
|
||||
self._revenue_cache_time: float = 0
|
||||
self._revenue_cache_ttl: float = 300 # 5 minutes
|
||||
|
||||
# =========================================================================
|
||||
# Payment Storage
|
||||
# =========================================================================
|
||||
|
||||
def store_payment(self, session: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Store enriched payment data from a completed Checkout Session.
|
||||
|
||||
Args:
|
||||
session: Stripe Checkout Session object (expanded with payment_intent,
|
||||
charge, and balance_transaction)
|
||||
|
||||
Returns:
|
||||
True if stored successfully
|
||||
"""
|
||||
try:
|
||||
session_id = session.get("id", "")
|
||||
metadata = session.get("metadata", {})
|
||||
|
||||
# Extract payment intent and charge details
|
||||
payment_intent = session.get("payment_intent", {})
|
||||
if isinstance(payment_intent, str):
|
||||
# Not expanded - just store the ID
|
||||
payment_intent_id = payment_intent
|
||||
charge_data = {}
|
||||
balance_txn = {}
|
||||
else:
|
||||
payment_intent_id = payment_intent.get("id", "")
|
||||
charges = payment_intent.get("latest_charge", {})
|
||||
if isinstance(charges, str):
|
||||
charge_data = {}
|
||||
balance_txn = {}
|
||||
else:
|
||||
charge_data = charges or {}
|
||||
bt = charge_data.get("balance_transaction", {})
|
||||
balance_txn = bt if isinstance(bt, dict) else {}
|
||||
|
||||
# Extract payment method details
|
||||
payment_method_details = charge_data.get("payment_method_details", {})
|
||||
pm_type = payment_method_details.get("type", "unknown")
|
||||
card_info = payment_method_details.get("card", {})
|
||||
|
||||
# Determine order type
|
||||
order_type = metadata.get("order_type", "credit_purchase")
|
||||
package_id = metadata.get("package_id")
|
||||
credits = 0
|
||||
try:
|
||||
credits = int(metadata.get("credits", 0))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Build product description
|
||||
if order_type == "made_for_you":
|
||||
artist = metadata.get("artist", "")
|
||||
title = metadata.get("title", "")
|
||||
product_description = f"Made For You: {artist} - {title}"
|
||||
else:
|
||||
from backend.services.stripe_service import CREDIT_PACKAGES
|
||||
pkg = CREDIT_PACKAGES.get(package_id, {})
|
||||
product_description = pkg.get("name", f"{credits} Credits")
|
||||
|
||||
# Extract discount info
|
||||
total_details = session.get("total_details", {})
|
||||
discount_amount = 0
|
||||
promotion_code = None
|
||||
if total_details:
|
||||
discount_obj = total_details.get("amount_discount", 0)
|
||||
discount_amount = discount_obj if isinstance(discount_obj, int) else 0
|
||||
|
||||
# Determine if test payment
|
||||
is_test = not (session.get("livemode", False))
|
||||
|
||||
payment_data = {
|
||||
"session_id": session_id,
|
||||
"payment_intent_id": payment_intent_id,
|
||||
"charge_id": charge_data.get("id", ""),
|
||||
# Financial (cents)
|
||||
"amount_total": session.get("amount_total", 0),
|
||||
"currency": session.get("currency", "usd"),
|
||||
"stripe_fee": balance_txn.get("fee", 0),
|
||||
"net_amount": balance_txn.get("net", 0),
|
||||
# Customer
|
||||
"customer_email": (
|
||||
metadata.get("user_email")
|
||||
or metadata.get("customer_email")
|
||||
or session.get("customer_email", "")
|
||||
).lower().strip(),
|
||||
"customer_name": session.get("customer_details", {}).get("name", ""),
|
||||
"stripe_customer_id": session.get("customer", ""),
|
||||
# Payment method
|
||||
"payment_method_type": pm_type,
|
||||
"card_brand": card_info.get("brand", ""),
|
||||
"card_last4": card_info.get("last4", ""),
|
||||
# Order details
|
||||
"order_type": order_type,
|
||||
"package_id": package_id,
|
||||
"credits_granted": credits,
|
||||
"product_description": product_description,
|
||||
# Made-for-you fields
|
||||
"artist": metadata.get("artist"),
|
||||
"title": metadata.get("title"),
|
||||
"job_id": metadata.get("job_id"),
|
||||
# Status
|
||||
"status": "succeeded",
|
||||
"refund_amount": 0,
|
||||
"refund_id": None,
|
||||
"refunded_at": None,
|
||||
"refund_reason": None,
|
||||
# Timestamps
|
||||
"created_at": datetime.utcfromtimestamp(session["created"]) if session.get("created") else datetime.utcnow(),
|
||||
"processed_at": datetime.utcnow(),
|
||||
# Metadata
|
||||
"is_test": is_test,
|
||||
"promotion_code": promotion_code,
|
||||
"discount_amount": discount_amount,
|
||||
}
|
||||
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc_ref.set(payment_data)
|
||||
|
||||
# Invalidate revenue cache
|
||||
self._revenue_cache = None
|
||||
|
||||
logger.info(
|
||||
f"Stored payment data for session {session_id}: "
|
||||
f"${payment_data['amount_total'] / 100:.2f} from {payment_data['customer_email']}"
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error storing payment data for session {session.get('id', 'unknown')}")
|
||||
return False
|
||||
|
||||
def update_payment_status(self, session_id: str, updates: Dict[str, Any]) -> bool:
|
||||
"""Update payment status fields (for refunds/disputes)."""
|
||||
try:
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
logger.warning(f"Payment {session_id} not found for status update")
|
||||
return False
|
||||
|
||||
doc_ref.update(updates)
|
||||
self._revenue_cache = None
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception(f"Error updating payment status for {session_id}")
|
||||
return False
|
||||
|
||||
# =========================================================================
|
||||
# Revenue Analytics
|
||||
# =========================================================================
|
||||
|
||||
def get_revenue_summary(
|
||||
self, days: int = 30, exclude_test: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get revenue summary metrics.
|
||||
|
||||
Returns total gross, fees, net, refunds, count, AOV, revenue by product type.
|
||||
Uses in-memory cache with 5-minute TTL.
|
||||
"""
|
||||
cache_key = f"{days}_{exclude_test}"
|
||||
now = time.time()
|
||||
if (
|
||||
self._revenue_cache
|
||||
and self._revenue_cache.get("_key") == cache_key
|
||||
and (now - self._revenue_cache_time) < self._revenue_cache_ttl
|
||||
):
|
||||
return self._revenue_cache
|
||||
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = collection
|
||||
|
||||
if days > 0:
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
query = query.where("created_at", ">=", cutoff)
|
||||
|
||||
total_gross = 0
|
||||
total_fees = 0
|
||||
total_net = 0
|
||||
total_refunds = 0
|
||||
count = 0
|
||||
by_type: Dict[str, int] = {}
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
amount = data.get("amount_total", 0)
|
||||
total_gross += amount
|
||||
total_fees += data.get("stripe_fee", 0)
|
||||
total_net += data.get("net_amount", 0)
|
||||
total_refunds += data.get("refund_amount", 0)
|
||||
count += 1
|
||||
|
||||
order_type = data.get("order_type", "credit_purchase")
|
||||
by_type[order_type] = by_type.get(order_type, 0) + amount
|
||||
|
||||
aov = total_gross / count if count > 0 else 0
|
||||
|
||||
result = {
|
||||
"_key": cache_key,
|
||||
"total_gross": total_gross,
|
||||
"total_fees": total_fees,
|
||||
"total_net": total_net,
|
||||
"total_refunds": total_refunds,
|
||||
"transaction_count": count,
|
||||
"average_order_value": round(aov),
|
||||
"revenue_by_type": by_type,
|
||||
}
|
||||
|
||||
self._revenue_cache = result
|
||||
self._revenue_cache_time = now
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error calculating revenue summary")
|
||||
return {
|
||||
"total_gross": 0,
|
||||
"total_fees": 0,
|
||||
"total_net": 0,
|
||||
"total_refunds": 0,
|
||||
"transaction_count": 0,
|
||||
"average_order_value": 0,
|
||||
"revenue_by_type": {},
|
||||
}
|
||||
|
||||
def get_revenue_by_period(
|
||||
self,
|
||||
days: int = 30,
|
||||
group_by: str = "day",
|
||||
exclude_test: bool = True,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get revenue grouped by time period for charting.
|
||||
|
||||
Args:
|
||||
days: Number of days to look back
|
||||
group_by: 'day' or 'week' or 'month'
|
||||
exclude_test: Exclude test transactions
|
||||
|
||||
Returns:
|
||||
List of {date, gross, net, fees, count} dicts
|
||||
"""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
query = collection.where("created_at", ">=", cutoff)
|
||||
|
||||
buckets: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
created = data.get("created_at")
|
||||
if not created:
|
||||
continue
|
||||
if isinstance(created, str):
|
||||
try:
|
||||
created = datetime.fromisoformat(created.replace("Z", "+00:00"))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if group_by == "week":
|
||||
# Start of week (Monday)
|
||||
start = created - timedelta(days=created.weekday())
|
||||
key = start.strftime("%Y-%m-%d")
|
||||
elif group_by == "month":
|
||||
key = created.strftime("%Y-%m-01")
|
||||
else:
|
||||
key = created.strftime("%Y-%m-%d")
|
||||
|
||||
if key not in buckets:
|
||||
buckets[key] = {"date": key, "gross": 0, "net": 0, "fees": 0, "count": 0}
|
||||
|
||||
buckets[key]["gross"] += data.get("amount_total", 0)
|
||||
buckets[key]["net"] += data.get("net_amount", 0)
|
||||
buckets[key]["fees"] += data.get("stripe_fee", 0)
|
||||
buckets[key]["count"] += 1
|
||||
|
||||
result = sorted(buckets.values(), key=lambda x: x["date"])
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error getting revenue by period")
|
||||
return []
|
||||
|
||||
# =========================================================================
|
||||
# Payment Listing & Details
|
||||
# =========================================================================
|
||||
|
||||
def list_payments(
|
||||
self,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
order_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
email: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
List payments with pagination and filters.
|
||||
|
||||
Returns:
|
||||
{payments: [...], total: int, has_more: bool}
|
||||
"""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = collection.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
|
||||
if order_type:
|
||||
query = collection.where("order_type", "==", order_type).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
if status:
|
||||
query = collection.where("status", "==", status).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
if email:
|
||||
query = collection.where("customer_email", "==", email.lower()).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
|
||||
# Stream and filter (Firestore doesn't support multiple inequality filters)
|
||||
payments = []
|
||||
skipped = 0
|
||||
total = 0
|
||||
|
||||
for doc in query.limit(1000).stream():
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
# Apply filters that couldn't be done in query
|
||||
if order_type and data.get("order_type") != order_type:
|
||||
continue
|
||||
if status and data.get("status") != status:
|
||||
continue
|
||||
if email and data.get("customer_email", "").lower() != email.lower():
|
||||
continue
|
||||
|
||||
total += 1
|
||||
if skipped < offset:
|
||||
skipped += 1
|
||||
continue
|
||||
if len(payments) < limit:
|
||||
# Convert datetime objects for JSON serialization
|
||||
for key in ["created_at", "processed_at", "refunded_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
payments.append(data)
|
||||
|
||||
return {
|
||||
"payments": payments,
|
||||
"total": total,
|
||||
"has_more": total > offset + limit,
|
||||
}
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error listing payments")
|
||||
return {"payments": [], "total": 0, "has_more": False}
|
||||
|
||||
def get_payment_detail(self, session_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get full payment details for a single payment.
|
||||
|
||||
Combines Firestore data with on-demand Stripe API call for receipt_url.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
|
||||
# Convert datetime objects
|
||||
for key in ["created_at", "processed_at", "refunded_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
|
||||
# On-demand: fetch receipt URL from Stripe
|
||||
charge_id = data.get("charge_id")
|
||||
if charge_id:
|
||||
try:
|
||||
charge = stripe.Charge.retrieve(charge_id)
|
||||
data["receipt_url"] = charge.get("receipt_url")
|
||||
data["stripe_dashboard_url"] = (
|
||||
f"https://dashboard.stripe.com/payments/{data.get('payment_intent_id', '')}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not fetch charge {charge_id}: {e}")
|
||||
data["receipt_url"] = None
|
||||
|
||||
return data
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error getting payment detail for {session_id}")
|
||||
return None
|
||||
|
||||
def get_user_payment_history(self, email: str) -> Dict[str, Any]:
|
||||
"""Get all payments for a user with total_spent."""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
# Try with order_by first (requires composite index on customer_email + created_at)
|
||||
try:
|
||||
query = (
|
||||
collection.where("customer_email", "==", email.lower())
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
)
|
||||
docs = list(query.stream())
|
||||
except Exception:
|
||||
# Fallback: query without order_by if composite index doesn't exist yet
|
||||
logger.warning(
|
||||
f"Composite index missing for stripe_payments(customer_email, created_at). "
|
||||
f"Falling back to unordered query for {email}"
|
||||
)
|
||||
query = collection.where("customer_email", "==", email.lower())
|
||||
docs = list(query.stream())
|
||||
|
||||
payments = []
|
||||
total_spent = 0
|
||||
total_refunded = 0
|
||||
|
||||
for doc in docs:
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
total_spent += data.get("amount_total", 0)
|
||||
total_refunded += data.get("refund_amount", 0)
|
||||
|
||||
for key in ["created_at", "processed_at", "refunded_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
|
||||
payments.append(data)
|
||||
|
||||
# Sort by created_at descending (handles both indexed and fallback paths)
|
||||
payments.sort(key=lambda p: p.get("created_at", ""), reverse=True)
|
||||
|
||||
first_payment = payments[-1]["created_at"] if payments else None
|
||||
last_payment = payments[0]["created_at"] if payments else None
|
||||
|
||||
return {
|
||||
"email": email,
|
||||
"payments": payments,
|
||||
"total_spent": total_spent,
|
||||
"total_refunded": total_refunded,
|
||||
"net_spent": total_spent - total_refunded,
|
||||
"payment_count": len(payments),
|
||||
"first_payment_at": first_payment,
|
||||
"last_payment_at": last_payment,
|
||||
}
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error getting payment history for {email}")
|
||||
return {
|
||||
"email": email,
|
||||
"payments": [],
|
||||
"total_spent": 0,
|
||||
"total_refunded": 0,
|
||||
"net_spent": 0,
|
||||
"payment_count": 0,
|
||||
"first_payment_at": None,
|
||||
"last_payment_at": None,
|
||||
}
|
||||
|
||||
# =========================================================================
|
||||
# Stripe Balance & Payouts
|
||||
# =========================================================================
|
||||
|
||||
def get_stripe_balance(self) -> Dict[str, Any]:
|
||||
"""Get current Stripe account balance (available + pending)."""
|
||||
try:
|
||||
balance = stripe.Balance.retrieve()
|
||||
available = sum(b.get("amount", 0) for b in balance.get("available", []))
|
||||
pending = sum(b.get("amount", 0) for b in balance.get("pending", []))
|
||||
return {
|
||||
"available": available,
|
||||
"pending": pending,
|
||||
"currency": "usd",
|
||||
}
|
||||
except Exception:
|
||||
logger.exception("Error fetching Stripe balance")
|
||||
return {"available": 0, "pending": 0, "currency": "usd"}
|
||||
|
||||
def get_recent_payouts(self, limit: int = 10) -> List[Dict[str, Any]]:
|
||||
"""Get recent payouts from Stripe."""
|
||||
try:
|
||||
payouts = stripe.Payout.list(limit=limit)
|
||||
result = []
|
||||
for p in payouts.get("data", []):
|
||||
result.append({
|
||||
"id": p.get("id"),
|
||||
"amount": p.get("amount"),
|
||||
"currency": p.get("currency"),
|
||||
"status": p.get("status"),
|
||||
"arrival_date": p.get("arrival_date"),
|
||||
"created": p.get("created"),
|
||||
"description": p.get("description"),
|
||||
"method": p.get("method"),
|
||||
})
|
||||
return result
|
||||
except Exception:
|
||||
logger.exception("Error fetching payouts")
|
||||
return []
|
||||
|
||||
# =========================================================================
|
||||
# Disputes
|
||||
# =========================================================================
|
||||
|
||||
def get_recent_disputes(self) -> List[Dict[str, Any]]:
|
||||
"""Get open and recent disputes from Stripe."""
|
||||
try:
|
||||
disputes = stripe.Dispute.list(limit=20)
|
||||
result = []
|
||||
for d in disputes.get("data", []):
|
||||
result.append({
|
||||
"id": d.get("id"),
|
||||
"amount": d.get("amount"),
|
||||
"currency": d.get("currency"),
|
||||
"status": d.get("status"),
|
||||
"reason": d.get("reason"),
|
||||
"charge_id": d.get("charge"),
|
||||
"created": d.get("created"),
|
||||
"evidence_due_by": d.get("evidence_details", {}).get("due_by"),
|
||||
"payment_intent_id": d.get("payment_intent"),
|
||||
})
|
||||
return result
|
||||
except Exception:
|
||||
logger.exception("Error fetching disputes")
|
||||
return []
|
||||
|
||||
# =========================================================================
|
||||
# Refund Processing
|
||||
# =========================================================================
|
||||
|
||||
def process_refund(
|
||||
self,
|
||||
session_id: str,
|
||||
amount: Optional[int] = None,
|
||||
reason: str = "requested_by_customer",
|
||||
) -> Tuple[bool, str]:
|
||||
"""
|
||||
Process a refund for a payment.
|
||||
|
||||
Args:
|
||||
session_id: Checkout session ID
|
||||
amount: Refund amount in cents (None for full refund)
|
||||
reason: Refund reason
|
||||
|
||||
Returns:
|
||||
(success, message)
|
||||
"""
|
||||
try:
|
||||
# Get payment record
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return False, "Payment not found"
|
||||
|
||||
data = doc.to_dict()
|
||||
payment_intent_id = data.get("payment_intent_id")
|
||||
if not payment_intent_id:
|
||||
return False, "No payment intent ID found"
|
||||
|
||||
current_refund = data.get("refund_amount", 0)
|
||||
original_amount = data.get("amount_total", 0)
|
||||
refund_amount = amount or (original_amount - current_refund)
|
||||
|
||||
if refund_amount <= 0:
|
||||
return False, "Invalid refund amount"
|
||||
if current_refund + refund_amount > original_amount:
|
||||
return False, f"Refund would exceed original amount (${original_amount / 100:.2f})"
|
||||
|
||||
# Create Stripe refund
|
||||
refund_params: Dict[str, Any] = {
|
||||
"payment_intent": payment_intent_id,
|
||||
"amount": refund_amount,
|
||||
"reason": reason,
|
||||
}
|
||||
refund = stripe.Refund.create(**refund_params)
|
||||
|
||||
# Update Firestore record
|
||||
new_total_refund = current_refund + refund_amount
|
||||
new_status = "refunded" if new_total_refund >= original_amount else "partially_refunded"
|
||||
|
||||
doc_ref.update({
|
||||
"status": new_status,
|
||||
"refund_amount": new_total_refund,
|
||||
"refund_id": refund.get("id"),
|
||||
"refunded_at": datetime.utcnow(),
|
||||
"refund_reason": reason,
|
||||
})
|
||||
|
||||
self._revenue_cache = None
|
||||
|
||||
logger.info(
|
||||
f"Processed refund for {session_id}: "
|
||||
f"${refund_amount / 100:.2f} ({new_status})"
|
||||
)
|
||||
return True, f"Refund of ${refund_amount / 100:.2f} processed successfully"
|
||||
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Stripe refund error for {session_id}: {e}")
|
||||
return False, f"Stripe error: {str(e)}"
|
||||
except Exception:
|
||||
logger.exception(f"Error processing refund for {session_id}")
|
||||
return False, "Unexpected error processing refund"
|
||||
|
||||
# =========================================================================
|
||||
# Webhook Event Logging
|
||||
# =========================================================================
|
||||
|
||||
def log_webhook_event(
|
||||
self,
|
||||
event_id: str,
|
||||
event_type: str,
|
||||
status: str = "processing",
|
||||
session_id: Optional[str] = None,
|
||||
customer_email: Optional[str] = None,
|
||||
summary: Optional[str] = None,
|
||||
error_message: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Log a webhook event for audit trail."""
|
||||
try:
|
||||
doc_ref = self.db.collection(STRIPE_WEBHOOK_EVENTS_COLLECTION).document(event_id)
|
||||
data = {
|
||||
"event_id": event_id,
|
||||
"event_type": event_type,
|
||||
"created_at": datetime.utcnow(),
|
||||
"status": status,
|
||||
"session_id": session_id,
|
||||
"customer_email": customer_email,
|
||||
"summary": summary,
|
||||
"error_message": error_message,
|
||||
}
|
||||
if status in ("success", "error"):
|
||||
data["processed_at"] = datetime.utcnow()
|
||||
doc_ref.set(data, merge=True)
|
||||
except Exception:
|
||||
logger.exception(f"Error logging webhook event {event_id}")
|
||||
|
||||
def list_webhook_events(
|
||||
self,
|
||||
limit: int = 50,
|
||||
event_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""List recent webhook events."""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_WEBHOOK_EVENTS_COLLECTION)
|
||||
query = collection.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
|
||||
if event_type:
|
||||
query = collection.where("event_type", "==", event_type).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
|
||||
events = []
|
||||
for doc in query.limit(limit).stream():
|
||||
data = doc.to_dict()
|
||||
if status and data.get("status") != status:
|
||||
continue
|
||||
for key in ["created_at", "processed_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
events.append(data)
|
||||
|
||||
return events
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error listing webhook events")
|
||||
return []
|
||||
|
||||
def normalize_customer_emails(self) -> Dict[str, Any]:
|
||||
"""Backfill: lowercase all customer_email values in stripe_payments."""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
updated = 0
|
||||
skipped = 0
|
||||
|
||||
for doc in collection.stream():
|
||||
data = doc.to_dict()
|
||||
email = data.get("customer_email", "")
|
||||
normalized = email.lower().strip()
|
||||
if email != normalized:
|
||||
doc.reference.update({"customer_email": normalized})
|
||||
updated += 1
|
||||
else:
|
||||
skipped += 1
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"updated": updated,
|
||||
"skipped": skipped,
|
||||
"total": updated + skipped,
|
||||
}
|
||||
except Exception:
|
||||
logger.exception("Error normalizing customer emails")
|
||||
raise
|
||||
|
||||
|
||||
# Global instance
|
||||
_stripe_admin_service = None
|
||||
|
||||
|
||||
def get_stripe_admin_service() -> StripeAdminService:
|
||||
"""Get the global Stripe admin service instance."""
|
||||
global _stripe_admin_service
|
||||
if _stripe_admin_service is None:
|
||||
_stripe_admin_service = StripeAdminService()
|
||||
return _stripe_admin_service
|
||||
@@ -48,7 +48,7 @@ CREDIT_PACKAGES = {
|
||||
|
||||
# Made-for-you service package (not a credit package - creates a job directly)
|
||||
MADE_FOR_YOU_PACKAGE = {
|
||||
"price_cents": 5000, # $50.00
|
||||
"price_cents": 1500, # $15.00
|
||||
"name": "Made For You Karaoke Video",
|
||||
"description": "Professional 4K karaoke video with perfectly synced lyrics, delivered to your email within 24 hours",
|
||||
"images": ["https://gen.nomadkaraoke.com/nomad-logo.png"],
|
||||
|
||||
@@ -6,8 +6,8 @@ This allows updating email content without code deployment.
|
||||
|
||||
Template locations:
|
||||
- gs://{bucket}/templates/job-completion.txt - Job completion email (plain text)
|
||||
- gs://{bucket}/templates/action-needed-lyrics.txt - Combined review reminder (lyrics + instrumental)
|
||||
- gs://{bucket}/templates/action-needed-instrumental.txt - Instrumental selection reminder (finalise-only jobs)
|
||||
- gs://{bucket}/templates/action-needed-lyrics.txt - Lyrics review reminder
|
||||
- gs://{bucket}/templates/action-needed-instrumental.txt - Instrumental selection reminder
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
@@ -52,11 +52,11 @@ Thanks again and have a great day!
|
||||
|
||||
DEFAULT_ACTION_NEEDED_LYRICS_TEMPLATE = """Hi {name},
|
||||
|
||||
Your karaoke video for "{artist} - {title}" is ready for review!
|
||||
Your karaoke video for "{artist} - {title}" is ready for lyrics review!
|
||||
|
||||
Our system has transcribed and synchronized the lyrics, but they may need some corrections. You'll also be able to select your preferred instrumental track (with or without backing vocals).
|
||||
Our system has transcribed and synchronized the lyrics, but they may need some corrections. Please review and make any corrections necessary so we can finish generating your video.
|
||||
|
||||
Please review your lyrics and select an instrumental:
|
||||
Review your lyrics here:
|
||||
{review_url}
|
||||
|
||||
This usually takes just a few minutes.
|
||||
@@ -79,18 +79,6 @@ Thanks!
|
||||
"""
|
||||
|
||||
|
||||
DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE = """Hi {name},
|
||||
|
||||
Great news! Your karaoke video for "{artist} - {title}" has been uploaded to YouTube:
|
||||
{youtube_url}
|
||||
|
||||
This upload was briefly delayed while our systems processed other uploads, but everything is all set now.
|
||||
|
||||
Thanks!
|
||||
-Andrew
|
||||
"""
|
||||
|
||||
|
||||
class TemplateService:
|
||||
"""
|
||||
Service for fetching and rendering email templates from GCS.
|
||||
@@ -224,8 +212,6 @@ class TemplateService:
|
||||
title: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
feedback_url: Optional[str] = None,
|
||||
is_private: bool = False,
|
||||
youtube_queued: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
Render the job completion email template.
|
||||
@@ -238,29 +224,11 @@ class TemplateService:
|
||||
title: Song title
|
||||
job_id: Job ID
|
||||
feedback_url: Feedback form URL (optional)
|
||||
is_private: If True, remove YouTube section entirely (private/non-published tracks)
|
||||
youtube_queued: If True, YouTube upload was deferred - show pending message
|
||||
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self.get_job_completion_template()
|
||||
|
||||
# For private tracks, remove the YouTube section entirely
|
||||
if is_private:
|
||||
template = re.sub(
|
||||
r"\n*Here's the link for the karaoke video published to YouTube:\n\{youtube_url\}\n*",
|
||||
'\n',
|
||||
template,
|
||||
)
|
||||
elif youtube_queued and not youtube_url:
|
||||
# Replace YouTube URL with pending message
|
||||
template = template.replace(
|
||||
"Here's the link for the karaoke video published to YouTube:\n{youtube_url}",
|
||||
"Your YouTube upload is queued and will be processed automatically. "
|
||||
"You'll receive a follow-up email with the link shortly."
|
||||
)
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"youtube_url": youtube_url or "[YouTube URL not available]",
|
||||
@@ -280,16 +248,13 @@ class TemplateService:
|
||||
review_url: str = "",
|
||||
) -> str:
|
||||
"""
|
||||
Render the combined review reminder template.
|
||||
|
||||
This is used for the combined lyrics + instrumental review flow.
|
||||
Users review lyrics and select their instrumental in a single session.
|
||||
Render the lyrics review reminder template.
|
||||
|
||||
Args:
|
||||
name: User's display name
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
review_url: Combined review URL
|
||||
review_url: Lyrics review URL
|
||||
|
||||
Returns:
|
||||
Rendered email content
|
||||
@@ -313,10 +278,6 @@ class TemplateService:
|
||||
"""
|
||||
Render the instrumental selection reminder template.
|
||||
|
||||
This is only used for finalise-only jobs where users upload pre-rendered
|
||||
video and only need to select the instrumental track. For normal jobs,
|
||||
instrumental selection is combined with lyrics review (see render_action_needed_lyrics).
|
||||
|
||||
Args:
|
||||
name: User's display name
|
||||
artist: Artist name
|
||||
@@ -335,39 +296,6 @@ class TemplateService:
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def render_youtube_upload_complete(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Render the YouTube upload complete follow-up email template.
|
||||
|
||||
Sent when a deferred YouTube upload completes after quota becomes available.
|
||||
|
||||
Args:
|
||||
name: User's display name
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
youtube_url: YouTube video URL
|
||||
|
||||
Returns:
|
||||
Rendered email content
|
||||
"""
|
||||
template = self._fetch_template_from_gcs("youtube-upload-complete.txt")
|
||||
if template is None:
|
||||
template = DEFAULT_YOUTUBE_UPLOAD_COMPLETE_TEMPLATE
|
||||
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
"title": title or "Unknown Title",
|
||||
"youtube_url": youtube_url or "[YouTube URL not available]",
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def upload_template(self, template_name: str, content: str) -> bool:
|
||||
"""
|
||||
Upload a template to GCS.
|
||||
|
||||
@@ -48,7 +48,7 @@ class UserService:
|
||||
"""Service for user management and authentication."""
|
||||
|
||||
# Number of free credits granted to new users
|
||||
NEW_USER_FREE_CREDITS = 2
|
||||
NEW_USER_FREE_CREDITS = 1
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize user service with Firestore client."""
|
||||
@@ -59,50 +59,16 @@ class UserService:
|
||||
# User CRUD Operations
|
||||
# =========================================================================
|
||||
|
||||
def get_user_doc_ref(self, email: str):
|
||||
"""Get the Firestore document reference for a user by email.
|
||||
|
||||
Handles both email-keyed docs (doc ID = email) and hash-keyed docs
|
||||
(doc ID = hash, email stored as field). Returns None if not found.
|
||||
"""
|
||||
try:
|
||||
# First try direct lookup by email as doc ID
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
return doc_ref
|
||||
|
||||
# Fallback: query by email field (for hash-keyed docs)
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email.lower())
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
if results:
|
||||
return results[0].reference
|
||||
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception(f"Error finding user doc ref for {email}")
|
||||
return None
|
||||
|
||||
def get_user(self, email: str) -> Optional[User]:
|
||||
"""Get a user by email."""
|
||||
try:
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc = doc_ref.get()
|
||||
|
||||
if doc.exists:
|
||||
return User(**doc.to_dict())
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
# Fallback: query by email field (for hash-keyed docs)
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email.lower())
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
if results:
|
||||
return User(**results[0].to_dict())
|
||||
|
||||
return None
|
||||
return User(**doc.to_dict())
|
||||
except Exception:
|
||||
logger.exception(f"Error getting user {email}")
|
||||
return None
|
||||
@@ -161,10 +127,7 @@ class UserService:
|
||||
"""Update user fields."""
|
||||
try:
|
||||
updates['updated_at'] = datetime.utcnow()
|
||||
doc_ref = self.get_user_doc_ref(email)
|
||||
if not doc_ref:
|
||||
logger.warning(f"Cannot update user {email}: doc not found")
|
||||
return None
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc_ref.update(updates)
|
||||
return self.get_user(email)
|
||||
except Exception:
|
||||
@@ -805,62 +768,15 @@ class UserService:
|
||||
logger.exception("Error enabling user")
|
||||
return False
|
||||
|
||||
def delete_user(self, email: str, admin_email: str) -> bool:
|
||||
"""
|
||||
Permanently delete a user and all their associated data.
|
||||
|
||||
Deletes: user document, sessions, magic links.
|
||||
Does NOT delete jobs (they remain as historical records).
|
||||
|
||||
Args:
|
||||
email: Email of the user to delete
|
||||
admin_email: Email/ID of the admin performing the action
|
||||
|
||||
Returns:
|
||||
True if user was deleted, False if user not found
|
||||
|
||||
Raises:
|
||||
ValueError: If trying to delete an admin user
|
||||
"""
|
||||
try:
|
||||
email = email.lower()
|
||||
user = self.get_user(email)
|
||||
|
||||
if not user:
|
||||
return False
|
||||
|
||||
if user.role == UserRole.ADMIN:
|
||||
raise ValueError("Cannot delete admin users")
|
||||
|
||||
# Revoke all active sessions
|
||||
self.revoke_all_sessions(email)
|
||||
|
||||
# Delete magic links for the user
|
||||
magic_links = self.db.collection(MAGIC_LINKS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email)
|
||||
).stream()
|
||||
for doc in magic_links:
|
||||
doc.reference.delete()
|
||||
|
||||
# Delete the user document
|
||||
self.db.collection(USERS_COLLECTION).document(email).delete()
|
||||
|
||||
logger.info(f"Admin {admin_email} permanently deleted user {email}")
|
||||
return True
|
||||
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(f"Error deleting user {email}")
|
||||
return False
|
||||
|
||||
def increment_jobs_completed(self, email: str) -> bool:
|
||||
"""Increment the completed jobs counter for a user using atomic increment."""
|
||||
try:
|
||||
doc_ref = self.get_user_doc_ref(email)
|
||||
if not doc_ref:
|
||||
# Check user exists first
|
||||
if not self.get_user(email):
|
||||
return False
|
||||
|
||||
# Use atomic increment to prevent race conditions
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc_ref.update({
|
||||
'total_jobs_completed': Increment(1),
|
||||
'updated_at': datetime.utcnow()
|
||||
|
||||
@@ -1,300 +0,0 @@
|
||||
"""
|
||||
Visibility change service for completed jobs.
|
||||
|
||||
Handles changing a job's visibility between public and private:
|
||||
- Public -> Private: redistribute existing finals to private destination (fast, ~1-2 min)
|
||||
- Private -> Public: reset styles, regenerate screens, re-render, re-encode (slow, ~15-30 min)
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VisibilityChangeService:
|
||||
"""Service for changing job visibility after completion."""
|
||||
|
||||
def __init__(self, job_manager: Optional[JobManager] = None):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
|
||||
def validate_change(self, job, user_email: str, is_admin: bool, target_visibility: str) -> Optional[str]:
|
||||
"""Validate a visibility change request. Returns error message or None if valid."""
|
||||
if not job:
|
||||
return "Job not found"
|
||||
|
||||
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
|
||||
return f"Can only change visibility on completed jobs. Current status: {job.status}"
|
||||
|
||||
if getattr(job, 'tenant_id', None):
|
||||
return "Cannot change visibility on tenant jobs"
|
||||
|
||||
current_is_private = getattr(job, 'is_private', False)
|
||||
target_is_private = target_visibility == "private"
|
||||
|
||||
if current_is_private == target_is_private:
|
||||
current = "private" if current_is_private else "public"
|
||||
return f"Job is already {current}"
|
||||
|
||||
# Check user owns the job or is admin
|
||||
if not is_admin and job.user_email != user_email:
|
||||
return "You can only change visibility on your own jobs"
|
||||
|
||||
# Check for in-progress visibility change
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get('visibility_change_in_progress'):
|
||||
return "A visibility change is already in progress for this job"
|
||||
|
||||
return None
|
||||
|
||||
async def change_to_private(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
Change a public job to private (fast path).
|
||||
|
||||
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
|
||||
then redistributes to private destination.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
# Set guard flag
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
try:
|
||||
# Step 1: Delete distributed outputs (keep GCS finals)
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
|
||||
|
||||
# Step 2: Update job to private
|
||||
job_ref.update({
|
||||
"is_private": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility changed to private by {user_email}",
|
||||
}]),
|
||||
})
|
||||
|
||||
# Step 3: Trigger redistribution via video worker
|
||||
from backend.workers.video_worker import redistribute_video
|
||||
success = await redistribute_video(job_id)
|
||||
|
||||
if not success:
|
||||
raise RuntimeError("Redistribution failed - check worker logs")
|
||||
|
||||
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to private complete")
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"reprocessing_required": False,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
|
||||
# Clear guard flag on failure
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
raise
|
||||
|
||||
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
Change a private job to public (slow path).
|
||||
|
||||
Resets custom styles, deletes all outputs/screens/rendered video,
|
||||
and triggers full re-processing from screens worker onward.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: private -> public (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
storage = StorageService()
|
||||
|
||||
# Step 1: Delete distributed outputs + GCS finals
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=False)
|
||||
|
||||
# Step 2: Delete screens and rendered video from GCS
|
||||
for path in [
|
||||
f"jobs/{job_id}/screens/title.mov",
|
||||
f"jobs/{job_id}/screens/title.jpg",
|
||||
f"jobs/{job_id}/screens/title.png",
|
||||
f"jobs/{job_id}/screens/end.mov",
|
||||
f"jobs/{job_id}/screens/end.jpg",
|
||||
f"jobs/{job_id}/screens/end.png",
|
||||
f"jobs/{job_id}/videos/with_vocals.mkv",
|
||||
f"jobs/{job_id}/videos/with_vocals.mov",
|
||||
]:
|
||||
try:
|
||||
storage.delete_file(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Delete custom style files from GCS
|
||||
try:
|
||||
style_prefix = f"jobs/{job_id}/style/"
|
||||
storage.delete_folder(style_prefix)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Step 3: Prepare nomad theme style files for the job
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
style_params_path, style_assets_dict, _youtube_desc = _prepare_theme_for_job(
|
||||
job_id=job_id, theme_id="nomad"
|
||||
)
|
||||
|
||||
# Step 4: Reset styles and update job fields
|
||||
# Step 5: Set status to LYRICS_COMPLETE with regen_restore_status
|
||||
# Step 6: Clear progress keys and set guard flag
|
||||
update_payload = {
|
||||
"is_private": False,
|
||||
"theme_id": "nomad",
|
||||
"color_overrides": {},
|
||||
"style_assets": style_assets_dict,
|
||||
"style_params_gcs_path": style_params_path,
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"outputs_deleted_at": None,
|
||||
"outputs_deleted_by": None,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "lyrics_complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility change to public initiated by {user_email}. "
|
||||
"Re-processing from screens generation.",
|
||||
}]),
|
||||
}
|
||||
job_ref.update(update_payload)
|
||||
|
||||
# Step 6: Trigger screens worker
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_screens_worker(job_id)
|
||||
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Failed to trigger screens worker for visibility change")
|
||||
# Restore to complete status on failure
|
||||
job_ref.update({
|
||||
"status": "complete",
|
||||
"is_private": True,
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
raise RuntimeError("Failed to trigger screens worker")
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to public initiated, screens worker triggered")
|
||||
return {
|
||||
"status": "processing",
|
||||
"message": "Visibility change to public started. The video will be re-rendered "
|
||||
"with default branding and published publicly. This takes ~15-30 minutes.",
|
||||
"reprocessing_required": True,
|
||||
}
|
||||
|
||||
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
|
||||
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
|
||||
import re
|
||||
|
||||
state_data = job.state_data or {}
|
||||
|
||||
# Delete YouTube video
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False, non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
finalise.delete_youtube_video(video_id)
|
||||
logger.info(f"[job:{job_id}] Deleted YouTube video {video_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete YouTube video: {e}")
|
||||
|
||||
# Delete Dropbox folder
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
dropbox.delete_folder(full_path)
|
||||
logger.info(f"[job:{job_id}] Deleted Dropbox folder {full_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Dropbox folder: {e}")
|
||||
|
||||
# Delete Google Drive files
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
gdrive.delete_files(file_ids)
|
||||
logger.info(f"[job:{job_id}] Deleted Google Drive files")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete Google Drive files: {e}")
|
||||
|
||||
# Delete GCS finals if requested
|
||||
if not keep_gcs_finals:
|
||||
try:
|
||||
storage = StorageService()
|
||||
deleted_count = storage.delete_folder(f"jobs/{job_id}/finals/")
|
||||
if deleted_count > 0:
|
||||
logger.info(f"[job:{job_id}] Deleted {deleted_count} GCS finals files")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to delete GCS finals: {e}")
|
||||
|
||||
# Recycle brand code
|
||||
if brand_code:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"[job:{job_id}] Recycled brand code {brand_code}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to recycle brand code: {e}")
|
||||
|
||||
# Clear distribution state_data
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
update = {}
|
||||
for key in ['youtube_url', 'brand_code', 'dropbox_link', 'gdrive_files']:
|
||||
if key in state_data:
|
||||
update[f"state_data.{key}"] = DELETE_FIELD
|
||||
if update:
|
||||
job_ref.update(update)
|
||||
@@ -38,7 +38,6 @@ WORKER_QUEUES = {
|
||||
"render-video": "render-worker-queue",
|
||||
"video": "video-worker-queue",
|
||||
"idle-reminder": "idle-reminder-queue", # For delayed idle reminder checks
|
||||
"gdrive-validation": "gdrive-validation-queue", # For delayed post-job validation
|
||||
}
|
||||
|
||||
# Dispatch deadlines for each worker type (in seconds)
|
||||
@@ -52,15 +51,10 @@ WORKER_DISPATCH_DEADLINES = {
|
||||
"render-video": 1800, # 30 min - Video encoding can be slow
|
||||
"video": 1800, # 30 min - Video encoding can be slow
|
||||
"idle-reminder": 60, # 1 min - Quick check and potential email send
|
||||
"gdrive-validation": 120, # 2 min - Calls Cloud Function which validates GDrive
|
||||
}
|
||||
|
||||
# Default delay for idle reminders (seconds)
|
||||
IDLE_REMINDER_DELAY_SECONDS = 2 * 60 # 2 minutes
|
||||
|
||||
# Default delay for post-job GDrive validation (seconds)
|
||||
# Gives E2E tests time to verify output and clean up before validator runs
|
||||
GDRIVE_VALIDATION_DELAY_SECONDS = 5 * 60 # 5 minutes
|
||||
IDLE_REMINDER_DELAY_SECONDS = 5 * 60 # 5 minutes
|
||||
|
||||
|
||||
class WorkerService:
|
||||
@@ -361,52 +355,14 @@ class WorkerService:
|
||||
|
||||
# Convenience methods for specific workers
|
||||
# These provide a cleaner API and better IDE autocomplete
|
||||
|
||||
async def trigger_audio_download_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger audio download worker.
|
||||
|
||||
Downloads audio from the selected source (Spotify, YouTube, RED, OPS)
|
||||
and then triggers audio separation + lyrics workers.
|
||||
|
||||
Uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
downloads. This replaces the BackgroundTasks approach that caused
|
||||
jobs to get stuck when Cloud Run scaled down instances.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-download-job",
|
||||
worker_module="audio_download_worker",
|
||||
)
|
||||
|
||||
|
||||
async def trigger_audio_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger audio separation worker.
|
||||
|
||||
Always uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
|
||||
instances mid-processing when no HTTP requests were active.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-separation-job",
|
||||
worker_module="audio_worker",
|
||||
)
|
||||
|
||||
"""Trigger audio separation worker."""
|
||||
return await self.trigger_worker("audio", job_id)
|
||||
|
||||
async def trigger_lyrics_worker(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger lyrics transcription worker.
|
||||
|
||||
Always uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
AudioShake transcription. The BackgroundTasks approach caused Cloud Run to
|
||||
terminate instances mid-processing (e.g., job c94cc9d6) when no HTTP requests
|
||||
were active, even though the worker was still processing.
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="lyrics-transcription-job",
|
||||
worker_module="lyrics_worker",
|
||||
)
|
||||
"""Trigger lyrics transcription worker."""
|
||||
return await self.trigger_worker("lyrics", job_id)
|
||||
|
||||
async def trigger_screens_worker(self, job_id: str) -> bool:
|
||||
"""Trigger screen generation worker."""
|
||||
@@ -427,83 +383,50 @@ class WorkerService:
|
||||
async def _trigger_cloud_run_job(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger video encoding as a Cloud Run Job.
|
||||
|
||||
|
||||
Cloud Run Jobs support up to 24 hours of execution time,
|
||||
making them suitable for very long video encoding tasks.
|
||||
|
||||
|
||||
Args:
|
||||
job_id: Job ID to process
|
||||
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
"""
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="video-encoding-job",
|
||||
worker_module="video_worker",
|
||||
)
|
||||
|
||||
async def _trigger_worker_cloud_run_job(
|
||||
self,
|
||||
job_id: str,
|
||||
cloud_run_job_name: str,
|
||||
worker_module: str,
|
||||
) -> bool:
|
||||
"""
|
||||
Trigger a worker as a Cloud Run Job.
|
||||
|
||||
Cloud Run Jobs run to completion without HTTP request lifecycle concerns,
|
||||
avoiding the instance termination issue where Cloud Run would shut down
|
||||
instances mid-processing when using BackgroundTasks.
|
||||
|
||||
Args:
|
||||
job_id: Job ID to process
|
||||
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
|
||||
worker_module: Worker module name (e.g., "lyrics_worker")
|
||||
|
||||
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
from google.cloud import run_v2
|
||||
|
||||
|
||||
project = self.settings.google_cloud_project
|
||||
if not project:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
|
||||
return False
|
||||
|
||||
|
||||
location = self.settings.gcp_region
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
|
||||
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/video-encoding-job"
|
||||
|
||||
# Create Cloud Run Jobs client
|
||||
client = run_v2.JobsClient()
|
||||
|
||||
|
||||
# Run the job with overrides for the specific job_id
|
||||
request = run_v2.RunJobRequest(
|
||||
name=job_name,
|
||||
overrides=run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[
|
||||
run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=[
|
||||
"python", "-m", f"backend.workers.{worker_module}",
|
||||
"--job-id", job_id,
|
||||
],
|
||||
args=["python", "-m", "backend.workers.video_worker", "--job-id", job_id],
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# Run the job (async operation)
|
||||
operation = client.run_job(request=request)
|
||||
logger.info(
|
||||
f"[job:{job_id}] Started Cloud Run Job {cloud_run_job_name}: "
|
||||
f"{operation.metadata}"
|
||||
)
|
||||
logger.info(f"Started Cloud Run Job for video encoding, job {job_id}: {operation.metadata}")
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[job:{job_id}] Failed to trigger Cloud Run Job {cloud_run_job_name}: {e}",
|
||||
f"Failed to trigger Cloud Run Job for video/{job_id}: {e}",
|
||||
exc_info=True
|
||||
)
|
||||
return False
|
||||
@@ -605,93 +528,6 @@ class WorkerService:
|
||||
)
|
||||
return False
|
||||
|
||||
async def schedule_gdrive_validation(
|
||||
self,
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
) -> bool:
|
||||
"""
|
||||
Schedule a delayed GDrive validation check.
|
||||
|
||||
Fires after the specified delay so that E2E test cleanup completes
|
||||
before the validator runs, avoiding false "all clear" reports.
|
||||
|
||||
Args:
|
||||
delay_seconds: Delay before executing the validation (default: 5 minutes)
|
||||
|
||||
Returns:
|
||||
True if task was scheduled successfully, False otherwise
|
||||
"""
|
||||
if not self._use_cloud_tasks:
|
||||
logger.info(
|
||||
f"GDrive validation not scheduled (Cloud Tasks disabled). "
|
||||
f"Would have fired in {delay_seconds}s."
|
||||
)
|
||||
return True
|
||||
|
||||
try:
|
||||
from google.cloud import tasks_v2
|
||||
from google.protobuf import timestamp_pb2
|
||||
import time
|
||||
|
||||
queue_name = WORKER_QUEUES.get("gdrive-validation")
|
||||
if not queue_name:
|
||||
logger.error("GDrive validation queue not configured")
|
||||
return False
|
||||
|
||||
project = self.settings.google_cloud_project
|
||||
if not project:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
|
||||
# Build queue path
|
||||
parent = self.tasks_client.queue_path(project, location, queue_name)
|
||||
|
||||
# Build headers
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
if self._admin_token:
|
||||
headers["X-Admin-Token"] = self._admin_token
|
||||
|
||||
headers = inject_trace_context(headers)
|
||||
|
||||
# Calculate schedule time
|
||||
schedule_time = timestamp_pb2.Timestamp()
|
||||
schedule_time.FromSeconds(int(time.time()) + delay_seconds)
|
||||
|
||||
dispatch_deadline_seconds = WORKER_DISPATCH_DEADLINES.get("gdrive-validation", 120)
|
||||
|
||||
# Build task payload
|
||||
task = {
|
||||
"http_request": {
|
||||
"http_method": tasks_v2.HttpMethod.POST,
|
||||
"url": f"{self._base_url}/api/internal/trigger-gdrive-validation",
|
||||
"headers": headers,
|
||||
"body": b"{}",
|
||||
"oidc_token": {
|
||||
"service_account_email": f"karaoke-backend@{project}.iam.gserviceaccount.com",
|
||||
},
|
||||
},
|
||||
"schedule_time": schedule_time,
|
||||
"dispatch_deadline": duration_pb2.Duration(seconds=dispatch_deadline_seconds),
|
||||
}
|
||||
|
||||
response = self.tasks_client.create_task(parent=parent, task=task)
|
||||
logger.info(
|
||||
f"Scheduled GDrive validation in {delay_seconds}s: {response.name}"
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Failed to schedule GDrive validation: {e}",
|
||||
exc_info=True
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
# Global worker service instance
|
||||
_worker_service: Optional[WorkerService] = None
|
||||
|
||||
@@ -1,379 +0,0 @@
|
||||
"""
|
||||
YouTube download service for cloud backend.
|
||||
|
||||
This service provides a single entry point for all YouTube downloads in the cloud.
|
||||
It automatically routes downloads through the remote flacfetch service when configured,
|
||||
avoiding YouTube bot detection issues on Cloud Run IPs.
|
||||
|
||||
The flow is:
|
||||
1. Check if remote flacfetch is configured (FLACFETCH_API_URL)
|
||||
2. If yes: Use FlacfetchClient.download_by_id() - downloads on VM, uploads to GCS
|
||||
3. If no: Use local yt_dlp (with warning about bot detection risk)
|
||||
|
||||
All entry points (audio search selection, direct URL submission) should use this
|
||||
service for YouTube downloads to ensure consistent behavior.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from typing import Optional
|
||||
|
||||
from .flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from .storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class YouTubeDownloadError(Exception):
|
||||
"""Error downloading from YouTube."""
|
||||
pass
|
||||
|
||||
|
||||
class YouTubeDownloadService:
|
||||
"""
|
||||
Single point of entry for all YouTube downloads in the cloud backend.
|
||||
|
||||
When remote flacfetch is configured (FLACFETCH_API_URL), downloads happen
|
||||
on the flacfetch VM which has YouTube cookies and avoids bot detection.
|
||||
|
||||
When remote is not configured, falls back to local yt_dlp with a warning
|
||||
that downloads may be blocked on Cloud Run IPs.
|
||||
|
||||
Usage:
|
||||
service = get_youtube_download_service()
|
||||
gcs_path = await service.download(
|
||||
url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
job_id="job123",
|
||||
artist="Rick Astley",
|
||||
title="Never Gonna Give You Up",
|
||||
)
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._flacfetch_client = get_flacfetch_client()
|
||||
self._storage_service = StorageService()
|
||||
|
||||
if self._flacfetch_client:
|
||||
logger.info("YouTubeDownloadService using REMOTE flacfetch (recommended)")
|
||||
else:
|
||||
logger.warning(
|
||||
"YouTubeDownloadService using LOCAL yt_dlp - "
|
||||
"downloads may fail due to YouTube bot detection on Cloud Run IPs"
|
||||
)
|
||||
|
||||
def is_remote_enabled(self) -> bool:
|
||||
"""Check if remote flacfetch is configured."""
|
||||
return self._flacfetch_client is not None
|
||||
|
||||
async def check_availability(self, url: str) -> Optional[dict]:
|
||||
"""
|
||||
Check if a YouTube video is available for download.
|
||||
|
||||
Uses the flacfetch /check-youtube endpoint to detect geo-restrictions,
|
||||
private/removed videos, etc. before creating a job.
|
||||
|
||||
Returns:
|
||||
Check result dict if check succeeds, None if check can't be
|
||||
performed (no remote configured, network error, etc.).
|
||||
Callers should treat None as "unknown, proceed anyway".
|
||||
"""
|
||||
if not self._flacfetch_client:
|
||||
return None
|
||||
|
||||
video_id = self._extract_video_id(url)
|
||||
if not video_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
result = await self._flacfetch_client.check_youtube(url)
|
||||
logger.info(
|
||||
f"YouTube availability check for {video_id}: "
|
||||
f"available={result.get('available')}"
|
||||
)
|
||||
return result
|
||||
except FlacfetchServiceError as e:
|
||||
logger.warning(f"YouTube availability check failed for {video_id}, proceeding anyway: {e}")
|
||||
return None
|
||||
|
||||
async def download(
|
||||
self,
|
||||
url: str,
|
||||
job_id: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Download YouTube audio and upload to GCS.
|
||||
|
||||
Args:
|
||||
url: YouTube URL (any format - watch, youtu.be, shorts, etc.)
|
||||
job_id: Job ID for GCS path
|
||||
artist: Optional artist name for filename
|
||||
title: Optional title for filename
|
||||
|
||||
Returns:
|
||||
GCS path (not gs:// prefix, just the path portion)
|
||||
Example: "uploads/job123/audio/Artist - Title.flac"
|
||||
|
||||
Raises:
|
||||
YouTubeDownloadError: If download fails
|
||||
"""
|
||||
video_id = self._extract_video_id(url)
|
||||
if not video_id:
|
||||
raise YouTubeDownloadError(f"Could not extract video ID from URL: {url}")
|
||||
|
||||
logger.info(f"YouTube download: video_id={video_id}, job_id={job_id}")
|
||||
|
||||
if self._flacfetch_client:
|
||||
return await self._download_remote(video_id, job_id, artist, title)
|
||||
else:
|
||||
logger.warning(
|
||||
"Remote flacfetch not configured. Attempting local download, "
|
||||
"but this may fail due to YouTube bot detection on Cloud Run IPs."
|
||||
)
|
||||
return await self._download_local(url, job_id, artist, title)
|
||||
|
||||
async def download_by_id(
|
||||
self,
|
||||
video_id: str,
|
||||
job_id: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Download YouTube audio by video ID.
|
||||
|
||||
Same as download() but takes a video ID directly instead of URL.
|
||||
|
||||
Args:
|
||||
video_id: YouTube video ID (e.g., "dQw4w9WgXcQ")
|
||||
job_id: Job ID for GCS path
|
||||
artist: Optional artist name for filename
|
||||
title: Optional title for filename
|
||||
|
||||
Returns:
|
||||
GCS path (path portion only, no gs:// prefix)
|
||||
|
||||
Raises:
|
||||
YouTubeDownloadError: If download fails
|
||||
"""
|
||||
url = f"https://www.youtube.com/watch?v={video_id}"
|
||||
return await self.download(url, job_id, artist, title)
|
||||
|
||||
def _extract_video_id(self, url: str) -> Optional[str]:
|
||||
"""
|
||||
Extract YouTube video ID from various URL formats.
|
||||
|
||||
Supports:
|
||||
- https://www.youtube.com/watch?v=VIDEO_ID
|
||||
- https://youtu.be/VIDEO_ID
|
||||
- https://www.youtube.com/shorts/VIDEO_ID
|
||||
- https://www.youtube.com/embed/VIDEO_ID
|
||||
- https://youtube.com/v/VIDEO_ID
|
||||
|
||||
Returns:
|
||||
Video ID string, or None if extraction fails
|
||||
"""
|
||||
patterns = [
|
||||
# Standard watch URL
|
||||
r'(?:youtube\.com/watch\?v=|youtube\.com/watch\?.*&v=)([a-zA-Z0-9_-]{11})',
|
||||
# Short URL
|
||||
r'youtu\.be/([a-zA-Z0-9_-]{11})',
|
||||
# Shorts URL
|
||||
r'youtube\.com/shorts/([a-zA-Z0-9_-]{11})',
|
||||
# Embed URL
|
||||
r'youtube\.com/embed/([a-zA-Z0-9_-]{11})',
|
||||
# Old-style URL
|
||||
r'youtube\.com/v/([a-zA-Z0-9_-]{11})',
|
||||
]
|
||||
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, url)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
return None
|
||||
|
||||
async def _download_remote(
|
||||
self,
|
||||
video_id: str,
|
||||
job_id: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Download using remote flacfetch service."""
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
# Build output filename if artist/title provided
|
||||
output_filename = None
|
||||
if artist and title:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
safe_artist = sanitize_filename(artist)
|
||||
safe_title = sanitize_filename(title)
|
||||
output_filename = f"{safe_artist} - {safe_title}"
|
||||
|
||||
logger.info(
|
||||
f"Remote YouTube download: video_id={video_id}, "
|
||||
f"gcs_path={gcs_destination}, filename={output_filename}"
|
||||
)
|
||||
|
||||
try:
|
||||
# Start download
|
||||
download_id = await self._flacfetch_client.download_by_id(
|
||||
source_name="YouTube",
|
||||
source_id=video_id,
|
||||
output_filename=output_filename,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
logger.info(f"Remote download started: {download_id}")
|
||||
|
||||
# Wait for completion
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = await self._flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=300, # 5 minute timeout for YouTube downloads
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
|
||||
# Extract GCS path from response
|
||||
gcs_path = final_status.get("gcs_path")
|
||||
if not gcs_path:
|
||||
raise YouTubeDownloadError(
|
||||
"Remote download completed but no GCS path returned"
|
||||
)
|
||||
|
||||
# Convert gs:// URL to path portion
|
||||
if gcs_path.startswith("gs://"):
|
||||
parts = gcs_path.replace("gs://", "").split("/", 1)
|
||||
if len(parts) == 2:
|
||||
gcs_path = parts[1]
|
||||
|
||||
logger.info(f"Remote YouTube download complete: {gcs_path}")
|
||||
return gcs_path
|
||||
|
||||
except FlacfetchServiceError as e:
|
||||
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
|
||||
except Exception as e:
|
||||
logger.error(f"Remote YouTube download error: {e}", exc_info=True)
|
||||
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
|
||||
|
||||
async def _download_local(
|
||||
self,
|
||||
url: str,
|
||||
job_id: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Download using local yt_dlp (fallback when remote not configured).
|
||||
|
||||
Warning: This may fail on Cloud Run due to YouTube bot detection.
|
||||
"""
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"youtube_{job_id}_")
|
||||
|
||||
try:
|
||||
from karaoke_gen.file_handler import FileHandler
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
# Create FileHandler
|
||||
file_handler = FileHandler(
|
||||
logger=logger,
|
||||
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
|
||||
create_track_subfolders=False,
|
||||
dry_run=False
|
||||
)
|
||||
|
||||
# Build output filename
|
||||
safe_artist = sanitize_filename(artist) if artist else "Unknown"
|
||||
safe_title = sanitize_filename(title) if title else "Unknown"
|
||||
output_filename_no_extension = os.path.join(
|
||||
temp_dir, f"{safe_artist} - {safe_title}"
|
||||
)
|
||||
|
||||
# Get cookies from environment
|
||||
cookies_str = os.environ.get("YOUTUBE_COOKIES")
|
||||
if cookies_str:
|
||||
logger.info("Using YouTube cookies for local download")
|
||||
|
||||
# Download
|
||||
logger.info(f"Local YouTube download: {url}")
|
||||
downloaded_file = file_handler.download_video(
|
||||
url=url,
|
||||
output_filename_no_extension=output_filename_no_extension,
|
||||
cookies_str=cookies_str
|
||||
)
|
||||
|
||||
if not downloaded_file or not os.path.exists(downloaded_file):
|
||||
raise YouTubeDownloadError(
|
||||
f"Local download failed - no file returned. "
|
||||
"This is likely due to YouTube bot detection on Cloud Run IPs. "
|
||||
"Configure FLACFETCH_API_URL for remote downloads."
|
||||
)
|
||||
|
||||
logger.info(f"Downloaded video: {downloaded_file}")
|
||||
|
||||
# Convert to WAV for processing
|
||||
wav_file = file_handler.convert_to_wav(
|
||||
input_filename=downloaded_file,
|
||||
output_filename_no_extension=output_filename_no_extension
|
||||
)
|
||||
|
||||
if not wav_file or not os.path.exists(wav_file):
|
||||
raise YouTubeDownloadError("WAV conversion failed")
|
||||
|
||||
logger.info(f"Converted to WAV: {wav_file}")
|
||||
|
||||
# Upload to GCS
|
||||
filename = os.path.basename(wav_file)
|
||||
gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
|
||||
content_type, _ = mimetypes.guess_type(wav_file)
|
||||
with open(wav_file, 'rb') as f:
|
||||
self._storage_service.upload_fileobj(
|
||||
f,
|
||||
gcs_path,
|
||||
content_type=content_type or 'audio/wav'
|
||||
)
|
||||
|
||||
logger.info(f"Uploaded to GCS: {gcs_path}")
|
||||
return gcs_path
|
||||
|
||||
except YouTubeDownloadError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Local YouTube download error: {e}", exc_info=True)
|
||||
raise YouTubeDownloadError(f"Local download failed: {e}") from e
|
||||
finally:
|
||||
# Cleanup temp directory
|
||||
try:
|
||||
import shutil
|
||||
if os.path.exists(temp_dir):
|
||||
shutil.rmtree(temp_dir)
|
||||
except Exception as cleanup_error:
|
||||
logger.warning(f"Failed to cleanup temp dir: {cleanup_error}")
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_youtube_download_service: Optional[YouTubeDownloadService] = None
|
||||
|
||||
|
||||
def get_youtube_download_service() -> YouTubeDownloadService:
|
||||
"""Get the singleton YouTubeDownloadService instance."""
|
||||
global _youtube_download_service
|
||||
if _youtube_download_service is None:
|
||||
_youtube_download_service = YouTubeDownloadService()
|
||||
return _youtube_download_service
|
||||
|
||||
|
||||
def reset_youtube_download_service():
|
||||
"""Reset the singleton (for testing)."""
|
||||
global _youtube_download_service
|
||||
_youtube_download_service = None
|
||||
@@ -1,318 +0,0 @@
|
||||
"""
|
||||
YouTube Data API v3 quota tracking service.
|
||||
|
||||
Uses GCP Cloud Monitoring as the single source of truth for quota usage,
|
||||
with a lightweight Firestore pending buffer for the ~7-minute delay before
|
||||
GCP reflects newly completed uploads.
|
||||
|
||||
Formula: current_usage = gcp_reported + pending_buffer
|
||||
"""
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Tuple, Optional, Dict, Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
YOUTUBE_QUOTA_PENDING_COLLECTION = "youtube_quota_pending"
|
||||
PACIFIC_TZ = ZoneInfo("America/Los_Angeles")
|
||||
|
||||
# Pending entries older than this are ignored (GCP should have caught up)
|
||||
PENDING_EXPIRY_MINUTES = 10
|
||||
|
||||
# In-memory cache for GCP usage to avoid hammering Cloud Monitoring
|
||||
_gcp_cache: Dict[str, Any] = {
|
||||
"value": None,
|
||||
"timestamp": 0.0,
|
||||
}
|
||||
GCP_CACHE_TTL_SECONDS = 60
|
||||
|
||||
|
||||
def _get_today_date_pt() -> str:
|
||||
"""Get today's date in Pacific Time as YYYY-MM-DD string."""
|
||||
return datetime.now(PACIFIC_TZ).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _seconds_until_midnight_pt() -> int:
|
||||
"""Calculate seconds until Pacific Time midnight (when YouTube quota resets)."""
|
||||
now = datetime.now(PACIFIC_TZ)
|
||||
midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
next_midnight = midnight + timedelta(days=1)
|
||||
return int((next_midnight - now).total_seconds())
|
||||
|
||||
|
||||
class YouTubeQuotaService:
|
||||
"""
|
||||
Service for tracking YouTube Data API v3 quota consumption.
|
||||
|
||||
Uses GCP Cloud Monitoring as the primary data source, with a Firestore
|
||||
pending buffer for recent uploads not yet reflected in GCP metrics.
|
||||
"""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def check_quota_available(self, estimated_units: Optional[int] = None) -> Tuple[bool, int, str]:
|
||||
"""
|
||||
Check if enough quota is available for an upload.
|
||||
|
||||
Args:
|
||||
estimated_units: Estimated units needed. Defaults to settings.youtube_quota_upload_cost.
|
||||
|
||||
Returns:
|
||||
Tuple of (allowed, remaining_units, message)
|
||||
"""
|
||||
if estimated_units is None:
|
||||
estimated_units = settings.youtube_quota_upload_cost
|
||||
|
||||
limit = settings.youtube_quota_daily_limit
|
||||
safety_margin = settings.youtube_quota_safety_margin
|
||||
effective_limit = limit - safety_margin
|
||||
|
||||
if limit == 0:
|
||||
return True, -1, "No YouTube quota limit configured"
|
||||
|
||||
gcp_usage = self._get_gcp_usage()
|
||||
pending = self._get_pending_units()
|
||||
consumed = gcp_usage + pending
|
||||
remaining = max(0, effective_limit - consumed)
|
||||
|
||||
if consumed + estimated_units > effective_limit:
|
||||
seconds = _seconds_until_midnight_pt()
|
||||
hours = seconds // 3600
|
||||
minutes = (seconds % 3600) // 60
|
||||
logger.warning(
|
||||
f"YouTube quota insufficient: {consumed}/{effective_limit} units used "
|
||||
f"(GCP: {gcp_usage}, pending: {pending}, need {estimated_units} more), "
|
||||
f"resets in {hours}h {minutes}m"
|
||||
)
|
||||
return (
|
||||
False,
|
||||
remaining,
|
||||
f"YouTube API quota insufficient ({consumed}/{effective_limit} units used, "
|
||||
f"need {estimated_units}). Resets in {hours}h {minutes}m."
|
||||
)
|
||||
|
||||
return True, remaining, f"{remaining} quota units remaining today"
|
||||
|
||||
def record_upload(self, job_id: str, units: Optional[int] = None) -> None:
|
||||
"""
|
||||
Record a YouTube upload in the pending buffer.
|
||||
|
||||
Called once after a successful upload. The pending buffer bridges
|
||||
the ~7-minute gap before GCP Cloud Monitoring reflects the usage.
|
||||
|
||||
Args:
|
||||
job_id: Job ID that triggered the upload
|
||||
units: Quota units consumed. Defaults to settings.youtube_quota_upload_cost.
|
||||
"""
|
||||
if units is None:
|
||||
units = settings.youtube_quota_upload_cost
|
||||
|
||||
date_str = _get_today_date_pt()
|
||||
doc_ref = self.db.collection(YOUTUBE_QUOTA_PENDING_COLLECTION).document(date_str)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if doc.exists:
|
||||
data = doc.to_dict()
|
||||
pending_uploads = data.get("pending_uploads", [])
|
||||
else:
|
||||
pending_uploads = []
|
||||
|
||||
pending_uploads.append({
|
||||
"job_id": job_id,
|
||||
"units": units,
|
||||
"recorded_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
|
||||
# Recalculate pending_units from non-expired entries
|
||||
cutoff = datetime.now(PACIFIC_TZ) - timedelta(minutes=PENDING_EXPIRY_MINUTES)
|
||||
active_units = sum(
|
||||
e.get("units", 0) for e in pending_uploads
|
||||
if e.get("recorded_at") and e["recorded_at"] >= cutoff
|
||||
)
|
||||
|
||||
transaction.set(doc_ref, {
|
||||
"pending_units": active_units,
|
||||
"pending_uploads": pending_uploads,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
|
||||
transaction = self.db.transaction()
|
||||
update_in_transaction(transaction, doc_ref)
|
||||
logger.info(
|
||||
f"Recorded YouTube upload pending: {units} units for job {job_id}"
|
||||
)
|
||||
|
||||
def get_quota_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get current quota statistics for admin dashboard.
|
||||
|
||||
Returns:
|
||||
Dict with quota usage stats including GCP and pending breakdown.
|
||||
"""
|
||||
date_str = _get_today_date_pt()
|
||||
|
||||
limit = settings.youtube_quota_daily_limit
|
||||
safety_margin = settings.youtube_quota_safety_margin
|
||||
effective_limit = limit - safety_margin
|
||||
|
||||
gcp_usage = self._get_gcp_usage()
|
||||
pending = self._get_pending_units()
|
||||
consumed = gcp_usage + pending
|
||||
remaining = max(0, effective_limit - consumed)
|
||||
|
||||
upload_cost = settings.youtube_quota_upload_cost
|
||||
estimated_uploads = remaining // upload_cost if upload_cost > 0 else -1
|
||||
|
||||
upload_count = self._get_pending_upload_count()
|
||||
|
||||
return {
|
||||
"date_pt": date_str,
|
||||
"units_consumed": consumed,
|
||||
"gcp_usage": gcp_usage,
|
||||
"pending_units": pending,
|
||||
"units_limit": limit,
|
||||
"effective_limit": effective_limit,
|
||||
"units_remaining": remaining,
|
||||
"upload_cost": upload_cost,
|
||||
"estimated_uploads_remaining": estimated_uploads,
|
||||
"seconds_until_reset": _seconds_until_midnight_pt(),
|
||||
"upload_count": upload_count,
|
||||
}
|
||||
|
||||
def _get_gcp_usage(self) -> int:
|
||||
"""
|
||||
Query GCP Cloud Monitoring for today's YouTube API quota usage.
|
||||
|
||||
Uses a 60-second in-memory cache. Falls back to stale cache on error,
|
||||
or 0 if no cache exists.
|
||||
"""
|
||||
global _gcp_cache
|
||||
|
||||
now = time.time()
|
||||
cache_age = now - _gcp_cache["timestamp"]
|
||||
|
||||
# Return cached value if fresh
|
||||
if _gcp_cache["value"] is not None and cache_age < GCP_CACHE_TTL_SECONDS:
|
||||
return _gcp_cache["value"]
|
||||
|
||||
try:
|
||||
from google.cloud import monitoring_v3
|
||||
from google.protobuf.timestamp_pb2 import Timestamp
|
||||
|
||||
client = monitoring_v3.MetricServiceClient()
|
||||
project_name = f"projects/{settings.google_cloud_project}"
|
||||
|
||||
# Query from midnight PT today
|
||||
now_utc = datetime.now(PACIFIC_TZ).astimezone(ZoneInfo("UTC"))
|
||||
midnight_pt = datetime.now(PACIFIC_TZ).replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
).astimezone(ZoneInfo("UTC"))
|
||||
|
||||
start_time = Timestamp()
|
||||
start_time.FromDatetime(midnight_pt)
|
||||
end_time = Timestamp()
|
||||
end_time.FromDatetime(now_utc)
|
||||
|
||||
interval = monitoring_v3.TimeInterval(
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
)
|
||||
|
||||
results = client.list_time_series(
|
||||
request={
|
||||
"name": project_name,
|
||||
"filter": (
|
||||
'metric.type = "serviceruntime.googleapis.com/quota/rate/net_usage"'
|
||||
' AND resource.labels.service = "youtube.googleapis.com"'
|
||||
),
|
||||
"interval": interval,
|
||||
"view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
|
||||
}
|
||||
)
|
||||
|
||||
# Sum all datapoints (no aggregation — raw per-minute values)
|
||||
total = 0
|
||||
for ts in results:
|
||||
for point in ts.points:
|
||||
total += int(point.value.int64_value)
|
||||
|
||||
_gcp_cache["value"] = total
|
||||
_gcp_cache["timestamp"] = now
|
||||
return total
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to query GCP Cloud Monitoring: {e}")
|
||||
# Fallback to stale cache if available
|
||||
if _gcp_cache["value"] is not None:
|
||||
logger.info(f"Using stale GCP cache (age: {cache_age:.0f}s)")
|
||||
return _gcp_cache["value"]
|
||||
return 0
|
||||
|
||||
def _get_pending_units(self) -> int:
|
||||
"""
|
||||
Get pending quota units from Firestore (entries < PENDING_EXPIRY_MINUTES old).
|
||||
"""
|
||||
date_str = _get_today_date_pt()
|
||||
doc_ref = self.db.collection(YOUTUBE_QUOTA_PENDING_COLLECTION).document(date_str)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return 0
|
||||
|
||||
data = doc.to_dict()
|
||||
pending_uploads = data.get("pending_uploads", [])
|
||||
cutoff = datetime.now(PACIFIC_TZ) - timedelta(minutes=PENDING_EXPIRY_MINUTES)
|
||||
|
||||
total = 0
|
||||
for entry in pending_uploads:
|
||||
recorded_at = entry.get("recorded_at")
|
||||
if recorded_at and recorded_at >= cutoff:
|
||||
total += entry.get("units", 0)
|
||||
|
||||
return total
|
||||
|
||||
def _get_pending_upload_count(self) -> int:
|
||||
"""Get count of pending uploads (non-expired) for today."""
|
||||
date_str = _get_today_date_pt()
|
||||
doc_ref = self.db.collection(YOUTUBE_QUOTA_PENDING_COLLECTION).document(date_str)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return 0
|
||||
|
||||
data = doc.to_dict()
|
||||
pending_uploads = data.get("pending_uploads", [])
|
||||
cutoff = datetime.now(PACIFIC_TZ) - timedelta(minutes=PENDING_EXPIRY_MINUTES)
|
||||
|
||||
count = 0
|
||||
for entry in pending_uploads:
|
||||
recorded_at = entry.get("recorded_at")
|
||||
if recorded_at and recorded_at >= cutoff:
|
||||
count += 1
|
||||
|
||||
return count
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_youtube_quota_service: Optional[YouTubeQuotaService] = None
|
||||
|
||||
|
||||
def get_youtube_quota_service() -> YouTubeQuotaService:
|
||||
"""Get the singleton YouTubeQuotaService instance."""
|
||||
global _youtube_quota_service
|
||||
if _youtube_quota_service is None:
|
||||
_youtube_quota_service = YouTubeQuotaService()
|
||||
return _youtube_quota_service
|
||||
@@ -1,282 +0,0 @@
|
||||
"""
|
||||
YouTube upload queue service.
|
||||
|
||||
When YouTube API quota is insufficient during job completion, uploads are
|
||||
queued here instead of being silently skipped. A scheduled processor
|
||||
retries queued uploads when quota is available.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional, List, Dict, Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
YOUTUBE_UPLOAD_QUEUE_COLLECTION = "youtube_upload_queue"
|
||||
PACIFIC_TZ = ZoneInfo("America/Los_Angeles")
|
||||
|
||||
|
||||
class YouTubeUploadQueueService:
|
||||
"""
|
||||
Service for managing deferred YouTube uploads.
|
||||
|
||||
When quota is exhausted during job completion, uploads are queued
|
||||
and retried by a scheduled processor.
|
||||
"""
|
||||
|
||||
def __init__(self, db: Optional[firestore.Client] = None):
|
||||
if db is None:
|
||||
self.db = firestore.Client(project=settings.google_cloud_project)
|
||||
else:
|
||||
self.db = db
|
||||
|
||||
def queue_upload(
|
||||
self,
|
||||
job_id: str,
|
||||
user_email: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
brand_code: Optional[str],
|
||||
reason: str = "quota_exceeded",
|
||||
) -> None:
|
||||
"""
|
||||
Queue a YouTube upload for later processing.
|
||||
|
||||
Args:
|
||||
job_id: Job ID to upload
|
||||
user_email: User's email address
|
||||
artist: Artist name
|
||||
title: Song title
|
||||
brand_code: Release ID (e.g., "NOMAD-1287")
|
||||
reason: Why the upload was deferred
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
now = datetime.now(PACIFIC_TZ)
|
||||
|
||||
doc_ref.set({
|
||||
"job_id": job_id,
|
||||
"status": "queued",
|
||||
"reason": reason,
|
||||
"user_email": user_email,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"brand_code": brand_code,
|
||||
"queued_at": now,
|
||||
"attempts": 0,
|
||||
"max_attempts": 5,
|
||||
"last_error": None,
|
||||
"youtube_url": None,
|
||||
"notification_sent": False,
|
||||
"updated_at": now,
|
||||
})
|
||||
|
||||
logger.info(
|
||||
f"Queued YouTube upload for job {job_id} ({artist} - {title}), "
|
||||
f"reason: {reason}"
|
||||
)
|
||||
|
||||
def get_queued_uploads(self, limit: int = 20) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get queued uploads ordered by queued_at (oldest first).
|
||||
|
||||
Args:
|
||||
limit: Maximum number of entries to return
|
||||
|
||||
Returns:
|
||||
List of queued upload dicts
|
||||
"""
|
||||
query = (
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "queued")
|
||||
.order_by("queued_at")
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
return [doc.to_dict() for doc in query.stream()]
|
||||
|
||||
def get_all_queue_entries(self, limit: int = 50) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get all queue entries (any status) for admin dashboard.
|
||||
|
||||
Args:
|
||||
limit: Maximum entries to return
|
||||
|
||||
Returns:
|
||||
List of queue entry dicts, newest first
|
||||
"""
|
||||
query = (
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.order_by("queued_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
return [doc.to_dict() for doc in query.stream()]
|
||||
|
||||
def mark_processing(self, job_id: str) -> bool:
|
||||
"""
|
||||
Atomically mark a queued upload as processing.
|
||||
|
||||
Uses a transaction to prevent concurrent processing.
|
||||
|
||||
Returns:
|
||||
True if successfully claimed, False if already processing/completed
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def claim_in_transaction(transaction, doc_ref):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
if not doc.exists:
|
||||
return False
|
||||
|
||||
data = doc.to_dict()
|
||||
if data.get("status") != "queued":
|
||||
return False
|
||||
|
||||
attempts = data.get("attempts", 0)
|
||||
max_attempts = data.get("max_attempts", 5)
|
||||
if attempts >= max_attempts:
|
||||
transaction.update(doc_ref, {
|
||||
"status": "failed",
|
||||
"last_error": f"Max attempts ({max_attempts}) exceeded",
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
return False
|
||||
|
||||
transaction.update(doc_ref, {
|
||||
"status": "processing",
|
||||
"attempts": attempts + 1,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
return True
|
||||
|
||||
transaction = self.db.transaction()
|
||||
return claim_in_transaction(transaction, doc_ref)
|
||||
|
||||
def mark_completed(self, job_id: str, youtube_url: str) -> None:
|
||||
"""Mark a queued upload as completed with the YouTube URL."""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
doc_ref.update({
|
||||
"status": "completed",
|
||||
"youtube_url": youtube_url,
|
||||
"completed_at": datetime.now(PACIFIC_TZ),
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
logger.info(f"YouTube upload completed for queued job {job_id}: {youtube_url}")
|
||||
|
||||
def mark_failed(self, job_id: str, error: str) -> None:
|
||||
"""
|
||||
Mark a queued upload as failed.
|
||||
|
||||
If max attempts haven't been reached, resets to 'queued' for retry.
|
||||
Uses a transaction for atomic read-then-write.
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def update_in_transaction(transaction):
|
||||
doc = doc_ref.get(transaction=transaction)
|
||||
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
data = doc.to_dict()
|
||||
attempts = data.get("attempts", 0)
|
||||
max_attempts = data.get("max_attempts", 5)
|
||||
|
||||
new_status = "failed" if attempts >= max_attempts else "queued"
|
||||
|
||||
transaction.update(doc_ref, {
|
||||
"status": new_status,
|
||||
"last_error": error,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
return (new_status, attempts, max_attempts)
|
||||
|
||||
transaction = self.db.transaction()
|
||||
result = update_in_transaction(transaction)
|
||||
|
||||
if result:
|
||||
new_status, attempts, max_attempts = result
|
||||
logger.warning(
|
||||
f"YouTube upload {'failed permanently' if new_status == 'failed' else 'will retry'} "
|
||||
f"for job {job_id} (attempt {attempts}/{max_attempts}): {error}"
|
||||
)
|
||||
|
||||
def retry_upload(self, job_id: str) -> bool:
|
||||
"""
|
||||
Admin manual retry: reset a failed upload back to queued.
|
||||
|
||||
Returns:
|
||||
True if reset, False if not found or not in failed/queued state
|
||||
"""
|
||||
doc_ref = self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return False
|
||||
|
||||
data = doc.to_dict()
|
||||
if data.get("status") not in ("failed", "queued"):
|
||||
return False
|
||||
|
||||
doc_ref.update({
|
||||
"status": "queued",
|
||||
"attempts": 0,
|
||||
"last_error": None,
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
logger.info(f"Admin retry: reset YouTube upload for job {job_id} to queued")
|
||||
return True
|
||||
|
||||
def get_queue_stats(self) -> Dict[str, Any]:
|
||||
"""Get queue statistics for admin dashboard."""
|
||||
queued = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "queued")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
processing = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "processing")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
failed = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "failed")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
completed = len(list(
|
||||
self.db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION)
|
||||
.where("status", "==", "completed")
|
||||
.select([])
|
||||
.stream()
|
||||
))
|
||||
|
||||
return {
|
||||
"queued": queued,
|
||||
"processing": processing,
|
||||
"failed": failed,
|
||||
"completed": completed,
|
||||
"total": queued + processing + failed + completed,
|
||||
}
|
||||
|
||||
|
||||
# Singleton instance
|
||||
_youtube_upload_queue_service: Optional[YouTubeUploadQueueService] = None
|
||||
|
||||
|
||||
def get_youtube_upload_queue_service() -> YouTubeUploadQueueService:
|
||||
"""Get the singleton YouTubeUploadQueueService instance."""
|
||||
global _youtube_upload_queue_service
|
||||
if _youtube_upload_queue_service is None:
|
||||
_youtube_upload_queue_service = YouTubeUploadQueueService()
|
||||
return _youtube_upload_queue_service
|
||||
+15
-24
@@ -94,7 +94,7 @@ def mock_auth_dependency(request):
|
||||
|
||||
# Skip for service-only unit tests that don't need the FastAPI app
|
||||
# Also skip tests that manage their own auth mocks (e.g., push tests use AuthResult objects)
|
||||
service_only_tests = ['test_email_validation_service', 'test_gce_encoding_worker', 'test_push_routes', 'test_push_notification_service']
|
||||
service_only_tests = ['test_rate_limit_service', 'test_email_validation_service', 'test_rate_limits_api', 'test_gce_encoding_worker', 'test_push_routes', 'test_push_notification_service']
|
||||
if any(test_name in test_path for test_name in service_only_tests):
|
||||
yield
|
||||
return
|
||||
@@ -105,41 +105,32 @@ def mock_auth_dependency(request):
|
||||
yield
|
||||
return
|
||||
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.api.dependencies import require_auth, require_admin, require_review_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.api.dependencies import require_auth, require_admin, require_review_auth, require_instrumental_auth
|
||||
from backend.main import app
|
||||
|
||||
# Create mock auth functions that return AuthResult objects
|
||||
|
||||
# Create mock auth functions
|
||||
async def mock_require_auth():
|
||||
"""Mock require_auth to always return valid admin credentials."""
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
)
|
||||
|
||||
return ("test-admin-token", UserType.ADMIN, 999)
|
||||
|
||||
async def mock_require_admin():
|
||||
"""Mock require_admin to always return valid admin credentials."""
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Test admin token",
|
||||
is_admin=True,
|
||||
user_email="test@example.com",
|
||||
)
|
||||
|
||||
return ("test-admin-token", UserType.ADMIN, 999)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
"""Mock require_review_auth to always return valid review access."""
|
||||
return (job_id, "full")
|
||||
|
||||
|
||||
async def mock_require_instrumental_auth(job_id: str = "test123"):
|
||||
"""Mock require_instrumental_auth to always return valid instrumental review access."""
|
||||
return (job_id, "full")
|
||||
|
||||
# Use FastAPI's dependency override system
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_admin] = mock_require_admin
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
app.dependency_overrides[require_instrumental_auth] = mock_require_instrumental_auth
|
||||
|
||||
yield
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""E2E tests for backend functionality."""
|
||||
@@ -1,360 +0,0 @@
|
||||
"""
|
||||
E2E tests that verify actual audio synchronization in generated videos.
|
||||
|
||||
These tests generate real (short) videos and verify the audio offset.
|
||||
Uses ffprobe to analyze video/audio streams.
|
||||
|
||||
These tests are SLOW and should be run on-demand, not on every PR.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import subprocess
|
||||
import tempfile
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
def ffprobe_available():
|
||||
"""Check if ffprobe is available."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['ffprobe', '-version'],
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
return result.returncode == 0
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
|
||||
# Skip all tests if ffprobe not available
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not ffprobe_available(),
|
||||
reason="ffprobe not available. Install ffmpeg to run these tests."
|
||||
)
|
||||
|
||||
|
||||
class TestAudioFileAnalysis:
|
||||
"""Helper tests for audio file analysis functions."""
|
||||
|
||||
def test_ffprobe_can_analyze_audio(self, tmp_path):
|
||||
"""Verify ffprobe can analyze audio files."""
|
||||
# Create a silent audio file for testing
|
||||
test_audio = tmp_path / "test.wav"
|
||||
|
||||
# Generate 5 seconds of silence using ffmpeg
|
||||
result = subprocess.run([
|
||||
'ffmpeg', '-y', '-f', 'lavfi',
|
||||
'-i', 'anullsrc=r=44100:cl=stereo',
|
||||
'-t', '5',
|
||||
str(test_audio)
|
||||
], capture_output=True)
|
||||
|
||||
if result.returncode != 0:
|
||||
pytest.skip("Could not create test audio file")
|
||||
|
||||
# Analyze with ffprobe
|
||||
probe_result = subprocess.run([
|
||||
'ffprobe', '-v', 'quiet',
|
||||
'-print_format', 'json',
|
||||
'-show_format',
|
||||
str(test_audio)
|
||||
], capture_output=True, text=True)
|
||||
|
||||
assert probe_result.returncode == 0
|
||||
data = json.loads(probe_result.stdout)
|
||||
assert 'format' in data
|
||||
duration = float(data['format']['duration'])
|
||||
assert 4.9 < duration < 5.1 # ~5 seconds
|
||||
|
||||
|
||||
class TestCountdownAudioPadding:
|
||||
"""Tests for audio padding functionality."""
|
||||
|
||||
@pytest.fixture
|
||||
def source_audio(self, tmp_path):
|
||||
"""Create a short source audio file."""
|
||||
audio_path = tmp_path / "source.flac"
|
||||
|
||||
# Create a 5-second audio file with a tone at the start
|
||||
# This simulates audio content that starts immediately
|
||||
result = subprocess.run([
|
||||
'ffmpeg', '-y', '-f', 'lavfi',
|
||||
'-i', 'sine=frequency=440:duration=5',
|
||||
'-c:a', 'flac',
|
||||
str(audio_path)
|
||||
], capture_output=True)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"FFmpeg failed to create source audio: {result.stderr.decode()}")
|
||||
|
||||
return audio_path
|
||||
|
||||
def test_padding_adds_correct_duration(self, source_audio, tmp_path):
|
||||
"""Verify that padding adds exactly the specified duration."""
|
||||
padded_audio = tmp_path / "padded.flac"
|
||||
padding_seconds = 3.0
|
||||
|
||||
# Apply padding using the same method as CountdownProcessor
|
||||
# adelay filter adds delay in milliseconds
|
||||
delay_ms = int(padding_seconds * 1000)
|
||||
|
||||
result = subprocess.run([
|
||||
'ffmpeg', '-y',
|
||||
'-i', str(source_audio),
|
||||
'-af', f'adelay={delay_ms}|{delay_ms}',
|
||||
'-c:a', 'flac',
|
||||
str(padded_audio)
|
||||
], capture_output=True)
|
||||
|
||||
assert result.returncode == 0, f"FFmpeg failed: {result.stderr}"
|
||||
|
||||
# Analyze both files
|
||||
def get_duration(path):
|
||||
probe = subprocess.run([
|
||||
'ffprobe', '-v', 'quiet',
|
||||
'-print_format', 'json',
|
||||
'-show_format',
|
||||
str(path)
|
||||
], capture_output=True, text=True)
|
||||
data = json.loads(probe.stdout)
|
||||
return float(data['format']['duration'])
|
||||
|
||||
source_duration = get_duration(source_audio)
|
||||
padded_duration = get_duration(padded_audio)
|
||||
|
||||
# Padded should be source + padding
|
||||
expected_duration = source_duration + padding_seconds
|
||||
assert abs(padded_duration - expected_duration) < 0.1, (
|
||||
f"Expected duration ~{expected_duration}s, got {padded_duration}s"
|
||||
)
|
||||
|
||||
def test_karaoke_finalise_pad_audio_file(self, source_audio, tmp_path):
|
||||
"""Test KaraokeFinalise._pad_audio_file creates correctly padded audio."""
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
|
||||
padded_audio = tmp_path / "padded_via_finalise.flac"
|
||||
padding_seconds = 3.0
|
||||
|
||||
finalise = KaraokeFinalise(non_interactive=True)
|
||||
finalise._pad_audio_file(str(source_audio), str(padded_audio), padding_seconds)
|
||||
|
||||
assert padded_audio.exists(), "Padded audio file was not created"
|
||||
|
||||
# Verify duration
|
||||
probe = subprocess.run([
|
||||
'ffprobe', '-v', 'quiet',
|
||||
'-print_format', 'json',
|
||||
'-show_format',
|
||||
str(padded_audio)
|
||||
], capture_output=True, text=True)
|
||||
|
||||
data = json.loads(probe.stdout)
|
||||
padded_duration = float(data['format']['duration'])
|
||||
|
||||
# Get source duration
|
||||
source_probe = subprocess.run([
|
||||
'ffprobe', '-v', 'quiet',
|
||||
'-print_format', 'json',
|
||||
'-show_format',
|
||||
str(source_audio)
|
||||
], capture_output=True, text=True)
|
||||
|
||||
source_data = json.loads(source_probe.stdout)
|
||||
source_duration = float(source_data['format']['duration'])
|
||||
|
||||
expected = source_duration + padding_seconds
|
||||
assert abs(padded_duration - expected) < 0.1, (
|
||||
f"Expected ~{expected}s, got {padded_duration}s"
|
||||
)
|
||||
|
||||
|
||||
class TestAudioSyncVerification:
|
||||
"""
|
||||
Tests that verify the final audio sync between vocals and instrumental.
|
||||
|
||||
These tests create test audio files and verify that when countdown is added:
|
||||
1. Vocals are padded by countdown duration
|
||||
2. Instrumental is padded by same duration
|
||||
3. Relative timing is preserved
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def vocals_audio(self, tmp_path):
|
||||
"""Create vocals audio with a distinctive marker at 0.5s."""
|
||||
audio_path = tmp_path / "vocals.flac"
|
||||
|
||||
# Create audio: 0.5s silence, then 1s tone, then silence
|
||||
# Total 5 seconds
|
||||
filter_complex = (
|
||||
'aevalsrc=0:d=0.5[silence1];'
|
||||
'sine=frequency=880:duration=1[tone];'
|
||||
'aevalsrc=0:d=3.5[silence2];'
|
||||
'[silence1][tone][silence2]concat=n=3:v=0:a=1'
|
||||
)
|
||||
|
||||
subprocess.run([
|
||||
'ffmpeg', '-y', '-f', 'lavfi',
|
||||
'-i', filter_complex,
|
||||
'-c:a', 'flac',
|
||||
str(audio_path)
|
||||
], capture_output=True)
|
||||
|
||||
return audio_path
|
||||
|
||||
@pytest.fixture
|
||||
def instrumental_audio(self, tmp_path):
|
||||
"""Create instrumental audio with marker at 0.5s."""
|
||||
audio_path = tmp_path / "instrumental.flac"
|
||||
|
||||
filter_complex = (
|
||||
'aevalsrc=0:d=0.5[silence1];'
|
||||
'sine=frequency=440:duration=1[tone];'
|
||||
'aevalsrc=0:d=3.5[silence2];'
|
||||
'[silence1][tone][silence2]concat=n=3:v=0:a=1'
|
||||
)
|
||||
|
||||
subprocess.run([
|
||||
'ffmpeg', '-y', '-f', 'lavfi',
|
||||
'-i', filter_complex,
|
||||
'-c:a', 'flac',
|
||||
str(audio_path)
|
||||
], capture_output=True)
|
||||
|
||||
return audio_path
|
||||
|
||||
def test_both_tracks_padded_equally(self, vocals_audio, instrumental_audio, tmp_path):
|
||||
"""
|
||||
When countdown is applied, both vocals and instrumental must be
|
||||
padded by the same amount to maintain sync.
|
||||
"""
|
||||
padding_seconds = 3.0
|
||||
delay_ms = int(padding_seconds * 1000)
|
||||
|
||||
padded_vocals = tmp_path / "padded_vocals.flac"
|
||||
padded_instrumental = tmp_path / "padded_instrumental.flac"
|
||||
|
||||
# Pad both
|
||||
for src, dst in [(vocals_audio, padded_vocals), (instrumental_audio, padded_instrumental)]:
|
||||
subprocess.run([
|
||||
'ffmpeg', '-y',
|
||||
'-i', str(src),
|
||||
'-af', f'adelay={delay_ms}|{delay_ms}',
|
||||
'-c:a', 'flac',
|
||||
str(dst)
|
||||
], capture_output=True)
|
||||
|
||||
# Get durations
|
||||
def get_duration(path):
|
||||
probe = subprocess.run([
|
||||
'ffprobe', '-v', 'quiet',
|
||||
'-print_format', 'json',
|
||||
'-show_format',
|
||||
str(path)
|
||||
], capture_output=True, text=True)
|
||||
data = json.loads(probe.stdout)
|
||||
return float(data['format']['duration'])
|
||||
|
||||
vocals_dur = get_duration(padded_vocals)
|
||||
inst_dur = get_duration(padded_instrumental)
|
||||
|
||||
# Both should have same duration (sync maintained)
|
||||
assert abs(vocals_dur - inst_dur) < 0.1, (
|
||||
f"Padded vocals ({vocals_dur}s) and instrumental ({inst_dur}s) "
|
||||
"have different durations - sync will be off"
|
||||
)
|
||||
|
||||
|
||||
class TestCountdownTimingInvariant:
|
||||
"""
|
||||
Tests for the critical audio timing invariant.
|
||||
|
||||
INVARIANT: If vocals start at time T (after countdown),
|
||||
instrumental must also start at time T (also padded).
|
||||
|
||||
Violation of this invariant causes audio desync.
|
||||
"""
|
||||
|
||||
def test_relative_timing_preserved_after_padding(self):
|
||||
"""
|
||||
The relative timing between vocals and instrumental must be preserved.
|
||||
|
||||
If vocals originally start at 0.5s with content at 0.5s,
|
||||
after 3s padding, vocals content is at 3.5s.
|
||||
Instrumental must also be padded so its content is at 3.5s.
|
||||
"""
|
||||
original_content_start = 0.5 # seconds
|
||||
padding_seconds = 3.0
|
||||
|
||||
# After padding
|
||||
vocals_content_after_padding = original_content_start + padding_seconds
|
||||
instrumental_start_after_padding = 0 + padding_seconds # instrumental starts at 0
|
||||
|
||||
# The relative offset should be preserved
|
||||
original_relative_offset = original_content_start - 0 # vocals relative to instrumental start
|
||||
new_relative_offset = vocals_content_after_padding - instrumental_start_after_padding
|
||||
|
||||
assert original_relative_offset == new_relative_offset, (
|
||||
"INVARIANT VIOLATION: Padding changed the relative timing "
|
||||
"between vocals and instrumental"
|
||||
)
|
||||
|
||||
def test_sync_check_formula(self):
|
||||
"""
|
||||
Formula for checking if audio is in sync:
|
||||
If has_countdown_padding=True:
|
||||
expected_instrumental_start = countdown_padding_seconds
|
||||
actual_instrumental_start should equal expected
|
||||
"""
|
||||
countdown_padding_seconds = 3.0
|
||||
has_countdown_padding = True
|
||||
|
||||
if has_countdown_padding:
|
||||
expected_instrumental_start = countdown_padding_seconds
|
||||
else:
|
||||
expected_instrumental_start = 0
|
||||
|
||||
# If instrumental is correctly padded
|
||||
actual_instrumental_start = 3.0 # (padded)
|
||||
|
||||
assert actual_instrumental_start == expected_instrumental_start, (
|
||||
"Audio sync check failed"
|
||||
)
|
||||
|
||||
|
||||
class TestAudioSyncDriftAcceptance:
|
||||
"""
|
||||
Tests for acceptable audio drift tolerance.
|
||||
|
||||
Small amounts of drift (<100ms) are acceptable in karaoke videos.
|
||||
Larger drift (>100ms) is noticeable and indicates a bug.
|
||||
"""
|
||||
|
||||
def test_acceptable_drift_threshold(self):
|
||||
"""Define the acceptable drift threshold."""
|
||||
acceptable_drift_ms = 100 # 100ms
|
||||
acceptable_drift_s = acceptable_drift_ms / 1000
|
||||
|
||||
# A 50ms drift is acceptable
|
||||
actual_drift_s = 0.050
|
||||
assert actual_drift_s <= acceptable_drift_s, "50ms drift should be acceptable"
|
||||
|
||||
# A 200ms drift is NOT acceptable
|
||||
actual_drift_s = 0.200
|
||||
assert actual_drift_s > acceptable_drift_s, "200ms drift is too much"
|
||||
|
||||
def test_countdown_sync_within_tolerance(self):
|
||||
"""
|
||||
After countdown processing, drift should be within tolerance.
|
||||
"""
|
||||
# Ideal case: no drift
|
||||
expected_sync = 3.0 # seconds
|
||||
actual_sync = 3.0 # seconds
|
||||
|
||||
drift = abs(actual_sync - expected_sync)
|
||||
acceptable_drift = 0.1 # 100ms
|
||||
|
||||
assert drift <= acceptable_drift, (
|
||||
f"Drift of {drift*1000}ms exceeds tolerance of {acceptable_drift*1000}ms"
|
||||
)
|
||||
@@ -1,122 +0,0 @@
|
||||
"""
|
||||
Integration tests for admin job reset endpoint.
|
||||
|
||||
These tests use the real Firestore emulator and real JobManager,
|
||||
catching bugs that unit tests with mocks might miss (e.g., incorrect
|
||||
assumptions about return values).
|
||||
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.tests.emulator.conftest import emulators_running
|
||||
|
||||
# Skip all tests if emulators aren't running
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
|
||||
)
|
||||
|
||||
# Only import if emulators are running
|
||||
if emulators_running():
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
|
||||
class TestUpdateJobReturnValue:
|
||||
"""
|
||||
Critical tests documenting that update_job() returns None, not boolean.
|
||||
|
||||
This test class exists because a production bug (PR #371) was caused by
|
||||
assuming update_job() returns a boolean success indicator. The real API
|
||||
returns None on success and raises on failure. Mocks that return True
|
||||
hide this behavior.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
"""Create a real JobManager using emulator."""
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
"""Create a real FirestoreService using emulator."""
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.fixture
|
||||
def test_job(self, firestore_service):
|
||||
"""Create a test job for verification."""
|
||||
job_id = f"update-return-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
)
|
||||
|
||||
firestore_service.create_job(job)
|
||||
|
||||
yield job
|
||||
|
||||
# Cleanup
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def test_update_job_returns_none_not_boolean(self, job_manager, test_job):
|
||||
"""
|
||||
Verify update_job() returns None, not a boolean.
|
||||
|
||||
This test exists because a production bug was introduced when code
|
||||
assumed update_job() returns a boolean. The method actually returns
|
||||
None on success and raises an exception on failure.
|
||||
|
||||
Bug pattern that this test prevents:
|
||||
```python
|
||||
success = job_manager.update_job(job_id, updates)
|
||||
if not success: # BUG: None is falsy, so this is always True!
|
||||
raise HTTPException(status_code=500, ...)
|
||||
```
|
||||
|
||||
Correct pattern:
|
||||
```python
|
||||
# update_job() raises on failure, returns None on success
|
||||
job_manager.update_job(job_id, updates)
|
||||
```
|
||||
"""
|
||||
# update_job() should return None, not True/False
|
||||
result = job_manager.update_job(
|
||||
test_job.job_id,
|
||||
{"status": JobStatus.PENDING.value}
|
||||
)
|
||||
|
||||
# The actual return value is None, not True
|
||||
assert result is None, (
|
||||
"update_job() should return None, not a boolean. "
|
||||
"Code checking 'if not update_job(...)' will always be True!"
|
||||
)
|
||||
|
||||
def test_update_job_on_nonexistent_job(self, job_manager):
|
||||
"""
|
||||
Document update_job() behavior for non-existent jobs.
|
||||
|
||||
In production Firestore, update() on non-existent doc raises NotFound.
|
||||
The key insight for preventing the admin reset bug is understanding
|
||||
that update_job() returns None (not boolean) on success.
|
||||
"""
|
||||
try:
|
||||
result = job_manager.update_job(
|
||||
"nonexistent-job-id-12345",
|
||||
{"status": JobStatus.PENDING.value}
|
||||
)
|
||||
# If no exception raised (emulator quirk), verify return is still None
|
||||
assert result is None, "update_job should return None even on non-existent doc"
|
||||
except Exception:
|
||||
# Exception is the expected behavior in production Firestore
|
||||
pass
|
||||
@@ -1,69 +0,0 @@
|
||||
"""
|
||||
Integration tests for admin job reset using REAL job fixture from production.
|
||||
|
||||
This test validates that update_job() returns None, not a boolean
|
||||
(the root cause of PR #371 bug).
|
||||
|
||||
Uses actual data from production job 984da08b which needed admin reset.
|
||||
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.tests.emulator.conftest import emulators_running
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
|
||||
)
|
||||
|
||||
if emulators_running():
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
|
||||
class TestAdminResetBugFix:
|
||||
"""
|
||||
Tests that prove the PR #371 bug fix works using real emulator.
|
||||
|
||||
The bug: admin reset endpoint returned 500 because:
|
||||
success = job_manager.update_job(job_id, updates)
|
||||
if not success: # BUG: update_job returns None, not True!
|
||||
raise HTTPException(500)
|
||||
"""
|
||||
|
||||
def test_update_job_returns_none_not_boolean(self):
|
||||
"""
|
||||
Prove that update_job() returns None, not a boolean.
|
||||
|
||||
This is the root cause of the bug. Any code that does
|
||||
'if not update_job(...)' will always be True.
|
||||
"""
|
||||
jm = JobManager()
|
||||
job_id = f"test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.COMPLETE,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Mark Mallman",
|
||||
title="Minneapolis",
|
||||
)
|
||||
|
||||
try:
|
||||
jm.firestore.create_job(job)
|
||||
|
||||
# THE KEY TEST: update_job returns None
|
||||
result = jm.update_job(job_id, {"status": "pending"})
|
||||
|
||||
assert result is None, (
|
||||
"update_job() must return None. "
|
||||
"Code checking 'if not success:' would always fail!"
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
jm.firestore.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,361 +0,0 @@
|
||||
"""
|
||||
Integration tests for countdown padding across the full worker pipeline.
|
||||
|
||||
These tests use Firestore emulator to verify real state updates flow correctly
|
||||
between workers. They mock only external services (Modal, AudioShake, etc.)
|
||||
but use real Firestore for state persistence.
|
||||
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
import tempfile
|
||||
|
||||
# Import base fixtures from conftest
|
||||
from backend.tests.emulator.conftest import emulators_running
|
||||
|
||||
# Skip all tests if emulators aren't running
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
|
||||
)
|
||||
|
||||
# Only import if emulators are running
|
||||
if emulators_running():
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
|
||||
class TestCountdownStateFlowThroughPipeline:
|
||||
"""
|
||||
Integration tests verifying countdown state flows correctly through
|
||||
the full worker pipeline: lyrics -> render_video -> video.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
"""Create a real JobManager using emulator."""
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
"""Create a real FirestoreService using emulator for direct job operations."""
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.fixture
|
||||
def storage_service(self):
|
||||
"""Create a real StorageService using emulator."""
|
||||
return StorageService()
|
||||
|
||||
@pytest.fixture
|
||||
def job_with_early_start_song(self, job_manager, firestore_service):
|
||||
"""
|
||||
Create a job where lyrics start within 3 seconds (needs countdown).
|
||||
|
||||
This simulates a song where the first word appears at 0.5 seconds,
|
||||
which triggers countdown processing.
|
||||
"""
|
||||
job_id = f"countdown-test-early-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Early Start Song",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': False,
|
||||
'countdown_padding_seconds': 0.0,
|
||||
'first_word_start_time': 0.5, # Within 3s threshold
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Create job in Firestore directly
|
||||
firestore_service.create_job(job)
|
||||
|
||||
yield job
|
||||
|
||||
# Cleanup
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@pytest.fixture
|
||||
def job_with_late_start_song(self, job_manager, firestore_service):
|
||||
"""
|
||||
Create a job where lyrics start after 3 seconds (no countdown needed).
|
||||
|
||||
This simulates a song where the first word appears at 5.0 seconds,
|
||||
which does NOT trigger countdown processing.
|
||||
"""
|
||||
job_id = f"countdown-test-late-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Late Start Song",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': False,
|
||||
'countdown_padding_seconds': 0.0,
|
||||
'first_word_start_time': 5.0, # After 3s threshold
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
firestore_service.create_job(job)
|
||||
|
||||
yield job
|
||||
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_update_persists_to_firestore(self, job_with_early_start_song, job_manager):
|
||||
"""
|
||||
Verify that state updates via update_state_data() persist to Firestore.
|
||||
|
||||
This is the foundation of the countdown state flow - if updates don't
|
||||
persist, video_worker can't read the countdown state.
|
||||
"""
|
||||
job = job_with_early_start_song
|
||||
|
||||
# Simulate render_video_worker updating countdown state
|
||||
new_lyrics_metadata = {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
'first_word_start_time': 0.5,
|
||||
}
|
||||
|
||||
job_manager.update_state_data(job.job_id, 'lyrics_metadata', new_lyrics_metadata)
|
||||
|
||||
# Read job back from Firestore
|
||||
refreshed_job = job_manager.get_job(job.job_id)
|
||||
|
||||
assert refreshed_job is not None
|
||||
lyrics_metadata = refreshed_job.state_data.get('lyrics_metadata', {})
|
||||
assert lyrics_metadata.get('has_countdown_padding') is True
|
||||
assert lyrics_metadata.get('countdown_padding_seconds') == 3.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_worker_reads_updated_state(self, job_with_early_start_song, job_manager):
|
||||
"""
|
||||
Verify that video_worker can read countdown state after render_video_worker sets it.
|
||||
|
||||
This simulates the full flow:
|
||||
1. render_video_worker sets has_countdown_padding=True
|
||||
2. video_worker reads the state and extracts countdown_padding_seconds
|
||||
"""
|
||||
job = job_with_early_start_song
|
||||
|
||||
# Step 1: render_video_worker updates state
|
||||
new_lyrics_metadata = {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
}
|
||||
job_manager.update_state_data(job.job_id, 'lyrics_metadata', new_lyrics_metadata)
|
||||
|
||||
# Step 2: video_worker reads state (simulated)
|
||||
refreshed_job = job_manager.get_job(job.job_id)
|
||||
|
||||
# video_worker extraction logic
|
||||
lyrics_metadata = refreshed_job.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
assert countdown_padding_seconds == 3.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_countdown_state_when_not_needed(self, job_with_late_start_song, job_manager):
|
||||
"""
|
||||
Verify that when song doesn't need countdown, state remains False.
|
||||
"""
|
||||
job = job_with_late_start_song
|
||||
|
||||
# Read initial state
|
||||
current_job = job_manager.get_job(job.job_id)
|
||||
lyrics_metadata = current_job.state_data.get('lyrics_metadata', {})
|
||||
|
||||
assert lyrics_metadata.get('has_countdown_padding') is False
|
||||
assert lyrics_metadata.get('countdown_padding_seconds') == 0.0
|
||||
|
||||
# video_worker extraction logic
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
assert countdown_padding_seconds is None
|
||||
|
||||
|
||||
class TestCountdownStateTransitions:
|
||||
"""Tests for state transitions during countdown processing."""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_transitions_preserve_countdown_info(self, job_manager, firestore_service):
|
||||
"""
|
||||
Countdown state should survive job state transitions.
|
||||
|
||||
When job moves from GENERATING_VIDEO to ENCODING,
|
||||
the lyrics_metadata should remain intact.
|
||||
"""
|
||||
job_id = f"transition-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job in GENERATING_VIDEO state (valid predecessor to ENCODING)
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.GENERATING_VIDEO,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# Transition to ENCODING (valid transition from GENERATING_VIDEO)
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.ENCODING,
|
||||
progress=75,
|
||||
message="Starting encoding"
|
||||
)
|
||||
|
||||
# Read job and verify countdown state preserved
|
||||
refreshed_job = job_manager.get_job(job_id)
|
||||
lyrics_metadata = refreshed_job.state_data.get('lyrics_metadata', {})
|
||||
|
||||
assert lyrics_metadata.get('has_countdown_padding') is True
|
||||
assert lyrics_metadata.get('countdown_padding_seconds') == 3.0
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class TestWorkerStateDataIsolation:
|
||||
"""Tests that different workers don't overwrite each other's state data."""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lyrics_metadata_not_overwritten_by_other_updates(self, job_manager, firestore_service):
|
||||
"""
|
||||
Updating video_worker state should NOT overwrite lyrics_metadata.
|
||||
|
||||
Each worker stores its state in separate keys within state_data.
|
||||
"""
|
||||
job_id = f"isolation-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job with countdown state
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# Update video_worker state (different key)
|
||||
job_manager.update_state_data(job_id, 'video_worker', {
|
||||
'instrumental_source': 'clean',
|
||||
'encoding_started': True,
|
||||
})
|
||||
|
||||
# Verify lyrics_metadata preserved
|
||||
refreshed_job = job_manager.get_job(job_id)
|
||||
lyrics_metadata = refreshed_job.state_data.get('lyrics_metadata', {})
|
||||
|
||||
assert lyrics_metadata.get('has_countdown_padding') is True
|
||||
assert lyrics_metadata.get('countdown_padding_seconds') == 3.0
|
||||
|
||||
# Verify video_worker state also present
|
||||
video_worker_state = refreshed_job.state_data.get('video_worker', {})
|
||||
assert video_worker_state.get('instrumental_source') == 'clean'
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class TestCountdownStateUpdateCodeExists:
|
||||
"""
|
||||
Verify the render_video_worker code contains the state update logic.
|
||||
|
||||
This is a code inspection test rather than an execution test, since running
|
||||
the actual worker requires too much complex setup (audio files, corrections, etc.).
|
||||
The actual state update behavior is verified by the unit tests.
|
||||
"""
|
||||
|
||||
def test_render_video_worker_has_state_update_code(self):
|
||||
"""
|
||||
Verify render_video_worker.py contains the code to update lyrics_metadata
|
||||
when countdown padding is added.
|
||||
|
||||
This ensures the fix hasn't been accidentally removed.
|
||||
"""
|
||||
import inspect
|
||||
from backend.workers import render_video_worker
|
||||
|
||||
source = inspect.getsource(render_video_worker)
|
||||
|
||||
# The fix should include updating lyrics_metadata when padding_added is True
|
||||
assert "update_state_data" in source, (
|
||||
"render_video_worker must call update_state_data"
|
||||
)
|
||||
assert "has_countdown_padding" in source, (
|
||||
"render_video_worker must set has_countdown_padding"
|
||||
)
|
||||
assert "countdown_padding_seconds" in source, (
|
||||
"render_video_worker must set countdown_padding_seconds"
|
||||
)
|
||||
assert "lyrics_metadata" in source, (
|
||||
"render_video_worker must update lyrics_metadata"
|
||||
)
|
||||
@@ -1,380 +0,0 @@
|
||||
"""
|
||||
Tests that countdown state survives worker boundaries and job reloads.
|
||||
|
||||
These tests verify that countdown state persists correctly in Firestore
|
||||
and can be read across different worker invocations.
|
||||
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
import time
|
||||
|
||||
# Import base fixtures from conftest
|
||||
from backend.tests.emulator.conftest import emulators_running
|
||||
|
||||
# Skip all tests if emulators aren't running
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
|
||||
)
|
||||
|
||||
# Only import if emulators are running
|
||||
if emulators_running():
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
|
||||
class TestCountdownStatePersistence:
|
||||
"""Tests that countdown state persists between worker boundaries."""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
"""Create a real JobManager using emulator."""
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
"""Create a real FirestoreService using emulator for direct job operations."""
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_persists_between_render_and_video_workers(self, job_manager, firestore_service):
|
||||
"""
|
||||
State set by render_video_worker is readable by video_worker.
|
||||
|
||||
Simulates:
|
||||
1. render_video_worker completes, sets has_countdown_padding=True
|
||||
2. Some time passes (worker boundary)
|
||||
3. video_worker starts, reads has_countdown_padding
|
||||
"""
|
||||
job_id = f"persist-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create initial job (as lyrics_worker would leave it)
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.RENDERING_VIDEO,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': False,
|
||||
'countdown_padding_seconds': 0.0,
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# === render_video_worker completes ===
|
||||
job_manager.update_state_data(job_id, 'lyrics_metadata', {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
})
|
||||
|
||||
# Simulate worker boundary (job is re-fetched from Firestore)
|
||||
# Create a NEW JobManager instance to simulate video_worker starting
|
||||
video_job_manager = JobManager()
|
||||
|
||||
# === video_worker starts ===
|
||||
job_from_video_worker = video_job_manager.get_job(job_id)
|
||||
|
||||
# video_worker reads countdown state
|
||||
lyrics_metadata = job_from_video_worker.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
assert countdown_padding_seconds == 3.0, (
|
||||
"Countdown state did not persist between workers"
|
||||
)
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_state_survives_job_reload(self, job_manager, firestore_service):
|
||||
"""
|
||||
State persists when job is reloaded from Firestore multiple times.
|
||||
"""
|
||||
job_id = f"reload-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job with countdown state
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# Reload job multiple times
|
||||
for i in range(3):
|
||||
reloaded_job = job_manager.get_job(job_id)
|
||||
|
||||
lyrics_metadata = reloaded_job.state_data.get('lyrics_metadata', {})
|
||||
assert lyrics_metadata.get('has_countdown_padding') is True, (
|
||||
f"Countdown state lost after reload #{i+1}"
|
||||
)
|
||||
assert lyrics_metadata.get('countdown_padding_seconds') == 3.0, (
|
||||
f"Countdown duration changed after reload #{i+1}"
|
||||
)
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_partial_state_update_preserves_other_fields(self, job_manager, firestore_service):
|
||||
"""
|
||||
Updating one field in state_data doesn't affect other fields.
|
||||
"""
|
||||
job_id = f"partial-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job with multiple state fields
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
'original_field': 'should_be_preserved',
|
||||
},
|
||||
'audio_complete': True,
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# Update video_worker state (different key)
|
||||
job_manager.update_state_data(job_id, 'video_worker', {
|
||||
'encoding_started': True,
|
||||
})
|
||||
|
||||
# Verify lyrics_metadata is completely preserved
|
||||
reloaded_job = job_manager.get_job(job_id)
|
||||
lyrics_metadata = reloaded_job.state_data.get('lyrics_metadata', {})
|
||||
|
||||
assert lyrics_metadata.get('has_countdown_padding') is True
|
||||
assert lyrics_metadata.get('countdown_padding_seconds') == 3.0
|
||||
assert lyrics_metadata.get('original_field') == 'should_be_preserved'
|
||||
assert reloaded_job.state_data.get('audio_complete') is True
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class TestCountdownStateConsistency:
|
||||
"""Tests for state consistency under concurrent access patterns."""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_reads_see_same_state(self, job_manager, firestore_service):
|
||||
"""
|
||||
Multiple concurrent reads should see the same countdown state.
|
||||
"""
|
||||
job_id = f"concurrent-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job with countdown
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': True,
|
||||
'countdown_padding_seconds': 3.0,
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# Simulate concurrent reads
|
||||
reads = []
|
||||
for _ in range(5):
|
||||
reloaded = job_manager.get_job(job_id)
|
||||
lyrics_metadata = reloaded.state_data.get('lyrics_metadata', {})
|
||||
reads.append({
|
||||
'has_countdown_padding': lyrics_metadata.get('has_countdown_padding'),
|
||||
'countdown_padding_seconds': lyrics_metadata.get('countdown_padding_seconds'),
|
||||
})
|
||||
|
||||
# All reads should be consistent
|
||||
for read in reads:
|
||||
assert read['has_countdown_padding'] is True
|
||||
assert read['countdown_padding_seconds'] == 3.0
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class TestCountdownStateMigration:
|
||||
"""Tests for handling jobs with missing or old countdown state format."""
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(self):
|
||||
return JobManager()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self):
|
||||
return FirestoreService()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handles_missing_lyrics_metadata(self, job_manager, firestore_service):
|
||||
"""
|
||||
Jobs without lyrics_metadata should be handled gracefully.
|
||||
|
||||
This can happen for jobs created before the countdown feature.
|
||||
"""
|
||||
job_id = f"migration-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job WITHOUT lyrics_metadata (old format)
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={} # No lyrics_metadata
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
# video_worker logic should handle this
|
||||
reloaded = job_manager.get_job(job_id)
|
||||
lyrics_metadata = reloaded.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
# Should return None, not crash
|
||||
assert countdown_padding_seconds is None
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handles_missing_countdown_fields(self, job_manager, firestore_service):
|
||||
"""
|
||||
Jobs with lyrics_metadata but missing countdown fields handled gracefully.
|
||||
"""
|
||||
job_id = f"fields-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
# Create job with lyrics_metadata but no countdown fields
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'some_other_field': 'value',
|
||||
# No has_countdown_padding
|
||||
# No countdown_padding_seconds
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
reloaded = job_manager.get_job(job_id)
|
||||
lyrics_metadata = reloaded.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
# Should return None when has_countdown_padding is missing/falsy
|
||||
assert countdown_padding_seconds is None
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handles_countdown_true_without_duration(self, job_manager, firestore_service):
|
||||
"""
|
||||
If has_countdown_padding=True but duration missing, default to 3.0.
|
||||
"""
|
||||
job_id = f"default-duration-test-{datetime.now(UTC).timestamp()}"
|
||||
|
||||
try:
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.ENCODING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Test",
|
||||
state_data={
|
||||
'lyrics_metadata': {
|
||||
'has_countdown_padding': True,
|
||||
# countdown_padding_seconds intentionally missing
|
||||
}
|
||||
}
|
||||
)
|
||||
firestore_service.create_job(job)
|
||||
|
||||
reloaded = job_manager.get_job(job_id)
|
||||
lyrics_metadata = reloaded.state_data.get('lyrics_metadata', {})
|
||||
countdown_padding_seconds = None
|
||||
if lyrics_metadata.get('has_countdown_padding'):
|
||||
countdown_padding_seconds = lyrics_metadata.get('countdown_padding_seconds', 3.0)
|
||||
|
||||
# Should default to 3.0
|
||||
assert countdown_padding_seconds == 3.0
|
||||
|
||||
finally:
|
||||
try:
|
||||
firestore_service.delete_job(job_id)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,719 +0,0 @@
|
||||
"""
|
||||
Emulator integration tests for made-for-you orders with YouTube URLs.
|
||||
|
||||
These tests use REAL Firestore and GCS emulators to test the full API flow,
|
||||
mocking only external services (YouTube download, email, Stripe).
|
||||
|
||||
Tests cover:
|
||||
1. Job creation with YouTube URL metadata
|
||||
2. YouTube audio download and GCS storage
|
||||
3. Worker trigger sequencing (download before workers)
|
||||
4. Error handling for download failures
|
||||
5. Job state persistence and consistency
|
||||
|
||||
Run with: scripts/run-emulator-tests.sh
|
||||
Or directly: make test-e2e
|
||||
"""
|
||||
import pytest
|
||||
import time
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
|
||||
from .conftest import emulators_running
|
||||
|
||||
# Skip all tests if emulators not running
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh"
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Fixtures
|
||||
# =============================================================================
|
||||
|
||||
@pytest.fixture
|
||||
def youtube_order_metadata():
|
||||
"""Standard metadata for YouTube URL made-for-you order."""
|
||||
return {
|
||||
"order_type": "made_for_you",
|
||||
"customer_email": "customer@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"source_type": "youtube",
|
||||
"youtube_url": "https://youtube.com/watch?v=abc123",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def youtube_order_metadata_with_notes():
|
||||
"""YouTube order metadata with customer notes."""
|
||||
return {
|
||||
"order_type": "made_for_you",
|
||||
"customer_email": "customer@example.com",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"source_type": "youtube",
|
||||
"youtube_url": "https://youtube.com/watch?v=abc123",
|
||||
"notes": "Please make it extra special!",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stripe_service():
|
||||
"""Mock Stripe service for webhook verification."""
|
||||
service = MagicMock()
|
||||
service.is_configured.return_value = True
|
||||
service.verify_webhook_signature.return_value = (True, {}, "OK")
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_email_service():
|
||||
"""Mock email service for notification verification."""
|
||||
service = MagicMock()
|
||||
service.is_configured.return_value = True
|
||||
service.send_email.return_value = True
|
||||
service.send_made_for_you_order_confirmation.return_value = True
|
||||
service.send_made_for_you_admin_notification.return_value = True
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_user_service_for_webhook():
|
||||
"""Mock user service for webhook processing."""
|
||||
service = MagicMock()
|
||||
service.is_stripe_session_processed.return_value = False
|
||||
service._mark_stripe_session_processed.return_value = None
|
||||
|
||||
# Mock admin login token creation
|
||||
mock_admin_login = MagicMock()
|
||||
mock_admin_login.token = "test-admin-login-token"
|
||||
service.create_admin_login_token.return_value = mock_admin_login
|
||||
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_youtube_download_service():
|
||||
"""Mock YouTube download service returning valid GCS path."""
|
||||
service = MagicMock()
|
||||
service.download = AsyncMock(return_value="uploads/test-job-123/audio/test.webm")
|
||||
service.is_remote_enabled.return_value = True
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service_local():
|
||||
"""Mock worker service to track trigger calls (local scope, different name to avoid conftest collision)."""
|
||||
service = MagicMock()
|
||||
service.trigger_audio_worker = AsyncMock(return_value=True)
|
||||
service.trigger_lyrics_worker = AsyncMock(return_value=True)
|
||||
service.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_theme_service():
|
||||
"""Mock theme service to avoid real Firestore calls."""
|
||||
service = MagicMock()
|
||||
service.get_default_theme_id.return_value = "nomad"
|
||||
service.get_theme.return_value = MagicMock(
|
||||
theme_id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
style_params={}
|
||||
)
|
||||
return service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_distribution_settings():
|
||||
"""Mock distribution settings for made-for-you orders."""
|
||||
settings = MagicMock()
|
||||
settings.enable_youtube_upload = True
|
||||
settings.dropbox_path = "/Nomad Karaoke"
|
||||
settings.gdrive_folder_id = "test-folder-id"
|
||||
settings.brand_prefix = "Nomad Karaoke"
|
||||
settings.discord_webhook_url = None
|
||||
settings.youtube_description = None
|
||||
return settings
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Classes
|
||||
# =============================================================================
|
||||
|
||||
class TestMadeForYouYouTubeOrderFlow:
|
||||
"""
|
||||
Integration tests for made-for-you orders with YouTube URLs.
|
||||
|
||||
Uses real Firestore/GCS emulators to test the full flow:
|
||||
1. Webhook creates job with YouTube URL
|
||||
2. YouTube audio is downloaded to GCS
|
||||
3. Job is updated with input_media_gcs_path
|
||||
4. Workers are triggered with correct job state
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_url_order_creates_job_with_correct_fields(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that a YouTube URL order creates a job with the correct fields.
|
||||
|
||||
Verifies:
|
||||
- Job is created with made_for_you=True
|
||||
- customer_email is set correctly
|
||||
- url is set to the YouTube URL
|
||||
- theme_id defaults to "nomad"
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-youtube-fields"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_fields",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify job creation was called
|
||||
assert mock_job_manager.create_job.called
|
||||
|
||||
# Get the JobCreate argument
|
||||
job_create_arg = mock_job_manager.create_job.call_args[0][0]
|
||||
|
||||
# Verify made_for_you fields
|
||||
assert job_create_arg.made_for_you is True, \
|
||||
"Job must be marked as made_for_you"
|
||||
assert job_create_arg.customer_email == youtube_order_metadata["customer_email"], \
|
||||
"Customer email must be set for delivery"
|
||||
assert job_create_arg.url == youtube_order_metadata["youtube_url"], \
|
||||
"YouTube URL must be set on job"
|
||||
assert job_create_arg.user_email == ADMIN_EMAIL, \
|
||||
"Admin must own job during processing"
|
||||
assert job_create_arg.theme_id == "nomad", \
|
||||
"Default nomad theme should be applied"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_url_order_triggers_workers(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that YouTube URL orders trigger workers after downloading audio.
|
||||
|
||||
Verifies workers are called after YouTube download completes successfully.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-workers"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
# start_job_processing is async - mock it to call workers directly
|
||||
async def mock_start_job_processing(job_id, progress=15, message=""):
|
||||
await mock_worker_service_local.trigger_audio_worker(job_id)
|
||||
await mock_worker_service_local.trigger_lyrics_worker(job_id)
|
||||
mock_job_manager.start_job_processing = AsyncMock(side_effect=mock_start_job_processing)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_workers",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify workers were triggered via start_job_processing
|
||||
mock_worker_service_local.trigger_audio_worker.assert_called_once_with(mock_job.job_id)
|
||||
mock_worker_service_local.trigger_lyrics_worker.assert_called_once_with(mock_job.job_id)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_url_order_sends_notifications(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that YouTube URL orders send notification emails.
|
||||
|
||||
Verifies:
|
||||
- Customer receives order confirmation
|
||||
- Admin receives notification with job details
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-notifications"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
# start_job_processing is async - mock it as simple AsyncMock
|
||||
mock_job_manager.start_job_processing = AsyncMock()
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_notifications",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify customer confirmation email
|
||||
mock_email_service.send_made_for_you_order_confirmation.assert_called_once()
|
||||
confirm_call = mock_email_service.send_made_for_you_order_confirmation.call_args
|
||||
assert confirm_call.kwargs['to_email'] == youtube_order_metadata["customer_email"]
|
||||
assert confirm_call.kwargs['artist'] == youtube_order_metadata["artist"]
|
||||
assert confirm_call.kwargs['title'] == youtube_order_metadata["title"]
|
||||
|
||||
# Verify admin notification email
|
||||
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
|
||||
admin_call = mock_email_service.send_made_for_you_admin_notification.call_args
|
||||
assert admin_call.kwargs['to_email'] == ADMIN_EMAIL
|
||||
assert admin_call.kwargs['job_id'] == mock_job.job_id
|
||||
assert 'admin_login_token' in admin_call.kwargs
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_url_order_marks_session_processed(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that Stripe session is marked as processed for idempotency.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-idempotency"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_idempotency",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify session was marked processed
|
||||
mock_user_service_for_webhook._mark_stripe_session_processed.assert_called_once()
|
||||
mark_call = mock_user_service_for_webhook._mark_stripe_session_processed.call_args
|
||||
assert mark_call.kwargs['stripe_session_id'] == "sess_test_idempotency"
|
||||
assert mark_call.kwargs['email'] == youtube_order_metadata["customer_email"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_url_order_with_customer_notes(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata_with_notes
|
||||
):
|
||||
"""
|
||||
Test that customer notes are preserved on the job.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-notes"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_notes",
|
||||
metadata=youtube_order_metadata_with_notes,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
job_create_arg = mock_job_manager.create_job.call_args[0][0]
|
||||
assert job_create_arg.customer_notes == youtube_order_metadata_with_notes["notes"], \
|
||||
"Customer notes must be preserved on job"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_url_order_skips_audio_search(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that YouTube URL orders skip audio search (download + trigger workers directly).
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-no-search"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
# start_job_processing is async - mock it to call workers directly
|
||||
async def mock_start_job_processing(job_id, progress=15, message=""):
|
||||
await mock_worker_service_local.trigger_audio_worker(job_id)
|
||||
await mock_worker_service_local.trigger_lyrics_worker(job_id)
|
||||
mock_job_manager.start_job_processing = AsyncMock(side_effect=mock_start_job_processing)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.audio_search_service.get_audio_search_service') as mock_get_audio, \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
mock_audio_service = MagicMock()
|
||||
mock_get_audio.return_value = mock_audio_service
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_no_search",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Audio search should NOT be called for YouTube URL orders
|
||||
mock_audio_service.search.assert_not_called()
|
||||
|
||||
# Workers should be triggered directly via start_job_processing
|
||||
mock_worker_service_local.trigger_audio_worker.assert_called_once()
|
||||
|
||||
|
||||
class TestMadeForYouYouTubeJobState:
|
||||
"""
|
||||
Tests for job state consistency during YouTube URL processing.
|
||||
|
||||
These tests verify job state is set correctly when jobs are created
|
||||
through the made-for-you webhook handler.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_state_set_correctly_for_youtube_url_order(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that job state is set correctly for YouTube URL orders.
|
||||
|
||||
Verifies the JobCreate object has all required fields for proper
|
||||
job state persistence.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-state"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_state",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify job was created with correct state
|
||||
job_create_arg = mock_job_manager.create_job.call_args[0][0]
|
||||
|
||||
# Core made-for-you fields
|
||||
assert job_create_arg.made_for_you is True
|
||||
assert job_create_arg.customer_email == youtube_order_metadata["customer_email"]
|
||||
assert job_create_arg.url == youtube_order_metadata["youtube_url"]
|
||||
assert job_create_arg.artist == youtube_order_metadata["artist"]
|
||||
assert job_create_arg.title == youtube_order_metadata["title"]
|
||||
assert job_create_arg.user_email == ADMIN_EMAIL
|
||||
|
||||
# Job configuration
|
||||
assert job_create_arg.non_interactive is False # Admin will review
|
||||
assert job_create_arg.auto_download is False # Pause at audio selection
|
||||
|
||||
|
||||
class TestMadeForYouYouTubeErrorHandling:
|
||||
"""
|
||||
Tests for error handling scenarios in the YouTube URL flow.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_exception_sends_failure_notification(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_theme_service, mock_distribution_settings,
|
||||
youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that exceptions during processing send failure notification to admin.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
# Make job creation fail
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.create_job.side_effect = Exception("Database error")
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)):
|
||||
|
||||
# Should not raise - error is handled internally
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_error",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify failure email was sent to admin
|
||||
mock_email_service.send_email.assert_called()
|
||||
call_args = mock_email_service.send_email.call_args
|
||||
assert call_args.kwargs['to_email'] == ADMIN_EMAIL
|
||||
assert "[FAILED]" in call_args.kwargs['subject']
|
||||
assert "Database error" in call_args.kwargs['html_content']
|
||||
|
||||
|
||||
class TestMadeForYouWebhookIntegration:
|
||||
"""
|
||||
Tests for the Stripe webhook handling with made-for-you orders.
|
||||
|
||||
These tests verify the webhook handler processes made-for-you orders correctly.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handle_made_for_you_order_full_flow(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service, youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test the full made-for-you order handler flow.
|
||||
|
||||
This is what gets called when a Stripe webhook fires for a
|
||||
made-for-you order. Verifies:
|
||||
- Job is created with correct metadata
|
||||
- YouTube audio is downloaded
|
||||
- Workers are triggered
|
||||
- Emails are sent
|
||||
- Session is marked processed
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-webhook-flow"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
# start_job_processing is async - mock it to call workers directly
|
||||
async def mock_start_job_processing(job_id, progress=15, message=""):
|
||||
await mock_worker_service_local.trigger_audio_worker(job_id)
|
||||
await mock_worker_service_local.trigger_lyrics_worker(job_id)
|
||||
mock_job_manager.start_job_processing = AsyncMock(side_effect=mock_start_job_processing)
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="cs_test_webhook_flow",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# 1. Verify job was created
|
||||
assert mock_job_manager.create_job.called
|
||||
job_create_arg = mock_job_manager.create_job.call_args[0][0]
|
||||
assert job_create_arg.made_for_you is True
|
||||
assert job_create_arg.url == youtube_order_metadata["youtube_url"]
|
||||
|
||||
# 2. Verify YouTube download was called
|
||||
mock_youtube_download_service.download.assert_called_once()
|
||||
|
||||
# 3. Verify workers were triggered via start_job_processing
|
||||
mock_worker_service_local.trigger_audio_worker.assert_called_once()
|
||||
mock_worker_service_local.trigger_lyrics_worker.assert_called_once()
|
||||
|
||||
# 4. Verify emails were sent
|
||||
mock_email_service.send_made_for_you_order_confirmation.assert_called_once()
|
||||
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
|
||||
|
||||
# 5. Verify session marked processed
|
||||
mock_user_service_for_webhook._mark_stripe_session_processed.assert_called_once()
|
||||
assert mock_user_service_for_webhook._mark_stripe_session_processed.call_args.kwargs['stripe_session_id'] == "cs_test_webhook_flow"
|
||||
|
||||
|
||||
class TestMadeForYouYouTubeDistributionSettings:
|
||||
"""
|
||||
Tests for distribution settings on made-for-you YouTube orders.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_distribution_defaults_applied(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_youtube_download_service,
|
||||
youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
Test that distribution defaults are applied to made-for-you jobs.
|
||||
|
||||
Made-for-you jobs should have automatic distribution enabled.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-distribution"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
# Mock distribution settings
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.enable_youtube_upload = True
|
||||
mock_settings.dropbox_path = "/Nomad Karaoke"
|
||||
mock_settings.gdrive_folder_id = "test-folder-id"
|
||||
mock_settings.brand_prefix = "Nomad Karaoke"
|
||||
mock_settings.discord_webhook_url = None
|
||||
mock_settings.youtube_description = None
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_distribution",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify distribution settings were applied
|
||||
job_create_arg = mock_job_manager.create_job.call_args[0][0]
|
||||
|
||||
# These should match the mocked distribution settings
|
||||
assert job_create_arg.enable_youtube_upload == mock_settings.enable_youtube_upload
|
||||
assert job_create_arg.dropbox_path == mock_settings.dropbox_path
|
||||
assert job_create_arg.gdrive_folder_id == mock_settings.gdrive_folder_id
|
||||
assert job_create_arg.brand_prefix == mock_settings.brand_prefix
|
||||
|
||||
|
||||
class TestMadeForYouYouTubeGCSPath:
|
||||
"""
|
||||
Tests for GCS path format consistency in YouTube URL orders.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_url_set_correctly(
|
||||
self, mock_email_service, mock_user_service_for_webhook,
|
||||
mock_worker_service_local, mock_theme_service, mock_distribution_settings,
|
||||
mock_youtube_download_service
|
||||
):
|
||||
"""
|
||||
Test that the YouTube URL is stored correctly on the job.
|
||||
"""
|
||||
from backend.api.routes.users import _handle_made_for_you_order
|
||||
|
||||
test_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
metadata = {
|
||||
"order_type": "made_for_you",
|
||||
"customer_email": "customer@example.com",
|
||||
"artist": "Rick Astley",
|
||||
"title": "Never Gonna Give You Up",
|
||||
"source_type": "youtube",
|
||||
"youtube_url": test_url,
|
||||
}
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test-job-url"
|
||||
mock_job_manager.create_job.return_value = mock_job
|
||||
|
||||
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
|
||||
patch('backend.services.worker_service.get_worker_service', return_value=mock_worker_service_local), \
|
||||
patch('backend.services.storage_service.StorageService'), \
|
||||
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
|
||||
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
|
||||
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)), \
|
||||
patch('backend.api.routes.users._prepare_theme_for_job', return_value=(None, None, None)), \
|
||||
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_download_service):
|
||||
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_url",
|
||||
metadata=metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
job_create_arg = mock_job_manager.create_job.call_args[0][0]
|
||||
assert job_create_arg.url == test_url
|
||||
|
||||
|
||||
print("Made-for-you YouTube integration tests ready to run")
|
||||
@@ -1,348 +0,0 @@
|
||||
"""
|
||||
Integration tests for the job state machine flow.
|
||||
|
||||
These tests verify complete state transitions without mocking the state machine,
|
||||
ensuring the flow works correctly end-to-end (with mocked external services).
|
||||
|
||||
Created as part of state machine robustness improvements (2026-02-02).
|
||||
"""
|
||||
import pytest
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import Mock, AsyncMock, patch, MagicMock
|
||||
|
||||
# Mock Firestore before importing JobManager
|
||||
import sys
|
||||
sys.modules['google.cloud.firestore'] = MagicMock()
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.job_manager import JobManager, InvalidStateTransitionError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore_service():
|
||||
"""Mock FirestoreService."""
|
||||
with patch('backend.services.job_manager.FirestoreService') as mock:
|
||||
service = Mock()
|
||||
mock.return_value = service
|
||||
yield service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_manager(mock_firestore_service):
|
||||
"""Create JobManager instance with mocked Firestore."""
|
||||
return JobManager()
|
||||
|
||||
|
||||
class TestMadeForYouYouTubeFlow:
|
||||
"""
|
||||
Integration tests for Made-For-You YouTube order flow.
|
||||
|
||||
This was the flow that caused jobs 06cfea29 and 984da08b to get stuck.
|
||||
The fix ensures proper state transitions from PENDING -> DOWNLOADING.
|
||||
"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_complete_flow_pending_to_downloading(self, job_manager, mock_firestore_service):
|
||||
"""
|
||||
Test the flow from PENDING to DOWNLOADING for YouTube orders.
|
||||
|
||||
This verifies the fix for the bug where jobs got stuck at PENDING
|
||||
because start_job_processing wasn't called properly.
|
||||
"""
|
||||
# Create initial job in PENDING state
|
||||
job = Job(
|
||||
job_id="test-mfy-001",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="gs://bucket/test.mp3",
|
||||
state_data={},
|
||||
)
|
||||
# Access the firestore through the job_manager's instance
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
job_manager.firestore.update_job_status.return_value = True
|
||||
|
||||
# Mock worker service
|
||||
with patch('backend.services.worker_service.get_worker_service') as mock_get_worker:
|
||||
mock_worker = Mock()
|
||||
mock_worker.trigger_audio_worker = AsyncMock()
|
||||
mock_worker.trigger_lyrics_worker = AsyncMock()
|
||||
mock_get_worker.return_value = mock_worker
|
||||
|
||||
# Call start_job_processing - this is what _handle_made_for_you_order now uses
|
||||
await job_manager.start_job_processing("test-mfy-001")
|
||||
|
||||
# Verify transition to DOWNLOADING was called
|
||||
job_manager.firestore.update_job_status.assert_called()
|
||||
call_kwargs = job_manager.firestore.update_job_status.call_args.kwargs
|
||||
assert call_kwargs['status'] == JobStatus.DOWNLOADING
|
||||
|
||||
# Verify both workers were triggered
|
||||
mock_worker.trigger_audio_worker.assert_called_once_with("test-mfy-001")
|
||||
mock_worker.trigger_lyrics_worker.assert_called_once_with("test-mfy-001")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fails_if_job_stuck_at_wrong_state(self, job_manager, mock_firestore_service):
|
||||
"""
|
||||
Test that starting processing fails if job is in wrong state.
|
||||
|
||||
Jobs that are already past PENDING (e.g., DOWNLOADING) shouldn't
|
||||
be able to start processing again - this would indicate a bug.
|
||||
"""
|
||||
# Create job already in DOWNLOADING state
|
||||
job = Job(
|
||||
job_id="test-mfy-002",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING, # Already past PENDING
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="gs://bucket/test.mp3",
|
||||
state_data={},
|
||||
)
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
|
||||
# Attempting to start processing should raise InvalidStateTransitionError
|
||||
# because DOWNLOADING -> DOWNLOADING is not a valid transition
|
||||
with pytest.raises(InvalidStateTransitionError):
|
||||
await job_manager.start_job_processing("test-mfy-002")
|
||||
|
||||
|
||||
class TestParallelProcessingCoordination:
|
||||
"""
|
||||
Integration tests for parallel audio + lyrics processing coordination.
|
||||
|
||||
Both workers run in parallel and set flags when complete.
|
||||
Screens worker is triggered when both are done.
|
||||
"""
|
||||
|
||||
def test_audio_complete_updates_state_data(self, job_manager, mock_firestore_service):
|
||||
"""Test that mark_audio_complete updates state_data correctly."""
|
||||
job = Job(
|
||||
job_id="test-parallel-001",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={},
|
||||
)
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
job_manager.firestore.update_job.return_value = True
|
||||
|
||||
# Call mark_audio_complete
|
||||
job_manager.mark_audio_complete("test-parallel-001")
|
||||
|
||||
# Verify update_job was called to set the audio_complete flag
|
||||
job_manager.firestore.update_job.assert_called()
|
||||
|
||||
def test_lyrics_complete_updates_state_data(self, job_manager, mock_firestore_service):
|
||||
"""Test that mark_lyrics_complete updates state_data correctly."""
|
||||
job = Job(
|
||||
job_id="test-parallel-002",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={},
|
||||
)
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
job_manager.firestore.update_job.return_value = True
|
||||
|
||||
# Call mark_lyrics_complete
|
||||
job_manager.mark_lyrics_complete("test-parallel-002")
|
||||
|
||||
# Verify update_job was called to set the lyrics_complete flag
|
||||
job_manager.firestore.update_job.assert_called()
|
||||
|
||||
def test_both_complete_triggers_screens(self, job_manager, mock_firestore_service):
|
||||
"""Test that screens worker is triggered when both complete."""
|
||||
# First call: Job with audio already complete (for update_state_data)
|
||||
# Second call: Job with both complete (for check_parallel_processing_complete)
|
||||
job_audio_only = Job(
|
||||
job_id="test-parallel-003",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True},
|
||||
)
|
||||
job_both_complete = Job(
|
||||
job_id="test-parallel-003",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True, 'lyrics_complete': True},
|
||||
)
|
||||
# Return different jobs on subsequent calls
|
||||
job_manager.firestore.get_job.side_effect = [job_audio_only, job_both_complete]
|
||||
job_manager.firestore.update_job.return_value = True
|
||||
|
||||
# Mock the screens worker trigger
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
# Now lyrics completes
|
||||
job_manager.mark_lyrics_complete("test-parallel-003")
|
||||
|
||||
# Verify screens worker was triggered (both complete)
|
||||
mock_trigger.assert_called_once_with("test-parallel-003")
|
||||
|
||||
|
||||
class TestStateTransitionValidation:
|
||||
"""
|
||||
Integration tests for state transition validation.
|
||||
|
||||
Ensures invalid transitions are rejected with clear errors.
|
||||
"""
|
||||
|
||||
def test_valid_transition_succeeds(self, job_manager, mock_firestore_service):
|
||||
"""Test that valid transitions succeed."""
|
||||
job = Job(
|
||||
job_id="test-transition-001",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={},
|
||||
)
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
job_manager.firestore.update_job_status.return_value = True
|
||||
|
||||
# PENDING -> DOWNLOADING is valid
|
||||
result = job_manager.transition_to_state(
|
||||
job_id="test-transition-001",
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=10,
|
||||
message="Starting processing"
|
||||
)
|
||||
|
||||
assert result is True
|
||||
|
||||
def test_invalid_transition_raises_by_default(self, job_manager, mock_firestore_service):
|
||||
"""Test that invalid transitions raise exception by default."""
|
||||
job = Job(
|
||||
job_id="test-transition-002",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={},
|
||||
)
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
|
||||
# PENDING -> COMPLETE is invalid (skips many steps)
|
||||
with pytest.raises(InvalidStateTransitionError) as exc_info:
|
||||
job_manager.transition_to_state(
|
||||
job_id="test-transition-002",
|
||||
new_status=JobStatus.COMPLETE,
|
||||
)
|
||||
|
||||
assert "pending" in str(exc_info.value).lower()
|
||||
assert "complete" in str(exc_info.value).lower()
|
||||
|
||||
def test_invalid_transition_returns_false_when_not_raising(self, job_manager, mock_firestore_service):
|
||||
"""Test that invalid transitions return False when raise_on_invalid=False."""
|
||||
job = Job(
|
||||
job_id="test-transition-003",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={},
|
||||
)
|
||||
job_manager.firestore.get_job.return_value = job
|
||||
|
||||
# PENDING -> COMPLETE is invalid, but with raise_on_invalid=False
|
||||
result = job_manager.transition_to_state(
|
||||
job_id="test-transition-003",
|
||||
new_status=JobStatus.COMPLETE,
|
||||
raise_on_invalid=False
|
||||
)
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAdminResetFlow:
|
||||
"""
|
||||
Integration tests for admin reset functionality.
|
||||
|
||||
Admin resets bypass normal state machine validation but must
|
||||
properly clear state_data flags to avoid inconsistent state.
|
||||
"""
|
||||
|
||||
def test_reset_to_pending_clears_parallel_flags(self, job_manager, mock_firestore_service):
|
||||
"""
|
||||
Test that resetting to pending clears audio_complete and lyrics_complete.
|
||||
|
||||
This was a bug where the Start button would reset to pending but
|
||||
leave these flags set, causing inconsistent state.
|
||||
"""
|
||||
# This is tested via the admin endpoint, not directly in JobManager
|
||||
# The test in test_admin_job_reset.py covers this
|
||||
pass
|
||||
|
||||
|
||||
class TestConsistencyWithHealthService:
|
||||
"""
|
||||
Integration tests that verify the job health service correctly
|
||||
identifies inconsistencies in real job flows.
|
||||
"""
|
||||
|
||||
def test_detects_stuck_job_scenario(self, job_manager, mock_firestore_service):
|
||||
"""
|
||||
Test that the health service would detect the exact bug that
|
||||
caused jobs 06cfea29 and 984da08b to get stuck.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
|
||||
# Simulate the stuck job scenario:
|
||||
# - Job has input_media_gcs_path (YouTube download completed)
|
||||
# - But status is still PENDING (transition never happened)
|
||||
stuck_job = Job(
|
||||
job_id="test-stuck-001",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
input_media_gcs_path="gs://bucket/downloaded.mp3",
|
||||
state_data={},
|
||||
)
|
||||
|
||||
issues = check_job_consistency(stuck_job)
|
||||
|
||||
# Should detect the pending_with_input_media issue
|
||||
assert len(issues) > 0
|
||||
assert any("pending_with_input_media" in issue for issue in issues)
|
||||
|
||||
def test_detects_flag_status_mismatch(self, job_manager, mock_firestore_service):
|
||||
"""
|
||||
Test that the health service detects when flags don't match status.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
|
||||
# Simulate: audio_complete=True but status still PENDING
|
||||
# (would happen if mark_audio_complete ran but transition didn't)
|
||||
inconsistent_job = Job(
|
||||
job_id="test-inconsistent-001",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True},
|
||||
)
|
||||
|
||||
issues = check_job_consistency(inconsistent_job)
|
||||
|
||||
# Should detect the audio_complete_status_mismatch issue
|
||||
assert len(issues) > 0
|
||||
assert any("audio_complete_status_mismatch" in issue for issue in issues)
|
||||
@@ -1,338 +0,0 @@
|
||||
"""
|
||||
Integration tests for YouTube download flow.
|
||||
|
||||
Tests the full flow from API endpoint to download completion, verifying that
|
||||
both entry points (audio search selection and direct URL submission) correctly
|
||||
use the YouTubeDownloadService.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_youtube_service():
|
||||
"""Create a mock YouTubeDownloadService."""
|
||||
mock = MagicMock()
|
||||
mock.download = AsyncMock(return_value="uploads/test_job/audio/test.flac")
|
||||
mock.download_by_id = AsyncMock(return_value="uploads/test_job/audio/test.flac")
|
||||
mock.is_remote_enabled = MagicMock(return_value=True)
|
||||
mock._extract_video_id = MagicMock(return_value="test_video_id")
|
||||
return mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_services():
|
||||
"""Mock common services used across tests."""
|
||||
mocks = {
|
||||
'job_manager': MagicMock(),
|
||||
'storage_service': MagicMock(),
|
||||
'worker_service': MagicMock(),
|
||||
'auth_service': MagicMock(),
|
||||
}
|
||||
|
||||
# Configure job_manager mock
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "test_job_123"
|
||||
mock_job.status = "pending"
|
||||
mock_job.state_data = {}
|
||||
mocks['job_manager'].create_job = MagicMock(return_value=mock_job)
|
||||
mocks['job_manager'].get_job = MagicMock(return_value=mock_job)
|
||||
mocks['job_manager'].transition_to_state = MagicMock()
|
||||
mocks['job_manager'].update_job = MagicMock()
|
||||
mocks['job_manager'].fail_job = MagicMock()
|
||||
|
||||
# Configure worker service mock
|
||||
mocks['worker_service'].trigger_audio_worker = AsyncMock()
|
||||
mocks['worker_service'].trigger_lyrics_worker = AsyncMock()
|
||||
|
||||
return mocks
|
||||
|
||||
|
||||
class TestAudioSearchYouTubeFlow:
|
||||
"""Tests for YouTube downloads via audio search selection."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_audio_search_select_youtube_uses_youtube_service(self, mock_youtube_service, mock_services):
|
||||
"""
|
||||
When selecting a YouTube result from audio search,
|
||||
should use YouTubeDownloadService instead of direct download.
|
||||
"""
|
||||
# Configure mock job with search results
|
||||
mock_job = mock_services['job_manager'].get_job.return_value
|
||||
mock_job.status = "awaiting_audio_selection"
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'index': 0,
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'YouTube',
|
||||
'source_id': 'dQw4w9WgXcQ',
|
||||
'url': 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
|
||||
}],
|
||||
'audio_search_count': 1,
|
||||
}
|
||||
|
||||
# Import the route function
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
|
||||
# Patch dependencies
|
||||
with patch(
|
||||
'backend.api.routes.audio_search.get_youtube_download_service',
|
||||
return_value=mock_youtube_service
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.job_manager',
|
||||
mock_services['job_manager']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.storage_service',
|
||||
mock_services['storage_service']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.worker_service',
|
||||
mock_services['worker_service']
|
||||
):
|
||||
# Create a mock audio_search_service
|
||||
mock_audio_search_service = MagicMock()
|
||||
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
|
||||
|
||||
# Call the download function (now runs as background task, returns None)
|
||||
await _download_audio_and_trigger_workers(
|
||||
job_id="test_job_123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_search_service,
|
||||
)
|
||||
|
||||
# Verify YouTubeDownloadService was used
|
||||
mock_youtube_service.download_by_id.assert_called_once()
|
||||
call_args = mock_youtube_service.download_by_id.call_args
|
||||
|
||||
assert call_args.kwargs['video_id'] == 'dQw4w9WgXcQ'
|
||||
assert call_args.kwargs['job_id'] == 'test_job_123'
|
||||
assert call_args.kwargs['artist'] == 'Test Artist'
|
||||
assert call_args.kwargs['title'] == 'Test Song'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_torrent_download_does_not_use_youtube_service(self, mock_youtube_service, mock_services):
|
||||
"""
|
||||
When selecting a torrent result (RED/OPS), should NOT use YouTubeDownloadService.
|
||||
Should use FlacfetchClient directly instead.
|
||||
"""
|
||||
mock_job = mock_services['job_manager'].get_job.return_value
|
||||
mock_job.status = "awaiting_audio_selection"
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'index': 0,
|
||||
'title': 'Test Song',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'RED',
|
||||
'source_id': '12345',
|
||||
'target_file': 'test.flac',
|
||||
}],
|
||||
'audio_search_count': 1,
|
||||
}
|
||||
|
||||
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
|
||||
|
||||
mock_audio_search_service = MagicMock()
|
||||
|
||||
# Mock FlacfetchClient for direct async download
|
||||
mock_flacfetch = MagicMock()
|
||||
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-test-123")
|
||||
mock_flacfetch.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/test/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch(
|
||||
'backend.api.routes.audio_search.get_youtube_download_service',
|
||||
return_value=mock_youtube_service
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.get_flacfetch_client',
|
||||
return_value=mock_flacfetch
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.job_manager',
|
||||
mock_services['job_manager']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.storage_service',
|
||||
mock_services['storage_service']
|
||||
), patch(
|
||||
'backend.api.routes.audio_search.worker_service',
|
||||
mock_services['worker_service']
|
||||
):
|
||||
await _download_audio_and_trigger_workers(
|
||||
job_id="test_job_123",
|
||||
selection_index=0,
|
||||
audio_search_service=mock_audio_search_service,
|
||||
)
|
||||
|
||||
# YouTubeDownloadService should NOT be called for torrent
|
||||
mock_youtube_service.download_by_id.assert_not_called()
|
||||
|
||||
# FlacfetchClient.download_by_id should be called directly
|
||||
mock_flacfetch.download_by_id.assert_called_once()
|
||||
|
||||
|
||||
class TestDirectUrlSubmissionFlow:
|
||||
"""Tests for direct YouTube URL submission via /api/jobs/url endpoint."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_job_from_youtube_url_downloads_immediately(
|
||||
self, mock_youtube_service, mock_services
|
||||
):
|
||||
"""
|
||||
When creating a job from a YouTube URL, should download audio
|
||||
immediately (before triggering workers) using YouTubeDownloadService.
|
||||
"""
|
||||
from backend.api.routes.file_upload import _is_youtube_url
|
||||
|
||||
# Verify helper function works
|
||||
assert _is_youtube_url("https://www.youtube.com/watch?v=test") is True
|
||||
assert _is_youtube_url("https://youtu.be/test") is True
|
||||
assert _is_youtube_url("https://vimeo.com/test") is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_youtube_url_triggers_worker_download(self, mock_services):
|
||||
"""
|
||||
When creating a job from a non-YouTube URL (e.g., Vimeo),
|
||||
should trigger audio worker to handle the download.
|
||||
"""
|
||||
from backend.api.routes.file_upload import _is_youtube_url
|
||||
|
||||
# Non-YouTube URLs should not match
|
||||
assert _is_youtube_url("https://vimeo.com/123456") is False
|
||||
assert _is_youtube_url("https://soundcloud.com/artist/track") is False
|
||||
|
||||
|
||||
class TestYouTubeDownloadErrorHandling:
|
||||
"""Tests for error handling in YouTube download flow."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_download_failure_fails_job(self, mock_services):
|
||||
"""
|
||||
When YouTube download fails, should properly fail the job
|
||||
with a clear error message.
|
||||
"""
|
||||
from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadService,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
|
||||
# Create a service that will fail
|
||||
mock_client = MagicMock()
|
||||
mock_client.download_by_id = AsyncMock(
|
||||
side_effect=Exception("Bot detection triggered")
|
||||
)
|
||||
|
||||
with patch(
|
||||
'backend.services.youtube_download_service.get_flacfetch_client',
|
||||
return_value=mock_client
|
||||
):
|
||||
from backend.services.youtube_download_service import reset_youtube_download_service
|
||||
reset_youtube_download_service()
|
||||
|
||||
service = YouTubeDownloadService()
|
||||
|
||||
with pytest.raises(YouTubeDownloadError) as exc:
|
||||
await service.download(
|
||||
url="https://youtu.be/abcDEF12345",
|
||||
job_id="job123",
|
||||
)
|
||||
|
||||
assert "Remote download failed" in str(exc.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_youtube_url_raises_clear_error(self):
|
||||
"""
|
||||
When given an invalid YouTube URL (no video ID extractable),
|
||||
should raise a clear error.
|
||||
"""
|
||||
from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadService,
|
||||
YouTubeDownloadError,
|
||||
reset_youtube_download_service,
|
||||
)
|
||||
|
||||
with patch(
|
||||
'backend.services.youtube_download_service.get_flacfetch_client',
|
||||
return_value=None # No remote client
|
||||
):
|
||||
reset_youtube_download_service()
|
||||
service = YouTubeDownloadService()
|
||||
|
||||
with pytest.raises(YouTubeDownloadError) as exc:
|
||||
await service.download(
|
||||
url="not-a-valid-youtube-url",
|
||||
job_id="job123",
|
||||
)
|
||||
|
||||
assert "Could not extract video ID" in str(exc.value)
|
||||
|
||||
|
||||
class TestRemoteVsLocalDownload:
|
||||
"""Tests verifying correct routing between remote and local download."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remote_download_when_configured(self):
|
||||
"""
|
||||
When FLACFETCH_API_URL is configured, should use remote download.
|
||||
"""
|
||||
mock_client = MagicMock()
|
||||
mock_client.download_by_id = AsyncMock(return_value="download_123")
|
||||
mock_client.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://bucket/uploads/job_test/audio/test.flac",
|
||||
})
|
||||
|
||||
with patch(
|
||||
'backend.services.youtube_download_service.get_flacfetch_client',
|
||||
return_value=mock_client
|
||||
):
|
||||
from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadService,
|
||||
reset_youtube_download_service,
|
||||
)
|
||||
reset_youtube_download_service()
|
||||
|
||||
service = YouTubeDownloadService()
|
||||
assert service.is_remote_enabled() is True
|
||||
|
||||
result = await service.download(
|
||||
url="https://youtu.be/abcDEF12345",
|
||||
job_id="job_test",
|
||||
)
|
||||
|
||||
# Should have called remote client
|
||||
mock_client.download_by_id.assert_called_once()
|
||||
assert "uploads/job_test/audio/" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_local_download_when_remote_not_configured(self):
|
||||
"""
|
||||
When FLACFETCH_API_URL is not configured, should fall back to local.
|
||||
"""
|
||||
with patch(
|
||||
'backend.services.youtube_download_service.get_flacfetch_client',
|
||||
return_value=None # No remote client
|
||||
):
|
||||
from backend.services.youtube_download_service import (
|
||||
YouTubeDownloadService,
|
||||
reset_youtube_download_service,
|
||||
)
|
||||
reset_youtube_download_service()
|
||||
|
||||
service = YouTubeDownloadService()
|
||||
assert service.is_remote_enabled() is False
|
||||
|
||||
# Mock the local download to avoid actually calling yt_dlp
|
||||
with patch.object(
|
||||
service, '_download_local',
|
||||
new_callable=AsyncMock,
|
||||
return_value="uploads/job/audio/test.wav"
|
||||
) as mock_local:
|
||||
result = await service.download(
|
||||
url="https://youtu.be/abcDEF12345",
|
||||
job_id="job_test",
|
||||
)
|
||||
|
||||
mock_local.assert_called_once()
|
||||
assert result == "uploads/job/audio/test.wav"
|
||||
@@ -350,227 +350,3 @@ class TestDeleteOutputsAuthorization:
|
||||
app.dependency_overrides[require_admin] = original_override
|
||||
else:
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
class TestDeleteOutputsGCSFinals:
|
||||
"""Tests for GCS finals folder deletion."""
|
||||
|
||||
def test_delete_outputs_deletes_gcs_finals(self, client, mock_complete_job):
|
||||
"""Test that GCS finals folder is deleted when outputs are deleted."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.storage_service.StorageService') as mock_storage_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Mock storage service
|
||||
mock_storage = Mock()
|
||||
mock_storage.delete_folder.return_value = 4 # 4 files deleted
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
# Mock Firestore
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Verify GCS finals was deleted
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/test-job-123/finals/")
|
||||
assert "gcs_finals" in data["deleted_services"]
|
||||
assert data["deleted_services"]["gcs_finals"]["status"] == "success"
|
||||
assert data["deleted_services"]["gcs_finals"]["deleted_count"] == 4
|
||||
assert data["deleted_services"]["gcs_finals"]["path"] == "jobs/test-job-123/finals/"
|
||||
|
||||
def test_delete_outputs_gcs_success_with_zero_files(self, client, mock_complete_job):
|
||||
"""Test that GCS deletion reports success even when no files exist."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.storage_service.StorageService') as mock_storage_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Mock storage service - no files to delete
|
||||
mock_storage = Mock()
|
||||
mock_storage.delete_folder.return_value = 0
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
# Mock Firestore
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Still success even with zero files deleted
|
||||
assert data["deleted_services"]["gcs_finals"]["status"] == "success"
|
||||
assert data["deleted_services"]["gcs_finals"]["deleted_count"] == 0
|
||||
|
||||
def test_delete_outputs_continues_if_gcs_fails(self, client, mock_complete_job):
|
||||
"""Test that other deletions continue even if GCS deletion fails."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.storage_service.StorageService') as mock_storage_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Mock storage service to fail
|
||||
mock_storage = Mock()
|
||||
mock_storage.delete_folder.side_effect = Exception("GCS error")
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
# Mock Firestore
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
# Should still succeed (partial success) with error for GCS
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "gcs_finals" in data["deleted_services"]
|
||||
assert data["deleted_services"]["gcs_finals"]["status"] == "error"
|
||||
assert "GCS error" in data["deleted_services"]["gcs_finals"]["error"]
|
||||
|
||||
def test_delete_outputs_gcs_uses_correct_path(self, client, mock_complete_job):
|
||||
"""Test that GCS deletion uses the correct path format."""
|
||||
mock_complete_job.job_id = "abc-123-xyz"
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.storage_service.StorageService') as mock_storage_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.delete_folder.return_value = 2
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/abc-123-xyz/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify path format is jobs/{job_id}/finals/
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/abc-123-xyz/finals/")
|
||||
|
||||
|
||||
class TestDeleteOutputsBrandCodeRecycling:
|
||||
"""Tests for brand code recycling during output deletion."""
|
||||
|
||||
def test_brand_code_recycled_on_success(self, client, mock_complete_job):
|
||||
"""Test that brand code is recycled when Dropbox and GDrive cleanup succeed."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse, \
|
||||
patch('backend.services.brand_code_service.get_brand_code_service') as mock_get_svc:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
mock_parse.return_value = ("NOMAD", 1234)
|
||||
mock_svc = Mock()
|
||||
mock_get_svc.return_value = mock_svc
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Brand code should be recycled (all services skip = success condition)
|
||||
assert "brand_code" in data["deleted_services"]
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "recycled"
|
||||
assert data["deleted_services"]["brand_code"]["code"] == "NOMAD-1234"
|
||||
mock_svc.recycle_brand_code.assert_called_once_with("NOMAD", 1234)
|
||||
|
||||
def test_brand_code_not_recycled_without_brand_code(self, client, mock_job_no_outputs):
|
||||
"""Test that no recycling happens when job has no brand code."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_no_outputs
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-456/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# No brand_code key in response since there's nothing to recycle
|
||||
assert "brand_code" not in data["deleted_services"]
|
||||
|
||||
def test_brand_code_skipped_when_dropbox_fails(self, client, mock_complete_job):
|
||||
"""Test that brand code is NOT recycled when Dropbox cleanup fails."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service') as mock_dropbox_svc:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
# Make Dropbox fail
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.side_effect = Exception("Dropbox error")
|
||||
mock_dropbox_svc.return_value = mock_dropbox
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "skipped"
|
||||
assert "incomplete" in data["deleted_services"]["brand_code"]["reason"].lower()
|
||||
|
||||
def test_brand_code_recycle_error_handled_gracefully(self, client, mock_complete_job):
|
||||
"""Test that brand code recycling errors don't crash the endpoint."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
|
||||
patch('backend.services.brand_code_service.BrandCodeService.parse_brand_code') as mock_parse:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_complete_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_db = Mock()
|
||||
mock_job_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_job_ref
|
||||
mock_user_service.return_value.db = mock_db
|
||||
|
||||
# Make parse_brand_code raise an error
|
||||
mock_parse.side_effect = ValueError("Invalid brand code format")
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["deleted_services"]["brand_code"]["status"] == "failed"
|
||||
assert "Invalid brand code format" in data["deleted_services"]["brand_code"]["error"]
|
||||
@@ -1,235 +0,0 @@
|
||||
"""
|
||||
Unit tests for admin edit reviews endpoints.
|
||||
|
||||
Tests the GET /api/admin/edit-reviews and GET /api/admin/edit-reviews/{job_id}
|
||||
endpoints for reviewing user lyrics corrections.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
# Override the require_admin dependency
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Create a test client."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _make_job_doc(job_id, artist="Test Artist", title="Test Song",
|
||||
user_email="user@example.com", status="complete",
|
||||
has_edit_log=True, has_corrections_updated=True):
|
||||
"""Create a mock Firestore document for a job."""
|
||||
doc = Mock()
|
||||
doc.id = job_id
|
||||
now = datetime.now(timezone.utc)
|
||||
state_data = {}
|
||||
if has_edit_log:
|
||||
state_data["last_edit_log_path"] = f"jobs/{job_id}/lyrics/edit_log_session1.json"
|
||||
state_data["last_edit_log_session"] = "session1"
|
||||
|
||||
file_urls = {"lyrics": {"corrections": f"jobs/{job_id}/lyrics/corrections.json"}}
|
||||
if has_corrections_updated:
|
||||
file_urls["lyrics"]["corrections_updated"] = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
doc.to_dict.return_value = {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"user_email": user_email,
|
||||
"status": status,
|
||||
"state_data": state_data,
|
||||
"file_urls": file_urls,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
return doc
|
||||
|
||||
|
||||
class TestListEditReviews:
|
||||
"""Tests for GET /api/admin/edit-reviews."""
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_returns_only_jobs_with_edit_logs(self, mock_get_user_service, client):
|
||||
"""Only jobs with edit logs should appear."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_job_doc("job-1", has_edit_log=True),
|
||||
_make_job_doc("job-2", has_edit_log=False),
|
||||
_make_job_doc("job-3", has_edit_log=True),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 2
|
||||
assert len(data["reviews"]) == 2
|
||||
job_ids = [r["job_id"] for r in data["reviews"]]
|
||||
assert "job-1" in job_ids
|
||||
assert "job-3" in job_ids
|
||||
assert "job-2" not in job_ids
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_search_filter(self, mock_get_user_service, client):
|
||||
"""Search should filter by artist, title, and email."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_job_doc("job-1", artist="Beatles", title="Hey Jude"),
|
||||
_make_job_doc("job-2", artist="Queen", title="Bohemian Rhapsody"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews?search=beatles")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["artist"] == "Beatles"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_pagination(self, mock_get_user_service, client):
|
||||
"""Pagination should work with offset and limit."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [_make_job_doc(f"job-{i}") for i in range(5)]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews?limit=2&offset=0")
|
||||
data = response.json()
|
||||
assert len(data["reviews"]) == 2
|
||||
assert data["total"] == 5
|
||||
assert data["has_more"] is True
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
def test_list_exclude_test(self, mock_get_user_service, client):
|
||||
"""Test emails should be excluded when exclude_test=true."""
|
||||
mock_db = Mock()
|
||||
mock_get_user_service.return_value.db = mock_db
|
||||
|
||||
docs = [
|
||||
_make_job_doc("job-1", user_email="real@example.com"),
|
||||
_make_job_doc("job-2", user_email="test@inbox.testmail.app"),
|
||||
]
|
||||
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
|
||||
|
||||
response = client.get("/api/admin/edit-reviews?exclude_test=true")
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["reviews"][0]["user_email"] == "real@example.com"
|
||||
|
||||
|
||||
class TestGetEditReviewDetail:
|
||||
"""Tests for GET /api/admin/edit-reviews/{job_id}."""
|
||||
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_404_for_missing_job(self, MockJobManager, MockStorage, client):
|
||||
MockJobManager.return_value.get_job.return_value = None
|
||||
response = client.get("/api/admin/edit-reviews/nonexistent")
|
||||
assert response.status_code == 404
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.AudioTranscodingService")
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_returns_full_snapshot(self, MockJobManager, MockStorage, MockTranscoding, client):
|
||||
"""Should return all available data for a job."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Song"
|
||||
job.user_email = "user@example.com"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.created_at = datetime(2026, 3, 1, tzinfo=timezone.utc)
|
||||
job.updated_at = datetime(2026, 3, 2, tzinfo=timezone.utc)
|
||||
job.input_media_gcs_path = "jobs/test-job/input.flac"
|
||||
job.file_urls = {
|
||||
"lyrics": {
|
||||
"corrections": "jobs/test-job/lyrics/corrections.json",
|
||||
"corrections_updated": "jobs/test-job/lyrics/corrections_updated.json",
|
||||
}
|
||||
}
|
||||
job.state_data = {
|
||||
"last_edit_log_path": "jobs/test-job/lyrics/edit_log_session1.json",
|
||||
}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.download_json.side_effect = lambda path: {
|
||||
"jobs/test-job/lyrics/corrections.json": {"original": True},
|
||||
"jobs/test-job/lyrics/corrections_updated.json": {"updated": True},
|
||||
"jobs/test-job/lyrics/edit_log_session1.json": {"entries": []},
|
||||
"jobs/test-job/lyrics/annotations.json": {"annotations": []},
|
||||
}.get(path, {})
|
||||
storage.file_exists.return_value = True
|
||||
|
||||
response = client.get("/api/admin/edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
assert data["job"]["job_id"] == "test-job"
|
||||
assert data["job"]["artist"] == "Test Artist"
|
||||
assert data["original_corrections"] == {"original": True}
|
||||
assert data["updated_corrections"] == {"updated": True}
|
||||
assert data["edit_log"] == {"entries": []}
|
||||
assert data["annotations"] == {"annotations": []}
|
||||
|
||||
@patch("backend.api.routes.admin.StorageService")
|
||||
@patch("backend.api.routes.admin.JobManager")
|
||||
def test_handles_missing_gcs_files_gracefully(self, MockJobManager, MockStorage, client):
|
||||
"""Should return null for missing GCS files, not error."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job"
|
||||
job.artist = "Test"
|
||||
job.title = "Song"
|
||||
job.user_email = "u@e.com"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.created_at = None
|
||||
job.updated_at = None
|
||||
job.input_media_gcs_path = None
|
||||
job.file_urls = {"lyrics": {}}
|
||||
job.state_data = {}
|
||||
MockJobManager.return_value.get_job.return_value = job
|
||||
|
||||
storage = MockStorage.return_value
|
||||
storage.file_exists.return_value = False
|
||||
storage.download_json.side_effect = Exception("Not found")
|
||||
|
||||
response = client.get("/api/admin/edit-reviews/test-job")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["original_corrections"] is None
|
||||
assert data["updated_corrections"] is None
|
||||
assert data["edit_log"] is None
|
||||
assert data["annotations"] is None
|
||||
assert data["audio_url"] is None
|
||||
@@ -84,7 +84,7 @@ class TestResetJobToPending:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -104,7 +104,7 @@ class TestResetJobToPending:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -128,7 +128,7 @@ class TestResetJobToAwaitingAudioSelection:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -149,7 +149,7 @@ class TestResetJobToAwaitingReview:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -162,6 +162,27 @@ class TestResetJobToAwaitingReview:
|
||||
assert data["new_status"] == "awaiting_review"
|
||||
|
||||
|
||||
class TestResetJobToAwaitingInstrumentalSelection:
|
||||
"""Tests for resetting job to AWAITING_INSTRUMENTAL_SELECTION state."""
|
||||
|
||||
def test_reset_to_awaiting_instrumental_selection(self, client, mock_job):
|
||||
"""Test resetting a job to AWAITING_INSTRUMENTAL_SELECTION state."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_instrumental_selection"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "awaiting_instrumental_selection"
|
||||
|
||||
|
||||
class TestResetJobValidation:
|
||||
"""Tests for reset endpoint validation."""
|
||||
|
||||
@@ -247,7 +268,7 @@ class TestResetJobLogging:
|
||||
patch('backend.api.routes.admin.logger') as mock_logger:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -270,7 +291,7 @@ class TestResetJobTimeline:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -319,7 +340,7 @@ class TestResetJobClearsStateData:
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -332,57 +353,12 @@ class TestResetJobClearsStateData:
|
||||
data = response.json()
|
||||
assert "cleared_data" in data or "state_data" in str(data)
|
||||
|
||||
def test_reset_to_pending_clears_parallel_processing_flags(self, client):
|
||||
"""Test that resetting to PENDING clears audio_complete and lyrics_complete.
|
||||
|
||||
This is critical for proper re-processing - without clearing these flags,
|
||||
workers may think audio/lyrics processing is already done.
|
||||
"""
|
||||
from backend.models.job import Job, JobStatus
|
||||
from datetime import datetime, UTC
|
||||
|
||||
# Create a job with audio_complete and lyrics_complete set
|
||||
mock_job = Job(
|
||||
job_id="test-job-123",
|
||||
status=JobStatus.COMPLETE,
|
||||
artist="Test Artist",
|
||||
title="Test Title",
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={
|
||||
"audio_complete": True,
|
||||
"lyrics_complete": True,
|
||||
"audio_search_results": [{"source": "test"}],
|
||||
}
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Verify the cleared_data includes the parallel processing flags
|
||||
cleared_keys = data.get("cleared_data", [])
|
||||
assert "audio_complete" in cleared_keys, \
|
||||
f"audio_complete should be cleared. Cleared: {cleared_keys}"
|
||||
assert "lyrics_complete" in cleared_keys, \
|
||||
f"lyrics_complete should be cleared. Cleared: {cleared_keys}"
|
||||
|
||||
def test_reset_to_awaiting_review_preserves_audio_data(self, client, mock_job):
|
||||
"""Test that resetting to AWAITING_REVIEW preserves audio stems."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -392,15 +368,12 @@ class TestResetJobClearsStateData:
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_rejects_deprecated_awaiting_instrumental_selection(self, client, mock_job):
|
||||
"""Test that awaiting_instrumental_selection is no longer a valid reset target.
|
||||
|
||||
This state was deprecated in Jan 2026 when lyrics review and instrumental
|
||||
selection were combined into a single review step.
|
||||
"""
|
||||
def test_reset_to_instrumental_preserves_review_data(self, client, mock_job):
|
||||
"""Test that resetting to AWAITING_INSTRUMENTAL_SELECTION preserves review data."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
@@ -408,611 +381,4 @@ class TestResetJobClearsStateData:
|
||||
json={"target_state": "awaiting_instrumental_selection"},
|
||||
)
|
||||
|
||||
# Should be rejected as invalid
|
||||
assert response.status_code == 400
|
||||
assert "invalid" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
class TestResetJobToInstrumentalSelected:
|
||||
"""Tests for resetting job to INSTRUMENTAL_SELECTED state (reprocess video)."""
|
||||
|
||||
def test_reset_to_instrumental_selected_success(self, client, mock_job):
|
||||
"""Test resetting a job to INSTRUMENTAL_SELECTED state."""
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Mock worker service with async method
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "instrumental_selected"
|
||||
|
||||
def test_reset_to_instrumental_selected_triggers_video_worker(self, client, mock_job):
|
||||
"""Test that resetting to INSTRUMENTAL_SELECTED triggers video worker."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Mock worker service
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify worker was triggered
|
||||
mock_worker_service.trigger_video_worker.assert_called_once_with("test-job-123")
|
||||
# Verify message indicates worker was triggered
|
||||
data = response.json()
|
||||
assert "video worker triggered" in data["message"]
|
||||
|
||||
def test_reset_to_instrumental_selected_message_on_worker_failure(self, client, mock_job):
|
||||
"""Test message when video worker trigger fails."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Mock worker service failure
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=False)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Reset still succeeds even if worker trigger fails
|
||||
data = response.json()
|
||||
assert data["new_status"] == "instrumental_selected"
|
||||
# Message should NOT say worker was triggered
|
||||
assert "video worker triggered" not in data["message"]
|
||||
|
||||
def test_reset_to_instrumental_selected_clears_video_state(self, client, mock_job):
|
||||
"""Test that INSTRUMENTAL_SELECTED reset clears video/encoding/distribution state."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
mock_job.state_data = {
|
||||
"instrumental_selection": "clean",
|
||||
"lyrics_metadata": {"has_countdown_padding": True},
|
||||
"video_progress": {"stage": "running"},
|
||||
"brand_code": "NOMAD-1234",
|
||||
"youtube_url": "https://youtube.com/watch?v=xxx",
|
||||
"dropbox_link": "https://dropbox.com/xxx",
|
||||
}
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# These keys should be marked as cleared
|
||||
cleared = data.get("cleared_data", [])
|
||||
# At minimum, video_progress and brand_code should be cleared
|
||||
# (they exist in the mock job's state_data)
|
||||
assert any(key in ["video_progress", "brand_code", "youtube_url", "dropbox_link"]
|
||||
for key in cleared)
|
||||
|
||||
|
||||
class TestResetJobClearsErrorState:
|
||||
"""Tests that reset clears error_message and error_details."""
|
||||
|
||||
def test_reset_clears_error_message(self, client, mock_job):
|
||||
"""Test that resetting a job clears error_message field."""
|
||||
# Set job to failed state with error message
|
||||
mock_job.status = JobStatus.FAILED
|
||||
mock_job.error_message = "Previous error message"
|
||||
mock_job.error_details = {"code": "TEST_ERROR"}
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# The endpoint should issue an update that includes DELETE_FIELD for error fields
|
||||
# We verify this indirectly through the success of the operation
|
||||
|
||||
|
||||
class TestClearWorkersEndpoint:
|
||||
"""Tests for the POST /api/admin/jobs/{job_id}/clear-workers endpoint."""
|
||||
|
||||
def test_clear_workers_success(self, client, mock_job):
|
||||
"""Test clearing worker progress keys."""
|
||||
mock_job.state_data = {
|
||||
"render_progress": {"stage": "complete"},
|
||||
"video_progress": {"stage": "complete"},
|
||||
"encoding_progress": {"stage": "complete"},
|
||||
}
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/clear-workers")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert "cleared_keys" in data
|
||||
# Should have cleared the progress keys that exist
|
||||
assert any(k in data["cleared_keys"] for k in
|
||||
["render_progress", "video_progress", "encoding_progress"])
|
||||
|
||||
def test_clear_workers_no_progress_keys(self, client, mock_job):
|
||||
"""Test clearing workers when no progress keys exist."""
|
||||
mock_job.state_data = {"other_data": "value"}
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/clear-workers")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert len(data["cleared_keys"]) == 0
|
||||
|
||||
def test_clear_workers_job_not_found(self, client):
|
||||
"""Test clearing workers for non-existent job."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post("/api/admin/jobs/nonexistent/clear-workers")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_clear_workers_clears_all_worker_types(self, client, mock_job):
|
||||
"""Test that all defined worker progress keys can be cleared."""
|
||||
# Set all possible worker progress keys
|
||||
mock_job.state_data = {
|
||||
"audio_progress": {"stage": "complete"},
|
||||
"lyrics_progress": {"stage": "complete"},
|
||||
"render_progress": {"stage": "complete"},
|
||||
"screens_progress": {"stage": "complete"},
|
||||
"video_progress": {"stage": "complete"},
|
||||
"encoding_progress": {"stage": "complete"},
|
||||
}
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post("/api/admin/jobs/test-job-123/clear-workers")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Should have cleared all 6 progress keys
|
||||
assert len(data["cleared_keys"]) == 6
|
||||
|
||||
|
||||
class TestResetIncludesEncodingProgress:
|
||||
"""Tests that reset includes encoding_progress in cleared keys."""
|
||||
|
||||
def test_reset_to_awaiting_review_clears_encoding_progress(self, client, mock_job):
|
||||
"""Test that resetting to awaiting_review clears encoding_progress."""
|
||||
mock_job.state_data = {
|
||||
"encoding_progress": {"stage": "complete"},
|
||||
"video_progress": {"stage": "complete"},
|
||||
}
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_review"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# encoding_progress should be in cleared_data
|
||||
assert "encoding_progress" in data.get("cleared_data", [])
|
||||
|
||||
|
||||
class TestResetWorkerTriggerResponseFields:
|
||||
"""Tests that reset response includes worker_triggered and worker_trigger_error fields."""
|
||||
|
||||
def test_reset_to_instrumental_selected_includes_worker_triggered_true(self, client, mock_job):
|
||||
"""Test response includes worker_triggered=True when trigger succeeds."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["worker_triggered"] is True
|
||||
assert data.get("worker_trigger_error") is None
|
||||
|
||||
def test_reset_to_instrumental_selected_includes_worker_triggered_false_on_failure(self, client, mock_job):
|
||||
"""Test response includes worker_triggered=False and error when trigger fails."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=False)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["worker_triggered"] is False
|
||||
assert data["worker_trigger_error"] is not None
|
||||
assert "manual trigger" in data["message"].lower()
|
||||
|
||||
def test_reset_to_instrumental_selected_includes_error_on_exception(self, client, mock_job):
|
||||
"""Test response includes worker_trigger_error when exception occurs."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(
|
||||
side_effect=Exception("Connection timeout")
|
||||
)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "instrumental_selected"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["worker_triggered"] is False
|
||||
assert "Connection timeout" in data["worker_trigger_error"]
|
||||
|
||||
def test_reset_to_pending_has_null_worker_fields(self, client, mock_job):
|
||||
"""Test response has null worker fields for non-instrumental_selected resets."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = None # Matches real API: returns None, raises on error
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data.get("worker_triggered") is None
|
||||
assert data.get("worker_trigger_error") is None
|
||||
|
||||
|
||||
class TestTriggerWorkerEndpoint:
|
||||
"""Tests for POST /api/admin/jobs/{job_id}/trigger-worker endpoint."""
|
||||
|
||||
def test_trigger_video_worker_success(self, client, mock_job):
|
||||
"""Test successfully triggering video worker."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
mock_job.status = "instrumental_selected"
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={"worker_type": "video"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["job_id"] == "test-job-123"
|
||||
assert data["worker_type"] == "video"
|
||||
assert data["triggered"] is True
|
||||
assert data.get("error") is None
|
||||
mock_worker_service.trigger_video_worker.assert_called_once_with("test-job-123")
|
||||
|
||||
def test_trigger_worker_default_type_is_video(self, client, mock_job):
|
||||
"""Test that default worker_type is video."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
mock_job.status = "instrumental_selected"
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
# Send empty body - should default to video
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["worker_type"] == "video"
|
||||
|
||||
def test_trigger_worker_failure_returns_error(self, client, mock_job):
|
||||
"""Test response when worker trigger returns False."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
mock_job.status = "instrumental_selected"
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=False)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={"worker_type": "video"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert data["triggered"] is False
|
||||
assert data["error"] is not None
|
||||
|
||||
def test_trigger_worker_exception_returns_error(self, client, mock_job):
|
||||
"""Test response when worker trigger throws exception."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
mock_job.status = "instrumental_selected"
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(
|
||||
side_effect=Exception("Network error")
|
||||
)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={"worker_type": "video"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "error"
|
||||
assert data["triggered"] is False
|
||||
assert "Network error" in data["error"]
|
||||
|
||||
def test_trigger_worker_invalid_type_rejected(self, client, mock_job):
|
||||
"""Test that invalid worker_type is rejected."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={"worker_type": "invalid"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "unsupported" in response.json()["detail"].lower()
|
||||
|
||||
def test_trigger_worker_job_not_found(self, client):
|
||||
"""Test 404 when job doesn't exist."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/nonexistent/trigger-worker",
|
||||
json={"worker_type": "video"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_trigger_worker_logs_warning_for_unexpected_status(self, client, mock_job):
|
||||
"""Test that warning is logged when job is not in expected status."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
mock_job.status = "complete" # Not instrumental_selected
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.services.worker_service.get_worker_service') as mock_ws, \
|
||||
patch('backend.api.routes.admin.logger') as mock_logger:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_worker_service = Mock()
|
||||
mock_worker_service.trigger_video_worker = AsyncMock(return_value=True)
|
||||
mock_ws.return_value = mock_worker_service
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={"worker_type": "video"},
|
||||
)
|
||||
|
||||
# Should still succeed - we don't block based on status
|
||||
assert response.status_code == 200
|
||||
# But should log a warning
|
||||
mock_logger.warning.assert_called()
|
||||
warning_msg = mock_logger.warning.call_args[0][0]
|
||||
assert "unexpected status" in warning_msg.lower()
|
||||
|
||||
def test_trigger_worker_requires_admin(self, client, mock_job):
|
||||
"""Test that endpoint requires admin access."""
|
||||
original_override = app.dependency_overrides.get(require_admin)
|
||||
|
||||
def get_non_admin():
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
app.dependency_overrides[require_admin] = get_non_admin
|
||||
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/trigger-worker",
|
||||
json={"worker_type": "video"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
finally:
|
||||
if original_override:
|
||||
app.dependency_overrides[require_admin] = original_override
|
||||
else:
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
class TestResetEndpointWithRealJobData:
|
||||
"""
|
||||
Tests using real production job data (job 984da08b) as fixture.
|
||||
|
||||
This validates the admin reset endpoint works correctly with realistic
|
||||
state_data from a production job that needed manual admin reset.
|
||||
"""
|
||||
|
||||
# Real state_data from production job 984da08b
|
||||
REAL_JOB_STATE_DATA = {
|
||||
"backing_vocals_analysis": {"has_audible_content": True},
|
||||
"video_progress": {"stage": "running"}, # Stale progress
|
||||
"lyrics_complete": True,
|
||||
"audio_complete": True
|
||||
}
|
||||
|
||||
def test_reset_endpoint_returns_200_with_none_return_value(self, client):
|
||||
"""
|
||||
Test that reset endpoint returns 200 (not 500) when update_job
|
||||
returns None, matching the real API behavior.
|
||||
|
||||
Before fix: endpoint checked 'if not success:' which was always True
|
||||
After fix: endpoint doesn't check return value
|
||||
|
||||
Uses real production job 984da08b data as fixture.
|
||||
"""
|
||||
# Mock job with real production data
|
||||
mock_job = Mock(spec=Job)
|
||||
mock_job.job_id = "984da08b"
|
||||
mock_job.status = JobStatus.COMPLETE
|
||||
mock_job.artist = "Mark Mallman"
|
||||
mock_job.title = "Minneapolis"
|
||||
mock_job.theme_id = "nomad"
|
||||
mock_job.user_email = "madeforyou@nomadkaraoke.com"
|
||||
mock_job.file_urls = {"stems": {}, "lyrics": {}}
|
||||
mock_job.state_data = self.REAL_JOB_STATE_DATA.copy()
|
||||
mock_job.timeline = []
|
||||
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm:
|
||||
mock_jm.return_value.get_job.return_value = mock_job
|
||||
# KEY: return None (matching real API contract - not boolean!)
|
||||
mock_jm.return_value.update_job.return_value = None
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/984da08b/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
# This is the bug fix - before it was 500, now 200
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
assert response.json()["new_status"] == "pending"
|
||||
@@ -1,291 +0,0 @@
|
||||
"""
|
||||
Tests for admin payment API endpoints.
|
||||
|
||||
Tests cover:
|
||||
- Refund endpoint with credit deduction logic
|
||||
- Payment summary endpoint
|
||||
- Payment list endpoint
|
||||
- Payment detail endpoint (404 handling)
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
class TestRefundEndpoint:
|
||||
"""Tests for POST /api/admin/payments/{session_id}/refund."""
|
||||
|
||||
def test_full_refund_success(self, client):
|
||||
"""Test successful full refund."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 10,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund of $50.00 processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["success"] is True
|
||||
assert data["session_id"] == "cs_test"
|
||||
|
||||
# Verify credit deduction was called
|
||||
mock_us.add_credits.assert_called_once()
|
||||
call_kwargs = mock_us.add_credits.call_args[1]
|
||||
assert call_kwargs["email"] == "user@example.com"
|
||||
assert call_kwargs["amount"] == -10 # All credits deducted for full refund
|
||||
|
||||
def test_partial_refund_deducts_proportional_credits(self, client):
|
||||
"""Test that partial refund deducts proportional credits."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 10,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund of $25.00 processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"amount": 2500, "reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Proportional: 10 credits * (2500/5000) = 5 credits
|
||||
call_kwargs = mock_us.add_credits.call_args[1]
|
||||
assert call_kwargs["amount"] == -5
|
||||
|
||||
def test_made_for_you_refund_skips_credit_deduction(self, client):
|
||||
"""Test that made-for-you refund doesn't try to deduct credits."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_mfy",
|
||||
"order_type": "made_for_you",
|
||||
"credits_granted": 0,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_mfy/refund",
|
||||
json={"reason": "duplicate"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_us.add_credits.assert_not_called()
|
||||
|
||||
def test_refund_payment_not_found_returns_404(self, client):
|
||||
"""Test 404 when payment doesn't exist."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = None
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_nonexistent/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_refund_stripe_failure_returns_400(self, client):
|
||||
"""Test that Stripe refund failure returns 400."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 0,
|
||||
"amount_total": 5000,
|
||||
}
|
||||
mock_service.process_refund.return_value = (False, "Card declined")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Card declined" in response.json()["detail"]
|
||||
|
||||
def test_credit_deduction_failure_doesnt_fail_refund(self, client):
|
||||
"""Test that credit deduction failure doesn't roll back the refund."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 10,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_us.add_credits.side_effect = Exception("Firestore down")
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
# Refund should still succeed
|
||||
assert response.status_code == 200
|
||||
assert response.json()["success"] is True
|
||||
|
||||
|
||||
class TestPaymentSummaryEndpoint:
|
||||
"""Tests for GET /api/admin/payments/summary."""
|
||||
|
||||
def test_returns_revenue_summary(self, client):
|
||||
"""Test that summary endpoint returns data."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_revenue_summary.return_value = {
|
||||
"total_gross": 10000,
|
||||
"total_fees": 350,
|
||||
"total_net": 9650,
|
||||
"total_refunds": 0,
|
||||
"transaction_count": 2,
|
||||
"average_order_value": 5000,
|
||||
"revenue_by_type": {"credit_purchase": 10000},
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments/summary?days=30")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total_gross"] == 10000
|
||||
assert data["transaction_count"] == 2
|
||||
|
||||
|
||||
class TestPaymentDetailEndpoint:
|
||||
"""Tests for GET /api/admin/payments/{session_id}."""
|
||||
|
||||
def test_returns_payment_detail(self, client):
|
||||
"""Test getting payment detail."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"amount_total": 5000,
|
||||
"status": "succeeded",
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments/cs_test")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["session_id"] == "cs_test"
|
||||
|
||||
def test_returns_404_for_missing_payment(self, client):
|
||||
"""Test 404 when payment not found."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = None
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments/cs_nonexistent")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestPaymentListEndpoint:
|
||||
"""Tests for GET /api/admin/payments."""
|
||||
|
||||
def test_returns_paginated_payments(self, client):
|
||||
"""Test payment list with pagination."""
|
||||
mock_service = Mock()
|
||||
mock_service.list_payments.return_value = {
|
||||
"payments": [
|
||||
{"session_id": "cs_1", "amount_total": 5000},
|
||||
{"session_id": "cs_2", "amount_total": 3000},
|
||||
],
|
||||
"total": 2,
|
||||
"has_more": False,
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments?limit=50&offset=0")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["payments"]) == 2
|
||||
assert data["total"] == 2
|
||||
|
||||
def test_passes_filters_to_service(self, client):
|
||||
"""Test that query params are passed to service."""
|
||||
mock_service = Mock()
|
||||
mock_service.list_payments.return_value = {
|
||||
"payments": [],
|
||||
"total": 0,
|
||||
"has_more": False,
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get(
|
||||
"/api/admin/payments?order_type=credit_purchase&status=succeeded&email=user@example.com"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_service.list_payments.assert_called_once()
|
||||
call_kwargs = mock_service.list_payments.call_args[1]
|
||||
assert call_kwargs["order_type"] == "credit_purchase"
|
||||
assert call_kwargs["status"] == "succeeded"
|
||||
assert call_kwargs["email"] == "user@example.com"
|
||||
@@ -7,7 +7,7 @@ route logic without hitting real cloud services.
|
||||
import pytest
|
||||
import json
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import MagicMock, AsyncMock, patch, Mock
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
from io import BytesIO
|
||||
|
||||
@@ -44,178 +44,14 @@ class TestHealthRoutes:
|
||||
response = client.get("/", )
|
||||
assert response.status_code == 200
|
||||
|
||||
@patch('backend.api.routes.health.check_flacfetch_service_status')
|
||||
def test_flacfetch_health_not_configured(self, mock_check, client):
|
||||
"""Test /api/health/flacfetch when service is not configured."""
|
||||
mock_check.return_value = {"configured": False}
|
||||
response = client.get("/api/health/flacfetch")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["available"] is False
|
||||
assert data["status"] == "not_configured"
|
||||
|
||||
@patch('backend.api.routes.health.check_flacfetch_service_status')
|
||||
def test_flacfetch_health_offline(self, mock_check, client):
|
||||
"""Test /api/health/flacfetch when service is offline."""
|
||||
mock_check.return_value = {
|
||||
"configured": True,
|
||||
"available": False,
|
||||
"error": "Connection timeout"
|
||||
}
|
||||
response = client.get("/api/health/flacfetch")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["available"] is False
|
||||
assert data["status"] == "offline"
|
||||
assert data["error"] == "Connection timeout"
|
||||
|
||||
@patch('backend.api.routes.health.check_flacfetch_service_status')
|
||||
def test_flacfetch_health_ok(self, mock_check, client):
|
||||
"""Test /api/health/flacfetch when service is healthy."""
|
||||
mock_check.return_value = {
|
||||
"configured": True,
|
||||
"available": True,
|
||||
"status": "healthy",
|
||||
"version": "1.2.3"
|
||||
}
|
||||
response = client.get("/api/health/flacfetch")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["available"] is True
|
||||
assert data["status"] == "ok"
|
||||
assert data["version"] == "1.2.3"
|
||||
|
||||
@patch('backend.api.routes.health.check_encoding_worker_status')
|
||||
def test_encoding_worker_health_not_configured(self, mock_check, client):
|
||||
"""Test /api/health/encoding-worker when not configured."""
|
||||
mock_check.return_value = {"configured": False}
|
||||
response = client.get("/api/health/encoding-worker")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["available"] is False
|
||||
assert data["status"] == "not_configured"
|
||||
|
||||
@patch('backend.api.routes.health.check_encoding_worker_status')
|
||||
def test_encoding_worker_health_offline(self, mock_check, client):
|
||||
"""Test /api/health/encoding-worker when offline."""
|
||||
mock_check.return_value = {
|
||||
"configured": True,
|
||||
"available": False,
|
||||
"error": "Worker unreachable"
|
||||
}
|
||||
response = client.get("/api/health/encoding-worker")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["available"] is False
|
||||
assert data["status"] == "offline"
|
||||
assert data["error"] == "Worker unreachable"
|
||||
|
||||
@patch('backend.api.routes.health.check_encoding_worker_status')
|
||||
def test_encoding_worker_health_ok(self, mock_check, client):
|
||||
"""Test /api/health/encoding-worker when healthy."""
|
||||
mock_check.return_value = {
|
||||
"configured": True,
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"wheel_version": "0.123.0",
|
||||
"active_jobs": 2,
|
||||
"queue_length": 5
|
||||
}
|
||||
response = client.get("/api/health/encoding-worker")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["available"] is True
|
||||
assert data["status"] == "ok"
|
||||
assert data["version"] == "0.123.0"
|
||||
assert data["active_jobs"] == 2
|
||||
assert data["queue_length"] == 5
|
||||
|
||||
|
||||
class TestJobConsistencyEndpoint:
|
||||
"""Tests for the /health/job-consistency endpoint."""
|
||||
|
||||
@pytest.fixture
|
||||
def client(self):
|
||||
"""Create test client."""
|
||||
with patch('backend.api.routes.health.JobManager') as mock_jm_class:
|
||||
from backend.main import app
|
||||
return TestClient(app)
|
||||
|
||||
def test_job_consistency_returns_empty_when_no_jobs(self, client):
|
||||
"""Test endpoint returns empty results when no jobs exist."""
|
||||
with patch('backend.api.routes.health.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.list_jobs.return_value = []
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.get("/api/health/job-consistency")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total_checked"] == 0
|
||||
assert data["inconsistent_count"] == 0
|
||||
assert data["inconsistent_jobs"] == []
|
||||
|
||||
def test_job_consistency_detects_issues(self, client):
|
||||
"""Test endpoint detects inconsistent jobs."""
|
||||
from backend.models.job import Job, JobStatus
|
||||
from datetime import datetime, UTC
|
||||
|
||||
stuck_job = Job(
|
||||
job_id="stuck-123",
|
||||
artist="Test",
|
||||
title="Song",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True},
|
||||
input_media_gcs_path="gs://bucket/audio.mp3",
|
||||
)
|
||||
|
||||
with patch('backend.api.routes.health.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.list_jobs.return_value = [stuck_job]
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.get("/api/health/job-consistency")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total_checked"] == 1
|
||||
assert data["inconsistent_count"] == 1
|
||||
assert len(data["inconsistent_jobs"]) == 1
|
||||
assert data["inconsistent_jobs"][0]["job_id"] == "stuck-123"
|
||||
|
||||
def test_job_consistency_filters_by_status(self, client):
|
||||
"""Test endpoint filters by status parameter."""
|
||||
with patch('backend.api.routes.health.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.list_jobs.return_value = []
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.get("/api/health/job-consistency?status=pending")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status_filter"] == "pending"
|
||||
|
||||
def test_job_consistency_rejects_invalid_status(self, client):
|
||||
"""Test endpoint rejects invalid status parameter."""
|
||||
with patch('backend.api.routes.health.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.get("/api/health/job-consistency?status=invalid_status")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "error" in data
|
||||
assert "Invalid status" in data["error"]
|
||||
|
||||
|
||||
class TestJobRoutes:
|
||||
"""Tests for jobs.py routes.
|
||||
|
||||
|
||||
Note: These tests verify the route module structure.
|
||||
Full integration tests are in test_api_integration.py.
|
||||
"""
|
||||
|
||||
|
||||
def test_jobs_router_exists(self):
|
||||
"""Test jobs router can be imported."""
|
||||
from backend.api.routes import jobs
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
"""
|
||||
Tests for the audio download worker.
|
||||
|
||||
Tests the standalone worker that downloads audio from various sources
|
||||
(YouTube, Spotify, RED/OPS) and triggers processing workers.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.workers.audio_download_worker import (
|
||||
process_audio_download,
|
||||
_extract_gcs_path,
|
||||
_download_audio,
|
||||
)
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id: str = "test-job-123",
|
||||
status=JobStatus.DOWNLOADING_AUDIO,
|
||||
source_name: str = "YouTube",
|
||||
source_id: str = "dQw4w9WgXcQ",
|
||||
state_data: dict = None,
|
||||
**kwargs,
|
||||
) -> Job:
|
||||
"""Helper to create test Job objects."""
|
||||
return Job(
|
||||
job_id=job_id,
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=status,
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data=state_data or {},
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class TestExtractGcsPath:
|
||||
"""Tests for _extract_gcs_path helper."""
|
||||
|
||||
def test_strips_primary_bucket_prefix(self):
|
||||
path = "gs://karaoke-gen-storage-nomadkaraoke/uploads/123/audio/song.flac"
|
||||
assert _extract_gcs_path(path) == "uploads/123/audio/song.flac"
|
||||
|
||||
def test_strips_alternate_bucket_prefix(self):
|
||||
path = "gs://karaoke-gen-storage/uploads/123/audio/song.flac"
|
||||
assert _extract_gcs_path(path) == "uploads/123/audio/song.flac"
|
||||
|
||||
def test_unknown_gs_bucket_returned_as_is(self):
|
||||
"""Unknown bucket gs:// paths are returned unchanged (only known buckets stripped)."""
|
||||
path = "gs://other-bucket/uploads/123/audio/song.flac"
|
||||
# The function only strips known bucket prefixes
|
||||
assert _extract_gcs_path(path) == path
|
||||
|
||||
def test_returns_plain_path_unchanged(self):
|
||||
path = "uploads/123/audio/song.flac"
|
||||
assert _extract_gcs_path(path) == "uploads/123/audio/song.flac"
|
||||
|
||||
|
||||
class TestProcessAudioDownload:
|
||||
"""Tests for the main process_audio_download function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_when_job_not_found(self):
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"):
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
result = await process_audio_download("nonexistent-job")
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_when_no_download_params(self):
|
||||
"""Job in wrong state with no download params should abort."""
|
||||
job = _make_job(
|
||||
status=JobStatus.PENDING,
|
||||
source_name=None,
|
||||
source_id=None,
|
||||
)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"):
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_youtube_download_success(self):
|
||||
"""Successful YouTube download triggers workers."""
|
||||
job = _make_job(source_name="YouTube", source_id="dQw4w9WgXcQ")
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
|
||||
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
mock_jm.update_job.assert_called_once_with("test-job-123", {
|
||||
'input_media_gcs_path': "uploads/test-job-123/audio/song.mp3",
|
||||
'filename': "song.mp3",
|
||||
})
|
||||
mock_jm.transition_to_state.assert_called_once()
|
||||
mock_ws.trigger_audio_worker.assert_awaited_once_with("test-job-123")
|
||||
mock_ws.trigger_lyrics_worker.assert_awaited_once_with("test-job-123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_error_fails_job(self):
|
||||
"""DownloadError should fail the job and return False."""
|
||||
job = _make_job()
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.side_effect = DownloadError("Download timed out")
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is False
|
||||
mock_jm.fail_job.assert_called_once()
|
||||
assert "Download timed out" in mock_jm.fail_job.call_args[0][1]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uses_state_data_selection_when_available(self):
|
||||
"""Should prefer state_data search results over job-level params."""
|
||||
job = _make_job(
|
||||
source_name="YouTube",
|
||||
source_id="fallback-id",
|
||||
state_data={
|
||||
'audio_search_results': [
|
||||
{'provider': 'Spotify', 'source_id': 'spotify123', 'target_file': None, 'url': None},
|
||||
],
|
||||
'selected_audio_index': 0,
|
||||
},
|
||||
)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
|
||||
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
await process_audio_download("test-job-123")
|
||||
|
||||
# Should have called with Spotify params from state_data, not YouTube fallback
|
||||
call_kwargs = mock_dl.call_args[1]
|
||||
assert call_kwargs['source_name'] == 'Spotify'
|
||||
assert call_kwargs['source_id'] == 'spotify123'
|
||||
|
||||
|
||||
class TestDownloadAudio:
|
||||
"""Tests for _download_audio routing."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_routes_youtube_download(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with patch("backend.workers.audio_download_worker._download_youtube", new_callable=AsyncMock) as mock_yt:
|
||||
mock_yt.return_value = ("uploads/j/audio/song.mp3", "song.mp3")
|
||||
|
||||
result = await _download_audio(
|
||||
job_id="j", source_name="YouTube", source_id="vid123",
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
assert result == ("uploads/j/audio/song.mp3", "song.mp3")
|
||||
mock_yt.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_routes_red_to_torrent(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with patch("backend.workers.audio_download_worker._download_torrent", new_callable=AsyncMock) as mock_torrent:
|
||||
mock_torrent.return_value = ("uploads/j/audio/song.flac", "song.flac")
|
||||
|
||||
await _download_audio(
|
||||
job_id="j", source_name="RED", source_id="123",
|
||||
target_file="track.flac", download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
mock_torrent.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_routes_spotify_download(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with patch("backend.workers.audio_download_worker._download_spotify", new_callable=AsyncMock) as mock_sp:
|
||||
mock_sp.return_value = ("uploads/j/audio/song.ogg", "song.ogg")
|
||||
|
||||
await _download_audio(
|
||||
job_id="j", source_name="Spotify", source_id="track123",
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
mock_sp.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_raises_for_unsupported_source(self):
|
||||
mock_storage = MagicMock()
|
||||
|
||||
with pytest.raises(DownloadError, match="Unsupported audio source"):
|
||||
await _download_audio(
|
||||
job_id="j", source_name="SoundCloud", source_id="123",
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
+161
-915
File diff suppressed because it is too large.
Load diff
@@ -1,396 +0,0 @@
|
||||
"""
|
||||
Tests for audio_transcoding_service.py - Review audio transcoding to OGG Opus.
|
||||
|
||||
These tests mock StorageService and subprocess to verify:
|
||||
- Cache path derivation for various GCS paths
|
||||
- Cache hit path (no ffmpeg call)
|
||||
- Cache miss with successful transcode
|
||||
- Fallback to FLAC on transcoding failure
|
||||
- Bulk prepare_review_audio_for_job transcodes all expected files
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, call, ANY
|
||||
|
||||
|
||||
class TestGetCachePath:
|
||||
"""Test _get_cache_path() derivation logic."""
|
||||
|
||||
def _make_service(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
return AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
def test_input_audio_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/input/song.flac")
|
||||
assert result == "jobs/abc123/review-audio/song.ogg"
|
||||
|
||||
def test_stem_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/stems/instrumental_clean.flac")
|
||||
assert result == "jobs/abc123/review-audio/instrumental_clean.ogg"
|
||||
|
||||
def test_backing_vocals_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/stems/backing_vocals.flac")
|
||||
assert result == "jobs/abc123/review-audio/backing_vocals.ogg"
|
||||
|
||||
def test_nested_job_path(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/4bed6f80/stems/instrumental_with_backing.flac")
|
||||
assert result == "jobs/4bed6f80/review-audio/instrumental_with_backing.ogg"
|
||||
|
||||
def test_wav_extension(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("jobs/abc123/input/song.wav")
|
||||
assert result == "jobs/abc123/review-audio/song.ogg"
|
||||
|
||||
def test_no_jobs_prefix_fallback_uses_hash(self):
|
||||
service = self._make_service()
|
||||
result = service._get_cache_path("other/path/audio.flac")
|
||||
# Should use a hash-based fallback, not a literal "_unknown"
|
||||
assert result.startswith("jobs/_")
|
||||
assert result.endswith("/review-audio/audio.ogg")
|
||||
assert len(result.split("/")[1]) == 13 # "_" + 12-char hash
|
||||
|
||||
def test_no_jobs_prefix_different_paths_different_hashes(self):
|
||||
service = self._make_service()
|
||||
result1 = service._get_cache_path("other/path/audio.flac")
|
||||
result2 = service._get_cache_path("another/path/audio.flac")
|
||||
# Different source paths should produce different cache paths
|
||||
assert result1 != result2
|
||||
|
||||
|
||||
class TestTranscodeIfNeeded:
|
||||
"""Test transcode_if_needed() cache hit/miss logic."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_cache_hit_skips_transcode(self, mock_subprocess):
|
||||
"""When cached file exists, return it without transcoding."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.transcode_if_needed("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "jobs/abc/review-audio/song.ogg"
|
||||
mock_storage.file_exists.assert_called_once_with("jobs/abc/review-audio/song.ogg")
|
||||
mock_subprocess.run.assert_not_called()
|
||||
mock_storage.download_file.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_cache_miss_transcodes_and_uploads(self, mock_subprocess):
|
||||
"""When cached file is missing, download + transcode + upload."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_subprocess.run.return_value = Mock(returncode=0, stderr="")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.transcode_if_needed("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "jobs/abc/review-audio/song.ogg"
|
||||
|
||||
# Verify download from correct source path
|
||||
download_args = mock_storage.download_file.call_args[0]
|
||||
assert download_args[0] == "jobs/abc/input/song.flac"
|
||||
|
||||
# Verify ffmpeg command
|
||||
mock_subprocess.run.assert_called_once()
|
||||
ffmpeg_call = mock_subprocess.run.call_args
|
||||
ffmpeg_cmd = ffmpeg_call[0][0]
|
||||
assert "ffmpeg" in ffmpeg_cmd[0]
|
||||
assert "libopus" in ffmpeg_cmd
|
||||
assert "128k" in ffmpeg_cmd
|
||||
assert "-vn" in ffmpeg_cmd
|
||||
# Verify timeout is set
|
||||
assert ffmpeg_call[1]["timeout"] == 120
|
||||
|
||||
# Verify upload to correct cache path
|
||||
upload_args = mock_storage.upload_file.call_args[0]
|
||||
assert upload_args[1] == "jobs/abc/review-audio/song.ogg"
|
||||
|
||||
|
||||
class TestGetReviewAudioUrl:
|
||||
"""Test get_review_audio_url() with fallback behavior."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_returns_transcoded_url_on_success(self, mock_subprocess):
|
||||
"""On success, return signed URL for transcoded file."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.ogg"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/review-audio/song.ogg", 120
|
||||
)
|
||||
|
||||
def test_falls_back_to_flac_on_error(self):
|
||||
"""On transcoding error with no cache, fall back to original FLAC signed URL."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_storage.download_file.side_effect = Exception("GCS download failed")
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.flac"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.flac"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/input/song.flac", 120
|
||||
)
|
||||
# file_exists called twice: once in transcode_if_needed (cache miss),
|
||||
# once in fallback (cache still missing → fall through to FLAC)
|
||||
assert mock_storage.file_exists.call_count == 2
|
||||
|
||||
def test_serves_cache_when_source_deleted(self):
|
||||
"""When source is deleted but OGG cache exists, serve the cache."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
# First file_exists (in transcode_if_needed): cache miss
|
||||
# download_file fails: source deleted
|
||||
# Second file_exists (in fallback): cache found
|
||||
mock_storage.file_exists.side_effect = [False, True]
|
||||
mock_storage.download_file.side_effect = Exception("blob not found")
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.ogg"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/review-audio/song.ogg", 120
|
||||
)
|
||||
|
||||
def test_falls_back_to_flac_when_cache_check_also_fails(self):
|
||||
"""When source is deleted and file_exists() also throws, fall back to FLAC."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
# First file_exists (in transcode_if_needed): cache miss
|
||||
# download_file fails: source deleted
|
||||
# Second file_exists (in fallback): also throws
|
||||
mock_storage.file_exists.side_effect = [False, Exception("GCS unavailable")]
|
||||
mock_storage.download_file.side_effect = Exception("blob not found")
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.flac"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed-url/song.flac"
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/input/song.flac", 120
|
||||
)
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_custom_expiration_minutes(self, mock_subprocess):
|
||||
"""Custom expiration_minutes is passed through to generate_signed_url."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url/song.ogg"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
service.get_review_audio_url("jobs/abc/input/song.flac", expiration_minutes=60)
|
||||
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/review-audio/song.ogg", 60
|
||||
)
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_falls_back_on_ffmpeg_failure(self, mock_subprocess):
|
||||
"""On ffmpeg failure, fall back to original FLAC signed URL."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False
|
||||
mock_subprocess.run.return_value = Mock(returncode=1, stderr="codec error")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
# Should fall back to FLAC URL
|
||||
mock_storage.generate_signed_url.assert_called_once_with(
|
||||
"jobs/abc/input/song.flac", 120
|
||||
)
|
||||
|
||||
|
||||
class TestPrepareReviewAudioForJob:
|
||||
"""Test prepare_review_audio_for_job() bulk transcoding."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_transcodes_all_expected_files(self, mock_subprocess):
|
||||
"""Should transcode input + all stems and return correct cache paths."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True # All cache hits
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/abc123/stems/instrumental_with_backing.flac",
|
||||
"backing_vocals": "jobs/abc123/stems/backing_vocals.flac",
|
||||
}
|
||||
}
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
assert len(result) == 4
|
||||
assert "jobs/abc123/review-audio/song.ogg" in result
|
||||
assert "jobs/abc123/review-audio/instrumental_clean.ogg" in result
|
||||
assert "jobs/abc123/review-audio/instrumental_with_backing.ogg" in result
|
||||
assert "jobs/abc123/review-audio/backing_vocals.ogg" in result
|
||||
assert mock_storage.file_exists.call_count == 4
|
||||
# No ffmpeg calls since all are cache hits
|
||||
mock_subprocess.run.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_continues_on_individual_failure(self, mock_subprocess):
|
||||
"""If one file fails to transcode, others should still succeed."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
# First call (input): cache miss + download fails
|
||||
# Subsequent calls: cache hits
|
||||
mock_storage.file_exists.side_effect = [False, True, True, True]
|
||||
mock_storage.download_file.side_effect = Exception("download failed")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/abc123/stems/instrumental_with_backing.flac",
|
||||
"backing_vocals": "jobs/abc123/stems/backing_vocals.flac",
|
||||
}
|
||||
}
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
# 3 out of 4 succeeded (the 3 cache hits)
|
||||
assert len(result) == 3
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_handles_missing_stems(self, mock_subprocess):
|
||||
"""Should handle jobs with missing stem paths gracefully."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {"stems": {}} # No stems
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
# Only the input audio
|
||||
assert len(result) == 1
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_handles_no_input_audio(self, mock_subprocess):
|
||||
"""Should handle jobs with no input_media_gcs_path."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = None
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/abc123/stems/instrumental_clean.flac",
|
||||
}
|
||||
}
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
def test_handles_no_stems_key(self, mock_subprocess):
|
||||
"""Should handle jobs where file_urls has no stems key at all."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.job_id = "abc123"
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.file_urls = {} # No stems key
|
||||
|
||||
result = service.prepare_review_audio_for_job(mock_job)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0] == "jobs/abc123/review-audio/song.ogg"
|
||||
|
||||
|
||||
class TestInit:
|
||||
"""Test AudioTranscodingService initialization."""
|
||||
|
||||
@patch("backend.services.audio_transcoding_service.StorageService")
|
||||
def test_creates_default_storage_service(self, mock_storage_class):
|
||||
"""Creates a StorageService when none is provided."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
service = AudioTranscodingService()
|
||||
|
||||
mock_storage_class.assert_called_once()
|
||||
assert service.storage is mock_storage_class.return_value
|
||||
|
||||
def test_uses_provided_storage_service(self):
|
||||
"""Uses the provided storage service instead of creating one."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
assert service.storage is mock_storage
|
||||
|
||||
|
||||
class TestGetReviewAudioUrlAsync:
|
||||
"""Test async wrapper."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.services.audio_transcoding_service.subprocess")
|
||||
async def test_async_wrapper_delegates(self, mock_subprocess):
|
||||
"""Async wrapper should call sync method via to_thread."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed/url"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
result = await service.get_review_audio_url_async("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed/url"
|
||||
@@ -1,148 +0,0 @@
|
||||
"""
|
||||
Tests for download_audio() upload persistence in audio_worker.py.
|
||||
|
||||
Verifies that uploaded files (uploads/ prefix) are copied to jobs/ prefix
|
||||
so they survive the 7-day GCS lifecycle rule on uploads/.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, AsyncMock
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_upload_persisted_to_jobs_prefix(MockJobManager):
|
||||
"""Uploaded audio (uploads/ prefix) should be copied to jobs/{id}/input/."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_jm = Mock()
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "uploads/abc123/audio/My Song.flac"
|
||||
mock_job.filename = "My Song.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
result = await download_audio(
|
||||
job_id="abc123",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=mock_jm,
|
||||
)
|
||||
|
||||
# Should download from original upload path
|
||||
mock_storage.download_file.assert_called_once_with(
|
||||
"uploads/abc123/audio/My Song.flac", os.path.join("/tmp/test", "My Song.flac")
|
||||
)
|
||||
|
||||
# Should re-upload to persistent jobs/ path
|
||||
mock_storage.upload_file.assert_called_once_with(
|
||||
os.path.join("/tmp/test", "My Song.flac"),
|
||||
"jobs/abc123/input/My Song.flac",
|
||||
)
|
||||
|
||||
# Should update job metadata
|
||||
mock_jm.update_job.assert_called_once_with(
|
||||
"abc123", {"input_media_gcs_path": "jobs/abc123/input/My Song.flac"}
|
||||
)
|
||||
mock_jm.update_file_url.assert_called_once_with(
|
||||
"abc123", "input", "audio", "jobs/abc123/input/My Song.flac"
|
||||
)
|
||||
|
||||
assert result == os.path.join("/tmp/test", "My Song.flac")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_jobs_prefix_not_re_persisted(MockJobManager):
|
||||
"""Files already in jobs/ prefix should NOT be re-uploaded."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_jm = Mock()
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "jobs/abc123/input/song.flac"
|
||||
mock_job.filename = "song.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
result = await download_audio(
|
||||
job_id="abc123",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=mock_jm,
|
||||
)
|
||||
|
||||
# Should download but NOT re-upload
|
||||
mock_storage.download_file.assert_called_once()
|
||||
mock_storage.upload_file.assert_not_called()
|
||||
mock_jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_upload_persistence_creates_job_manager_if_none(MockJobManager):
|
||||
"""If no job_manager_instance provided, creates one for persistence."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_jm_instance = Mock()
|
||||
MockJobManager.return_value = mock_jm_instance
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "uploads/def456/audio/track.flac"
|
||||
mock_job.filename = "track.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
await download_audio(
|
||||
job_id="def456",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=None,
|
||||
)
|
||||
|
||||
# Should have created a JobManager
|
||||
MockJobManager.assert_called_once()
|
||||
# Should use the created instance
|
||||
mock_jm_instance.update_job.assert_called_once()
|
||||
mock_jm_instance.update_file_url.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("backend.workers.audio_worker.JobManager")
|
||||
async def test_persistence_failure_does_not_block_download(MockJobManager):
|
||||
"""If upload_file fails during persistence, download still succeeds."""
|
||||
from backend.workers.audio_worker import download_audio
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.upload_file.side_effect = Exception("GCS upload failed")
|
||||
mock_jm = Mock()
|
||||
|
||||
mock_job = Mock()
|
||||
mock_job.input_media_gcs_path = "uploads/abc123/audio/song.flac"
|
||||
mock_job.filename = "song.flac"
|
||||
mock_job.url = None
|
||||
mock_job.file_urls = {}
|
||||
|
||||
result = await download_audio(
|
||||
job_id="abc123",
|
||||
temp_dir="/tmp/test",
|
||||
storage=mock_storage,
|
||||
job=mock_job,
|
||||
job_manager_instance=mock_jm,
|
||||
)
|
||||
|
||||
# Download succeeded despite persistence failure
|
||||
assert result == os.path.join("/tmp/test", "song.flac")
|
||||
mock_storage.download_file.assert_called_once()
|
||||
# upload_file was attempted but failed
|
||||
mock_storage.upload_file.assert_called_once()
|
||||
# Metadata update should NOT have been called (upload failed first)
|
||||
mock_jm.update_job.assert_not_called()
|
||||
@@ -32,35 +32,6 @@ class TestAuthServiceBasics:
|
||||
assert hasattr(AuthService, 'validate_token') or hasattr(AuthService, 'verify_token')
|
||||
|
||||
|
||||
class TestIncrementTokenUsage:
|
||||
"""Tests for increment_token_usage after credit deduction cleanup."""
|
||||
|
||||
def test_session_token_does_not_deduct_credits(self):
|
||||
"""
|
||||
Verify that increment_token_usage does NOT deduct credits for session tokens.
|
||||
|
||||
Credit deduction is handled by JobManager.create_job(), not here.
|
||||
This test ensures the dead code removal didn't break the method.
|
||||
"""
|
||||
mock_firestore = MagicMock()
|
||||
# Session token: not in admin_tokens, not in Firestore auth_tokens
|
||||
mock_firestore.get_token.return_value = None
|
||||
|
||||
with patch('backend.services.auth_service.FirestoreService', return_value=mock_firestore), \
|
||||
patch.dict('os.environ', {'ADMIN_TOKENS': 'admin-token'}):
|
||||
from backend.services.auth_service import AuthService
|
||||
service = AuthService()
|
||||
|
||||
# Mock validate_token to return valid session user
|
||||
with patch.object(service, 'validate_token', return_value=(True, 'stripe', 5, 'OK')):
|
||||
result = service.increment_token_usage("session-token-123", "job-abc")
|
||||
|
||||
# Should return True (no-op for session tokens)
|
||||
assert result is True
|
||||
# Should NOT try to deduct credits via user_service
|
||||
# (If it did, it would fail since user_service is not mocked)
|
||||
|
||||
|
||||
class TestFirestoreServiceBasics:
|
||||
"""Basic tests for FirestoreService."""
|
||||
|
||||
|
||||
@@ -1,590 +0,0 @@
|
||||
"""
|
||||
Tests for BrandCodeService - atomic brand code allocation via Firestore counters.
|
||||
|
||||
Tests cover:
|
||||
- Sequential allocation returns unique codes
|
||||
- Recycled numbers are reused (smallest first)
|
||||
- One-time initialization from Dropbox scan
|
||||
- Both NOMAD and NOMADNP prefixes work independently
|
||||
- Recycle then allocate round-trip
|
||||
- parse_brand_code utility
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, MagicMock, patch
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import sys
|
||||
sys.modules.setdefault('google.cloud.firestore', MagicMock())
|
||||
sys.modules.setdefault('google.cloud.storage', MagicMock())
|
||||
|
||||
|
||||
def _make_doc_snapshot(exists, data=None):
|
||||
"""Create a mock Firestore document snapshot."""
|
||||
doc = Mock()
|
||||
doc.exists = exists
|
||||
if data:
|
||||
doc.to_dict.return_value = data
|
||||
return doc
|
||||
|
||||
|
||||
def _setup_service_and_mocks(mock_db, doc_snapshot):
|
||||
"""Common setup: create service with fake transactional decorator."""
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_doc_ref.get.return_value = doc_snapshot
|
||||
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
return mock_doc_ref, mock_transaction
|
||||
|
||||
|
||||
class TestBrandCodeServiceAllocate:
|
||||
"""Test allocate_brand_code method."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_allocate_sequential_number(self, mock_db):
|
||||
"""Test allocation returns next sequential number when no recycled numbers."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == "NOMAD-1264"
|
||||
# Transaction.update should have been called to increment next_number
|
||||
mock_transaction.update.assert_called_once()
|
||||
update_args = mock_transaction.update.call_args[0]
|
||||
assert update_args[0] is mock_doc_ref # first arg is doc_ref
|
||||
assert update_args[1]["next_number"] == 1265
|
||||
|
||||
def test_allocate_uses_recycled_number(self, mock_db):
|
||||
"""Test allocation pops smallest recycled number first."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250, 1230, 1245],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMAD", "/path")
|
||||
|
||||
assert result == "NOMAD-1230"
|
||||
# Verify recycled list was updated (1230 removed, sorted remainder)
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert update_args["recycled"] == [1245, 1250]
|
||||
|
||||
def test_allocate_initializes_from_dropbox_when_no_counter(self, mock_db):
|
||||
"""Test first allocation scans Dropbox and creates counter doc."""
|
||||
doc_snapshot = _make_doc_snapshot(False)
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
with patch.object(svc, '_get_initial_next_number', return_value=1264):
|
||||
result = svc.allocate_brand_code("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == "NOMAD-1264"
|
||||
# Verify counter doc was created via transaction.set
|
||||
mock_transaction.set.assert_called_once()
|
||||
set_args = mock_transaction.set.call_args[0]
|
||||
assert set_args[0] is mock_doc_ref
|
||||
assert set_args[1]["prefix"] == "NOMAD"
|
||||
assert set_args[1]["next_number"] == 1265
|
||||
assert set_args[1]["recycled"] == []
|
||||
|
||||
def test_allocate_nomadnp_prefix(self, mock_db):
|
||||
"""Test NOMADNP prefix works independently."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMADNP",
|
||||
"next_number": 13,
|
||||
"recycled": [],
|
||||
})
|
||||
_setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMADNP", "/Karaoke/NP")
|
||||
|
||||
assert result == "NOMADNP-0013"
|
||||
mock_db.collection.assert_called_with("brand_code_counters")
|
||||
mock_db.collection.return_value.document.assert_called_with("NOMADNP")
|
||||
|
||||
def test_allocate_formats_with_leading_zeros(self, mock_db):
|
||||
"""Test brand codes are zero-padded to 4 digits."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMADNP",
|
||||
"next_number": 5,
|
||||
"recycled": [],
|
||||
})
|
||||
_setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc.allocate_brand_code("NOMADNP", "/path")
|
||||
|
||||
assert result == "NOMADNP-0005"
|
||||
|
||||
|
||||
class TestBrandCodeServiceRecycle:
|
||||
"""Test recycle_brand_code method."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_recycle_adds_number_to_pool(self, mock_db):
|
||||
"""Test recycling adds number to the recycled list."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert 1230 in update_args["recycled"]
|
||||
assert 1250 in update_args["recycled"]
|
||||
|
||||
def test_recycle_rejects_number_at_or_above_next(self, mock_db):
|
||||
"""Test recycling a number >= next_number is rejected."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
# Number equal to next_number — hasn't been allocated yet
|
||||
svc.recycle_brand_code("NOMAD", 1264)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_rejects_zero_or_negative(self, mock_db):
|
||||
"""Test recycling zero or negative numbers is rejected."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 0)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_skips_duplicate(self, mock_db):
|
||||
"""Test recycling a number already in the pool doesn't duplicate it."""
|
||||
doc_snapshot = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1250],
|
||||
})
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1250)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
def test_recycle_no_counter_doc_logs_warning(self, mock_db):
|
||||
"""Test recycling when counter doc doesn't exist logs warning and returns."""
|
||||
doc_snapshot = _make_doc_snapshot(False)
|
||||
mock_doc_ref, mock_transaction = _setup_service_and_mocks(mock_db, doc_snapshot)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
mock_transaction.set.assert_not_called()
|
||||
|
||||
|
||||
class TestBrandCodeServiceRecycleRoundTrip:
|
||||
"""Test recycle-then-allocate round trip."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_recycle_then_allocate_reuses_number(self, mock_db):
|
||||
"""Test that a recycled number is returned on next allocation."""
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Step 1: Recycle number 1230
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
svc.recycle_brand_code("NOMAD", 1230)
|
||||
|
||||
# Step 2: Allocate — should get recycled 1230
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [1230],
|
||||
})
|
||||
result = svc.allocate_brand_code("NOMAD", "/path")
|
||||
|
||||
assert result == "NOMAD-1230"
|
||||
|
||||
|
||||
class TestInitializeFromDropbox:
|
||||
"""Test _get_initial_next_number."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
def test_init_from_dropbox_finds_max(self, mock_db):
|
||||
"""Test initialization finds the max existing number and adds 1."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = [
|
||||
"NOMAD-1260 - Artist A - Song A",
|
||||
"NOMAD-1261 - Artist B - Song B",
|
||||
"NOMAD-1263 - Artist C - Song C",
|
||||
"Some Other Folder",
|
||||
]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/Karaoke/Tracks-Organized")
|
||||
|
||||
assert result == 1264 # max(1260, 1261, 1263) + 1
|
||||
|
||||
def test_init_from_dropbox_no_existing(self, mock_db):
|
||||
"""Test initialization returns 1 when no existing codes found."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = ["Some Random Folder"]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/path")
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_init_from_dropbox_not_configured(self, mock_db):
|
||||
"""Test initialization returns 1 when Dropbox not configured."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = False
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMAD", "/path")
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_init_nomadnp_prefix_independent(self, mock_db):
|
||||
"""Test NOMADNP initialization only finds NOMADNP codes, not NOMAD."""
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.list_folders.return_value = [
|
||||
"NOMADNP-0010 - Artist A",
|
||||
"NOMADNP-0012 - Artist B",
|
||||
"NOMAD-1263 - Artist C", # Should NOT match NOMADNP prefix
|
||||
]
|
||||
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings, \
|
||||
patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox):
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
result = svc._get_initial_next_number("NOMADNP", "/Karaoke/NP")
|
||||
|
||||
assert result == 13 # max(10, 12) + 1
|
||||
|
||||
|
||||
class TestParseBrandCode:
|
||||
"""Test parse_brand_code static method."""
|
||||
|
||||
def test_parse_nomad_code(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-1234")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1234
|
||||
|
||||
def test_parse_nomadnp_code(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMADNP-0012")
|
||||
assert prefix == "NOMADNP"
|
||||
assert number == 12
|
||||
|
||||
def test_parse_leading_zeros(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-0001")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1
|
||||
|
||||
def test_parse_invalid_format_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("invalid")
|
||||
|
||||
def test_parse_no_dash_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("NOMAD1234")
|
||||
|
||||
def test_parse_lowercase_raises(self):
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
with pytest.raises(ValueError, match="Invalid brand code format"):
|
||||
BrandCodeService.parse_brand_code("nomad-1234")
|
||||
|
||||
|
||||
class TestCleanupDistributionRecycling:
|
||||
"""Test that cleanup_distribution endpoint recycles brand codes correctly."""
|
||||
|
||||
def test_parse_and_recycle_nomad_brand_code(self):
|
||||
"""Test that a NOMAD brand code is correctly parsed and recycled."""
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMAD-1234")
|
||||
assert prefix == "NOMAD"
|
||||
assert number == 1234
|
||||
|
||||
def test_parse_and_recycle_nomadnp_brand_code(self):
|
||||
"""Test that a NOMADNP brand code is correctly parsed and recycled."""
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
|
||||
prefix, number = BrandCodeService.parse_brand_code("NOMADNP-0012")
|
||||
assert prefix == "NOMADNP"
|
||||
assert number == 12
|
||||
|
||||
def test_recycle_called_after_successful_dropbox_delete(self):
|
||||
"""Test the integration pattern: parse brand code, then recycle the number."""
|
||||
mock_db = MagicMock()
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(True, {
|
||||
"prefix": "NOMAD",
|
||||
"next_number": 1264,
|
||||
"recycled": [],
|
||||
})
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Simulate what cleanup_distribution does:
|
||||
# 1. Parse the brand code
|
||||
brand_code = "NOMAD-1234"
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
# 2. Recycle it
|
||||
svc.recycle_brand_code(prefix, number)
|
||||
|
||||
# Verify transaction.update was called to add 1234 to recycled pool
|
||||
mock_transaction.update.assert_called_once()
|
||||
update_args = mock_transaction.update.call_args[0][1]
|
||||
assert 1234 in update_args["recycled"]
|
||||
|
||||
def test_recycle_failure_does_not_raise(self):
|
||||
"""Test that recycling a brand code with no counter doc doesn't raise."""
|
||||
mock_db = MagicMock()
|
||||
mock_doc_ref = Mock()
|
||||
mock_db.collection.return_value.document.return_value = mock_doc_ref
|
||||
mock_transaction = Mock()
|
||||
mock_db.transaction.return_value = mock_transaction
|
||||
|
||||
mock_doc_ref.get.return_value = _make_doc_snapshot(False)
|
||||
|
||||
with patch('backend.services.brand_code_service.firestore') as mock_fs, \
|
||||
patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
def fake_transactional(func):
|
||||
def wrapper(transaction, *args, **kwargs):
|
||||
return func(transaction, *args, **kwargs)
|
||||
return wrapper
|
||||
mock_fs.transactional = fake_transactional
|
||||
|
||||
from backend.services.brand_code_service import BrandCodeService
|
||||
svc = BrandCodeService(db=mock_db)
|
||||
|
||||
# Should not raise — cleanup should be resilient
|
||||
svc.recycle_brand_code("NOMAD", 1234)
|
||||
|
||||
mock_transaction.update.assert_not_called()
|
||||
|
||||
|
||||
class TestGetBrandCodeService:
|
||||
"""Test singleton getter."""
|
||||
|
||||
def test_returns_same_instance(self):
|
||||
"""Test get_brand_code_service returns singleton."""
|
||||
with patch('backend.services.brand_code_service.settings') as mock_settings:
|
||||
mock_settings.google_cloud_project = 'test-project'
|
||||
|
||||
import backend.services.brand_code_service as module
|
||||
# Reset singleton
|
||||
module._brand_code_service = None
|
||||
|
||||
svc1 = module.get_brand_code_service()
|
||||
svc2 = module.get_brand_code_service()
|
||||
assert svc1 is svc2
|
||||
|
||||
# Clean up
|
||||
module._brand_code_service = None
|
||||
@@ -1,194 +0,0 @@
|
||||
"""
|
||||
Tests for catalog API routes — proxy endpoints and community check.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Test client with mocked auth."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
"""Headers for authenticated requests."""
|
||||
return {"Authorization": "Bearer test-admin-token"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_rate_limits():
|
||||
"""Clear rate limit state between tests."""
|
||||
from backend.api.routes.catalog import _rate_limit_windows
|
||||
_rate_limit_windows.clear()
|
||||
yield
|
||||
_rate_limit_windows.clear()
|
||||
|
||||
|
||||
# --- Artist search ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock)
|
||||
def test_search_artists_returns_results(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = [
|
||||
{"name": "Fleetwood Mac", "mbid": "abc-123", "popularity": 85},
|
||||
{"name": "Fleet Foxes", "mbid": "def-456", "popularity": 72},
|
||||
]
|
||||
|
||||
response = client.get("/api/catalog/artists?q=flee", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 2
|
||||
assert data[0]["name"] == "Fleetwood Mac"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock)
|
||||
def test_search_artists_empty_results(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = []
|
||||
|
||||
response = client.get("/api/catalog/artists?q=zzzzz", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == []
|
||||
|
||||
|
||||
def test_search_artists_requires_min_query_length(client, auth_headers):
|
||||
response = client.get("/api/catalog/artists?q=a", headers=auth_headers)
|
||||
assert response.status_code == 422 # Validation error
|
||||
|
||||
|
||||
# --- Track search ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_tracks", new_callable=AsyncMock)
|
||||
def test_search_tracks_returns_results(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = [
|
||||
{"track_name": "Dreams", "artist_name": "Fleetwood Mac", "popularity": 82},
|
||||
]
|
||||
|
||||
response = client.get("/api/catalog/tracks?q=dreams", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["track_name"] == "Dreams"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_tracks", new_callable=AsyncMock)
|
||||
def test_search_tracks_with_artist_filter(mock_search, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_search.return_value = []
|
||||
|
||||
response = client.get(
|
||||
"/api/catalog/tracks?q=dreams&artist=Fleetwood+Mac",
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
mock_search.assert_called_once_with("dreams", "Fleetwood Mac", 10)
|
||||
|
||||
|
||||
# --- Community check ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.karaokenerds_service.check_community_versions", new_callable=AsyncMock)
|
||||
def test_community_check_found(mock_check, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_check.return_value = {
|
||||
"has_community": True,
|
||||
"songs": [
|
||||
{
|
||||
"title": "Dreams",
|
||||
"artist": "Fleetwood Mac",
|
||||
"community_tracks": [
|
||||
{
|
||||
"brand_name": "Karaoke Version",
|
||||
"brand_code": "KV",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=abc",
|
||||
"is_community": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=abc",
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
"/api/catalog/community-check",
|
||||
json={"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["has_community"] is True
|
||||
assert len(data["songs"]) == 1
|
||||
assert data["best_youtube_url"] == "https://www.youtube.com/watch?v=abc"
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.karaokenerds_service.check_community_versions", new_callable=AsyncMock)
|
||||
def test_community_check_not_found(mock_check, mock_auth, client, auth_headers):
|
||||
mock_auth.return_value = MagicMock(user_email="test@example.com", token_id="test")
|
||||
mock_check.return_value = {
|
||||
"has_community": False,
|
||||
"songs": [],
|
||||
"best_youtube_url": None,
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
"/api/catalog/community-check",
|
||||
json={"artist": "Unknown Artist", "title": "Unknown Song"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["has_community"] is False
|
||||
|
||||
|
||||
def test_community_check_validation_error(client, auth_headers):
|
||||
response = client.post(
|
||||
"/api/catalog/community-check",
|
||||
json={"artist": "", "title": "Dreams"},
|
||||
headers=auth_headers,
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# --- Rate limiting ---
|
||||
|
||||
|
||||
@patch("backend.api.routes.catalog.require_auth")
|
||||
@patch("backend.services.catalog_proxy_service.search_artists", new_callable=AsyncMock)
|
||||
def test_rate_limit_enforced(mock_search, mock_auth, client, auth_headers):
|
||||
"""Rate limit allows up to 20 requests per minute, then returns 429."""
|
||||
# Use a unique email so other tests' requests don't interfere
|
||||
unique_email = "ratelimit-unique-test@test.com"
|
||||
mock_auth.return_value = MagicMock(user_email=unique_email, token_id="test")
|
||||
mock_search.return_value = []
|
||||
|
||||
# Clear any existing rate limit state for this user
|
||||
from backend.api.routes.catalog import _rate_limit_windows
|
||||
_rate_limit_windows.pop(unique_email, None)
|
||||
|
||||
# First 20 requests should succeed
|
||||
for i in range(20):
|
||||
resp = client.get("/api/catalog/artists?q=test", headers=auth_headers)
|
||||
assert resp.status_code == 200, f"Request {i+1}/20 failed with {resp.status_code}"
|
||||
|
||||
# 21st request should be rate limited
|
||||
resp = client.get("/api/catalog/artists?q=test", headers=auth_headers)
|
||||
assert resp.status_code == 429
|
||||
assert "Rate limit exceeded" in resp.json()["detail"]
|
||||
|
||||
# Clean up
|
||||
_rate_limit_windows.pop(unique_email, None)
|
||||
@@ -1,249 +0,0 @@
|
||||
"""
|
||||
Tests for CDG countdown handling.
|
||||
|
||||
Tests cover:
|
||||
- _remove_countdown_from_lyrics() helper method
|
||||
- CDG generation with countdown-padded LRC files
|
||||
- Timestamp adjustment for instrumental audio sync
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
|
||||
|
||||
|
||||
class TestCDGCountdownRemoval:
|
||||
"""Test the _remove_countdown_from_lyrics helper method."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self, tmp_path):
|
||||
"""Create a CDGGenerator instance for testing."""
|
||||
return CDGGenerator(output_dir=str(tmp_path))
|
||||
|
||||
def test_removes_countdown_segment(self, generator):
|
||||
"""Test that countdown segment is removed from lyrics data."""
|
||||
# Simulated LRC data with countdown at 0.1s and first word at 3.6s
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "3... 2... 1..."}, # 0.1s = 10 centiseconds
|
||||
{"timestamp": 360, "text": "IF"}, # 3.6s = 360 centiseconds
|
||||
{"timestamp": 380, "text": "YOU"},
|
||||
{"timestamp": 624, "text": "COULD"},
|
||||
]
|
||||
|
||||
# Remove 3 second countdown padding
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# Countdown segment should be removed (timestamp < 300cs)
|
||||
assert len(result) == 3
|
||||
assert result[0]["text"] == "IF"
|
||||
|
||||
# Timestamps should be shifted back by 300cs (3 seconds)
|
||||
assert result[0]["timestamp"] == 60 # 360 - 300
|
||||
assert result[1]["timestamp"] == 80 # 380 - 300
|
||||
assert result[2]["timestamp"] == 324 # 624 - 300
|
||||
|
||||
def test_handles_multiple_countdown_segments(self, generator):
|
||||
"""Test with multiple early segments (e.g., multi-part countdown)."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "3"},
|
||||
{"timestamp": 100, "text": "2"},
|
||||
{"timestamp": 200, "text": "1"},
|
||||
{"timestamp": 360, "text": "HELLO"},
|
||||
{"timestamp": 500, "text": "WORLD"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# All segments before 300cs should be removed
|
||||
assert len(result) == 2
|
||||
assert result[0]["text"] == "HELLO"
|
||||
assert result[0]["timestamp"] == 60 # 360 - 300
|
||||
assert result[1]["text"] == "WORLD"
|
||||
assert result[1]["timestamp"] == 200 # 500 - 300
|
||||
|
||||
def test_handles_no_countdown_segment(self, generator):
|
||||
"""Test when LRC has no countdown segment but flag is set."""
|
||||
# All timestamps are after the countdown duration
|
||||
lyrics_data = [
|
||||
{"timestamp": 400, "text": "FIRST"},
|
||||
{"timestamp": 500, "text": "SECOND"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# Should still shift timestamps back
|
||||
assert len(result) == 2
|
||||
assert result[0]["timestamp"] == 100 # 400 - 300
|
||||
assert result[1]["timestamp"] == 200 # 500 - 300
|
||||
|
||||
def test_handles_different_padding_durations(self, generator):
|
||||
"""Test with different countdown padding durations."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 50, "text": "COUNTDOWN"}, # 0.5s
|
||||
{"timestamp": 560, "text": "WORD"}, # 5.6s
|
||||
]
|
||||
|
||||
# With 5s padding (500cs)
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 5.0)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0]["text"] == "WORD"
|
||||
assert result[0]["timestamp"] == 60 # 560 - 500
|
||||
|
||||
def test_preserves_text_unchanged(self, generator):
|
||||
"""Test that text content is preserved exactly."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "3... 2... 1..."},
|
||||
{"timestamp": 360, "text": "HELLO, WORLD!"},
|
||||
{"timestamp": 500, "text": "IT'S ME"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
assert result[0]["text"] == "HELLO, WORLD!"
|
||||
assert result[1]["text"] == "IT'S ME"
|
||||
|
||||
def test_empty_lyrics_list(self, generator):
|
||||
"""Test with empty lyrics list."""
|
||||
result = generator._remove_countdown_from_lyrics([], 3.0)
|
||||
assert result == []
|
||||
|
||||
def test_all_segments_in_countdown_period(self, generator):
|
||||
"""Test when all segments are within countdown period."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 10, "text": "A"},
|
||||
{"timestamp": 100, "text": "B"},
|
||||
{"timestamp": 200, "text": "C"},
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# All segments removed - should return empty after shifting
|
||||
assert len(result) == 0
|
||||
|
||||
def test_segment_exactly_at_boundary(self, generator):
|
||||
"""Test with segment timestamp exactly at countdown boundary."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 299, "text": "ALMOST"}, # Just before 3s
|
||||
{"timestamp": 300, "text": "EXACTLY"}, # Exactly at 3s
|
||||
{"timestamp": 301, "text": "AFTER"}, # Just after 3s
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.0)
|
||||
|
||||
# timestamp < countdown_cs means 299 is removed, 300 and 301 stay
|
||||
assert len(result) == 2
|
||||
assert result[0]["text"] == "EXACTLY"
|
||||
assert result[0]["timestamp"] == 0 # 300 - 300
|
||||
assert result[1]["text"] == "AFTER"
|
||||
assert result[1]["timestamp"] == 1 # 301 - 300
|
||||
|
||||
def test_fractional_countdown_duration(self, generator):
|
||||
"""Test with fractional countdown duration (e.g., 3.5 seconds)."""
|
||||
lyrics_data = [
|
||||
{"timestamp": 100, "text": "EARLY"}, # 1s
|
||||
{"timestamp": 340, "text": "MIDDLE"}, # 3.4s - still in countdown
|
||||
{"timestamp": 360, "text": "AFTER"}, # 3.6s - after 3.5s
|
||||
]
|
||||
|
||||
result = generator._remove_countdown_from_lyrics(lyrics_data, 3.5)
|
||||
|
||||
# 350cs boundary
|
||||
assert len(result) == 1
|
||||
assert result[0]["text"] == "AFTER"
|
||||
assert result[0]["timestamp"] == 10 # 360 - 350
|
||||
|
||||
|
||||
class TestCDGGenerateFromLRCWithCountdown:
|
||||
"""Test generate_cdg_from_lrc with countdown parameters."""
|
||||
|
||||
@pytest.fixture
|
||||
def generator(self, tmp_path):
|
||||
"""Create a CDGGenerator instance for testing."""
|
||||
return CDGGenerator(output_dir=str(tmp_path))
|
||||
|
||||
def test_passes_countdown_params_to_parse(self, generator, tmp_path, mocker):
|
||||
"""Test that countdown params are used when processing LRC."""
|
||||
# Create a test LRC file with countdown
|
||||
lrc_file = tmp_path / "test.lrc"
|
||||
lrc_file.write_text("""[re:MidiCo]
|
||||
[00:00.100]1:/3... 2... 1...
|
||||
[00:03.600]1:/If
|
||||
[00:03.800]1:you
|
||||
""")
|
||||
|
||||
audio_file = tmp_path / "test.flac"
|
||||
audio_file.write_text("fake audio")
|
||||
|
||||
# Mock the methods that would actually generate the CDG
|
||||
mock_remove = mocker.patch.object(
|
||||
generator, "_remove_countdown_from_lyrics", wraps=generator._remove_countdown_from_lyrics
|
||||
)
|
||||
mocker.patch.object(generator, "_validate_and_setup_font")
|
||||
mocker.patch.object(generator, "_create_toml_file", return_value=str(tmp_path / "test.toml"))
|
||||
mocker.patch.object(generator, "_compose_cdg")
|
||||
mocker.patch.object(generator, "_find_cdg_zip", return_value=str(tmp_path / "test.zip"))
|
||||
mocker.patch.object(generator, "_extract_cdg_files")
|
||||
mocker.patch.object(generator, "_get_cdg_path", return_value=str(tmp_path / "test.cdg"))
|
||||
mocker.patch.object(generator, "_get_mp3_path", return_value=str(tmp_path / "test.mp3"))
|
||||
mocker.patch.object(generator, "_verify_output_files")
|
||||
|
||||
# Create mock files
|
||||
(tmp_path / "test.toml").write_text("")
|
||||
(tmp_path / "test.zip").write_text("")
|
||||
(tmp_path / "test.cdg").write_text("")
|
||||
(tmp_path / "test.mp3").write_text("")
|
||||
|
||||
# Call with countdown padding enabled
|
||||
generator.generate_cdg_from_lrc(
|
||||
lrc_file=str(lrc_file),
|
||||
audio_file=str(audio_file),
|
||||
title="Test",
|
||||
artist="Artist",
|
||||
cdg_styles={"font_path": None}, # Minimal styles to avoid validation
|
||||
lrc_has_countdown_padding=True,
|
||||
countdown_padding_seconds=3.0,
|
||||
)
|
||||
|
||||
# Verify _remove_countdown_from_lyrics was called
|
||||
mock_remove.assert_called_once()
|
||||
# The method is called with (lyrics_data, countdown_padding_seconds)
|
||||
call_args = mock_remove.call_args
|
||||
# Check positional args - second arg should be countdown_padding_seconds
|
||||
assert call_args[0][1] == 3.0
|
||||
|
||||
def test_skips_countdown_processing_when_disabled(self, generator, tmp_path, mocker):
|
||||
"""Test that countdown processing is skipped when flag is False."""
|
||||
lrc_file = tmp_path / "test.lrc"
|
||||
lrc_file.write_text("[00:03.600]1:/Test\n")
|
||||
|
||||
audio_file = tmp_path / "test.flac"
|
||||
audio_file.write_text("fake audio")
|
||||
|
||||
mock_remove = mocker.patch.object(generator, "_remove_countdown_from_lyrics")
|
||||
mocker.patch.object(generator, "_validate_and_setup_font")
|
||||
mocker.patch.object(generator, "_create_toml_file", return_value=str(tmp_path / "test.toml"))
|
||||
mocker.patch.object(generator, "_compose_cdg")
|
||||
mocker.patch.object(generator, "_find_cdg_zip", return_value=str(tmp_path / "test.zip"))
|
||||
mocker.patch.object(generator, "_extract_cdg_files")
|
||||
mocker.patch.object(generator, "_get_cdg_path", return_value=str(tmp_path / "test.cdg"))
|
||||
mocker.patch.object(generator, "_get_mp3_path", return_value=str(tmp_path / "test.mp3"))
|
||||
mocker.patch.object(generator, "_verify_output_files")
|
||||
|
||||
# Create mock files
|
||||
(tmp_path / "test.toml").write_text("")
|
||||
(tmp_path / "test.zip").write_text("")
|
||||
(tmp_path / "test.cdg").write_text("")
|
||||
(tmp_path / "test.mp3").write_text("")
|
||||
|
||||
# Call with countdown padding DISABLED (default)
|
||||
generator.generate_cdg_from_lrc(
|
||||
lrc_file=str(lrc_file),
|
||||
audio_file=str(audio_file),
|
||||
title="Test",
|
||||
artist="Artist",
|
||||
cdg_styles={"font_path": None},
|
||||
lrc_has_countdown_padding=False,
|
||||
)
|
||||
|
||||
# Verify _remove_countdown_from_lyrics was NOT called
|
||||
mock_remove.assert_not_called()
|
||||
@@ -1,369 +0,0 @@
|
||||
"""
|
||||
Tests for the visibility change service.
|
||||
|
||||
Tests validation logic and the two visibility change flows:
|
||||
- Public -> Private (fast redistribution)
|
||||
- Private -> Public (full re-processing)
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.visibility_change_service import VisibilityChangeService
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id="test-123",
|
||||
status="complete",
|
||||
is_private=False,
|
||||
tenant_id="",
|
||||
user_email="user@example.com",
|
||||
state_data=None,
|
||||
):
|
||||
"""Create a mock job object for testing."""
|
||||
return SimpleNamespace(
|
||||
job_id=job_id,
|
||||
status=status,
|
||||
is_private=is_private,
|
||||
tenant_id=tenant_id,
|
||||
user_email=user_email,
|
||||
state_data=state_data or {},
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
outputs_deleted_at=None,
|
||||
dropbox_path="/Tracks-Organized",
|
||||
file_urls={"finals": {"lossy_4k_mp4": "gs://test/4k.mp4"}},
|
||||
)
|
||||
|
||||
|
||||
class TestValidation:
|
||||
"""Test validation logic for visibility changes."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = VisibilityChangeService(job_manager=MagicMock())
|
||||
|
||||
def test_validates_job_exists(self):
|
||||
error = self.service.validate_change(None, "user@example.com", False, "private")
|
||||
assert error == "Job not found"
|
||||
|
||||
def test_validates_complete_status(self):
|
||||
job = _make_job(status="generating_video")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "completed jobs" in error
|
||||
|
||||
def test_validates_not_tenant_job(self):
|
||||
job = _make_job(tenant_id="vocalstar")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "tenant" in error
|
||||
|
||||
def test_validates_different_visibility(self):
|
||||
job = _make_job(is_private=True)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "already private" in error
|
||||
|
||||
def test_validates_same_visibility_public(self):
|
||||
job = _make_job(is_private=False)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "public")
|
||||
assert "already public" in error
|
||||
|
||||
def test_validates_ownership(self):
|
||||
job = _make_job(user_email="owner@example.com")
|
||||
error = self.service.validate_change(job, "other@example.com", False, "private")
|
||||
assert "your own jobs" in error
|
||||
|
||||
def test_admin_can_change_any_job(self):
|
||||
job = _make_job(user_email="owner@example.com")
|
||||
error = self.service.validate_change(job, "admin@example.com", True, "private")
|
||||
assert error is None
|
||||
|
||||
def test_owner_can_change_own_job(self):
|
||||
job = _make_job(user_email="user@example.com")
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert error is None
|
||||
|
||||
def test_validates_no_concurrent_change(self):
|
||||
job = _make_job(state_data={"visibility_change_in_progress": True})
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert "already in progress" in error
|
||||
|
||||
def test_valid_public_to_private(self):
|
||||
job = _make_job(is_private=False)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "private")
|
||||
assert error is None
|
||||
|
||||
def test_valid_private_to_public(self):
|
||||
job = _make_job(is_private=True)
|
||||
error = self.service.validate_change(job, "user@example.com", False, "public")
|
||||
assert error is None
|
||||
|
||||
|
||||
class TestChangeToPrivate:
|
||||
"""Test public -> private visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calls_redistribute(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
|
||||
|
||||
result = await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["reprocessing_required"] is False
|
||||
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
|
||||
mock_redist.assert_called_once_with("test-123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sets_is_private_true(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
|
||||
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Check that is_private was set to True in one of the update calls
|
||||
update_calls = mock_job_ref.update.call_args_list
|
||||
found_private_update = any(
|
||||
call.args[0].get("is_private") is True
|
||||
for call in update_calls
|
||||
)
|
||||
assert found_private_update
|
||||
|
||||
|
||||
class TestChangeToPublic:
|
||||
"""Test private -> public visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_triggers_screens_worker(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={
|
||||
"brand_code": "NOMADNP-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)) as mock_theme, \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
result = await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "processing"
|
||||
assert result["reprocessing_required"] is True
|
||||
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
|
||||
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_styles_to_nomad_theme(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
# Verify the update payload resets styles
|
||||
update_calls = mock_job_ref.update.call_args_list
|
||||
# Find the main update call (the one with theme_id)
|
||||
style_update = None
|
||||
for call in update_calls:
|
||||
payload = call.args[0]
|
||||
if "theme_id" in payload:
|
||||
style_update = payload
|
||||
break
|
||||
|
||||
assert style_update is not None
|
||||
assert style_update["theme_id"] == "nomad"
|
||||
assert style_update["color_overrides"] == {}
|
||||
assert style_update["style_assets"] == {"bg": "bg.png"}
|
||||
assert style_update["style_params_gcs_path"] == "jobs/test-123/style/style_params.json"
|
||||
assert style_update["is_private"] is False
|
||||
assert style_update["status"] == "lyrics_complete"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_worker_failure(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage_cls.return_value = MagicMock()
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=False)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
with pytest.raises(RuntimeError, match="Failed to trigger screens worker"):
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
# Verify rollback was attempted
|
||||
rollback_call = mock_job_ref.update.call_args_list[-1]
|
||||
payload = rollback_call.args[0]
|
||||
assert payload["status"] == "complete"
|
||||
assert payload["is_private"] is True
|
||||
|
||||
|
||||
class TestChangeToPrivateErrors:
|
||||
"""Test error handling in public -> private flow."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_redistribute_failure(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
|
||||
|
||||
with pytest.raises(RuntimeError, match="Redistribution failed"):
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
|
||||
last_update = mock_job_ref.update.call_args_list[-1]
|
||||
val = last_update.args[0].get("state_data.visibility_change_in_progress")
|
||||
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
|
||||
|
||||
|
||||
class TestDeleteDistributedOutputs:
|
||||
"""Test cleanup of distributed outputs."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recycles_brand_code(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={"brand_code": "NOMAD-0042"})
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
|
||||
mock_brand_svc = MagicMock()
|
||||
mock_bcs.return_value = mock_brand_svc
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clears_distribution_state_keys(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 1)):
|
||||
mock_bcs.return_value = MagicMock()
|
||||
|
||||
# Patch YouTube deletion to avoid real service calls
|
||||
with patch("backend.services.youtube_service.get_youtube_service") as mock_yt, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service") as mock_dbx:
|
||||
mock_yt.return_value = MagicMock(is_configured=False)
|
||||
mock_dbx.return_value = MagicMock(is_configured=False)
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
update_call = mock_job_ref.update.call_args
|
||||
payload = update_call.args[0]
|
||||
# Verify keys are set to DELETE_FIELD sentinel
|
||||
for key in ["state_data.youtube_url", "state_data.brand_code", "state_data.dropbox_link"]:
|
||||
assert key in payload, f"Expected {key} in update payload"
|
||||
assert "sentinel" in str(payload[key]).lower() or "delete" in str(type(payload[key])).lower()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deletes_gcs_finals_when_not_kept(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.delete_folder.return_value = 3
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=False)
|
||||
|
||||
mock_storage.delete_folder.assert_called_once_with("jobs/test-123/finals/")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_gcs_finals_deletion_when_kept(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls:
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
await service._delete_distributed_outputs("test-123", job, keep_gcs_finals=True)
|
||||
|
||||
mock_storage.delete_folder.assert_not_called()
|
||||
|
||||
|
||||
class TestStateTransitions:
|
||||
"""Test that the COMPLETE -> LYRICS_COMPLETE state transition is valid."""
|
||||
|
||||
def test_complete_allows_lyrics_complete_transition(self):
|
||||
from backend.models.job import STATE_TRANSITIONS, JobStatus
|
||||
allowed = STATE_TRANSITIONS[JobStatus.COMPLETE]
|
||||
assert JobStatus.LYRICS_COMPLETE in allowed
|
||||
@@ -1,381 +0,0 @@
|
||||
"""
|
||||
Tests for the cleanup-distribution endpoint in jobs.py.
|
||||
|
||||
Verifies:
|
||||
- GDrive cleanup uses tracked file IDs from state_data when available (fast path)
|
||||
- GDrive cleanup falls back to brand_code search when gdrive_files is empty (fallback path)
|
||||
- Brand code is recycled ONLY after both Dropbox AND GDrive are confirmed clean
|
||||
- Brand code is NOT recycled when GDrive cleanup fails or is skipped
|
||||
- Endpoint returns correct status for each distribution service
|
||||
|
||||
The cleanup-distribution endpoint is used by the E2E happy-path test (Step 12)
|
||||
to remove test job files from YouTube, Dropbox, and Google Drive after the test.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime, UTC
|
||||
|
||||
from backend.api.routes.jobs import router
|
||||
from backend.api.dependencies import require_admin, require_auth, AuthResult, UserType
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# ─── Test App ────────────────────────────────────────────────────────────────
|
||||
|
||||
def get_mock_admin():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
app.dependency_overrides[require_auth] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
# ─── Fixtures ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_job(
|
||||
*,
|
||||
brand_code="NOMAD-1271",
|
||||
gdrive_files=None,
|
||||
gdrive_folder_id="root-folder-id",
|
||||
dropbox_path="/Tracks-PublicShare",
|
||||
artist="piri",
|
||||
title="dog",
|
||||
):
|
||||
"""Make a mock Job in COMPLETE state with the given distribution data."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-id"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.artist = artist
|
||||
job.title = title
|
||||
job.dropbox_path = dropbox_path
|
||||
job.gdrive_folder_id = gdrive_folder_id
|
||||
job.state_data = {
|
||||
"brand_code": brand_code,
|
||||
"gdrive_files": gdrive_files if gdrive_files is not None else {},
|
||||
}
|
||||
return job
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fast Path (tracked file IDs) ───────────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveTrackedFileIDs:
|
||||
"""GDrive cleanup uses tracked file IDs from state_data when available."""
|
||||
|
||||
def test_gdrive_cleanup_uses_tracked_file_ids(self, client):
|
||||
"""When gdrive_files has file IDs, delete_files is called with those IDs."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id-mp4": True, "file-id-cdg": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have used the tracked file IDs (fast path)
|
||||
mock_gdrive.delete_files.assert_called_once_with(["file-id-mp4", "file-id-cdg"])
|
||||
# Should NOT have searched by brand code
|
||||
mock_gdrive.find_files_by_brand_code.assert_not_called()
|
||||
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_gdrive_cleanup_reports_partial_when_some_deletes_fail(self, client):
|
||||
"""When some file deletes fail, status is 'partial'."""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # This one failed
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "partial"
|
||||
|
||||
|
||||
# ─── GDrive Cleanup — Fallback Path (brand_code search) ──────────────────────
|
||||
|
||||
class TestCleanupDistributionGDriveFallback:
|
||||
"""GDrive cleanup searches by brand_code when gdrive_files is empty."""
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_empty(self, client):
|
||||
"""When gdrive_files={}, search GDrive by brand_code and delete found files."""
|
||||
job = _make_job(gdrive_files={}) # Empty — simulates old jobs / silently-failed uploads
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
# find_files_by_brand_code returns file IDs found by searching GDrive
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["old-file-id-cdg", "old-file-id-mp4"]
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"old-file-id-cdg": True,
|
||||
"old-file-id-mp4": True,
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Should have searched by brand code (fallback path)
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once_with(
|
||||
"root-folder-id", "NOMAD-1271"
|
||||
)
|
||||
# Should have deleted the found files
|
||||
mock_gdrive.delete_files.assert_called_once()
|
||||
assert data["gdrive"]["status"] == "success"
|
||||
|
||||
def test_falls_back_to_brand_code_search_when_gdrive_files_none(self, client):
|
||||
"""When gdrive_files not in state_data (old job), search by brand_code."""
|
||||
job = _make_job(gdrive_files=None)
|
||||
job.state_data = {"brand_code": "NOMAD-1271"} # No gdrive_files key at all
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = ["legacy-file-id"]
|
||||
mock_gdrive.delete_files.return_value = {"legacy-file-id": True}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_gdrive.find_files_by_brand_code.assert_called_once()
|
||||
|
||||
def test_reports_skipped_when_no_files_found_by_brand_code(self, client):
|
||||
"""When brand_code search finds nothing, GDrive status is 'skipped'."""
|
||||
job = _make_job(gdrive_files={})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # Nothing found
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["gdrive"]["status"] == "skipped"
|
||||
assert "no files found" in data["gdrive"]["reason"]
|
||||
|
||||
|
||||
# ─── Brand Code Recycling — Gated on GDrive Success ──────────────────────────
|
||||
|
||||
class TestCleanupDistributionBrandCodeRecycling:
|
||||
"""Brand code is recycled only after BOTH Dropbox AND GDrive are confirmed clean."""
|
||||
|
||||
def test_brand_code_recycled_when_both_dropbox_and_gdrive_cleaned(self, client):
|
||||
"""Brand code is recycled when Dropbox delete succeeds and GDrive cleanup succeeds."""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {"file-id": True} # GDrive success
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should be recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_cleanup_partial(self, client):
|
||||
"""Brand code is NOT recycled when GDrive delete only partially succeeded.
|
||||
|
||||
If GDrive still has files with this brand code, recycling would allow a new
|
||||
job to get the same brand code, creating a duplicate in the public share.
|
||||
"""
|
||||
job = _make_job(gdrive_files={"mp4": "file-id-mp4", "cdg": "file-id-cdg"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True # Dropbox success
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.delete_files.return_value = {
|
||||
"file-id-mp4": True,
|
||||
"file-id-cdg": False, # CDG file still on GDrive
|
||||
}
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Brand code should NOT be recycled because GDrive still has a file
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
# recycled_brand_code key should be absent (recycling never attempted)
|
||||
assert "recycled_brand_code" not in data.get("dropbox", {})
|
||||
|
||||
def test_brand_code_not_recycled_when_gdrive_not_configured(self, client):
|
||||
"""Brand code is NOT recycled when GDrive is not configured.
|
||||
|
||||
Without GDrive credentials, we cannot confirm that GDrive was cleaned.
|
||||
A previous upload may have succeeded (e.g., different credentials rotation).
|
||||
"""
|
||||
job = _make_job(gdrive_files={"cdg": "file-id"})
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = False # GDrive not configured
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
# Brand code NOT recycled — GDrive might still have files
|
||||
mock_brand_service.recycle_brand_code.assert_not_called()
|
||||
|
||||
def test_brand_code_recycled_when_gdrive_finds_nothing_to_delete(self, client):
|
||||
"""Brand code IS recycled when GDrive search finds nothing (already clean)."""
|
||||
job = _make_job(gdrive_files={}) # Empty — no tracked IDs
|
||||
|
||||
mock_dropbox = Mock()
|
||||
mock_dropbox.is_configured = True
|
||||
mock_dropbox.delete_folder.return_value = True
|
||||
|
||||
mock_gdrive = Mock()
|
||||
mock_gdrive.is_configured = True
|
||||
mock_gdrive.find_files_by_brand_code.return_value = [] # GDrive already clean
|
||||
|
||||
mock_brand_service = Mock()
|
||||
|
||||
with patch("backend.api.routes.jobs.job_manager") as mock_jm, \
|
||||
patch("backend.services.dropbox_service.get_dropbox_service", return_value=mock_dropbox), \
|
||||
patch("backend.services.gdrive_service.get_gdrive_service", return_value=mock_gdrive), \
|
||||
patch("backend.services.brand_code_service.BrandCodeService") as mock_bcs_class, \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service", return_value=mock_brand_service):
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.delete_job.return_value = None
|
||||
mock_bcs_class.parse_brand_code.return_value = ("NOMAD", 1271)
|
||||
|
||||
response = client.post("/api/jobs/test-job-id/cleanup-distribution")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# GDrive was confirmed clean (nothing found), so brand code IS recycled
|
||||
mock_brand_service.recycle_brand_code.assert_called_once()
|
||||
assert data["dropbox"].get("recycled_brand_code") is True
|
||||
@@ -1,321 +0,0 @@
|
||||
"""
|
||||
Integration tests for the combined review flow.
|
||||
|
||||
These tests verify that corrections made during human review survive the full flow:
|
||||
1. User edits lyrics in LyricsAnalyzer
|
||||
2. Corrections saved via POST /api/jobs/{job_id}/corrections
|
||||
3. User navigates to InstrumentalSelector
|
||||
4. InstrumentalSelector fetches via GET /api/review/{job_id}/correction-data
|
||||
5. Corrections are included in final submission
|
||||
6. render_video_worker uses the corrected data
|
||||
|
||||
The key invariant: If corrections_updated.json exists, the API must return its
|
||||
contents, not the original corrections.json.
|
||||
"""
|
||||
import pytest
|
||||
import json
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from datetime import datetime
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
class TestGetCorrectionDataReturnsUpdatedCorrections:
|
||||
"""Test that get_correction_data returns updated corrections when available.
|
||||
|
||||
This is the critical fix for the bug where user's lyrics corrections were
|
||||
being ignored because InstrumentalSelector was fetching original corrections.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job(self):
|
||||
"""Create a mock job in AWAITING_REVIEW state."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-123"
|
||||
job.status = JobStatus.AWAITING_REVIEW
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
job.input_media_gcs_path = "jobs/test-job-123/input/audio.flac"
|
||||
job.file_urls = {
|
||||
"lyrics": {
|
||||
"corrections": "jobs/test-job-123/lyrics/corrections.json",
|
||||
},
|
||||
"stems": {},
|
||||
"analysis": {},
|
||||
}
|
||||
job.state_data = {}
|
||||
job.style_params_gcs_path = None
|
||||
job.style_assets = {}
|
||||
return job
|
||||
|
||||
@pytest.fixture
|
||||
def original_corrections(self):
|
||||
"""Original corrections from lyrics processing (before user edits)."""
|
||||
return {
|
||||
"corrected_segments": [
|
||||
{"id": 1, "text": "Hello world"}, # Original: "Hello world"
|
||||
],
|
||||
"corrections": [],
|
||||
"metadata": {"source": "original"},
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def updated_corrections(self):
|
||||
"""Updated corrections after user edits."""
|
||||
return {
|
||||
"corrected_segments": [
|
||||
{"id": 1, "text": "Hello beautiful world"}, # User changed this!
|
||||
],
|
||||
"corrections": [
|
||||
{"id": 1, "type": "edit", "original": "Hello world", "corrected": "Hello beautiful world"}
|
||||
],
|
||||
"metadata": {"source": "updated"},
|
||||
}
|
||||
|
||||
def test_returns_updated_corrections_when_file_exists(
|
||||
self, mock_job, original_corrections, updated_corrections
|
||||
):
|
||||
"""Verify endpoint returns updated corrections when corrections_updated.json exists.
|
||||
|
||||
This is the main test for the bug fix.
|
||||
"""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
|
||||
# Add corrections_updated to file_urls
|
||||
mock_job.file_urls["lyrics"]["corrections_updated"] = "jobs/test-job-123/lyrics/corrections_updated.json"
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService:
|
||||
|
||||
# Setup mocks
|
||||
job_manager = MockJobManager.return_value
|
||||
job_manager.get_job.return_value = mock_job
|
||||
|
||||
storage = MockStorageService.return_value
|
||||
# Return True for corrections_updated.json
|
||||
storage.file_exists.return_value = True
|
||||
# Return updated corrections (not original)
|
||||
storage.download_json.return_value = updated_corrections.copy()
|
||||
storage.generate_signed_url.return_value = "https://signed-url.com"
|
||||
|
||||
# Call the endpoint (synchronously for testing)
|
||||
import asyncio
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Verify it downloaded from corrections_updated, not corrections
|
||||
storage.download_json.assert_called_once()
|
||||
downloaded_path = storage.download_json.call_args[0][0]
|
||||
assert "corrections_updated" in downloaded_path, \
|
||||
f"Expected to download corrections_updated.json, got: {downloaded_path}"
|
||||
|
||||
# Verify the returned data has the user's edits
|
||||
assert result["corrected_segments"][0]["text"] == "Hello beautiful world"
|
||||
assert result["metadata"]["source"] == "updated"
|
||||
|
||||
def test_falls_back_to_original_when_no_updates(
|
||||
self, mock_job, original_corrections
|
||||
):
|
||||
"""Verify endpoint falls back to original corrections when no updates exist."""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService:
|
||||
|
||||
# Setup mocks
|
||||
job_manager = MockJobManager.return_value
|
||||
job_manager.get_job.return_value = mock_job
|
||||
|
||||
storage = MockStorageService.return_value
|
||||
# Return False for corrections_updated.json (doesn't exist)
|
||||
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
|
||||
# Return original corrections
|
||||
storage.download_json.return_value = original_corrections.copy()
|
||||
storage.generate_signed_url.return_value = "https://signed-url.com"
|
||||
|
||||
# Call the endpoint
|
||||
import asyncio
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Verify it downloaded from corrections.json (original)
|
||||
storage.download_json.assert_called_once()
|
||||
downloaded_path = storage.download_json.call_args[0][0]
|
||||
assert "corrections.json" in downloaded_path
|
||||
|
||||
# Verify the returned data is the original
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
|
||||
def test_checks_direct_gcs_path_when_not_in_file_urls(
|
||||
self, mock_job, updated_corrections
|
||||
):
|
||||
"""Verify endpoint checks direct GCS path for corrections_updated.json."""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
|
||||
# Remove corrections_updated from file_urls (simulates older job)
|
||||
# But the file exists in GCS from a previous save
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService:
|
||||
|
||||
# Setup mocks
|
||||
job_manager = MockJobManager.return_value
|
||||
job_manager.get_job.return_value = mock_job
|
||||
|
||||
storage = MockStorageService.return_value
|
||||
# Return True for direct path check of corrections_updated.json
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = updated_corrections.copy()
|
||||
storage.generate_signed_url.return_value = "https://signed-url.com"
|
||||
|
||||
# Call the endpoint
|
||||
import asyncio
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Verify it checked for corrections_updated.json via direct path
|
||||
file_exists_calls = storage.file_exists.call_args_list
|
||||
checked_paths = [call[0][0] for call in file_exists_calls]
|
||||
assert any("corrections_updated" in path for path in checked_paths), \
|
||||
f"Expected to check for corrections_updated.json, checked: {checked_paths}"
|
||||
|
||||
def test_falls_back_when_file_urls_has_stale_corrections_updated(
|
||||
self, mock_job, original_corrections
|
||||
):
|
||||
"""Verify endpoint falls back to original when corrections_updated in file_urls but file deleted.
|
||||
|
||||
This handles the edge case where:
|
||||
1. User saved corrections (corrections_updated added to file_urls)
|
||||
2. Admin reset job or file was deleted
|
||||
3. corrections_updated.json no longer exists in GCS
|
||||
4. Endpoint should fall back to original corrections.json
|
||||
"""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
|
||||
# Add corrections_updated to file_urls (stale reference)
|
||||
mock_job.file_urls["lyrics"]["corrections_updated"] = "jobs/test-job-123/lyrics/corrections_updated.json"
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService:
|
||||
|
||||
job_manager = MockJobManager.return_value
|
||||
job_manager.get_job.return_value = mock_job
|
||||
|
||||
storage = MockStorageService.return_value
|
||||
# corrections_updated.json does NOT exist (stale reference)
|
||||
# but corrections.json does
|
||||
def file_exists_check(path):
|
||||
return "corrections_updated" not in path
|
||||
storage.file_exists.side_effect = file_exists_check
|
||||
storage.download_json.return_value = original_corrections.copy()
|
||||
storage.generate_signed_url.return_value = "https://signed-url.com"
|
||||
|
||||
import asyncio
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Should fall back to original corrections
|
||||
downloaded_path = storage.download_json.call_args[0][0]
|
||||
assert "corrections.json" in downloaded_path or "corrections_updated" not in downloaded_path
|
||||
|
||||
# Verify original data was returned
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
|
||||
|
||||
class TestCorrectionDataPreservation:
|
||||
"""Test that correction data is preserved through the full flow."""
|
||||
|
||||
def test_post_corrections_saves_to_corrections_updated(self):
|
||||
"""Verify POST /api/jobs/{job_id}/corrections saves to corrections_updated.json."""
|
||||
# This documents the expected behavior of the jobs.py endpoint
|
||||
# The actual implementation saves to f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
job_id = "test-job-123"
|
||||
expected_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
assert "corrections_updated" in expected_gcs_path
|
||||
assert job_id in expected_gcs_path
|
||||
|
||||
def test_complete_review_submits_correction_data(self):
|
||||
"""Verify POST /api/review/{job_id}/complete receives and saves corrections."""
|
||||
# This documents what data complete_review expects
|
||||
expected_payload = {
|
||||
"corrections": [{"id": 1, "type": "edit"}],
|
||||
"corrected_segments": [{"id": 1, "text": "corrected"}],
|
||||
"instrumental_selection": "with_backing", # Required
|
||||
}
|
||||
|
||||
# instrumental_selection is required
|
||||
assert "instrumental_selection" in expected_payload
|
||||
# corrections data should be included
|
||||
assert "corrections" in expected_payload
|
||||
assert "corrected_segments" in expected_payload
|
||||
|
||||
|
||||
class TestRenderVideoWorkerUsesCorrectedData:
|
||||
"""Test that render_video_worker uses the corrected data.
|
||||
|
||||
This verifies that the fix is consistent with render_video_worker's behavior.
|
||||
"""
|
||||
|
||||
def test_render_worker_checks_corrections_updated_first(self):
|
||||
"""Document that render_video_worker checks corrections_updated first.
|
||||
|
||||
From render_video_worker.py lines 128-142, the worker:
|
||||
1. Checks file_urls.lyrics.corrections_updated
|
||||
2. Falls back to file_urls.lyrics.corrections
|
||||
3. Falls back to direct GCS paths
|
||||
|
||||
This is the same pattern the API endpoint should use.
|
||||
"""
|
||||
# Document the expected check order
|
||||
check_order = [
|
||||
"file_urls.lyrics.corrections_updated",
|
||||
"file_urls.lyrics.corrections",
|
||||
"jobs/{job_id}/lyrics/corrections_updated.json",
|
||||
"jobs/{job_id}/lyrics/corrections.json",
|
||||
]
|
||||
|
||||
# corrections_updated must be checked before corrections
|
||||
updated_index = next(i for i, p in enumerate(check_order) if "corrections_updated" in p)
|
||||
original_index = next(i for i, p in enumerate(check_order) if "corrections.json" in p or
|
||||
(p == "file_urls.lyrics.corrections"))
|
||||
|
||||
# Only check the file_urls entries (indices 0 and 1)
|
||||
assert updated_index < 2, "corrections_updated should be in top 2 checks"
|
||||
|
||||
def test_render_worker_merges_corrections(self):
|
||||
"""Document that render_video_worker merges corrections.
|
||||
|
||||
From render_video_worker.py lines 159-175:
|
||||
- Downloads original corrections.json
|
||||
- If corrections_updated.json exists, downloads and merges
|
||||
- Merged data has user's corrections with original metadata
|
||||
"""
|
||||
original_data = {
|
||||
"original_segments": [{"id": 1}],
|
||||
"corrected_segments": [{"id": 1, "text": "original"}],
|
||||
"corrections": [],
|
||||
"metadata": {"preserved": True},
|
||||
}
|
||||
|
||||
updated_data = {
|
||||
"corrected_segments": [{"id": 1, "text": "user-edited"}],
|
||||
"corrections": [{"id": 1, "type": "edit"}],
|
||||
}
|
||||
|
||||
# Apply merge logic (same as render_video_worker.py lines 169-172)
|
||||
if 'corrections' in updated_data:
|
||||
original_data['corrections'] = updated_data['corrections']
|
||||
if 'corrected_segments' in updated_data:
|
||||
original_data['corrected_segments'] = updated_data['corrected_segments']
|
||||
|
||||
# Verify merge result
|
||||
assert original_data['corrected_segments'][0]['text'] == "user-edited"
|
||||
assert original_data['corrections'][0]['type'] == "edit"
|
||||
# Metadata and original_segments preserved
|
||||
assert original_data['metadata']['preserved'] is True
|
||||
assert original_data['original_segments'][0]['id'] == 1
|
||||
Loaded 100 of 1153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user