Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️ 38498461ae Merge branch 'main' into add-gdrive-validator-plan 2026-02-28 16:42:52 -05:00
Andrew Beveridge bea0df8ab3 Added docs/archive/2026-02-28-gdrive-validator-email-alerts-plan.md 2026-02-28 16:42:28 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 e102a2bf36 Fix event loop blocking in audio search endpoints (#422)
@coderabbitai ignore

## Summary
- Fix `/api/audio-search/{job_id}/select` taking 20-36s to respond
(should be <1s) and `/api/audio-search/search` sometimes taking 25-47s
- Root cause: async endpoints called sync methods that create new event
loops via `loop.run_until_complete()`, blocking the FastAPI event loop
- RED/OPS and Spotify download paths now call FlacfetchClient async
methods directly (matching YouTubeDownloadService pattern)
- Generic downloads use `asyncio.to_thread()` as safe fallback
- Search endpoint uses `search_async()` instead of sync `search()`
- Fixed `InsufficientCreditsError` occasionally returning 500 instead of
402
- Added fail-fast guard for missing `remote_search_id` in torrent
download fallback

## Test plan
- [x] 14 new tests covering async download paths, error handling, and
exception propagation
- [x] All 2099 tests pass (1 pre-existing unrelated failure in test
ordering)
- [x] CodeRabbit review: 1 finding fixed (missing remote_search_id
guard)
- [ ] Deploy to prod and verify `/select` latency drops from 20-36s to
<1s
- [ ] Verify InsufficientCreditsError returns 402 not 500

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 16:41:59 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 18fa1aa03f Fix gdrive-validator scheduler IAM + API key whitespace (#420)
@coderabbitai ignore

## Summary

- Add `roles/run.invoker` for the validator's own service account on the
Cloud Run service — Gen2 functions need this for Cloud Scheduler's OIDC
token to be accepted
- Strip whitespace from Pushbullet and SendGrid API key env vars
(handles trailing newlines in Secret Manager values)

This codifies the manual gcloud fix from #412 into Pulumi IaC and closes
that PR.

## Already deployed

- Pulumi applied: IAM binding created
- Cloud function redeployed with `.strip()` fix

## Test plan

- [x] `pulumi preview` — clean, 1 create
- [x] `pulumi up` — applied successfully
- [x] Cloud function redeployed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 01:14:23 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 e0c8645fea Add email alerts, manual trigger, and post-job check to GDrive validator (#419)
@coderabbitai ignore

## Summary

- **Email notifications via SendGrid** — replaces Pushbullet as the
primary notification channel for the GDrive validator cloud function.
Pushbullet kept as secondary fallback.
- **Post-job trigger** — the backend orchestrator now triggers GDrive
validation after each job that uploads to the public share, catching
duplicates within minutes instead of up to 24 hours.
- **Manual CLI** — `python scripts/check_public_share.py` for on-demand
validation checks with formatted output and `--json` flag.
- **Comprehensive docs** — `docs/GDRIVE-VALIDATOR.md` with architecture,
configuration, troubleshooting, and operational reference.

Motivated by the NOMAD-1271 duplicate brand code incident where
daily-only checks left a duplicate undetected for ~24 hours.

## Changes

| File | Change |
|------|--------|
| `infrastructure/functions/gdrive_validator/main.py` | Add
`send_email_notification()` via SendGrid, unified `send_notification()`
sends both email + Pushbullet |
| `infrastructure/functions/gdrive_validator/requirements.txt` | Add
`sendgrid>=6.0.0` |
| `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid
secret + email env vars |
| `infrastructure/__main__.py` | Add SendGrid secret to function,
backend SA invoker IAM (Cloud Functions + Cloud Run) |
| `infrastructure/modules/secrets.py` | Add `gdrive-validator-url`
secret |
| `.github/workflows/ci.yml` | Add `GDRIVE_VALIDATOR_URL` to Cloud Run
deploy secrets |
| `backend/services/gdrive_validator_client.py` | **New**: HTTP client
with OIDC auth, fire-and-forget pattern |
| `backend/workers/video_worker_orchestrator.py` | Add Stage 6:
post-distribution GDrive validation (only when `gdrive_folder_id` set) |
| `scripts/check_public_share.py` | **New**: CLI tool for manual
validation checks |
| `docs/GDRIVE-VALIDATOR.md` | **New**: Comprehensive validator
documentation |
| `pyproject.toml` | Version bump to 0.119.9 |

## Already deployed

- Pulumi infrastructure applied (IAM bindings, secrets, function config)
- Cloud Function redeployed with SendGrid support
- `gdrive-validator-url` secret set in Secret Manager
- Tested via `check_public_share.py` — validated 3,608 files, email sent
successfully

## Test plan

- [x] `make test` — 170 passed, 3 skipped (1 pre-existing failure in
credit-enforcement unrelated to this PR)
- [x] `pulumi preview` — clean, 3 creates + 1 update
- [x] `pulumi up` — applied successfully
- [x] Cloud Function deployed and tested end-to-end
- [x] `python scripts/check_public_share.py` — formatted output works
- [x] `python scripts/check_public_share.py --json` — JSON output works
- [x] Email received at gen@nomadkaraoke.com (notification_sent: true)
- [ ] Post-job trigger: will verify on next job completion (backend
needs redeploy via CI merge)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 01:05:16 -05:00
Andrew Beveridge ☄️andClaude c7b7f4bee5 fix: gate brand code recycling on full GDrive cleanup confirmation (#418)
## Summary

- Brand code `NOMAD-1271` was reused for a real song (Hot Mulligan - Pop
Shuvit) while old E2E test job files still existed in Google Drive,
creating a duplicate in the public share
- Root cause: `cleanup-distribution` endpoint had two bugs that allowed
brand codes to be recycled before GDrive was confirmed clean

## Root Causes

1. **Empty dict was falsy**: `if gdrive_files:` skips cleanup when
`gdrive_files = {}` (empty dict). This happened when GDrive uploads
silently failed (pre-PR #417), so test job files accumulated in GDrive
without ever being cleaned
2. **Brand code recycled too early**: Brand code was recycled
immediately after Dropbox cleanup succeeded, *without* confirming GDrive
was also clean — a new job could claim the recycled code while old
GDrive files still existed

## Changes

- **`gdrive_service.py`**: Added `find_files_by_brand_code()` — searches
CDG/, MP4/, MP4-720p/ subfolders by brand code prefix as a fallback when
tracked file IDs aren't available (old jobs, or jobs where upload failed
silently). Raises `RuntimeError` if any subfolder search fails so
callers can't misread an incomplete search as "GDrive is clean"
- **`jobs.py` (`cleanup-distribution`)**: Now uses tracked file IDs
(fast path) OR falls back to brand_code search; brand code is only
recycled after **both** Dropbox AND GDrive are confirmed clean. Fixed
`method` key being lost when results dict was replaced (use local
variable instead of interim mutation)
- **`scripts/cleanup_test_job_gdrive.py`**: Remediation script to delete
existing stranded test job files from GDrive

## Testing

- 41 tests passing, 94% coverage on `gdrive_service.py`
- New `TestDeleteFile` class (5 tests for `delete_file`/`delete_files` —
previously uncovered)
- New `test_cleanup_distribution.py` (9 tests covering fast path,
fallback, and brand code gating logic)
- Updated error handling test to verify `RuntimeError` is raised (not
swallowed) on subfolder search failure
- [x] CodeRabbit CLI review completed, 2 findings fixed

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-27 17:35:50 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 0f5ddb0092 Fix silent Google Drive upload failures with retry + alerting (#417)
## Summary
- Added tenacity retry with connection reset to Google Drive API calls
(`get_or_create_folder`, `upload_file`, `delete_file`) to handle stale
HTTP connections on idle Cloud Run containers
- Added `distribution_warnings` field to `OrchestratorResult` and
`_handle_native_distribution()` to track non-fatal upload failures
(YouTube, Dropbox, GDrive)
- Added Pushbullet notification when distribution uploads fail, so
operator is alerted immediately
- Added backfill script (`scripts/backfill_gdrive_uploads.py`) for
affected jobs - already run successfully for 12 affected jobs
- Updated docs: LESSONS-LEARNED.md and TROUBLESHOOTING.md with GDrive
stale connection pattern

## Context
Every GDrive upload silently failed for ~1 month (64 errors, 12+
affected jobs). The root cause was the singleton `GoogleDriveService`
caching its HTTP connection, which went stale when Cloud Run containers
sat idle between jobs. The orchestrator caught all exceptions and
continued, so jobs completed with `gdrive_files: {}` and no alert was
sent.

## Test plan
- [x] 5 new retry behavior tests in `test_gdrive_service.py`
(BrokenPipeError, SSLError, give up after 3, service reset, no retry on
non-transient)
- [x] 3 new distribution warnings tests in
`test_video_worker_orchestrator.py`
- [x] All 76 affected tests pass
- [x] Full backend test suite passes
- [x] Backfill script already run successfully for all 12 affected jobs

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:47:30 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 23a8b0fb98 Fix missing CDG ZIP packages: fail-fast validation + remediation (#416)
## Summary

- **Systemic fix**: Orchestrator now validates CDG/TXT outputs after
packaging, before encoding. If `enable_cdg=True` but no CDG ZIP was
produced, the job fails immediately with a clear error instead of
silently completing without the package.
- **Remediation**: Created `scripts/regenerate_cdg.py` to regenerate and
distribute CDG/TXT packages for affected jobs (5b6aba25, 5161b069).
Packages uploaded to GCS, GDrive, and Dropbox.
- **Root cause**: Before b671b83f, `instrumental_selection: custom` had
no case in the orchestrator config builder — fell through to "Backing"
suffix, CDG generator looked for wrong filename, `FileNotFoundError` was
silently caught.

## Changes

| File | Change |
|------|--------|
| `backend/workers/video_worker_orchestrator.py` | Post-packaging
validation + LRC-missing check update |
| `backend/tests/test_video_worker_orchestrator.py` | 8 new tests in
`TestPackagingValidation` |
| `scripts/regenerate_cdg.py` | One-time remediation script (GCS +
Firestore + GDrive + Dropbox) |
| `docs/LESSONS-LEARNED.md` | Pipeline stage validation pattern |
| `docs/TROUBLESHOOTING.md` | CDG missing recovery runbook |
| `docs/README.md` | Updated recent changes |
| `pyproject.toml` | Version 0.119.6 → 0.119.7 |

## Test plan

- [x] 8 new tests in `TestPackagingValidation` (CDG fails, TXT fails,
combined CDG+TXT fails, CDG succeeds, CDG disabled, LRC missing raises
with CDG, LRC missing raises with TXT, LRC missing skips without CDG)
- [x] All 2062+ backend tests pass
- [x] Remediation script run successfully for both affected jobs
- [x] Verified CDG/TXT ZIPs in GCS, Firestore, GDrive, and Dropbox

> **CodeRabbit note**: 1 finding (unreachable `else` branch in
`_run_packaging` LRC check) — kept as defensive code since the test
`test_lrc_missing_skips_when_cdg_disabled` exercises this path directly.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:13:22 +00:00
Andrew Beveridge ☄️ 028e9f40d4 docs: add TROUBLESHOOTING.md with encoding recovery runbook (#415)
Follows up on #414 — that PR got merged before the force-push landed, so
TROUBLESHOOTING.md was missing.

- Creates `docs/TROUBLESHOOTING.md` with the encoding recovery runbook
- Trims the verbose block from CLAUDE.md down to a one-line pointer
- Adds TROUBLESHOOTING.md to the quick reference table in CLAUDE.md

Docs-only, no code changes.

<!-- @coderabbitai ignore -->
2026-02-27 12:53:45 -05:00
Andrew Beveridge ☄️ c04397d1d1 docs: add stuck encoding job recovery procedure (#414)
Adds a clear recovery procedure to CLAUDE.md for the known scenario
where a Cloud Run deployment kills a poller mid-encoding, leaving a job
stuck at `encoding` status.

**What's added:**
- Diagnosis steps (health endpoint, GCE worker status check)
- Recovery command (re-trigger video worker)
- Note that SSH restart is no longer needed since PR #413 made `/encode`
idempotent

This is purely documentation — no code changes.

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-02-27 12:39:03 -05:00
30 changed files with 3938 additions and 273 deletions

No files matched your search

+1 -1
View File
@@ -1243,7 +1243,7 @@ jobs:
--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"
--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"
- name: Verify deployment and version
run: |
+8 -5
View File
@@ -19,6 +19,7 @@
| **Testing & code quality** | `docs/TESTING.md` |
| API reference | `docs/API.md` |
| Past learnings | `docs/LESSONS-LEARNED.md` |
| **Operational runbooks** | `docs/TROUBLESHOOTING.md` |
| **Product communication** | `docs/PRODUCT-COMMUNICATION-GUIDE.md` |
| Brand style guide | `docs/BRAND-STYLE-GUIDE.md` |
@@ -128,15 +129,17 @@ EOF
### GCE Encoding Worker
```bash
# 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"
# Check health
# 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)
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).
### What Doesn't Work
- `gcloud auth print-identity-token` - Wrong token type for internal endpoints
- Cloud Tasks without proper service account - Gets 401 from Cloud Run
+56 -22
View File
@@ -35,6 +35,7 @@ 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,
@@ -382,8 +383,9 @@ async def _download_audio_and_trigger_workers(
raise DownloadError(f"YouTube download failed: {e}")
elif source_name in ['RED', 'OPS']:
# Torrent sources - must use remote flacfetch
if not audio_search_service.is_remote_enabled():
# 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."
@@ -393,31 +395,48 @@ async def _download_audio_and_trigger_workers(
if source_id:
logger.info(f"Torrent download via download_by_id: {source_name} ID={source_id}")
result = audio_search_service.download_by_id(
download_id = await flacfetch_client.download_by_id(
source_name=source_name,
source_id=source_id,
output_dir="",
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")
result = audio_search_service.download(
download_id = await flacfetch_client.download(
search_id=remote_search_id,
result_index=selection_index,
output_dir="",
gcs_path=gcs_destination,
remote_search_id=remote_search_id,
)
# Extract GCS path from result
audio_gcs_path = _extract_gcs_path(result.filepath)
filename = os.path.basename(result.filepath)
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 audio_search_service
if not audio_search_service.is_remote_enabled():
# 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."
@@ -426,25 +445,40 @@ async def _download_audio_and_trigger_workers(
gcs_destination = f"uploads/{job_id}/audio/"
logger.info(f"Spotify download: source_id={source_id}")
result = audio_search_service.download_by_id(
download_id = await flacfetch_client.download_by_id(
source_name=source_name,
source_id=source_id,
output_dir="",
download_url=download_url,
gcs_path=gcs_destination,
)
audio_gcs_path = _extract_gcs_path(result.filepath)
filename = os.path.basename(result.filepath)
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
# 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 = audio_search_service.download(
result = await asyncio.to_thread(
audio_search_service.download,
result_index=selection_index,
output_dir=temp_dir,
remote_search_id=remote_search_id,
@@ -494,7 +528,7 @@ async def _download_audio_and_trigger_workers(
worker_service.trigger_lyrics_worker(job_id)
)
except DownloadError as e:
except (DownloadError, FlacfetchServiceError) as e:
logger.error(f"Download failed for job {job_id}: {e}")
job_manager.fail_job(job_id, f"Audio download failed: {e}")
except Exception as e:
@@ -734,7 +768,7 @@ async def search_audio(
audio_search_service = get_audio_search_service()
try:
search_results = audio_search_service.search(body.artist, body.title)
search_results = await audio_search_service.search_async(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(
@@ -867,9 +901,9 @@ async def search_audio(
except HTTPException:
raise
except (InsufficientCreditsError, RateLimitExceededError):
raise
except Exception as e:
if isinstance(e, (InsufficientCreditsError, RateLimitExceededError)):
raise
logger.error(f"Error in audio search: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
+80 -23
View File
@@ -1655,6 +1655,7 @@ async def cleanup_distribution(
# Clean up Dropbox
brand_code = state_data.get('brand_code')
dropbox_path = getattr(job, 'dropbox_path', None)
dropbox_cleaned = False
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
@@ -1664,22 +1665,11 @@ async def cleanup_distribution(
folder_name = f"{brand_code} - {base_name}"
full_path = f"{dropbox_path}/{folder_name}"
success = dropbox.delete_folder(full_path)
dropbox_cleaned = success
results["dropbox"] = {
"status": "success" if success else "failed",
"path": full_path
}
# Recycle the brand code number so it can be reused
if success:
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)
results["dropbox"]["recycled_brand_code"] = True
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["dropbox"]["recycled_brand_code"] = False
else:
results["dropbox"] = {"status": "failed", "reason": "Dropbox credentials not configured"}
except Exception as e:
@@ -1687,25 +1677,92 @@ async def cleanup_distribution(
results["dropbox"] = {"status": "error", "error": str(e)}
# Clean up Google Drive
# Use tracked file IDs if available; otherwise fall back to searching by brand code.
# This handles old jobs where gdrive_files was not persisted (e.g., uploaded before
# file ID tracking was implemented, or when GDrive upload silently failed and a
# previous test run left files behind).
gdrive_files = state_data.get('gdrive_files')
if gdrive_files:
gdrive_folder_id = getattr(job, 'gdrive_folder_id', None)
gdrive_cleaned = False
if gdrive_files or (gdrive_folder_id and brand_code):
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
# gdrive_files is a dict like {"mp4": "file_id", "mp4_720p": "file_id", "cdg": "file_id"}
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results
}
file_ids: list = []
gdrive_method = None # track how files were located for response
if gdrive_files and isinstance(gdrive_files, dict):
# Fast path: delete using tracked file IDs from state_data
file_ids = [v for v in gdrive_files.values() if v]
logger.info(
f"GDrive cleanup for job {job_id}: "
f"using {len(file_ids)} tracked file IDs"
)
if not file_ids and gdrive_folder_id and brand_code:
# Fallback: search by brand code prefix in CDG/, MP4/, MP4-720p/ subfolders.
# Handles jobs where gdrive_files was not tracked (old jobs, or jobs where
# GDrive upload succeeded but file IDs were lost).
logger.info(
f"GDrive cleanup for job {job_id}: "
f"no tracked file IDs, searching by brand_code '{brand_code}'"
)
file_ids = gdrive.find_files_by_brand_code(gdrive_folder_id, brand_code)
gdrive_method = "brand_code_search"
if file_ids:
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
gdrive_cleaned = all_success
results["gdrive"] = {
"status": "success" if all_success else "partial",
"files": delete_results,
}
if gdrive_method:
results["gdrive"]["method"] = gdrive_method
else:
gdrive_cleaned = True # Nothing to delete
results["gdrive"] = {
"status": "skipped",
"reason": "no files found to delete",
}
else:
results["gdrive"] = {"status": "failed", "reason": "Google Drive credentials not configured"}
results["gdrive"] = {
"status": "failed",
"reason": "Google Drive credentials not configured",
}
except Exception as e:
logger.error(f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True)
logger.error(
f"Error cleaning up Google Drive for job {job_id}: {e}", exc_info=True
)
results["gdrive"] = {"status": "error", "error": str(e)}
else:
if not gdrive_folder_id:
results["gdrive"]["reason"] = "no gdrive_folder_id on job and no tracked file IDs"
# Recycle the brand code so it can be reused — but only after GDrive is confirmed clean.
# If we recycle before GDrive cleanup, a new job could claim the same brand code and
# collide with leftover files on GDrive (duplicate brand code in public share).
if dropbox_cleaned and brand_code and gdrive_cleaned:
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)
results["dropbox"]["recycled_brand_code"] = True
logger.info(f"Recycled brand code {brand_code} after full distribution cleanup")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
results["dropbox"]["recycled_brand_code"] = False
elif dropbox_cleaned and brand_code:
logger.warning(
f"Brand code {brand_code} NOT recycled: GDrive cleanup did not confirm success "
f"(gdrive_cleaned={gdrive_cleaned}). Brand code will remain reserved to prevent "
f"collisions with leftover GDrive files."
)
# Delete the job if requested
if delete_job:
+12 -9
View File
@@ -612,13 +612,13 @@ class AudioSearchService:
async def search_async(self, artist: str, title: str) -> List[AudioSearchResult]:
"""
Async version of search for use in async routes.
Note: Currently wraps sync search in executor. Future optimization
could make this fully async.
Runs the sync search in a thread executor to avoid blocking
the event loop.
"""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self.search, artist, title)
async def download_async(
self,
result_index: int,
@@ -630,10 +630,10 @@ class AudioSearchService:
"""
Async version of download for use in async routes.
Note: Currently wraps sync download in executor. Future optimization
could make this fully async.
Runs the sync download in a thread executor to avoid blocking
the event loop.
"""
loop = asyncio.get_event_loop()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None,
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
@@ -651,8 +651,11 @@ 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_event_loop()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None,
lambda: self.download_by_id(
+189 -66
View File
@@ -12,13 +12,19 @@ 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."""
@@ -33,6 +39,11 @@ 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:
@@ -127,6 +138,9 @@ 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
@@ -134,33 +148,41 @@ class GoogleDriveService:
Returns:
Folder ID
"""
logger.info(f"Looking for folder '{folder_name}' in parent {parent_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}")
# 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,
@@ -172,6 +194,9 @@ 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
@@ -183,49 +208,57 @@ class GoogleDriveService:
"""
from googleapiclient.http import MediaFileUpload
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}"
)
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}"
)
# 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,
@@ -308,6 +341,9 @@ 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
@@ -317,9 +353,17 @@ class GoogleDriveService:
logger.info(f"Deleting Google Drive file: {file_id}")
try:
self.service.files().delete(fileId=file_id).execute()
logger.info(f"Successfully deleted file: {file_id}")
return True
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
except Exception as e:
# Check if it's a 404 (already deleted)
if hasattr(e, 'resp') and e.resp.status == 404:
@@ -343,6 +387,85 @@ 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
@@ -0,0 +1,62 @@
"""
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
+14 -8
View File
@@ -115,6 +115,7 @@ class TestAudioSearchYouTubeFlow:
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"
@@ -132,16 +133,22 @@ class TestAudioSearchYouTubeFlow:
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
# Mock audio_search_service for torrent download
mock_audio_search_service = MagicMock()
mock_audio_search_service.is_remote_enabled = MagicMock(return_value=True)
mock_result = MagicMock()
mock_result.filepath = "gs://bucket/uploads/test/audio/test.flac"
mock_audio_search_service.download_by_id = MagicMock(return_value=mock_result)
# 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']
@@ -152,7 +159,6 @@ class TestAudioSearchYouTubeFlow:
'backend.api.routes.audio_search.worker_service',
mock_services['worker_service']
):
# 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,
@@ -162,8 +168,8 @@ class TestAudioSearchYouTubeFlow:
# YouTubeDownloadService should NOT be called for torrent
mock_youtube_service.download_by_id.assert_not_called()
# audio_search_service.download_by_id should be called instead
mock_audio_search_service.download_by_id.assert_called_once()
# FlacfetchClient.download_by_id should be called directly
mock_flacfetch.download_by_id.assert_called_once()
class TestDirectUrlSubmissionFlow:
+607 -89
View File
@@ -1173,58 +1173,60 @@ class TestAudioSearchApiRouteDownload:
def test_remote_download_passes_gcs_path(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""
Test that remote torrent downloads include GCS path for direct upload.
Test that remote torrent downloads use FlacfetchClient directly with GCS path.
This was the bug: we were calling download() without gcs_path for
torrent sources, causing flacfetch VM to return a local path that
Cloud Run couldn't access.
The route bypasses audio_search_service and calls flacfetch_client.download_by_id()
directly to avoid event loop blocking.
"""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
# Setup mock job with RED search result
# Setup mock job with RED search result (includes source_id for download_by_id path)
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Unwanted',
'artist': 'Avril Lavigne',
'provider': 'RED', # Torrent source
'provider': 'RED',
'quality': 'FLAC 16bit CD',
'source_id': 'torrent123',
'target_file': 'Unwanted.flac',
'url': '',
}]
}
mock_job.audio_search_artist = 'Avril Lavigne'
mock_job.audio_search_title = 'Unwanted'
mock_job_manager.get_job.return_value = mock_job
# Create mock audio search service with remote client
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
# Mock download to return GCS path
mock_download_result = Mock()
mock_download_result.filepath = "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac"
mock_audio_service.download.return_value = mock_download_result
# Mock FlacfetchClient
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-123")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job123/audio/Avril Lavigne - Unwanted.flac",
})
# Run the async function
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job123",
selection_index=0,
audio_search_service=mock_audio_service,
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job123",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# CRITICAL: Verify download was called with gcs_path for remote torrent source
mock_audio_service.download.assert_called_once()
call_kwargs = mock_audio_service.download.call_args.kwargs
# The gcs_path should be set for remote torrent downloads
assert 'gcs_path' in call_kwargs
# CRITICAL: Verify FlacfetchClient.download_by_id was called with gcs_path
mock_flacfetch.download_by_id.assert_called_once()
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
assert call_kwargs['gcs_path'] == "uploads/job123/audio/"
assert call_kwargs['source_name'] == 'RED'
assert call_kwargs['source_id'] == 'torrent123'
def test_youtube_remote_download_uses_youtube_service(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""
@@ -1343,7 +1345,7 @@ class TestAudioSearchApiRouteDownload:
mock_youtube_service.download_by_id.assert_called_once()
def test_handles_gcs_path_response_correctly(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""Test that GCS path responses are parsed correctly."""
"""Test that GCS path responses from FlacfetchClient are parsed correctly."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
@@ -1355,31 +1357,35 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Test Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent789',
'target_file': 'test.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
# Create mock audio search service
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
# Mock download to return full GCS path
mock_download_result = Mock()
mock_download_result.filepath = "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac"
mock_audio_service.download.return_value = mock_download_result
# Mock FlacfetchClient returning full GCS path
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-789")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://karaoke-gen-bucket/uploads/job789/audio/test.flac",
})
# Run the async function
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job789",
selection_index=0,
audio_search_service=mock_audio_service,
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job789",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Verify job was updated with correct GCS path (without gs://bucket/ prefix)
update_calls = mock_job_manager.update_job.call_args_list
@@ -1398,9 +1404,9 @@ class TestAudioSearchApiRouteDownload:
def test_torrent_download_requires_remote(self, mock_job_manager, mock_storage_service):
"""
Test that torrent sources (RED/OPS) require remote flacfetch.
Test that torrent sources (RED/OPS) require remote flacfetch client.
When running as a background task, the error is caught and the job is failed.
When get_flacfetch_client() returns None, the job should be failed.
"""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
@@ -1417,22 +1423,21 @@ class TestAudioSearchApiRouteDownload:
}
mock_job_manager.get_job.return_value = mock_job
# Create mock audio search service WITHOUT remote client
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = False
loop = asyncio.new_event_loop()
try:
# The background task catches exceptions and fails the job
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_no_remote",
selection_index=0,
audio_search_service=mock_audio_service,
# No flacfetch client configured
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_no_remote",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Verify the job was failed with an appropriate error message
mock_job_manager.fail_job.assert_called_once()
@@ -1564,27 +1569,35 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent_w',
'target_file': 'test.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
mock_download_result = Mock()
mock_download_result.filepath = "gs://bucket/uploads/job_w/audio/test.flac"
mock_audio_service.download.return_value = mock_download_result
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_w",
selection_index=0,
audio_search_service=mock_audio_service,
# Mock FlacfetchClient
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-w")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_w/audio/test.flac",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_w",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Both workers should be triggered
mock_worker_service.trigger_audio_worker.assert_called_once_with("job_w")
@@ -1609,26 +1622,32 @@ class TestAudioSearchApiRouteDownload:
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent_err',
'target_file': 'test.flac',
'url': '',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_audio_service.is_remote_enabled.return_value = True
mock_audio_service.download.side_effect = RuntimeError("Unexpected connection error")
loop = asyncio.new_event_loop()
try:
# Should not raise - background tasks catch all exceptions
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_err",
selection_index=0,
audio_search_service=mock_audio_service,
# Mock FlacfetchClient that raises an error
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(side_effect=RuntimeError("Unexpected connection error"))
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
# Should not raise - background tasks catch all exceptions
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_err",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
)
finally:
loop.close()
finally:
loop.close()
# Job should be failed with error message
mock_job_manager.fail_job.assert_called_once()
@@ -1636,3 +1655,502 @@ class TestAudioSearchApiRouteDownload:
assert fail_args.args[0] == "job_err"
assert "Unexpected connection error" in fail_args.args[1]
class TestAsyncEventLoopFixes:
"""
Tests for the async event loop blocking fixes.
Verifies that:
- Background tasks use FlacfetchClient async methods directly (RED/OPS/Spotify)
- Background tasks use asyncio.to_thread for generic downloads
- Search endpoint uses search_async instead of sync search
- InsufficientCreditsError propagates as 402, not 500
- FlacfetchServiceError is handled in background tasks
"""
@pytest.fixture
def mock_job_manager(self):
with patch('backend.api.routes.audio_search.job_manager') as mock:
yield mock
@pytest.fixture
def mock_storage_service(self):
with patch('backend.api.routes.audio_search.storage_service') as mock:
yield mock
@pytest.fixture
def mock_worker_service(self):
with patch('backend.api.routes.audio_search.get_worker_service') as mock:
worker = Mock()
worker.trigger_audio_worker = AsyncMock()
worker.trigger_lyrics_worker = AsyncMock()
mock.return_value = worker
yield worker
def test_spotify_download_uses_flacfetch_client_directly(
self, mock_job_manager, mock_storage_service, mock_worker_service
):
"""Spotify downloads should use FlacfetchClient.download_by_id() directly."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Blinding Lights',
'artist': 'The Weeknd',
'provider': 'Spotify',
'quality': 'OGG 320kbps',
'source_id': 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b',
'url': 'https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-spotify-1")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_sp/audio/The Weeknd - Blinding Lights.ogg",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_sp",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Verify FlacfetchClient was used directly (not audio_search_service)
mock_flacfetch.download_by_id.assert_called_once()
call_kwargs = mock_flacfetch.download_by_id.call_args.kwargs
assert call_kwargs['source_name'] == 'Spotify'
assert call_kwargs['source_id'] == 'spotify:track:0VjIjW4GlUZAMYd2vXMi3b'
assert call_kwargs['gcs_path'] == 'uploads/job_sp/audio/'
mock_flacfetch.wait_for_download.assert_called_once()
# audio_search_service.download_by_id should NOT be called
mock_audio_service.download_by_id.assert_not_called()
def test_spotify_download_requires_flacfetch_client(self, mock_job_manager, mock_storage_service):
"""Spotify download should fail job when FlacfetchClient is not configured."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Test',
'provider': 'Spotify',
'quality': 'OGG',
'source_id': 'spotify:track:abc',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=None):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_sp_err",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "flacfetch" in mock_job_manager.fail_job.call_args.args[1].lower()
def test_generic_download_uses_asyncio_to_thread(self, mock_job_manager, mock_storage_service, mock_worker_service):
"""Generic/unknown source downloads should use asyncio.to_thread to avoid blocking."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
import tempfile
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test Song',
'artist': 'Unknown Artist',
'provider': 'SomeNewSource',
'quality': 'MP3',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
# Create a temporary file to simulate a downloaded file
tmp = tempfile.NamedTemporaryFile(suffix='.mp3', delete=False)
tmp.write(b'fake audio data')
tmp.close()
mock_download_result = Mock()
mock_download_result.filepath = tmp.name
mock_audio_service.download.return_value = mock_download_result
with patch('backend.api.routes.audio_search.asyncio') as mock_asyncio:
# Make to_thread return a coroutine that returns the mock result
mock_asyncio.to_thread = AsyncMock(return_value=mock_download_result)
mock_asyncio.gather = AsyncMock()
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_generic",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Verify asyncio.to_thread was called (not direct sync call)
mock_asyncio.to_thread.assert_called_once()
# Cleanup
import os
try:
os.unlink(tmp.name)
except OSError:
pass
def test_red_download_without_source_id_uses_search_download(
self, mock_job_manager, mock_storage_service, mock_worker_service
):
"""RED download without source_id should use flacfetch_client.download() with search_id."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
# No source_id — triggers the search-based download path
}],
'remote_search_id': 'search-abc-123',
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download = AsyncMock(return_value="dl-search-1")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_nosrc/audio/test.flac",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_nosrc",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
# Should use flacfetch_client.download() (not download_by_id)
mock_flacfetch.download.assert_called_once()
call_kwargs = mock_flacfetch.download.call_args.kwargs
assert call_kwargs['search_id'] == 'search-abc-123'
assert call_kwargs['result_index'] == 0
assert call_kwargs['gcs_path'] == 'uploads/job_nosrc/audio/'
def test_flacfetch_service_error_handled_in_background_task(
self, mock_job_manager, mock_storage_service
):
"""FlacfetchServiceError should be caught and job should be failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
from backend.services.flacfetch_client import FlacfetchServiceError
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'OPS',
'quality': 'FLAC',
'source_id': 'ops123',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(
side_effect=FlacfetchServiceError("Connection refused")
)
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_fserr",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "Connection refused" in mock_job_manager.fail_job.call_args.args[1]
def test_wait_for_download_no_filepath_fails_job(
self, mock_job_manager, mock_storage_service
):
"""If wait_for_download returns no filepath, job should be failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'RED',
'quality': 'FLAC',
'source_id': 'torrent_nofp',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
# wait_for_download returns status without gcs_path or output_path
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-nofp")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
# No gcs_path or output_path
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_nofp",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
def test_spotify_wait_for_download_no_filepath_fails_job(
self, mock_job_manager, mock_storage_service
):
"""Spotify: if wait_for_download returns no filepath, job should be failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Test',
'artist': 'Artist',
'provider': 'Spotify',
'quality': 'OGG',
'source_id': 'spotify:track:nofp',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_flacfetch = Mock()
mock_flacfetch.download_by_id = AsyncMock(return_value="dl-sp-nofp")
mock_flacfetch.wait_for_download = AsyncMock(return_value={
"status": "complete",
})
with patch('backend.api.routes.audio_search.get_flacfetch_client', return_value=mock_flacfetch):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_sp_nofp",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "no file path" in mock_job_manager.fail_job.call_args.args[1].lower()
def test_youtube_download_error_fails_job(
self, mock_job_manager, mock_storage_service
):
"""YouTubeDownloadError should be caught and job failed."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
from backend.services.youtube_download_service import YouTubeDownloadError
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Deleted Video',
'artist': 'Unknown',
'provider': 'YouTube',
'quality': 'Opus',
'source_id': 'deleted123',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_youtube_service = Mock()
mock_youtube_service.download_by_id = AsyncMock(
side_effect=YouTubeDownloadError("Video unavailable")
)
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_yt_err",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "Video unavailable" in mock_job_manager.fail_job.call_args.args[1]
def test_youtube_no_video_id_fails_job(
self, mock_job_manager, mock_storage_service
):
"""YouTube download with no source_id and no extractable video ID should fail."""
from backend.api.routes.audio_search import _download_audio_and_trigger_workers
import asyncio
mock_job = Mock()
mock_job.state_data = {
'audio_search_results': [{
'title': 'Bad Link',
'artist': 'Unknown',
'provider': 'YouTube',
'quality': 'Opus',
# No source_id
'url': 'https://example.com/not-youtube',
}]
}
mock_job_manager.get_job.return_value = mock_job
mock_audio_service = Mock()
mock_youtube_service = Mock()
mock_youtube_service._extract_video_id = Mock(return_value=None)
with patch('backend.api.routes.audio_search.get_youtube_download_service', return_value=mock_youtube_service):
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(
_download_audio_and_trigger_workers(
job_id="job_yt_noid",
selection_index=0,
audio_search_service=mock_audio_service,
)
)
finally:
loop.close()
mock_job_manager.fail_job.assert_called_once()
assert "video ID" in mock_job_manager.fail_job.call_args.args[1] or \
"No video" in mock_job_manager.fail_job.call_args.args[1]
class TestSearchAsyncUsage:
"""Tests that the search endpoint uses search_async instead of sync search."""
def test_search_async_uses_get_running_loop(self):
"""search_async should use asyncio.get_running_loop() (not deprecated get_event_loop)."""
import asyncio
import inspect
source = inspect.getsource(AudioSearchService.search_async)
assert 'get_running_loop' in source
assert 'get_event_loop' not in source
def test_download_async_uses_get_running_loop(self):
"""download_async should use asyncio.get_running_loop()."""
import inspect
source = inspect.getsource(AudioSearchService.download_async)
assert 'get_running_loop' in source
assert 'get_event_loop' not in source
def test_download_by_id_async_uses_get_running_loop(self):
"""download_by_id_async should use asyncio.get_running_loop()."""
import inspect
source = inspect.getsource(AudioSearchService.download_by_id_async)
assert 'get_running_loop' in source
assert 'get_event_loop' not in source
def test_search_endpoint_calls_search_async(self):
"""Verify the search endpoint source calls search_async, not sync search."""
import inspect
from backend.api.routes.audio_search import search_audio
source = inspect.getsource(search_audio)
assert 'search_async' in source
# Should NOT have a bare .search( call (which is sync)
# But it may have search_async( which contains "search" — so check specifically
# that search_async is used and not audio_search_service.search(
assert 'await audio_search_service.search_async(' in source
class TestInsufficientCreditsErrorPropagation:
"""Test that InsufficientCreditsError propagates correctly as 402."""
def test_exception_handler_uses_isinstance(self):
"""
Verify the exception handler uses isinstance() for InsufficientCreditsError.
This is robust against class identity issues from module reloading.
"""
import inspect
from backend.api.routes.audio_search import search_audio
source = inspect.getsource(search_audio)
assert 'isinstance(e, (InsufficientCreditsError, RateLimitExceededError))' in source
+381
View File
@@ -0,0 +1,381 @@
"""
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
+433 -5
View File
@@ -9,6 +9,7 @@ These tests mock the Google API client and Secret Manager to verify:
"""
import json
import os
import ssl
import pytest
from unittest.mock import Mock, MagicMock, patch
@@ -501,24 +502,451 @@ class TestUploadToPublicShare:
assert len(result) == 1
class TestRetryBehavior:
"""Test retry behavior for transient connection errors."""
@patch("backend.services.gdrive_service.get_settings")
def test_retries_on_broken_pipe(self, mock_get_settings):
"""Test that BrokenPipeError triggers retry and succeeds on second attempt."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
# First call raises BrokenPipeError, second succeeds
mock_list_result.execute.side_effect = [
BrokenPipeError("[Errno 32] Broken pipe"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to clear but re-set the mock (avoid real OAuth)
def mock_reset():
service._service = mock_drive
service._reset_service = mock_reset
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert mock_list_result.execute.call_count == 2
@patch("backend.services.gdrive_service.get_settings")
def test_gives_up_after_3_attempts(self, mock_get_settings):
"""Test that 3 consecutive failures raises the exception."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = BrokenPipeError("[Errno 32] Broken pipe")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to re-set the mock (avoid real OAuth)
service._reset_service = lambda: setattr(service, '_service', mock_drive)
with pytest.raises(BrokenPipeError):
service.get_or_create_folder("parent-123", "MP4")
assert mock_list_result.execute.call_count == 3
@patch("backend.services.gdrive_service.get_settings")
def test_service_reset_on_retry(self, mock_get_settings):
"""Test that _service is reset to None between retry attempts."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
BrokenPipeError("[Errno 32] Broken pipe"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to track calls but still do the reset
original_reset = service._reset_service
reset_calls = []
def tracked_reset():
reset_calls.append(True)
original_reset()
# Re-set mock service so the retry works
service._service = mock_drive
service._reset_service = tracked_reset
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert len(reset_calls) == 1 # Reset called once between attempt 1 and 2
@patch("backend.services.gdrive_service.get_settings")
def test_retries_on_ssl_error(self, mock_get_settings):
"""Test that SSLError triggers retry."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
ssl.SSLError("SSL: UNEXPECTED_EOF_WHILE_READING"),
{"files": [{"id": "folder-123", "name": "MP4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
# Patch _reset_service to re-set the mock (avoid real OAuth)
service._reset_service = lambda: setattr(service, '_service', mock_drive)
folder_id = service.get_or_create_folder("parent-123", "MP4")
assert folder_id == "folder-123"
assert mock_list_result.execute.call_count == 2
@patch("backend.services.gdrive_service.get_settings")
def test_no_retry_on_non_transient_error(self, mock_get_settings):
"""Test that non-transient errors are not retried."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = ValueError("bad value")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
with pytest.raises(ValueError):
service.get_or_create_folder("parent-123", "MP4")
assert mock_list_result.execute.call_count == 1
class TestDeleteFile:
"""Test delete_file and delete_files methods."""
def _make_service(self, mock_get_settings):
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
service._loaded = True
service._credentials_data = {"refresh_token": "token", "client_id": "id", "client_secret": "secret"}
return service
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_success(self, mock_get_settings):
"""Successful delete returns True."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
mock_delete.execute.return_value = None
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("file-id-123")
assert result is True
mock_files_api.delete.assert_called_once_with(fileId="file-id-123")
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_returns_true_on_404(self, mock_get_settings):
"""404 (already deleted) returns True — idempotent cleanup."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
not_found = Exception("File not found")
not_found.resp = Mock()
not_found.resp.status = 404
mock_delete.execute.side_effect = not_found
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("already-gone-id")
assert result is True
@patch("backend.services.gdrive_service.get_settings")
def test_delete_file_returns_false_on_error(self, mock_get_settings):
"""Non-404 errors return False."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_delete = Mock()
mock_delete.execute.side_effect = Exception("Permission denied")
mock_files_api.delete.return_value = mock_delete
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.delete_file("restricted-file")
assert result is False
@patch("backend.services.gdrive_service.get_settings")
def test_delete_files_calls_delete_file_for_each_id(self, mock_get_settings):
"""delete_files returns a per-ID success dict."""
service = self._make_service(mock_get_settings)
# Stub delete_file: first ID succeeds, second fails
results_by_id = {"id-1": True, "id-2": False}
service.delete_file = lambda fid: results_by_id[fid]
result = service.delete_files(["id-1", "id-2"])
assert result == {"id-1": True, "id-2": False}
@patch("backend.services.gdrive_service.get_settings")
def test_delete_files_empty_list(self, mock_get_settings):
"""delete_files with empty list returns empty dict."""
service = self._make_service(mock_get_settings)
result = service.delete_files([])
assert result == {}
class TestFindFilesByBrandCode:
"""Test find_files_by_brand_code method — used as fallback in cleanup-distribution."""
def _make_service(self, mock_get_settings):
"""Helper: make a GoogleDriveService with fake credentials pre-loaded."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
service = GoogleDriveService()
service._loaded = True
service._credentials_data = {
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
}
return service
def _attach_mock_drive(self, service, list_side_effects):
"""Attach a mock Drive client whose files().list().execute() returns given values."""
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = list_side_effects
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
return mock_files_api
@patch("backend.services.gdrive_service.get_settings")
def test_finds_files_in_all_subfolders(self, mock_get_settings):
"""Test finds matching files across CDG/, MP4/, MP4-720p/ subfolders."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
# Responses: for each subfolder: (1) find subfolder, (2) search for files
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
{"files": [{"id": "mp4-folder"}]}, # MP4 subfolder found
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
{"files": [{"id": "mp4720-folder"}]}, # MP4-720p subfolder found
{"files": [{"id": "mp4720-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert len(result) == 3
assert "cdg-file-1" in result
assert "mp4-file-1" in result
assert "mp4720-file-1" in result
@patch("backend.services.gdrive_service.get_settings")
def test_returns_empty_when_subfolder_not_found(self, mock_get_settings):
"""Test returns empty list when public share subfolders don't exist."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
# All subfolder lookups return empty
mock_list_result.execute.return_value = {"files": []}
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == []
@patch("backend.services.gdrive_service.get_settings")
def test_filters_by_exact_brand_code_prefix(self, mock_get_settings):
"""Test only returns files whose name starts with '{brand_code} - '."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
{
"files": [
{"id": "match-id", "name": "NOMAD-1271 - piri - dog.zip"},
# This one contains NOMAD-1271 but doesn't START with it — should be excluded
{"id": "no-match-id", "name": "BONUS-NOMAD-1271 - other.zip"},
]
},
{"files": []}, # MP4 subfolder not found
{"files": []}, # MP4-720p subfolder not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == ["match-id"]
@patch("backend.services.gdrive_service.get_settings")
def test_returns_empty_when_no_files_match_brand_code(self, mock_get_settings):
"""Test returns empty list when subfolder exists but has no matching files."""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
{"files": [{"id": "other-id", "name": "NOMAD-1300 - someone else.zip"}]},
{"files": []}, # MP4 not found
{"files": []}, # MP4-720p not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == []
@patch("backend.services.gdrive_service.get_settings")
def test_raises_after_all_subfolders_when_any_error(self, mock_get_settings):
"""When any subfolder search errors, raises RuntimeError after processing all subfolders.
This prevents the cleanup endpoint from treating an incomplete search result
as "GDrive is clean" and incorrectly recycling the brand code.
"""
service = self._make_service(mock_get_settings)
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]},
Exception("API error"), # CDG file search fails
{"files": [{"id": "mp4-folder"}]},
{"files": [{"id": "mp4-file-1", "name": "NOMAD-1271 - piri - dog.mp4"}]},
{"files": [{"id": "mp4720-folder"}]},
{"files": []},
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
# Should raise after processing all subfolders — an incomplete search must not
# be silently treated as "nothing found" by the caller
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
class TestGetGdriveService:
"""Test get_gdrive_service singleton."""
@patch("backend.services.gdrive_service.get_settings")
def test_get_gdrive_service_singleton(self, mock_get_settings):
"""Test get_gdrive_service returns singleton instance."""
from backend.services.gdrive_service import get_gdrive_service
import backend.services.gdrive_service as gdrive_module
# Reset singleton
gdrive_module._gdrive_service = None
mock_settings = Mock()
mock_settings.get_secret.return_value = None
mock_get_settings.return_value = mock_settings
service1 = get_gdrive_service()
service2 = get_gdrive_service()
assert service1 is service2
@@ -196,7 +196,7 @@ class TestUserEmailExtraction:
mock_jm.create_job.return_value = mock_job
mock_jm.get_job.return_value = mock_job
mock_cred.return_value.check_youtube_credentials.return_value = Mock(status=Mock(value="valid"))
mock_search.return_value.search.return_value = []
mock_search.return_value.search_async = AsyncMock(return_value=[])
await search_audio(
request=mock_request,
+293 -7
View File
@@ -250,8 +250,28 @@ class TestVideoWorkerOrchestratorPackaging:
"""Test packaging stage."""
@pytest.mark.asyncio
async def test_run_packaging_no_lrc(self):
"""Test packaging stage with no LRC file."""
async def test_run_packaging_no_lrc_cdg_disabled(self):
"""Test packaging stage with no LRC file and CDG disabled skips silently."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
@pytest.mark.asyncio
async def test_run_packaging_no_lrc_cdg_enabled_raises(self):
"""Test packaging stage raises when CDG enabled but no LRC file."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
@@ -264,10 +284,8 @@ class TestVideoWorkerOrchestratorPackaging:
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_run_packaging_cdg(self):
@@ -368,6 +386,209 @@ class TestVideoWorkerOrchestratorPackaging:
"countdown_padding_seconds must be passed for CDG timestamp adjustment"
class TestPackagingValidation:
"""Test CDG/TXT packaging validation checks.
These tests verify that the orchestrator fails fast when CDG/TXT
generation is enabled but fails, rather than silently proceeding
to expensive encoding. This prevents jobs from completing without
their requested CDG/TXT packages.
Added after jobs 5b6aba25 and 5161b069 completed with enable_cdg=True
but no CDG ZIP was produced due to a FileNotFoundError being silently caught.
"""
@pytest.mark.asyncio
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when CDG enabled but not produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
# Mock _run_packaging to NOT set result.final_karaoke_cdg_zip (simulates failure)
async def mock_packaging():
pass # CDG generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
assert "CDG generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called() # Should not reach encoding
@pytest.mark.asyncio
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when TXT enabled but not produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_txt=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # TXT generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
assert "TXT generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called()
@pytest.mark.asyncio
async def test_pipeline_succeeds_when_cdg_disabled(self):
"""Test that pipeline succeeds normally when CDG is not enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
enable_txt=False,
)
orchestrator = VideoWorkerOrchestrator(config)
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_pkg, \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True
mock_pkg.assert_not_called() # Packaging skipped entirely
@pytest.mark.asyncio
async def test_cdg_validation_passes_when_cdg_produced(self):
"""Test that validation passes when CDG is successfully produced."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging_success():
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_success), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True
@pytest.mark.asyncio
async def test_both_cdg_and_txt_validation_fail_together(self):
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
enable_txt=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # Both CDG and TXT "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
assert result.success is False
# CDG validation is checked first
assert "CDG generation was enabled but failed" in result.error_message
mock_encoding.assert_not_called()
@pytest.mark.asyncio
async def test_lrc_missing_raises_when_cdg_enabled(self):
"""Test that missing LRC file raises when CDG is enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
lrc_file_path="/nonexistent/path.lrc",
)
orchestrator = VideoWorkerOrchestrator(config)
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_lrc_missing_raises_when_txt_enabled(self):
"""Test that missing LRC file raises when TXT is enabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_txt=True,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
with pytest.raises(RuntimeError, match="LRC file not available"):
await orchestrator._run_packaging()
@pytest.mark.asyncio
async def test_lrc_missing_skips_when_cdg_disabled(self):
"""Test that missing LRC file just skips packaging when CDG/TXT disabled."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=False,
enable_txt=False,
lrc_file_path=None,
)
orchestrator = VideoWorkerOrchestrator(config)
# Should not raise, just skip
await orchestrator._run_packaging()
assert orchestrator.result.final_karaoke_cdg_zip is None
class TestVideoWorkerOrchestratorEncoding:
"""Test encoding stage."""
@@ -772,8 +993,12 @@ class TestVideoWorkerOrchestratorFullPipeline:
)
orchestrator = VideoWorkerOrchestrator(config)
# Mock packaging to set CDG result (validation requires it when enable_cdg=True)
async def mock_packaging_with_result():
orchestrator.result.final_karaoke_cdg_zip = "/output/cdg.zip"
# Mock all stages
with patch.object(orchestrator, "_run_packaging", new_callable=AsyncMock) as mock_packaging, \
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging_with_result) as mock_packaging, \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock) as mock_org, \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock) as mock_dist, \
@@ -1287,3 +1512,64 @@ class TestOrchestratorCountdownPadding:
assert captured_input is not None, "encode() should have been called"
assert captured_input.options.get("countdown_padding_seconds") == 3.0, \
"Orchestrator must pass countdown_padding_seconds in EncodingInput.options"
class TestDistributionWarnings:
"""Test distribution_warnings tracking in OrchestratorResult."""
def test_result_has_distribution_warnings_field(self):
"""Test that OrchestratorResult has distribution_warnings as empty list by default."""
result = OrchestratorResult(success=True)
assert result.distribution_warnings == []
@pytest.mark.asyncio
async def test_gdrive_failure_populates_warnings(self):
"""Test that Google Drive upload failure populates distribution_warnings."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
gdrive_folder_id="folder-123",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.brand_code = "NOMAD-0001"
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_get:
mock_gdrive = MagicMock()
mock_gdrive.is_configured = True
mock_gdrive.upload_to_public_share.side_effect = Exception("Connection refused")
mock_get.return_value = mock_gdrive
await orchestrator._upload_to_gdrive()
assert len(orchestrator.result.distribution_warnings) == 1
assert "Google Drive upload failed" in orchestrator.result.distribution_warnings[0]
@pytest.mark.asyncio
async def test_dropbox_failure_populates_warnings(self):
"""Test that Dropbox upload failure populates distribution_warnings."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
dropbox_path="/Public Share",
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.brand_code = "NOMAD-0001"
with patch("backend.services.dropbox_service.get_dropbox_service") as mock_get:
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.upload_folder.side_effect = Exception("Auth expired")
mock_get.return_value = mock_dropbox
await orchestrator._upload_to_dropbox()
assert len(orchestrator.result.distribution_warnings) == 1
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
+77 -17
View File
@@ -339,15 +339,26 @@ async def generate_video_orchestrated(job_id: str) -> bool:
# Store result metadata in job BEFORE transitioning to COMPLETE
# This ensures youtube_url is available when completion email is sent
logger.info(f"[job:{job_id}] Video generation complete")
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
}
})
state_update = {
**job.state_data,
'brand_code': result.brand_code,
'youtube_url': result.youtube_url,
'dropbox_link': result.dropbox_link,
'gdrive_files': result.gdrive_files,
}
if result.distribution_warnings:
state_update['distribution_warnings'] = result.distribution_warnings
job_manager.update_job(job_id, {'state_data': state_update})
# Send Pushbullet alert if any distribution uploads failed
if result.distribution_warnings:
_send_distribution_warning_notification(
job_id=job_id,
artist=job.artist,
title=job.title,
warnings=result.distribution_warnings,
settings=settings,
)
# Mark job as complete (triggers completion email with youtube_url now available)
job_manager.transition_to_state(
@@ -841,6 +852,7 @@ async def _handle_native_distribution(
job_log.warning(f"Dropbox SDK not installed: {e}")
except Exception as e:
job_log.error(f"Native Dropbox upload failed: {e}", exc_info=True)
result.setdefault('distribution_warnings', []).append(f"Dropbox upload failed: {e}")
# Don't fail the job - distribution is optional
# Upload to Google Drive using native API
@@ -884,6 +896,7 @@ async def _handle_native_distribution(
job_log.warning(f"Google API packages not installed: {e}")
except Exception as e:
job_log.error(f"Native Google Drive upload failed: {e}", exc_info=True)
result.setdefault('distribution_warnings', []).append(f"Google Drive upload failed: {e}")
# Don't fail the job - distribution is optional
elif existing_gdrive_files:
job_log.info(f"Skipping Google Drive upload - orchestrator already uploaded {len(existing_gdrive_files)} files")
@@ -891,17 +904,64 @@ async def _handle_native_distribution(
# Update job state_data with brand code and links
if brand_code or result.get('dropbox_link') or result.get('gdrive_files'):
try:
job_manager.update_job(job_id, {
'state_data': {
**job.state_data,
'brand_code': brand_code,
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
}
})
state_update = {
**job.state_data,
'brand_code': brand_code,
'dropbox_link': result.get('dropbox_link'),
'gdrive_files': result.get('gdrive_files'),
}
if result.get('distribution_warnings'):
state_update['distribution_warnings'] = result['distribution_warnings']
job_manager.update_job(job_id, {'state_data': state_update})
except Exception as e:
job_log.warning(f"Failed to update job state_data: {e}")
# Send Pushbullet alert if any distribution uploads failed
if result.get('distribution_warnings'):
_send_distribution_warning_notification(
job_id=job_id,
artist=job.artist,
title=job.title,
warnings=result['distribution_warnings'],
settings=settings,
)
def _send_distribution_warning_notification(
job_id: str,
artist: str,
title: str,
warnings: list[str],
settings=None,
) -> None:
"""Send Pushbullet notification when distribution uploads fail."""
try:
if settings is None:
settings = get_settings()
api_key = settings.get_secret("pushbullet-api-key")
if not api_key:
logger.warning("Pushbullet API key not found, skipping distribution warning notification")
return
import requests as req
push_title = f"Distribution Warning: {artist} - {title}"
body = f"Job {job_id} completed but {len(warnings)} upload(s) failed:\n\n"
body += "\n".join(f" - {w}" for w in warnings)
resp = req.post(
"https://api.pushbullet.com/v2/pushes",
headers={"Access-Token": api_key, "Content-Type": "application/json"},
json={"type": "note", "title": push_title, "body": body},
timeout=10,
)
if resp.ok:
logger.info(f"[job:{job_id}] Distribution warning notification sent via Pushbullet")
else:
logger.warning(f"[job:{job_id}] Pushbullet notification failed: {resp.status_code} {resp.text}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
def _validate_prerequisites(job) -> bool:
"""Validate that all prerequisites are met for video generation."""
@@ -109,6 +109,9 @@ class OrchestratorResult:
dropbox_link: Optional[str] = None
gdrive_files: Optional[Dict[str, str]] = field(default_factory=dict)
# Distribution warnings (non-fatal upload failures)
distribution_warnings: List[str] = field(default_factory=list)
# Timing
encoding_time_seconds: Optional[float] = None
total_time_seconds: Optional[float] = None
@@ -228,6 +231,18 @@ class VideoWorkerOrchestrator:
if self.config.enable_cdg or self.config.enable_txt:
await self._run_packaging()
# Validate required packaging outputs before expensive encoding
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
raise RuntimeError(
"CDG generation was enabled but failed. "
"Check worker logs for CDG-related errors."
)
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
raise RuntimeError(
"TXT generation was enabled but failed. "
"Check worker logs for TXT-related errors."
)
# Stage 2: Encoding
await self._run_encoding()
@@ -240,6 +255,11 @@ class VideoWorkerOrchestrator:
# Stage 5: Notifications (Discord)
await self._run_notifications()
# Stage 6: Post-distribution GDrive validation
# Only for jobs that uploaded to the public share (non-private)
if self.config.gdrive_folder_id:
await self._trigger_gdrive_validation()
self.result.success = True
self.result.total_time_seconds = time.time() - start_time
@@ -259,6 +279,10 @@ class VideoWorkerOrchestrator:
self.job_log.info("Starting packaging stage (CDG/TXT)")
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
if self.config.enable_cdg or self.config.enable_txt:
raise RuntimeError(
f"CDG/TXT generation enabled but LRC file not available: {self.config.lrc_file_path}"
)
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
return
@@ -587,6 +611,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"YouTube upload failed: {e}")
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
# Don't fail the pipeline - YouTube is optional
async def _upload_to_dropbox(self):
@@ -623,6 +648,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"Dropbox upload failed: {e}")
self.result.distribution_warnings.append(f"Dropbox upload failed: {e}")
# Don't fail the pipeline - Dropbox is optional
async def _upload_to_gdrive(self):
@@ -659,6 +685,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.error(f"Google Drive upload failed: {e}")
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
# Don't fail the pipeline - GDrive is optional
async def _run_notifications(self):
@@ -681,6 +708,16 @@ class VideoWorkerOrchestrator:
self.job_log.error(f"Discord notification failed: {e}")
# Don't fail the pipeline - notifications are optional
async def _trigger_gdrive_validation(self):
"""Trigger GDrive validation after uploading to the public share."""
try:
from backend.services.gdrive_validator_client import trigger_gdrive_validation
self.job_log.info("Triggering post-job GDrive validation")
trigger_gdrive_validation()
except Exception as e:
self.job_log.warning(f"GDrive validation trigger failed (non-fatal): {e}")
# Never fail the pipeline for validation
def create_orchestrator_config_from_job(
job,
+212
View File
@@ -0,0 +1,212 @@
# Google Drive Validator
Automated validation of the Nomad Karaoke public Google Drive share folder. Detects duplicate brand codes, invalid filenames, and sequence gaps.
## Overview
The public share folder (`1laRKAyxo0v817SstfM5XkpbWiNKNAMSX`) contains all published karaoke tracks organized into subfolders:
```
Public Share/
CDG/ # .zip files (MP3 + CDG for KJ players)
MP4/ # .mp4 files (4K lossless)
MP4-720p/ # .mp4 files (720p lossy)
```
Each file follows the naming convention: `NOMAD-XXXX - Artist - Title.(mp4|zip)`
The validator checks:
- **Duplicate sequence numbers** - e.g., two files both named `NOMAD-1271`
- **Invalid filenames** - files that don't match the expected pattern
- **Sequence gaps** - missing numbers in the NOMAD-XXXX sequence (with known exclusions)
## Architecture
```
┌────────────────────────┐
│ Cloud Scheduler │
│ (9 PM ET daily) │
└──────────┬─────────────┘
│ OIDC auth
▼
┌──────────────────┐ ┌────────────────────────┐ ┌──────────────┐
│ Backend (post- │ OIDC │ gdrive-validator │ API │ Google Drive │
│ job completion) │─────────→│ Cloud Function (Gen2) │─────────→│ API v3 │
└──────────────────┘ └──────────┬─────────────┘ └──────────────┘
│
┌──────────────────┐ ┌──────┴──────┐
│ gcloud functions │ │ │
│ call (manual) │─────────→ ▼ ▼
└──────────────────┘ ┌───────────┐ ┌────────────┐
│ SendGrid │ │ Pushbullet │
│ (primary) │ │ (fallback) │
└───────────┘ └────────────┘
```
### Trigger Points
| Trigger | When | How |
|---------|------|-----|
| **Daily schedule** | 9:00 PM ET every day | Cloud Scheduler → HTTP POST with OIDC token |
| **Post-job** | After each job uploads to public share | Backend orchestrator → HTTP POST with OIDC token |
| **Manual** | On demand | `python scripts/check_public_share.py` via gcloud CLI |
### Notifications
Notifications are sent via **both** channels (belt + suspenders):
1. **SendGrid email** (primary) - Sent to `gen@nomadkaraoke.com`. Provides a persistent, searchable record.
2. **Pushbullet** (fallback) - Push notification for immediate visibility.
Notifications are sent when:
- Issues are found (always)
- No issues found and `NOTIFY_ON_SUCCESS=true` (daily summary)
- Errors occur during validation
## Files
| File | Purpose |
|------|---------|
| `infrastructure/functions/gdrive_validator/main.py` | Cloud Function source code |
| `infrastructure/functions/gdrive_validator/requirements.txt` | Python dependencies |
| `infrastructure/functions/gdrive_validator/deploy.sh` | Manual deployment script |
| `infrastructure/__main__.py` | Pulumi config (env vars, secrets, IAM) |
| `infrastructure/modules/iam/worker_sas.py` | Service account definition |
| `backend/services/gdrive_validator_client.py` | Backend HTTP client (OIDC auth) |
| `backend/workers/video_worker_orchestrator.py` | Post-job trigger integration |
| `scripts/check_public_share.py` | Local CLI for manual checks |
## Configuration
### Environment Variables (Cloud Function)
| Variable | Value | Description |
|----------|-------|-------------|
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
### Secrets (Cloud Function)
| Secret | Source | Description |
|--------|--------|-------------|
| `SENDGRID_API_KEY` | `sendgrid-api-key:latest` | SendGrid API key for email |
| `PUSHBULLET_API_KEY` | `pushbullet-api-key:latest` | Pushbullet API key for push notifications |
### Secrets (Backend / Cloud Run)
| Secret | Source | Description |
|--------|--------|-------------|
| `GDRIVE_VALIDATOR_URL` | `gdrive-validator-url:latest` | Cloud Function URL for post-job trigger |
### IAM
| Principal | Role | Resource | Purpose |
|-----------|------|----------|---------|
| `gdrive-validator@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Self-invoke (Cloud Scheduler) |
| Cloud Scheduler agent | `roles/cloudfunctions.invoker` | gdrive-validator function | Daily trigger |
| `karaoke-backend@` SA | `roles/cloudfunctions.invoker` | gdrive-validator function | Post-job trigger |
| `karaoke-backend@` SA | `roles/run.invoker` | gdrive-validator Cloud Run service | Gen2 function HTTP access |
### Known Gaps
The validator knows about expected sequence gaps (historical missing numbers). These are configured identically in both:
- `infrastructure/functions/gdrive_validator/main.py` (Cloud Function)
- `scripts/validate_and_sync.py` (local script)
When a new gap is discovered intentionally (e.g., a track was removed), update the `KNOWN_GAPS` dict in **both** files.
## Usage
### Manual Check
```bash
# Formatted output
python scripts/check_public_share.py
# Raw JSON
python scripts/check_public_share.py --json
```
Exit codes: `0` = all clear, `1` = issues found, `2` = error.
### Checking Cloud Function Logs
```bash
gcloud functions logs read gdrive-validator --region=us-central1 --project=nomadkaraoke --limit=50
```
### Redeploying the Cloud Function
The Cloud Function source is not deployed via CI — it's deployed either:
1. **Via Pulumi** (infrastructure changes like env vars, secrets, IAM)
2. **Via `deploy.sh`** (code changes to `main.py`)
```bash
cd infrastructure/functions/gdrive_validator
./deploy.sh
```
Note: `deploy.sh` deploys the source code. Pulumi manages the infrastructure (env vars, secrets, IAM, scheduler). After running `deploy.sh`, the Pulumi-managed config is overwritten by the gcloud deploy — run `pulumi up` afterward if you need to restore Pulumi-managed settings.
## Troubleshooting
### Email Not Received
1. Check Cloud Function logs for SendGrid errors:
```bash
gcloud functions logs read gdrive-validator --region=us-central1 --limit=20
```
2. Verify the SendGrid API key is set:
```bash
gcloud secrets versions access latest --secret=sendgrid-api-key --project=nomadkaraoke | head -c 10
```
3. Check SendGrid dashboard for delivery status
4. Pushbullet should still work as fallback
### Post-Job Trigger Not Firing
1. Check that `GDRIVE_VALIDATOR_URL` secret is set:
```bash
gcloud secrets versions access latest --secret=gdrive-validator-url --project=nomadkaraoke
```
2. Check backend logs for the job — look for "Triggering post-job GDrive validation" or "GDrive validation trigger failed"
3. Verify the backend SA has invoker permissions:
```bash
gcloud functions get-iam-policy gdrive-validator --region=us-central1 --project=nomadkaraoke
```
4. The trigger only fires for non-private jobs (jobs with `gdrive_folder_id` set)
### False Positive Gaps
If the validator reports gaps that are intentional:
1. Add the gap number(s) to `KNOWN_GAPS` in both `main.py` and `scripts/validate_and_sync.py`
2. Redeploy the cloud function with `./deploy.sh`
### Duplicate Brand Code Detected
This is the most critical alert. Steps:
1. Check which files have the duplicate: the notification lists them
2. Determine which is correct (check Firestore job records)
3. Remove or rename the incorrect file in Google Drive
4. Re-trigger validation to confirm the fix
## Cloud Function vs Local Script
| Check | Cloud Function | Local Script (`validate_and_sync.py`) |
|-------|---------------|--------------------------------------|
| Duplicate sequence numbers | Yes | Yes |
| Invalid filenames | Yes | Yes |
| Sequence gaps | Yes | Yes |
| ZIP contents (MP3+CDG) | No (expensive) | Yes |
| Video resolution | No (expensive) | Yes |
| Render quality | No (expensive) | Yes |
| Bidirectional sync | No (read-only) | Yes (rclone) |
The cloud function does metadata-only checks via the GDrive API (fast, cheap, can run frequently). The local script does deep content validation that requires downloading files (slow, run manually).
## History
- **2025-12-24**: Initial cloud function deployed with Pushbullet notifications and daily Cloud Scheduler trigger
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
+35
View File
@@ -30,6 +30,17 @@ When two sequential human review steps can be combined into one, do it. We origi
## Common Gotchas
### Gate Resource Recycling on Full Cleanup Confirmation (Feb 2026)
**What happened**: Brand code NOMAD-1271 was recycled and reused for a real song while old E2E test job files still existed in Google Drive, creating a duplicate in the public share.
**Root causes**:
1. `if gdrive_files:` skips cleanup when `gdrive_files = {}` (empty dict is falsy) — any falsy check on a collection will silently skip work
2. Brand code recycled after Dropbox cleanup success, *before* confirming GDrive was clean — partial cleanup allowed resource reuse with orphaned files
**Fix**: Use `if gdrive_files is not None` (or check explicitly). Gate resource recycling on **all** cleanup steps succeeding, not just the first one. When a resource has been distributed to N places, it's only safe to recycle when all N locations are confirmed clean.
**Pattern**: Treat resource IDs (brand codes, sequential IDs) like distributed transactions — either all distribution points are cleaned, or the ID stays reserved.
### Fail Fast, Don't Fall Back
Silent fallbacks hide configuration errors. When critical configuration is missing (themes, credentials, etc.), raise clear errors instead of falling back to defaults. Better to fail loudly during testing than silently produce incorrect output in production. Example: Theme validation (v0.109.0) now raises `ValueError` on incomplete themes instead of merging with defaults. This ensures all cloud jobs use complete, explicit themes with no silent degradation.
@@ -58,6 +69,15 @@ When multiple code paths create jobs (file upload, audio search, webhooks), use
**Pattern**: When a function can fail, prefer exceptions over boolean returns. Silent failures accumulate into production bugs. Use centralized helpers for multi-step operations (state change + side effects) to prevent divergent implementations.
### Validate Pipeline Stage Outputs Before Proceeding (Feb 2026)
**What happened**: Jobs 5b6aba25 and 5161b069 completed with `enable_cdg=True` but no CDG ZIP was produced. The orchestrator silently caught a `FileNotFoundError` during CDG generation and proceeded to 11+ minutes of GPU encoding, distribution, and notifications — all for an incomplete output.
**Root cause**: CDG generation failed because `instrumental_selection: custom` had no case in the filename construction (fell through to "Backing" suffix). The `FileNotFoundError` was caught by a broad `except Exception` that just logged and continued, since "CDG is optional."
**Fix**: Add validation gates between pipeline stages. After packaging completes but before expensive encoding begins, verify that all enabled outputs were actually produced. If `enable_cdg=True` but no CDG ZIP exists, raise `RuntimeError` immediately. This fails fast, saves encoding costs, and makes the error visible.
**Pattern**: When a pipeline stage produces optional outputs that were explicitly requested, validate their existence before proceeding to the next stage. "Optional" means "can be disabled," not "can silently fail when enabled."
### Fix Both Sides of Dual Code Paths
When fixing a bug in a system with multiple code paths (e.g., legacy vs orchestrator, local vs cloud), verify ALL paths are fixed. PR #271 fixed the GCE worker to READ `instrumental_selection` but only checked the legacy path which was already SENDING it. The orchestrator path (production default) wasn't sending it. **Pattern**: If a component receives config from multiple callers, check ALL callers when fixing the receiving side. Write integration tests that cover each path.
@@ -213,6 +233,18 @@ When deferring processing from one worker to another, you MUST update the job st
### Google Drive Query Escaping
Escape special chars in Google Drive API queries: `'` → `\'`, `\` → `\\\\`.
### Google Drive Stale Connection on Cloud Run (Feb 2026)
**What happened**: Every GDrive upload silently failed for ~1 month (64 errors, 12+ jobs). Errors: `[Errno 32] Broken pipe` or `[SSL: UNEXPECTED_EOF_WHILE_READING]`. Jobs completed with `gdrive_files: {}` and no alert was sent.
**Root cause**: The singleton `GoogleDriveService` caches its HTTP connection. When Cloud Run containers sit idle between jobs, the underlying TCP connection goes stale. The next API call hits a dead socket. The orchestrator catches all exceptions in distribution and continues silently.
**Fix** (v0.119.7):
1. Added tenacity retry with `_reset_service()` (sets `self._service = None` to force fresh connection) on transient errors (`BrokenPipeError`, `ConnectionResetError`, `ssl.SSLError`)
2. Added `distribution_warnings` field to `OrchestratorResult` to track non-fatal upload failures
3. Added Pushbullet notification when distribution uploads fail, so operator is alerted immediately
**Pattern**: Any singleton service that caches HTTP connections should have retry logic with connection reset for stale connection errors. Cloud Run containers can idle for minutes between requests, killing keep-alive connections. Also, never silently swallow distribution failures - always track and alert on them.
### FFmpeg Path Escaping
For subprocess without shell, FFmpeg filter paths need: apostrophes escaped as `'\\''`, special chars as `\\[char]`.
@@ -637,6 +669,9 @@ Langfuse v3 is built on OpenTelemetry. If `CallbackHandler()` is created without
### Cold Start Mitigation
Set `min-instances > 0` for Cloud Run services with heavy initialization.
### Never Call sync-over-async from FastAPI async Routes (Feb 2026)
Sync methods that internally create new event loops (`asyncio.new_event_loop()` + `loop.run_until_complete()`) will **block the FastAPI event loop** when called from `async def` routes or background tasks. The response body gets queued but never flushed because the blocked loop can't process I/O — causing 20-36s endpoint latency instead of <1s. **Fix**: Either (a) call the underlying async client directly with `await` (preferred — e.g., `await flacfetch_client.download_by_id()`), or (b) wrap sync calls in `await asyncio.to_thread()` / `loop.run_in_executor()` to run them in a thread pool. The `nest_asyncio` library is NOT a reliable workaround — it patches CPython internals and can cause deadlocks. See `audio_search.py` and `youtube_download_service.py` for the correct async patterns.
---
## Data & Storage
+7 -1
View File
@@ -34,7 +34,7 @@
## Known Issues
- CDG format generation requires additional style configuration
(No known issues)
## Pending Work
@@ -42,6 +42,12 @@
## Recent Changes
- **Fix Event Loop Blocking in Audio Search Endpoints** (2026-02-28): Fixed `/api/audio-search/{job_id}/select` taking 20-36s to respond (should be <1s) and `/api/audio-search/search` sometimes taking 25-47s. **Root cause**: Async endpoints called sync methods that create new event loops via `loop.run_until_complete()`, blocking the FastAPI event loop — response body was queued but never flushed. **Fix**: RED/OPS and Spotify download paths now call `FlacfetchClient` async methods directly (matching `YouTubeDownloadService` pattern), generic downloads use `asyncio.to_thread()`, search endpoint uses `search_async()`. Also fixed `InsufficientCreditsError` occasionally returning 500 instead of 402 by using `isinstance()` check. Added 14 new tests. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
- **GDrive Cleanup Robustness + Brand Code Race Fix** (2026-02-27): Fixed duplicate brand codes appearing in the public Google Drive share after the daily E2E test (NOMAD-1271 appearing for both the test job "piri - dog" and real song "Hot Mulligan - Pop Shuvit"). **Root causes**: (1) `if gdrive_files:` was falsy for empty dict `{}` — when GDrive upload silently failed (pre-PR #417), the entire GDrive cleanup block was skipped, (2) Brand code was recycled immediately after Dropbox cleanup succeeded, without confirming GDrive was also clean — a new job could claim the recycled code while old GDrive files still existed. **Fixes**: Added `find_files_by_brand_code()` fallback to `GoogleDriveService` that searches CDG/MP4/MP4-720p subfolders by brand code prefix when tracked file IDs aren't available. `cleanup-distribution` endpoint now: (a) uses tracked file IDs (fast path) or falls back to brand_code search, (b) only recycles the brand code after **both** Dropbox AND GDrive are confirmed clean. Added `scripts/cleanup_test_job_gdrive.py` remediation script. Added 14 new tests (94% coverage on gdrive_service.py).
- **CDG Packaging Fail-Fast Validation** (2026-02-27): Fixed silent CDG generation failures where jobs completed with `enable_cdg=True` but no CDG ZIP was produced. **Root cause**: Jobs 5b6aba25 and 5161b069 had `instrumental_selection: custom` but before commit b671b83f, the orchestrator had no `custom` case — it fell through to `"Backing"` suffix. The CDG generator then hit a `FileNotFoundError` looking for the wrong filename, which was silently caught. **Fix**: (1) Orchestrator now validates CDG/TXT outputs after packaging stage and before encoding — if `enable_cdg=True` but no CDG ZIP was produced, the pipeline fails fast instead of silently continuing to expensive encoding, (2) Missing LRC file now raises when CDG/TXT is enabled instead of silently skipping, (3) Added `scripts/regenerate_cdg.py` remediation script for affected jobs. Removed "CDG requires additional style configuration" known issue (the nomad theme has complete CDG styles). Added 7 new tests for validation logic.
- **GCE Encoding Pipeline Resilience** (2026-02-26): Made encoding pipeline resilient to Cloud Run deployment interruptions. A deployment killed a poller mid-encoding, leaving job a03ad39c permanently stuck at `encoding` status. Three fixes: (1) GCE worker `/encode` endpoint now idempotent — returns cached results for completed jobs, allows retry on failure, returns status for in-progress (previously hard 409 reject), (2) `encoding_service.py` handles cached/in_progress responses and falls back to status check on 409, (3) Health service detects jobs stuck in `encoding` >50 min. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#resilient-remote-worker-interactions-feb-2026).
- **Private (Non-Published) Tracks** (2026-02-24): Added `is_private` flag on jobs for private/non-published track production. Private jobs upload to Dropbox `Tracks-NonPublished` folder with `NOMADNP` brand prefix, skip YouTube and Google Drive entirely, and send completion emails without the YouTube section. Available as a checkbox on all job creation tabs and as an admin toggle (auto-deletes outputs when toggling a completed job to private). See [archive/2026-02-24-private-tracks-plan.md](archive/2026-02-24-private-tracks-plan.md).
+94
View File
@@ -0,0 +1,94 @@
# Troubleshooting
Operational runbooks for known production issues.
---
## Job stuck at `encoding` status
**Cause:** A Cloud Run deployment killed the poller mid-encoding. The GCE worker finished but nobody received the result. The health service will flag this as `encoding_stuck` after 50 minutes.
**Recovery:**
```bash
# 1. Confirm the job is flagged
curl -s "https://api.nomadkaraoke.com/api/health/job-consistency" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
| python3 -m json.tool | grep -A3 "encoding_stuck"
# 2. Check what the GCE worker knows about the job
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
curl -s "$WORKER_URL/status/YOUR_JOB_ID" -H "X-API-Key: $WORKER_KEY" | python3 -m json.tool
# 3. Re-trigger the video worker — it will pick up the cached GCE result if encoding
# already finished, or rejoin the poll if it's still running
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
-H "Content-Type: application/json" \
-d '{"job_id": "YOUR_JOB_ID"}'
```
**Note:** SSH-restarting the encoding worker is **not needed** since v0.119.6 (PR #413). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
---
## CDG/TXT packages missing from completed job
**Cause:** Before v0.119.7, CDG/TXT generation failures were silently caught. Jobs would complete with `enable_cdg=True` but no CDG ZIP in outputs. Fixed in v0.119.7 with fail-fast validation — new jobs will now fail loudly if CDG/TXT generation fails.
**Recovery** (for jobs that already completed without CDG/TXT):
```bash
# Regenerate and distribute CDG/TXT packages for specific jobs
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
# Example:
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python -m scripts.regenerate_cdg 5b6aba25 5161b069
```
The script is idempotent — re-running it skips regeneration if the CDG ZIP already exists in GCS and proceeds to any missing distribution steps (GDrive, Dropbox).
---
## GCE encoding worker on wrong wheel version
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
```bash
# Check current wheel version
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health | python3 -m json.tool"
# Restart to pick up latest wheel
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
---
## Google Drive uploads missing (gdrive_files empty)
**Symptoms:** Jobs complete successfully but `state_data.gdrive_files` is empty `{}`. Cloud Run logs show `BrokenPipeError` or `SSL: UNEXPECTED_EOF_WHILE_READING`.
**Cause:** Stale HTTP connections in the singleton `GoogleDriveService`. Since v0.119.7, this is handled automatically with retry + connection reset.
**Backfill affected jobs:**
```bash
# Dry run - list affected jobs
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python scripts/backfill_gdrive_uploads.py --all-missing --dry-run
# Run for real
GCS_BUCKET_NAME=karaoke-gen-storage-nomadkaraoke \
GOOGLE_CLOUD_PROJECT=nomadkaraoke \
python scripts/backfill_gdrive_uploads.py --all-missing
# Specific jobs
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
```
@@ -0,0 +1,109 @@
# GDrive Validator: Email Alerts, Manual Trigger, Post-Job Check
## Context
The GDrive validator cloud function checks the public Google Drive share for duplicate brand codes, invalid filenames, and sequence gaps. Currently it:
- Runs once daily at 9 PM Eastern via Cloud Scheduler
- Sends results via Pushbullet (easy to miss, no persistent record)
- Cannot be easily triggered manually
- Doesn't run after each job, so issues can persist for up to 24 hours before detection
The recent NOMAD-1271 duplicate brand code incident showed that daily checks aren't frequent enough — the duplicate existed for at least a day before manual discovery.
## Changes
### 1. Cloud Function: Replace Pushbullet with Email (SendGrid)
**File:** `infrastructure/functions/gdrive_validator/main.py`
- Replace `send_pushbullet_notification()` with `send_email_notification()` using SendGrid API
- SendGrid API key already in Secret Manager as `sendgrid-api-key`
- Send from `gen@nomadkaraoke.com` to `gen@nomadkaraoke.com`
- Keep Pushbullet as a secondary fallback (both are cheap; belt + suspenders)
- Add `SENDGRID_API_KEY` env var to the function
**File:** `infrastructure/functions/gdrive_validator/requirements.txt`
- Add `sendgrid>=6.0.0`
**File:** `infrastructure/__main__.py`
- Add `sendgrid-api-key` secret to the function's `secret_environment_variables`
- Add `EMAIL_TO` env var = `gen@nomadkaraoke.com`
**File:** `infrastructure/functions/gdrive_validator/deploy.sh`
- Add `--set-secrets` entry for `SENDGRID_API_KEY=sendgrid-api-key:latest`
- Add `--set-env-vars` entry for `EMAIL_TO=gen@nomadkaraoke.com`
### 2. Local Command: `check_public_share`
**File:** `scripts/check_public_share.py`
- Calls the Cloud Function via `gcloud functions call gdrive-validator --region=us-central1`
- Parses the JSON response and prints formatted results to terminal
- Exit code 0 = all clear, 1 = issues found, 2 = error
- Supports `--json` flag for raw JSON output
### 3. Post-Job Trigger from Backend
**File:** `backend/services/gdrive_validator_client.py` (new)
- Lightweight client that calls the Cloud Function via HTTP with OIDC token
- Uses `google.oauth2.id_token.fetch_id_token()` for authentication
- Fire-and-forget pattern (never blocks or fails the job)
- Logs the response but does not raise on validation issues (just notifies)
**File:** `backend/workers/video_worker_orchestrator.py`
- After `_run_notifications()` (line ~253), add a new call: `await self._trigger_gdrive_validation()`
- Only triggers for non-private, non-test jobs (private jobs don't upload to public share)
- Wrapped in try/except so validation failure never blocks job completion
**File:** `infrastructure/__main__.py`
- Add IAM binding: grant `karaoke-backend` service account `roles/cloudfunctions.invoker` on the gdrive-validator function
- For Gen2 functions also need `roles/run.invoker` on the underlying Cloud Run service
**File:** `infrastructure/modules/iam/backend_sa.py`
- Add the Cloud Functions invoker permission
### 4. Pulumi Infrastructure Updates
All IAM and secret changes go through `infrastructure/__main__.py` — deployed automatically on merge to main.
## Comparison: Local Script vs Cloud Function
| Check | Local Script | Cloud Function |
|-------|-------------|----------------|
| Duplicate sequence numbers | ✅ | ✅ |
| Invalid filenames | ✅ | ✅ |
| Sequence gaps (with known gaps) | ✅ | ✅ |
| Known gaps config | ✅ (identical) | ✅ (identical) |
| ZIP contents (MP3+CDG) | ✅ | ❌ (expensive, needs file download) |
| Video resolution (4K/720p) | ✅ | ❌ (expensive, needs file download) |
| Render quality (pixel check) | ✅ | ❌ (expensive, needs ffmpeg) |
| Bidirectional sync | ✅ (rclone) | ❌ (read-only) |
The cloud function correctly implements the "quick/cheap" checks (metadata-only via GDrive API). The expensive content checks (ZIP, resolution, pixel) belong in the local script since they require downloading files. No changes needed to align them.
## Files Modified
| File | Change |
|------|--------|
| `infrastructure/functions/gdrive_validator/main.py` | Add SendGrid email, keep Pushbullet as fallback |
| `infrastructure/functions/gdrive_validator/requirements.txt` | Add `sendgrid` |
| `infrastructure/functions/gdrive_validator/deploy.sh` | Add SendGrid secret + EMAIL_TO env var |
| `infrastructure/__main__.py` | Add SendGrid secret to function, add backend invoker IAM |
| `backend/services/gdrive_validator_client.py` | New: HTTP client to invoke cloud function |
| `backend/workers/video_worker_orchestrator.py` | Add post-distribution GDrive validation trigger |
| `scripts/check_public_share.py` | New: local command to trigger cloud function |
## Verification
1. Deploy cloud function with `./deploy.sh`
2. Run `python scripts/check_public_share.py` — should print formatted results and receive email at gen@nomadkaraoke.com
3. Trigger a test job or wait for the daily E2E test — after job completes, check Cloud Function logs to confirm it was invoked
4. Check gen@nomadkaraoke.com inbox for the validation email
5. Run `make test` to verify no regressions
+39
View File
@@ -185,6 +185,8 @@ gdrive_validator_function = cloudfunctionsv2.Function(
environment_variables={
"GDRIVE_FOLDER_ID": GDRIVE_FOLDER_ID,
"NOTIFY_ON_SUCCESS": "true",
"EMAIL_TO": "gen@nomadkaraoke.com",
"EMAIL_FROM": "gen@nomadkaraoke.com",
},
secret_environment_variables=[
cloudfunctionsv2.FunctionServiceConfigSecretEnvironmentVariableArgs(
@@ -193,6 +195,12 @@ gdrive_validator_function = cloudfunctionsv2.Function(
secret=all_secrets["pushbullet-api-key"].secret_id,
version="latest",
),
cloudfunctionsv2.FunctionServiceConfigSecretEnvironmentVariableArgs(
key="SENDGRID_API_KEY",
project_id=PROJECT_ID,
secret=all_secrets["sendgrid-api-key"].secret_id,
version="latest",
),
],
),
)
@@ -217,6 +225,37 @@ gdrive_validator_sa_invoker = cloudfunctionsv2.FunctionIamMember(
member=gdrive_validator_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Gen2 functions need Cloud Run invoker for the validator's own SA too
# (Cloud Scheduler OIDC token hits Cloud Run, not Cloud Functions IAM)
gdrive_validator_sa_run_invoker = gcp.cloudrunv2.ServiceIamMember(
"gdrive-validator-sa-run-invoker",
project=PROJECT_ID,
location=REGION,
name=gdrive_validator_function.name,
role="roles/run.invoker",
member=gdrive_validator_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Allow backend service account to invoke the validator (post-job trigger)
gdrive_validator_backend_invoker = cloudfunctionsv2.FunctionIamMember(
"gdrive-validator-backend-invoker",
project=PROJECT_ID,
location=REGION,
cloud_function=gdrive_validator_function.name,
role="roles/cloudfunctions.invoker",
member=backend_service_account.email.apply(lambda email: f"serviceAccount:{email}"),
)
# For Gen2 functions, also need Cloud Run invoker on the underlying service
gdrive_validator_backend_run_invoker = gcp.cloudrunv2.ServiceIamMember(
"gdrive-validator-backend-run-invoker",
project=PROJECT_ID,
location=REGION,
name=gdrive_validator_function.name, # Gen2 Cloud Run service matches function name
role="roles/run.invoker",
member=backend_service_account.email.apply(lambda email: f"serviceAccount:{email}"),
)
# Cloud Scheduler job to trigger validation daily
gdrive_validator_scheduler = cloudscheduler.Job(
"gdrive-validator-scheduler",
@@ -53,8 +53,8 @@ gcloud functions deploy "${FUNCTION_NAME}" \
--min-instances=0 \
--max-instances=1 \
--service-account="gdrive-validator@${PROJECT_ID}.iam.gserviceaccount.com" \
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX" \
--set-secrets="PUSHBULLET_API_KEY=pushbullet-api-key:latest" \
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=true" \
--set-secrets="PUSHBULLET_API_KEY=pushbullet-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest" \
--project="${PROJECT_ID}"
echo ""
@@ -6,9 +6,10 @@ Validates the Nomad Karaoke public share folder for:
- Invalid filename formats
- Sequence gaps (with configurable known gaps)
Sends Pushbullet notification if issues are detected.
Sends email notification (via SendGrid) if issues are detected.
Pushbullet is kept as a secondary fallback.
Triggered daily via Cloud Scheduler.
Triggered daily via Cloud Scheduler and after each job completion.
"""
import os
import re
@@ -28,7 +29,10 @@ logger = logging.getLogger(__name__)
# Configuration from environment variables
GDRIVE_FOLDER_ID = os.environ.get("GDRIVE_FOLDER_ID", "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX")
PUSHBULLET_API_KEY = os.environ.get("PUSHBULLET_API_KEY", "")
PUSHBULLET_API_KEY = os.environ.get("PUSHBULLET_API_KEY", "").strip()
SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY", "").strip()
EMAIL_TO = os.environ.get("EMAIL_TO", "gen@nomadkaraoke.com")
EMAIL_FROM = os.environ.get("EMAIL_FROM", "gen@nomadkaraoke.com")
# Set to "true" to receive daily summary even when no issues found
# Set to "false" to only receive notifications when issues are detected
@@ -317,12 +321,50 @@ def format_notification(issues: dict) -> tuple[str, str]:
return title, body
def send_pushbullet_notification(title: str, body: str) -> bool:
"""Send a notification via Pushbullet API."""
if not PUSHBULLET_API_KEY:
logger.warning("PUSHBULLET_API_KEY not set, skipping notification")
def send_email_notification(subject: str, body: str) -> bool:
"""Send a notification via SendGrid email API."""
if not SENDGRID_API_KEY:
logger.warning("SENDGRID_API_KEY not set, skipping email notification")
return False
try:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Email, To, Content
sg = SendGridAPIClient(api_key=SENDGRID_API_KEY)
# Convert plain text body to simple HTML (preserve whitespace/newlines)
html_body = body.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
html_body = html_body.replace("\n", "<br>\n")
html_body = f"<pre style='font-family: monospace; white-space: pre-wrap;'>{html_body}</pre>"
message = Mail(
from_email=Email(EMAIL_FROM, "Nomad Karaoke GDrive Validator"),
to_emails=To(EMAIL_TO),
subject=subject,
html_content=Content("text/html", html_body),
)
response = sg.send(message)
if 200 <= response.status_code < 300:
logger.info(f"Email notification sent to {EMAIL_TO}")
return True
else:
logger.error(f"SendGrid returned status {response.status_code}")
return False
except Exception:
logger.exception("Failed to send email notification via SendGrid")
return False
def send_pushbullet_notification(title: str, body: str) -> bool:
"""Send a notification via Pushbullet API (secondary fallback)."""
if not PUSHBULLET_API_KEY:
logger.warning("PUSHBULLET_API_KEY not set, skipping Pushbullet notification")
return False
try:
response = requests.post(
"https://api.pushbullet.com/v2/pushes",
@@ -345,6 +387,13 @@ def send_pushbullet_notification(title: str, body: str) -> bool:
return False
def send_notification(title: str, body: str) -> bool:
"""Send notification via email (primary) and Pushbullet (fallback). Returns True if any succeeded."""
email_sent = send_email_notification(title, body)
pushbullet_sent = send_pushbullet_notification(title, body)
return email_sent or pushbullet_sent
@functions_framework.http
def validate_gdrive(request):
"""
@@ -376,11 +425,10 @@ def validate_gdrive(request):
# Check if there are any issues
if has_issues(issues):
logger.warning(f"Validation issues found: {issues}")
# Send Pushbullet notification
title, body = format_notification(issues)
notification_sent = send_pushbullet_notification(title, body)
notification_sent = send_notification(title, body)
return json.dumps({
"status": "issues_found",
"issues": issues,
@@ -389,7 +437,7 @@ def validate_gdrive(request):
else:
logger.info("No validation issues found")
summary = issues['summary']
# Send daily summary notification if enabled
if NOTIFY_ON_SUCCESS:
title = "✅ Karaoke GDrive: All Clear"
@@ -404,10 +452,10 @@ def validate_gdrive(request):
f"✓ No invalid filenames\n"
f"✓ No sequence gaps"
)
notification_sent = send_pushbullet_notification(title, body)
notification_sent = send_notification(title, body)
else:
notification_sent = False
return json.dumps({
"status": "ok",
"message": "No validation issues found",
@@ -420,7 +468,7 @@ def validate_gdrive(request):
# Try to send error notification
try:
send_pushbullet_notification(
send_notification(
"❌ Karaoke GDrive Validator Error",
f"Validation failed with error:\n\n{e!s}"
)
@@ -8,3 +8,6 @@ functions-framework>=3.0.0
# HTTP requests for Pushbullet API
requests>=2.31.0
# Email notifications via SendGrid
sendgrid>=6.0.0
+3
View File
@@ -41,6 +41,9 @@ def create_secrets() -> dict[str, secretmanager.Secret]:
# Notifications
"pushbullet-api-key",
# Internal service URLs
"gdrive-validator-url",
# Web Push (VAPID keys for mobile push notifications)
"vapid-public-key",
"vapid-private-key",
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.119.6"
version = "0.119.10"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""
Backfill Google Drive uploads for jobs that completed with empty gdrive_files.
This addresses the issue where GDrive uploads silently failed due to stale
HTTP connections (BrokenPipeError / SSLError) on idle Cloud Run containers.
Usage:
# Dry run - show what would be uploaded
python scripts/backfill_gdrive_uploads.py --dry-run --job-ids ca408e46,99baa198
# Upload specific jobs
python scripts/backfill_gdrive_uploads.py --job-ids ca408e46,99baa198
# Find and upload all jobs with empty gdrive_files
python scripts/backfill_gdrive_uploads.py --all-missing
# Override gdrive folder ID (instead of using DEFAULT_GDRIVE_FOLDER_ID env var)
python scripts/backfill_gdrive_uploads.py --job-ids ca408e46 --gdrive-folder-id 1abc...
Requires:
- google-cloud-firestore
- google-cloud-storage
- google-api-python-client, google-auth
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
"""
import argparse
import logging
import os
import sys
import tempfile
# Add project root to path so we can import backend modules
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from google.cloud import firestore, storage
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logger = logging.getLogger(__name__)
GCS_BUCKET = "karaoke-gen-storage-nomadkaraoke"
PROJECT = "nomadkaraoke"
# Default GDrive public share folder (from infrastructure/config.py)
DEFAULT_GDRIVE_FOLDER_ID = "1laRKAyxo0v817SstfM5XkpbWiNKNAMSX"
# Known affected jobs from the incident
KNOWN_AFFECTED_JOBS = [
"ca408e46", "99baa198", "1e15d1dd", "ebba0996",
"cb744c24", "1389f765", "fde3ae7d", "21f4b34f",
"443c34a1", "56192d3a", "fdb4dc63", "4eeaa729",
]
def get_job(db: firestore.Client, job_id: str) -> dict | None:
"""Fetch job document from Firestore."""
doc = db.collection("jobs").document(job_id).get()
if doc.exists:
return doc.to_dict()
return None
def find_jobs_with_missing_gdrive(db: firestore.Client) -> list[dict]:
"""Find completed jobs that have empty gdrive_files in state_data.
Looks for jobs that have a brand_code (indicating they went through
distribution) but have empty or missing gdrive_files.
"""
jobs = []
query = db.collection("jobs").where("status", "==", "complete")
for doc in query.stream():
data = doc.to_dict()
state_data = data.get("state_data", {})
gdrive_files = state_data.get("gdrive_files", {})
brand_code = state_data.get("brand_code")
# Job should have had GDrive uploads if it has a brand_code
# but gdrive_files is empty/missing
if brand_code and not gdrive_files:
jobs.append({"job_id": doc.id, **data})
return jobs
def _classify_blob(filename: str) -> str | None:
"""Classify a GCS blob filename to an output_files key, or None to skip.
Only returns keys for the 3 file types that get uploaded to GDrive:
lossy 4K MP4, lossy 720p MP4, and CDG ZIP.
"""
lower = filename.lower()
if lower.endswith(".zip") and "cdg" in lower:
return "final_karaoke_cdg_zip"
if "720p" in lower and lower.endswith(".mp4"):
return "final_karaoke_lossy_720p_mp4"
if "lossy" in lower and lower.endswith(".mp4") and "720p" not in lower:
return "final_karaoke_lossy_mp4"
return None
def download_finals(gcs_client: storage.Client, job_id: str, temp_dir: str) -> dict:
"""Download only the final output files needed for GDrive upload.
Only downloads lossy 4K MP4, lossy 720p MP4, and CDG ZIP — skips
lossless files, MKVs, karaoke video, etc. to save bandwidth.
Returns dict mapping output_files keys to local paths.
"""
bucket = gcs_client.bucket(GCS_BUCKET)
prefix = f"jobs/{job_id}/finals/"
blobs = list(bucket.list_blobs(prefix=prefix))
output_files = {}
for blob in blobs:
filename = os.path.basename(blob.name)
if not filename:
continue
key = _classify_blob(filename)
if key is None:
continue
if key in output_files:
continue # already have this type
local_path = os.path.join(temp_dir, filename)
logger.info(f" Downloading {filename} ({blob.size / 1024 / 1024:.1f} MB)")
blob.download_to_filename(local_path)
output_files[key] = local_path
return output_files
def list_finals(gcs_client: storage.Client, job_id: str) -> list[str]:
"""List uploadable final output files in GCS without downloading."""
bucket = gcs_client.bucket(GCS_BUCKET)
prefix = f"jobs/{job_id}/finals/"
blobs = list(bucket.list_blobs(prefix=prefix))
return [
f"{os.path.basename(b.name)} ({b.size / 1024 / 1024:.1f} MB)"
for b in blobs
if os.path.basename(b.name) and _classify_blob(os.path.basename(b.name))
]
def backfill_job(
db: firestore.Client,
gcs_client: storage.Client,
job_id: str,
gdrive_folder_id: str,
dry_run: bool = False,
) -> bool:
"""Backfill GDrive upload for a single job.
Returns True if successful (or dry run).
"""
logger.info(f"Processing job {job_id}")
# Fetch job data
job_data = get_job(db, job_id)
if not job_data:
logger.error(f" Job {job_id} not found in Firestore")
return False
state_data = job_data.get("state_data", {})
artist = job_data.get("artist", "Unknown")
title = job_data.get("title", "Unknown")
brand_code = state_data.get("brand_code")
status = job_data.get("status")
logger.info(f" {artist} - {title} (brand: {brand_code}, status: {status})")
# Check existing gdrive_files
existing = state_data.get("gdrive_files", {})
if existing:
logger.info(f" Already has gdrive_files: {existing}")
logger.info(f" Skipping (already uploaded)")
return True
if not brand_code:
logger.warning(f" No brand code, skipping")
return False
if dry_run:
# List what files are available in GCS
files = list_finals(gcs_client, job_id)
if files:
logger.info(f" [DRY RUN] Would upload {len(files)} files to GDrive folder {gdrive_folder_id}:")
for f in files:
logger.info(f" - {f}")
else:
logger.warning(f" [DRY RUN] No final files found in GCS")
return True
# Download files and upload
with tempfile.TemporaryDirectory(prefix=f"backfill-{job_id}-") as temp_dir:
# Download finals from GCS
logger.info(f" Downloading finals from GCS...")
output_files = download_finals(gcs_client, job_id, temp_dir)
if not output_files:
logger.warning(f" No final files found in GCS")
return False
logger.info(f" Found {len(output_files)} files to upload")
# Upload to GDrive
from backend.services.gdrive_service import GoogleDriveService
gdrive = GoogleDriveService()
if not gdrive.is_configured:
logger.error(f" Google Drive not configured")
return False
base_name = f"{artist} - {title}"
uploaded = gdrive.upload_to_public_share(
root_folder_id=gdrive_folder_id,
brand_code=brand_code,
base_name=base_name,
output_files=output_files,
)
logger.info(f" Uploaded {len(uploaded)} files: {uploaded}")
# Update Firestore
db.collection("jobs").document(job_id).update({
"state_data.gdrive_files": uploaded,
})
logger.info(f" Updated Firestore state_data.gdrive_files")
return True
def main():
parser = argparse.ArgumentParser(
description="Backfill Google Drive uploads for jobs with empty gdrive_files"
)
parser.add_argument(
"--job-ids",
help="Comma-separated list of job IDs to process",
)
parser.add_argument(
"--all-missing",
action="store_true",
help="Find and process all jobs with missing gdrive_files",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be done without making changes",
)
parser.add_argument(
"--gdrive-folder-id",
default=os.getenv("DEFAULT_GDRIVE_FOLDER_ID", DEFAULT_GDRIVE_FOLDER_ID),
help=f"Google Drive folder ID for public share (default: {DEFAULT_GDRIVE_FOLDER_ID})",
)
args = parser.parse_args()
if not args.job_ids and not args.all_missing:
parser.error("Specify --job-ids or --all-missing")
db = firestore.Client(project=PROJECT)
gcs_client = storage.Client(project=PROJECT)
if args.job_ids:
job_ids = [j.strip() for j in args.job_ids.split(",")]
elif args.all_missing:
logger.info("Searching for jobs with missing GDrive uploads...")
jobs = find_jobs_with_missing_gdrive(db)
job_ids = [j["job_id"] for j in jobs]
logger.info(f"Found {len(job_ids)} jobs with missing uploads")
if args.dry_run:
logger.info("[DRY RUN MODE]")
logger.info(f"GDrive folder: {args.gdrive_folder_id}")
success_count = 0
fail_count = 0
for job_id in job_ids:
try:
ok = backfill_job(
db, gcs_client, job_id,
gdrive_folder_id=args.gdrive_folder_id,
dry_run=args.dry_run,
)
if ok:
success_count += 1
else:
fail_count += 1
except Exception as e:
logger.error(f" Failed: {e}", exc_info=True)
fail_count += 1
logger.info(f"\nDone: {success_count} succeeded, {fail_count} failed out of {len(job_ids)} jobs")
if __name__ == "__main__":
main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""
Check the public Google Drive share for issues.
Invokes the gdrive-validator Cloud Function and displays results.
Usage:
python scripts/check_public_share.py # Formatted output
python scripts/check_public_share.py --json # Raw JSON output
Exit codes:
0 = all clear
1 = issues found
2 = error
"""
import argparse
import json
import subprocess
import sys
PROJECT_ID = "nomadkaraoke"
REGION = "us-central1"
FUNCTION_NAME = "gdrive-validator"
def call_cloud_function() -> dict:
"""Call the GDrive validator Cloud Function via gcloud."""
result = subprocess.run(
[
"gcloud", "functions", "call", FUNCTION_NAME,
f"--region={REGION}",
f"--project={PROJECT_ID}",
"--format=json",
],
capture_output=True,
text=True,
timeout=120,
)
if result.returncode != 0:
raise RuntimeError(f"gcloud call failed: {result.stderr.strip()}")
# gcloud functions call --format=json returns the response as a double-encoded JSON string
parsed = json.loads(result.stdout)
# If parsed is a string, it's the double-encoded function response
if isinstance(parsed, str):
return json.loads(parsed)
# If it's a dict with a "result" field (older gcloud versions), unwrap it
if isinstance(parsed, dict) and "result" in parsed:
inner = parsed["result"]
return json.loads(inner) if isinstance(inner, str) else inner
return parsed
def print_formatted(data: dict):
"""Print validation results in a human-readable format."""
status = data.get("status", "unknown")
if status == "ok":
summary = data.get("summary", {})
print("✅ All clear - no issues found\n")
print(f" MP4: {summary.get('mp4', 0):,} files")
print(f" MP4-720p:{summary.get('mp4_720p', 0):,} files")
print(f" CDG: {summary.get('cdg', 0):,} files")
print(f" Total: {summary.get('total', 0):,} files")
return
if status == "issues_found":
issues = data.get("issues", {})
# Duplicates
dupes = issues.get("duplicates", {})
if dupes:
print("⚠️ DUPLICATES:")
for folder, seq_map in dupes.items():
for seq_num, filenames in seq_map.items():
print(f" {folder}: NOMAD-{int(seq_num):04d} appears {len(filenames)} times")
for f in filenames[:3]:
print(f" - {f}")
if len(filenames) > 3:
print(f" - ...and {len(filenames) - 3} more")
print()
# Invalid filenames
invalid = issues.get("invalid_filenames", {})
if invalid:
print("⚠️ INVALID FILENAMES:")
for folder, filenames in invalid.items():
for f in filenames[:5]:
print(f" {folder}: {f}")
if len(filenames) > 5:
print(f" ...and {len(filenames) - 5} more in {folder}")
print()
# Gaps
gaps = issues.get("gaps", {})
if gaps:
print("⚠️ SEQUENCE GAPS:")
for folder, missing in gaps.items():
if len(missing) <= 10:
print(f" {folder}: missing {', '.join(map(str, missing))}")
else:
print(f" {folder}: {len(missing)} gaps (first 5: {', '.join(map(str, missing[:5]))}...)")
print()
# Summary
summary = issues.get("summary", {})
print(f"Checked: {summary.get('mp4', 0)} MP4, {summary.get('mp4_720p', 0)} 720p, {summary.get('cdg', 0)} CDG files")
return
if status == "warning":
print(f"⚠️ {data.get('message', 'Unknown warning')}")
return
print(f"❌ Unexpected status: {status}")
print(f" {data.get('message', '')}")
def main():
parser = argparse.ArgumentParser(description="Check public GDrive share for issues")
parser.add_argument("--json", action="store_true", help="Output raw JSON")
args = parser.parse_args()
try:
data = call_cloud_function()
except Exception as e:
if args.json:
print(json.dumps({"status": "error", "message": str(e)}))
else:
print(f"❌ Error: {e}")
sys.exit(2)
if args.json:
print(json.dumps(data, indent=2))
else:
print_formatted(data)
status = data.get("status", "error")
if status == "ok":
sys.exit(0)
elif status == "issues_found":
sys.exit(1)
else:
sys.exit(2)
if __name__ == "__main__":
main()
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""
Remove stranded E2E test job files from the Google Drive public share.
These files were left behind by the daily happy-path E2E test before the
cleanup-distribution endpoint existed (pre-PR #411) or when the GDrive
cleanup was silently skipped because gdrive_files was empty.
Usage:
# Dry run - show what would be deleted
python scripts/cleanup_test_job_gdrive.py --dry-run
# Delete all test job files (files whose name contains test song patterns)
python scripts/cleanup_test_job_gdrive.py
# Delete files with a specific brand code
python scripts/cleanup_test_job_gdrive.py --brand-code NOMAD-1271
# Use a different GDrive folder ID
python scripts/cleanup_test_job_gdrive.py --gdrive-folder-id 1abc...
Requires:
- google-api-python-client, google-auth
- DEFAULT_GDRIVE_FOLDER_ID env var (or --gdrive-folder-id flag)
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
(alternatively: gdrive-oauth-credentials secret in Secret Manager)
The test song used by the E2E happy path is:
Artist: piri
Title: dog
"""
import argparse
import json
import logging
import os
import sys
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logger = logging.getLogger(__name__)
# Patterns that identify test job files
# These match files created by the E2E happy-path test
TEST_FILE_PATTERNS = [
"piri - dog", # Current test song (artist: piri, title: dog)
]
PUBLIC_SHARE_SUBFOLDERS = ["CDG", "MP4", "MP4-720p"]
def build_gdrive_service():
"""Build Google Drive API service from credentials."""
try:
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
# Try Secret Manager first
try:
import google.cloud.secretmanager as sm
client = sm.SecretManagerServiceClient()
name = "projects/nomadkaraoke/secrets/gdrive-oauth-credentials/versions/latest"
response = client.access_secret_version(request={"name": name})
creds_data = json.loads(response.payload.data.decode("utf-8"))
credentials = Credentials(
token=creds_data.get("token"),
refresh_token=creds_data.get("refresh_token"),
token_uri=creds_data.get("token_uri", "https://oauth2.googleapis.com/token"),
client_id=creds_data.get("client_id"),
client_secret=creds_data.get("client_secret"),
scopes=creds_data.get("scopes", ["https://www.googleapis.com/auth/drive.file"]),
)
logger.info("Using GDrive credentials from Secret Manager")
except Exception as e:
logger.warning(f"Secret Manager failed ({e}), falling back to ADC")
import google.auth
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/drive"]
)
return build("drive", "v3", credentials=credentials)
except ImportError as e:
logger.error(f"Missing dependency: {e}")
logger.error("Install with: pip install google-api-python-client google-auth google-cloud-secret-manager")
sys.exit(1)
def find_test_files(service, root_folder_id: str, patterns: list[str]) -> list[dict]:
"""
Search CDG/, MP4/, MP4-720p/ subfolders for files matching test song patterns.
Returns list of dicts: {name, id, subfolder}
"""
found = []
for subfolder in PUBLIC_SHARE_SUBFOLDERS:
escaped = subfolder.replace("'", "\\'")
query = (
f"name='{escaped}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = 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, skipping")
continue
subfolder_id = results["files"][0]["id"]
logger.debug(f"Found subfolder '{subfolder}': {subfolder_id}")
# List all files in this subfolder
page_token = None
while True:
kwargs = dict(
q=f"'{subfolder_id}' in parents and trashed=false",
fields="nextPageToken, files(id, name)",
supportsAllDrives=True,
includeItemsFromAllDrives=True,
pageSize=200,
)
if page_token:
kwargs["pageToken"] = page_token
response = service.files().list(**kwargs).execute()
for f in response.get("files", []):
name_lower = f["name"].lower()
for pattern in patterns:
if pattern.lower() in name_lower:
found.append({
"name": f["name"],
"id": f["id"],
"subfolder": subfolder,
})
break
page_token = response.get("nextPageToken")
if not page_token:
break
return found
def find_files_by_brand_code(service, root_folder_id: str, brand_code: str) -> list[dict]:
"""Find all files with a specific brand code prefix in the public share subfolders."""
found = []
for subfolder in PUBLIC_SHARE_SUBFOLDERS:
escaped = subfolder.replace("'", "\\'")
query = (
f"name='{escaped}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = service.files().list(
q=query, fields="files(id, name)",
supportsAllDrives=True, includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
continue
subfolder_id = results["files"][0]["id"]
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents and trashed=false"
)
file_results = 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.append({
"name": f["name"],
"id": f["id"],
"subfolder": subfolder,
})
return found
def main():
parser = argparse.ArgumentParser(
description="Remove stranded E2E test job files from Google Drive public share"
)
parser.add_argument("--dry-run", action="store_true", help="Show what would be deleted")
parser.add_argument(
"--gdrive-folder-id",
default=os.getenv("DEFAULT_GDRIVE_FOLDER_ID"),
help="Root Google Drive folder ID (defaults to DEFAULT_GDRIVE_FOLDER_ID env var)",
)
parser.add_argument(
"--brand-code",
help="Delete only files with this specific brand code (e.g., NOMAD-1271)",
)
parser.add_argument(
"--patterns",
nargs="+",
default=TEST_FILE_PATTERNS,
help="Filename patterns to match (default: piri - dog)",
)
args = parser.parse_args()
if not args.gdrive_folder_id:
logger.error(
"No GDrive folder ID. Set DEFAULT_GDRIVE_FOLDER_ID env var "
"or pass --gdrive-folder-id"
)
sys.exit(1)
logger.info(f"GDrive root folder: {args.gdrive_folder_id}")
if args.dry_run:
logger.info("DRY RUN - no files will be deleted")
service = build_gdrive_service()
if args.brand_code:
logger.info(f"Searching for files with brand code: {args.brand_code}")
files = find_files_by_brand_code(service, args.gdrive_folder_id, args.brand_code)
else:
logger.info(f"Searching for test job files matching patterns: {args.patterns}")
files = find_test_files(service, args.gdrive_folder_id, args.patterns)
if not files:
logger.info("No test job files found")
return
logger.info(f"\nFound {len(files)} file(s) to delete:")
for f in files:
logger.info(f" [{f['subfolder']}] {f['name']} (id: {f['id']})")
if args.dry_run:
logger.info("\nDry run complete - no files deleted")
return
confirm = input(f"\nDelete {len(files)} file(s)? [y/N] ")
if confirm.lower() != "y":
logger.info("Aborted")
return
deleted = 0
failed = 0
for f in files:
try:
service.files().delete(
fileId=f["id"], supportsAllDrives=True
).execute()
logger.info(f"Deleted: [{f['subfolder']}] {f['name']}")
deleted += 1
except Exception as e:
logger.error(f"Failed to delete {f['name']}: {e}")
failed += 1
logger.info(f"\nDone: {deleted} deleted, {failed} failed")
if __name__ == "__main__":
main()
+395
View File
@@ -0,0 +1,395 @@
#!/usr/bin/env python3
"""
Regenerate CDG ZIP packages for jobs that completed without them.
This one-time remediation script handles the case where jobs completed with
enable_cdg=True but the CDG ZIP wasn't produced (e.g., due to the custom
instrumental path bug fixed in b671b83f).
For each job, the script:
1. Fetches job data from Firestore
2. Downloads LRC and instrumental audio from GCS
3. Loads theme CDG styles
4. Generates CDG package using PackagingService
5. Uploads CDG ZIP to GCS
6. Updates file_urls.packages.cdg_zip in Firestore
7. Uploads CDG ZIP to Google Drive (if GDrive was used)
8. Updates state_data.gdrive_files in Firestore
9. Uploads CDG/TXT ZIPs to Dropbox (if Dropbox was used)
Usage:
python -m scripts.regenerate_cdg JOB_ID [JOB_ID ...]
python -m scripts.regenerate_cdg 5b6aba25 5161b069
Requirements:
- GOOGLE_CLOUD_PROJECT=nomadkaraoke (or set via gcloud config)
- gcloud auth application-default login (for GCS/Firestore access)
"""
import argparse
import logging
import os
import sys
import tempfile
from pathlib import Path
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
from backend.services.storage_service import StorageService
from backend.services.job_manager import JobManager
from backend.services.packaging_service import PackagingService
from karaoke_gen.style_loader import get_cdg_format
from karaoke_gen.utils import sanitize_filename
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("regenerate_cdg")
def get_instrumental_gcs_key(instrumental_selection: str) -> str:
"""Get the GCS file_urls.stems key for the instrumental selection."""
if instrumental_selection == "custom":
return "custom_instrumental"
elif instrumental_selection == "clean":
return "instrumental_clean"
else: # with_backing
return "instrumental_with_backing"
def get_instrumental_suffix(instrumental_selection: str) -> str:
"""Get the filename suffix for the instrumental selection."""
if instrumental_selection == "custom":
return "Custom"
elif instrumental_selection == "clean":
return "Clean"
else:
return "Backing"
def regenerate_cdg_for_job(job_id: str, storage: StorageService, job_manager: JobManager, dry_run: bool = False):
"""Regenerate CDG ZIP for a single job."""
logger.info(f"=== Processing job {job_id} ===")
# 1. Fetch job from Firestore
job = job_manager.get_job(job_id)
if not job:
logger.error(f"Job {job_id} not found in Firestore")
return False
logger.info(f"Job: {job.artist} - {job.title}")
logger.info(f" enable_cdg: {job.enable_cdg}")
logger.info(f" status: {job.status}")
if not job.enable_cdg:
logger.warning(f"Job {job_id} does not have enable_cdg=True, skipping")
return False
# Check if CDG already exists in GCS
existing_cdg = job.file_urls.get("packages", {}).get("cdg_zip")
cdg_already_in_gcs = existing_cdg and storage.file_exists(existing_cdg)
if cdg_already_in_gcs:
logger.info(f"CDG ZIP already exists in GCS: {existing_cdg}")
elif existing_cdg:
logger.warning("CDG ZIP in Firestore but NOT in GCS, will regenerate")
# Get instrumental selection
instrumental_selection = job.state_data.get("instrumental_selection", "clean")
logger.info(f" instrumental_selection: {instrumental_selection}")
# Get lyrics metadata for countdown padding
lyrics_metadata = job.state_data.get("lyrics_metadata", {})
lrc_has_countdown_padding = lyrics_metadata.get("has_countdown_padding", False)
countdown_padding_seconds = lyrics_metadata.get("countdown_padding_seconds", 3.0)
logger.info(f" countdown_padding: {lrc_has_countdown_padding} ({countdown_padding_seconds}s)")
# Check required files exist in file_urls
lrc_url = job.file_urls.get("lyrics", {}).get("lrc")
if not lrc_url:
logger.error(f"Job {job_id} has no LRC file URL")
return False
instrumental_key = get_instrumental_gcs_key(instrumental_selection)
instrumental_url = job.file_urls.get("stems", {}).get(instrumental_key)
if not instrumental_url:
logger.error(f"Job {job_id} has no instrumental URL for key '{instrumental_key}'")
return False
# Get style_params for CDG styles
style_params_url = job.style_params_gcs_path
if dry_run:
logger.info(f"DRY RUN: Would regenerate CDG for {job.artist} - {job.title}")
return True
# 2. Download or regenerate CDG/TXT packages
with tempfile.TemporaryDirectory(prefix=f"cdg-regen-{job_id}-") as temp_dir:
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
base_name = f"{safe_artist} - {safe_title}"
instrumental_suffix = get_instrumental_suffix(instrumental_selection)
brand_code = getattr(job, "brand_code", None) or job.state_data.get("brand_code", "UNKNOWN")
cdg_zip_path = os.path.join(temp_dir, f"{base_name} (Final Karaoke CDG).zip")
txt_zip_path = os.path.join(temp_dir, f"{base_name} (Final Karaoke TXT).zip")
if cdg_already_in_gcs:
# Download existing CDG ZIP from GCS for distribution
logger.info("Downloading existing CDG ZIP from GCS for distribution...")
storage.download_file(existing_cdg, cdg_zip_path)
# Also download TXT if it exists
existing_txt = job.file_urls.get("packages", {}).get("txt_zip")
if existing_txt and storage.file_exists(existing_txt):
logger.info("Downloading existing TXT ZIP from GCS...")
storage.download_file(existing_txt, txt_zip_path)
else:
# Regenerate: download source files and generate packages
# Download LRC
lrc_path = os.path.join(temp_dir, f"{base_name} (Karaoke).lrc")
logger.info(f"Downloading LRC: {lrc_url}")
storage.download_file(lrc_url, lrc_path)
# Download instrumental
instrumental_path = os.path.join(temp_dir, f"{base_name} (Instrumental {instrumental_suffix}).flac")
logger.info(f"Downloading instrumental: {instrumental_url}")
storage.download_file(instrumental_url, instrumental_path)
# Download and parse style_params
import json
style_params_path = os.path.join(temp_dir, "style_params.json")
style_params = None
if style_params_url:
try:
logger.info(f"Downloading style params: {style_params_url}")
storage.download_file(style_params_url, style_params_path)
with open(style_params_path) as f:
style_params = json.load(f)
except Exception as e:
logger.warning(f"Failed to download style_params from {style_params_url}: {e}")
# Fallback: load theme style_params from GCS theme directory
if style_params is None:
theme_id = getattr(job, "theme_id", "nomad") or "nomad"
theme_path = f"themes/{theme_id}/style_params.json"
logger.info(f"Trying theme style_params: {theme_path}")
try:
storage.download_file(theme_path, style_params_path)
with open(style_params_path) as f:
style_params = json.load(f)
except Exception as e:
logger.error(f"Failed to load theme style_params: {e}")
return False
# Download CDG style assets (font, backgrounds) referenced in style_params
cdg_section = style_params.get("cdg", {})
style_dir = os.path.join(temp_dir, "style")
os.makedirs(style_dir, exist_ok=True)
# Resolve asset GCS paths. Per-job style_params have full paths like
# "themes/nomad/assets/AvenirNext-Bold.ttf". Theme-level style_params
# have bare filenames like "AvenirNext-Bold.ttf" that need to be
# resolved against the theme's assets directory.
theme_id = getattr(job, "theme_id", "nomad") or "nomad"
theme_assets_prefix = f"themes/{theme_id}/assets"
for asset_key in ["font_path", "instrumental_background", "title_screen_background", "outro_background"]:
asset_path = cdg_section.get(asset_key)
if not asset_path or not isinstance(asset_path, str) or os.path.isabs(asset_path):
continue
# Determine the GCS path — bare filenames need the theme prefix
if "/" not in asset_path:
gcs_path = f"{theme_assets_prefix}/{asset_path}"
else:
gcs_path = asset_path
local_path = os.path.join(style_dir, os.path.basename(asset_path))
try:
storage.download_file(gcs_path, local_path)
cdg_section[asset_key] = local_path
logger.info(f"Downloaded CDG asset {asset_key}: {gcs_path}")
except Exception as e:
logger.warning(f"Failed to download CDG asset {asset_key} from {gcs_path}: {e}")
# 3. Extract CDG styles
cdg_styles = get_cdg_format(style_params)
if not cdg_styles:
logger.error(f"No CDG styles found in theme for job {job_id}")
return False
logger.info("CDG styles loaded successfully")
# 4. Generate CDG package
packaging_service = PackagingService(
cdg_styles=cdg_styles,
dry_run=False,
non_interactive=True,
)
mp3_path = os.path.join(temp_dir, f"{base_name} (Karaoke).mp3")
cdg_path = os.path.join(temp_dir, f"{base_name} (Karaoke).cdg")
logger.info("Generating CDG package...")
zip_file, mp3_file, cdg_file = packaging_service.create_cdg_package(
lrc_file=lrc_path,
audio_file=instrumental_path,
output_zip_path=cdg_zip_path,
artist=job.artist,
title=job.title,
output_mp3_path=mp3_path,
output_cdg_path=cdg_path,
lrc_has_countdown_padding=lrc_has_countdown_padding,
countdown_padding_seconds=countdown_padding_seconds,
)
if not os.path.isfile(cdg_zip_path):
logger.error(f"CDG ZIP not created at expected path: {cdg_zip_path}")
return False
zip_size = os.path.getsize(cdg_zip_path)
logger.info(f"CDG ZIP created: {cdg_zip_path} ({zip_size / 1024:.1f} KB)")
# 5. Upload CDG ZIP to GCS
gcs_cdg_path = f"jobs/{job_id}/packages/cdg_zip.zip"
logger.info(f"Uploading CDG ZIP to GCS: {gcs_cdg_path}")
storage.upload_file(cdg_zip_path, gcs_cdg_path)
# 6. Update Firestore file_urls
logger.info("Updating Firestore file_urls.packages.cdg_zip")
job_manager.update_file_url(job_id, "packages", "cdg_zip", gcs_cdg_path)
# Also generate TXT if enabled
if job.enable_txt:
logger.info("Job also has enable_txt=True, generating TXT package...")
try:
txt_zip, txt_file = packaging_service.create_txt_package(
lrc_file=lrc_path,
mp3_file=mp3_path,
output_zip_path=txt_zip_path,
)
if os.path.isfile(txt_zip_path):
gcs_txt_path = f"jobs/{job_id}/packages/txt_zip.zip"
storage.upload_file(txt_zip_path, gcs_txt_path)
job_manager.update_file_url(job_id, "packages", "txt_zip", gcs_txt_path)
logger.info(f"TXT ZIP uploaded: {gcs_txt_path}")
except Exception as e:
logger.error(f"TXT generation failed: {e}")
# === Distribution steps (run for both new and existing packages) ===
# 7. Upload to GDrive if job uses it
gdrive_files = job.state_data.get("gdrive_files", {})
if gdrive_files and "cdg" not in gdrive_files:
logger.info("Uploading CDG ZIP to Google Drive...")
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
gdrive_folder_id = getattr(job, "gdrive_folder_id", None)
if gdrive_folder_id:
safe_base = sanitize_filename(f"{job.artist} - {job.title}")
filename_base = f"{brand_code} - {safe_base}"
cdg_folder_id = gdrive.get_or_create_folder(gdrive_folder_id, "CDG")
file_id = gdrive.upload_file(
cdg_zip_path,
cdg_folder_id,
f"{filename_base}.zip",
)
logger.info(f"Uploaded CDG to GDrive: {file_id}")
# 8. Update state_data.gdrive_files
gdrive_files["cdg"] = file_id
job_manager.update_job(job_id, {"state_data.gdrive_files": gdrive_files})
logger.info("Updated Firestore state_data.gdrive_files")
else:
logger.warning("No gdrive_folder_id on job, skipping GDrive upload")
else:
logger.warning("GDrive not configured, skipping upload")
except Exception as e:
logger.error(f"GDrive upload failed (non-fatal): {e}")
elif gdrive_files:
logger.info("GDrive already has CDG file, skipping GDrive upload")
else:
logger.info("No existing GDrive files, skipping GDrive upload")
# 9. Upload to Dropbox if job uses it
dropbox_path = job.dropbox_path
if dropbox_path:
logger.info("Uploading packages to Dropbox...")
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
safe_base = sanitize_filename(f"{job.artist} - {job.title}")
folder_name = f"{brand_code} - {safe_base}"
remote_folder = f"{dropbox_path}/{folder_name}"
# Upload CDG ZIP
if os.path.isfile(cdg_zip_path):
cdg_remote = f"{remote_folder}/{os.path.basename(cdg_zip_path)}"
dropbox.upload_file(cdg_zip_path, cdg_remote)
logger.info(f"Uploaded CDG to Dropbox: {cdg_remote}")
# Upload TXT ZIP
if os.path.isfile(txt_zip_path):
txt_remote = f"{remote_folder}/{os.path.basename(txt_zip_path)}"
dropbox.upload_file(txt_zip_path, txt_remote)
logger.info(f"Uploaded TXT to Dropbox: {txt_remote}")
else:
logger.warning("Dropbox not configured, skipping upload")
except Exception as e:
logger.error(f"Dropbox upload failed (non-fatal): {e}")
else:
logger.info("No dropbox_path on job, skipping Dropbox upload")
logger.info(f"=== Job {job_id} CDG regeneration complete ===")
return True
def main():
parser = argparse.ArgumentParser(
description="Regenerate CDG ZIP packages for jobs that completed without them."
)
parser.add_argument(
"job_ids",
nargs="+",
help="Job IDs to regenerate CDG for",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be done without making changes",
)
args = parser.parse_args()
storage = StorageService()
job_manager = JobManager()
results = {}
for job_id in args.job_ids:
try:
success = regenerate_cdg_for_job(job_id, storage, job_manager, dry_run=args.dry_run)
results[job_id] = "OK" if success else "FAILED"
except Exception as e:
logger.exception(f"Error processing job {job_id}: {e}")
results[job_id] = f"ERROR: {e}"
# Summary
logger.info("\n=== Summary ===")
for job_id, status in results.items():
logger.info(f" {job_id}: {status}")
# Exit with error if any failed
if any(s != "OK" for s in results.values()):
sys.exit(1)
if __name__ == "__main__":
main()