mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 18:08:07 +09:00
Compare commits
No files matched your search
+253
-4
@@ -1089,6 +1089,10 @@ jobs:
|
||||
id-token: write
|
||||
outputs:
|
||||
base_rebuilt: ${{ steps.check-base.outputs.needs_rebuild }}
|
||||
version: ${{ steps.version_check.outputs.version }}
|
||||
# R1: gates the post-deploy canary — "true" only when the backend version
|
||||
# actually changed (see "Detect backend version change" step).
|
||||
version_changed: ${{ steps.version_changed.outputs.changed }}
|
||||
env:
|
||||
REGISTRY: us-central1-docker.pkg.dev
|
||||
PROJECT_ID: nomadkaraoke
|
||||
@@ -1144,6 +1148,43 @@ jobs:
|
||||
echo "📋 Current version: $VERSION"
|
||||
echo "🚀 Deploying on every push to main"
|
||||
|
||||
# R1 gate — only run the post-deploy functional canary when the BACKEND
|
||||
# version actually changed. A frontend-/docs-/infra-only merge still runs
|
||||
# deploy-backend (image rebuild) but ships an identical version; a real
|
||||
# karaoke generation is slow + resource-heavy, so we short-circuit the
|
||||
# canary in that case. We compare the version we're about to ship against
|
||||
# the version currently served by production.
|
||||
- name: Detect backend version change
|
||||
id: version_changed
|
||||
run: |
|
||||
NEW_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
# Read the currently-serving version via the EDGE (api.nomadkaraoke.com),
|
||||
# NOT the raw Cloud Run origin URL, and retry. The single un-retried
|
||||
# origin probe returned empty on #987 (cold start on the scaled-to-zero
|
||||
# prior revision and/or origin edge-auth on the detailed endpoint), so
|
||||
# the gate fail-opened and ran the canary on a no-bump deploy — which
|
||||
# then flake-failed and paged. The edge URL is warm (real traffic) and
|
||||
# Cloudflare-fronted, so it returns the version reliably.
|
||||
CURRENT_VERSION=""
|
||||
for attempt in 1 2 3 4; do
|
||||
CURRENT_VERSION=$(curl -sf --connect-timeout 5 --max-time 25 \
|
||||
"https://api.nomadkaraoke.com/api/health/detailed" | jq -r '.version // empty' 2>/dev/null || echo "")
|
||||
[ -n "$CURRENT_VERSION" ] && break
|
||||
echo " version probe attempt $attempt/4 empty; retrying…"
|
||||
sleep 5
|
||||
done
|
||||
echo "Currently-serving version: ${CURRENT_VERSION:-<unknown>}"
|
||||
echo "New version: $NEW_VERSION"
|
||||
if [ -n "$CURRENT_VERSION" ] && [ "$CURRENT_VERSION" = "$NEW_VERSION" ]; then
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "↩️ Backend version unchanged — post-deploy canary will be SKIPPED."
|
||||
else
|
||||
# Unknown current version (first deploy / unreachable after retries) →
|
||||
# run the canary to be safe rather than skip a potentially real change.
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "✅ Backend version changed (or current unknown) — post-deploy canary will RUN."
|
||||
fi
|
||||
|
||||
- name: Capture build metadata
|
||||
id: build-meta
|
||||
run: |
|
||||
@@ -1908,17 +1949,43 @@ jobs:
|
||||
# header — i.e. direct-to-origin traffic bypassing the edge (health/root
|
||||
# exempt). Cutover done 2026-07-20; validated via prod E2E with 0 blocked
|
||||
# legit callers. To disable, set EDGE_AUTH_MODE=off here and redeploy.
|
||||
- name: Deploy to Cloud Run
|
||||
# R3/R4 — traffic-gated service canary.
|
||||
# Deploy the new revision with NO traffic and a `candidate` tag, smoke the
|
||||
# tagged candidate URL, then migrate 100% traffic only on pass. If the
|
||||
# smoke fails we simply don't migrate: traffic stays on the prior revision,
|
||||
# so a bad revision serves 0% instead of 100% (auto-revert by default).
|
||||
# NOTE: this protects only the Cloud Run *service*. The Cloud Run *jobs*
|
||||
# updated below cannot traffic-split, so they still rely on R1's real-job
|
||||
# post-deploy canary + the codified `scripts/rollback.sh` (R2).
|
||||
- name: Deploy to Cloud Run (candidate revision, no traffic)
|
||||
id: deploy_candidate
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
echo "🚀 Deploying to Cloud Run..."
|
||||
# Capture the revision currently serving traffic so we can name it in
|
||||
# logs / the failure message (it's what we auto-revert to on a failed
|
||||
# smoke — no action needed since we deploy --no-traffic).
|
||||
PREV_REVISION=$(gcloud run services describe karaoke-backend \
|
||||
--region us-central1 \
|
||||
--format='value(status.traffic[0].revisionName)' 2>/dev/null || echo "")
|
||||
echo "prev_revision=$PREV_REVISION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "🚀 Deploying candidate revision to Cloud Run (no traffic)..."
|
||||
echo "Image: $IMAGE"
|
||||
echo "Version: $VERSION"
|
||||
echo "Previously-serving revision: ${PREV_REVISION:-<unknown>}"
|
||||
|
||||
# --concurrency 16 (was 80): the backend is one uvicorn process per
|
||||
# 2-vCPU instance; review-page loads are heavy (audio byte-serving,
|
||||
# waveform work). At 80 a 10-tab burst all landed on the single
|
||||
# min-instance and wedged it ("no available instance" aborts,
|
||||
# 2026-09-18 investigation). 16 makes bursts trigger scale-out while
|
||||
# staying comfortably above normal per-instance load.
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
--no-traffic \
|
||||
--tag candidate \
|
||||
--region us-central1 \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
@@ -1928,15 +1995,69 @@ jobs:
|
||||
--cpu-throttling \
|
||||
--execution-environment gen2 \
|
||||
--timeout 1800 \
|
||||
--concurrency 80 \
|
||||
--concurrency 16 \
|
||||
--max-instances 20 \
|
||||
--min-instances 1 \
|
||||
--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,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,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,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,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,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,POSTMARK_SERVER_TOKEN=postmark-server-token: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,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms: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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
|
||||
|
||||
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
|
||||
- name: Smoke candidate revision
|
||||
run: |
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
|
||||
# The `candidate` tag gives the new (0%-traffic) revision its own URL.
|
||||
CANDIDATE_URL=$(gcloud run services describe karaoke-backend \
|
||||
--region us-central1 \
|
||||
--format='json' | jq -r '.status.traffic[] | select(.tag=="candidate") | .url' | head -1)
|
||||
|
||||
if [ -z "$CANDIDATE_URL" ] || [ "$CANDIDATE_URL" = "null" ]; then
|
||||
echo "❌ Could not resolve the candidate revision URL — aborting before traffic migration."
|
||||
exit 1
|
||||
fi
|
||||
echo "Candidate URL: $CANDIDATE_URL"
|
||||
|
||||
# Health check on the candidate only (traffic still on prior revision).
|
||||
curl -f --connect-timeout 5 --max-time 30 "$CANDIDATE_URL/api/health" || {
|
||||
echo "❌ Candidate health check failed — NOT migrating traffic (prior revision keeps serving)."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Version check with retries (new revision may take a moment to be routable).
|
||||
MAX_RETRIES=6
|
||||
RETRY_DELAY=10
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Checking candidate version (attempt $i/$MAX_RETRIES)..."
|
||||
CAND_VERSION=$(curl -sf --connect-timeout 5 --max-time 30 "$CANDIDATE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
if [ "$CAND_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Candidate serving expected version: $CAND_VERSION"
|
||||
break
|
||||
fi
|
||||
echo "⚠️ Candidate version: deployed=$CAND_VERSION expected=$EXPECTED_VERSION"
|
||||
if [ $i -lt $MAX_RETRIES ]; then
|
||||
sleep $RETRY_DELAY
|
||||
else
|
||||
echo "❌ Candidate never reported the expected version — NOT migrating traffic."
|
||||
echo " Prior revision '${{ steps.deploy_candidate.outputs.prev_revision }}' keeps serving 100%."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Migrate 100% traffic to candidate
|
||||
run: |
|
||||
echo "✅ Candidate passed smoke — migrating 100% traffic to the new revision."
|
||||
gcloud run services update-traffic karaoke-backend \
|
||||
--region us-central1 \
|
||||
--to-latest
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
# NOTE: Cloud Run *Jobs* cannot traffic-split or canary — this is an
|
||||
# image-only, all-or-nothing update picked up on each job's next
|
||||
# invocation. There is no per-revision smoke here; the jobs rely on R1's
|
||||
# post-deploy real-job canary and the codified `scripts/rollback.sh` (R2)
|
||||
# for recovery if a bad image reaches them.
|
||||
run: |
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
@@ -2026,6 +2147,134 @@ jobs:
|
||||
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
|
||||
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
|
||||
|
||||
# ============================================
|
||||
# R1 — POST-DEPLOY FUNCTIONAL CANARY (version-change-gated)
|
||||
# Runs the real production happy-path (admin-credit variant, no Stripe) after
|
||||
# a backend deploy — but ONLY when the backend version actually changed
|
||||
# (deploy-backend.outputs.version_changed == 'true'). A frontend-/docs-/
|
||||
# infra-only merge ships an identical backend version and short-circuits here,
|
||||
# so we don't burn encode-VM time + a real Drive/YouTube publish on a no-op.
|
||||
# On failure: the workflow fails loudly (Discord) — this is where an operator
|
||||
# invokes `scripts/rollback.sh` (R2) to revert the service + jobs.
|
||||
# ============================================
|
||||
deploy-verify:
|
||||
name: "Deploy - Post-Deploy Canary (Happy Path)"
|
||||
needs: [deploy-backend]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
if: >-
|
||||
github.ref == 'refs/heads/main' && github.event_name == 'push' &&
|
||||
needs.deploy-backend.result == 'success' &&
|
||||
needs.deploy-backend.outputs.version_changed == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
# Admin-credit variant: impersonate the E2E test runner (which holds
|
||||
# admin-granted credits) instead of going through Stripe. Same token-refresh
|
||||
# pattern as e2e-daily.yml's use_test_token path.
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf --connect-timeout 5 --max-time 30 -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run post-deploy happy-path canary
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
run: |
|
||||
echo "=== Post-deploy canary: happy path against production ==="
|
||||
echo "Deployed version: ${{ needs.deploy-backend.outputs.version }}"
|
||||
echo "Time: $(date)"
|
||||
# --retries=2: the happy-path has inherently flaky UI waits (e.g. the
|
||||
# review page's "proceed to instrumental" enable), and this canary
|
||||
# PAGES on failure — a single flaky attempt must not cry wolf. Only a
|
||||
# failure that survives 2 retries is treated as real.
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=chromium \
|
||||
--reporter=list \
|
||||
--retries=2 \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-canary.log
|
||||
# Capture Playwright's real exit code, not tee's (0). Matches
|
||||
# e2e-daily.yml's rationale (grepping the log is fragile).
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check canary result
|
||||
id: test_result
|
||||
run: |
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload canary artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: deploy-verify-canary-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output-canary.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Discord notification (canary failed)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 Post-deploy canary FAILED (v${{ needs.deploy-backend.outputs.version }})\", \"description\": \"The production happy-path failed AFTER deploying v${{ needs.deploy-backend.outputs.version }}. The service already migrated 100% traffic to the new revision — consider rolling back with scripts/rollback.sh.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}" || echo "Discord notify failed (non-fatal)"
|
||||
|
||||
- name: Fail if canary failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
echo "::error::Post-deploy canary failed for v${{ needs.deploy-backend.outputs.version }}."
|
||||
echo "Roll back now with:"
|
||||
echo " scripts/rollback.sh --list # find the previous good revision + version"
|
||||
echo " scripts/rollback.sh --to-revision <PREV_REV> --image-version <PREV_VERSION>"
|
||||
exit 1
|
||||
|
||||
# ============================================
|
||||
# PROPAGATE BASE IMAGE TO ALL RUNNERS
|
||||
# When base image is rebuilt, pull it to all 3 runners
|
||||
|
||||
+217
-5
@@ -11,10 +11,10 @@ import asyncio
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Tuple, List, Optional, Any, Dict
|
||||
from typing import Tuple, List, Literal, Optional, Any, Dict
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
@@ -135,6 +135,10 @@ EDITABLE_JOB_FIELDS = {
|
||||
"is_private",
|
||||
"review_mode",
|
||||
"backing_preference",
|
||||
# Exempts a job from the stale-review auto-expiry (48h cancel+refund) —
|
||||
# the stale_review_processor skips made_for_you jobs. Used for admin-driven
|
||||
# batches (e.g. KaraokeHunt outreach) that must wait at review indefinitely.
|
||||
"made_for_you",
|
||||
}
|
||||
|
||||
|
||||
@@ -631,7 +635,7 @@ async def clear_audio_search_cache(
|
||||
logger.debug(f"Skipping flacfetch cache clear - missing artist ({artist}) or title ({title})")
|
||||
|
||||
logger.info(
|
||||
f"Admin {auth_data[0]} cleared audio search cache for job {job_id}. "
|
||||
f"Admin {auth_data.user_email} cleared audio search cache for job {job_id}. "
|
||||
f"Cleared {results_count} results. Status changed from {previous_status} to pending. "
|
||||
f"Flacfetch cache cleared: {flacfetch_cache_cleared}"
|
||||
)
|
||||
@@ -681,7 +685,7 @@ async def reset_worker_state(
|
||||
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'pending'})
|
||||
job_manager.update_state_data(job_id, 'screens_progress', {'stage': 'pending'})
|
||||
|
||||
logger.info(f"Admin {auth_data[0]} reset worker state for job {job_id}")
|
||||
logger.info(f"Admin {auth_data.user_email} reset worker state for job {job_id}")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -714,7 +718,7 @@ async def clear_all_flacfetch_cache(
|
||||
try:
|
||||
deleted_count = await flacfetch_client.clear_all_cache()
|
||||
logger.info(
|
||||
f"Admin {auth_data[0]} cleared all flacfetch cache. "
|
||||
f"Admin {auth_data.user_email} cleared all flacfetch cache. "
|
||||
f"Deleted {deleted_count} entries."
|
||||
)
|
||||
return ClearAllCacheResponse(
|
||||
@@ -994,6 +998,13 @@ async def update_job(
|
||||
f"no account existed, created one"
|
||||
)
|
||||
|
||||
# A non-bool would silently break the stale-review exemption check.
|
||||
if "made_for_you" in updates and not isinstance(updates["made_for_you"], bool):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="made_for_you must be a boolean",
|
||||
)
|
||||
|
||||
# The executor treats any value other than "auto" as an enforcement blocker,
|
||||
# so a typo (e.g. "always-review") would silently force human review.
|
||||
if "review_mode" in updates and updates["review_mode"] not in ("auto", "always_review"):
|
||||
@@ -2162,6 +2173,41 @@ async def send_job_completion_email(
|
||||
)
|
||||
|
||||
|
||||
class MintLoginLinkRequest(BaseModel):
|
||||
"""Request to mint a one-click login link for a user."""
|
||||
expiry_hours: int = Field(168, ge=1, le=168)
|
||||
# e.g. "job_review:<job_id>" — verify maps known purposes to a redirect
|
||||
purpose: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/users/{email}/login-link")
|
||||
async def mint_user_login_link(
|
||||
email: str,
|
||||
request: MintLoginLinkRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Mint a one-click login link for a user (admin only). Sends NOTHING — returns
|
||||
the URL for embedding in manually-reviewed outreach emails. The link logs the
|
||||
user in and, when purpose is "job_review:<job_id>", lands them directly on
|
||||
that job's lyrics review page. Expiry up to 168h (7 days).
|
||||
"""
|
||||
import os as _os
|
||||
token = user_service.create_admin_login_token(
|
||||
email=email.strip().lower(),
|
||||
expiry_hours=request.expiry_hours,
|
||||
purpose=request.purpose,
|
||||
)
|
||||
frontend_url = _os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
|
||||
return {
|
||||
"email": token.email,
|
||||
"url": f"{frontend_url}/auth/verify?token={token.token}",
|
||||
"expires_at": token.expires_at.isoformat(),
|
||||
"purpose": request.purpose,
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Impersonation
|
||||
# =============================================================================
|
||||
@@ -4189,3 +4235,169 @@ def list_user_feedback(
|
||||
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
|
||||
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Requests board — full request history (admin view)
|
||||
# =============================================================================
|
||||
|
||||
class CommunityRequestItem(BaseModel):
|
||||
"""A requests-board song request, any status, for the admin history view."""
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
status: str
|
||||
submitted_by: str
|
||||
owner_email: Optional[str] = None
|
||||
vote_count: int
|
||||
job_id: Optional[str] = None
|
||||
youtube_url: Optional[str] = None
|
||||
review_state: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
picked_at: Optional[str] = None
|
||||
|
||||
|
||||
class CommunityRequestListResponse(BaseModel):
|
||||
requests: List[CommunityRequestItem]
|
||||
|
||||
|
||||
@router.get("/community-requests", response_model=CommunityRequestListResponse)
|
||||
async def list_community_requests(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Full history of requests-board submissions across every status — who asked,
|
||||
how it was voted, which job made it, and where it landed on YouTube."""
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
items = [
|
||||
CommunityRequestItem(
|
||||
id=r.id, artist=r.artist, title=r.title, status=r.status,
|
||||
submitted_by=r.submitted_by, owner_email=r.owner_email,
|
||||
vote_count=r.vote_count, job_id=r.job_id, youtube_url=r.youtube_url,
|
||||
review_state=r.review_state,
|
||||
created_at=r.created_at.isoformat() if r.created_at else None,
|
||||
picked_at=r.picked_at.isoformat() if r.picked_at else None,
|
||||
)
|
||||
for r in service.list_all()
|
||||
]
|
||||
return CommunityRequestListResponse(requests=items)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Requests board — existing-community-version review queue
|
||||
# =============================================================================
|
||||
|
||||
class CommunityReviewItem(BaseModel):
|
||||
"""A requests-board pick held for existing-community-version review."""
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
submitted_by: str
|
||||
vote_count: int
|
||||
upvoter_count: int
|
||||
community_versions: Optional[Dict[str, Any]] = None
|
||||
community_checked_at: Optional[str] = None
|
||||
|
||||
|
||||
class CommunityReviewListResponse(BaseModel):
|
||||
reviews: List[CommunityReviewItem]
|
||||
|
||||
|
||||
class CommunityReviewActionBody(BaseModel):
|
||||
# make = make our own version anyway; reject = decline + notify up-voters of the
|
||||
# existing version; keep = leave on the board, snooze re-review.
|
||||
action: Literal["make", "reject", "keep"]
|
||||
|
||||
|
||||
class CommunityReviewActionResponse(BaseModel):
|
||||
status: str
|
||||
request_id: str
|
||||
message: str
|
||||
|
||||
|
||||
@router.get("/community-reviews", response_model=CommunityReviewListResponse)
|
||||
async def list_community_reviews(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List requests-board picks the daily picker flagged because an existing
|
||||
community karaoke version was found (awaiting keep/make/reject)."""
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
items = []
|
||||
for r in service.list_pending_reviews():
|
||||
try:
|
||||
upvoters = service.list_upvoters(r.id)
|
||||
except Exception:
|
||||
upvoters = []
|
||||
items.append(CommunityReviewItem(
|
||||
id=r.id, artist=r.artist, title=r.title, submitted_by=r.submitted_by,
|
||||
vote_count=r.vote_count, upvoter_count=len(upvoters),
|
||||
community_versions=r.community_versions,
|
||||
community_checked_at=r.community_checked_at.isoformat() if r.community_checked_at else None,
|
||||
))
|
||||
return CommunityReviewListResponse(reviews=items)
|
||||
|
||||
|
||||
@router.post("/community-reviews/{request_id}", response_model=CommunityReviewActionResponse)
|
||||
async def action_community_review(
|
||||
request_id: str,
|
||||
body: CommunityReviewActionBody,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Resolve a flagged pick: make our own version, reject (notify up-voters of the
|
||||
existing version), or keep it on the board (snooze re-review)."""
|
||||
from backend.config import get_settings
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
settings = get_settings()
|
||||
|
||||
req = service.get_request(request_id)
|
||||
if req is None or req.review_state != "pending":
|
||||
raise HTTPException(status_code=404, detail="No pending review for that request.")
|
||||
|
||||
if body.action == "keep":
|
||||
until = datetime.now(timezone.utc) + timedelta(days=settings.community_review_snooze_days)
|
||||
service.snooze_review(request_id, until)
|
||||
return CommunityReviewActionResponse(
|
||||
status="snoozed", request_id=request_id,
|
||||
message=f"Kept on the board; won't be re-flagged for {settings.community_review_snooze_days} days.",
|
||||
)
|
||||
|
||||
if body.action == "reject":
|
||||
versions = req.community_versions or {}
|
||||
best_url = versions.get("best_youtube_url")
|
||||
if not best_url:
|
||||
tracks = versions.get("tracks") or []
|
||||
best_url = tracks[0].get("youtube_url") if tracks else None
|
||||
service.reject_request(request_id)
|
||||
# Notify up-voters of the existing community version (best-effort fan-out).
|
||||
notified = 0
|
||||
try:
|
||||
from backend.services.job_notification_service import get_job_notification_service
|
||||
notifier = get_job_notification_service()
|
||||
for voter in service.list_upvoters(request_id):
|
||||
ok = await notifier.send_community_existing_version_email(
|
||||
to_email=voter, artist=req.artist, title=req.title, youtube_url=best_url,
|
||||
)
|
||||
notified += 1 if ok else 0
|
||||
except Exception:
|
||||
logger.exception("community-review reject: voter notify failed for %s", request_id)
|
||||
return CommunityReviewActionResponse(
|
||||
status="rejected", request_id=request_id,
|
||||
message=f"Rejected; notified {notified} up-voter(s) of the existing version.",
|
||||
)
|
||||
|
||||
# action == "make": clear the flag and provision the job now (grant + create).
|
||||
from backend.workers.community_daily_pick import _provision_and_start
|
||||
service.clear_review(request_id)
|
||||
owner = (req.owner_email or req.submitted_by).lower()
|
||||
result = await _provision_and_start(service, settings, req, owner)
|
||||
if result.get("status") != "made":
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Failed to make request ({result.get('step')}): {result.get('message')}",
|
||||
)
|
||||
return CommunityReviewActionResponse(
|
||||
status="made", request_id=request_id,
|
||||
message=f"Making our version (job {result.get('job_id')}).",
|
||||
)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""POST /api/client-events — persistent telemetry for user-visible degradation.
|
||||
|
||||
Records every time the frontend shows a user a degraded-service surface (the
|
||||
orange "trouble reaching our servers" banner, the stronger "temporarily
|
||||
unavailable" error, a failed lyrics load, a slow/failed waveform), with enough
|
||||
metadata to review frequency and context later. Two sinks per event:
|
||||
|
||||
1. A structured INFO log line (``client_event type=…``) — queryable in Cloud
|
||||
Logging / Log Analytics alongside backend symptoms from the same window.
|
||||
2. A Firestore doc in ``client_events`` — survives log retention, cheap to
|
||||
aggregate for "how often are users seeing this?" reviews.
|
||||
|
||||
Unauthenticated (review-token users must be able to report) and rate-limited
|
||||
per IP, mirroring /api/client-errors. The limiter is process-local, so the
|
||||
effective ceiling is 120/min/IP × live instances — acceptable for this threat
|
||||
model (non-malicious browsers, 60s client-side per-type throttle); Cloudflare's
|
||||
zone-wide rate limit sits in front as a flood backstop. Events are dropped,
|
||||
never queued, when the limiter trips — telemetry, not a delivery guarantee.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
RateLimiter,
|
||||
is_bot_user_agent,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/client-events", tags=["client-events"])
|
||||
|
||||
# Sized for a legitimate worst case from ONE IP: a many-tab burst (e.g. 16 review
|
||||
# tabs at once) where every tab reports a banner + a waveform event — that must be
|
||||
# fully recorded, not self-suppressed. Each tab throttles per-type client-side.
|
||||
_limiter = RateLimiter(max_per_minute=120)
|
||||
_db_singleton = None
|
||||
|
||||
# The full closed set of reportable events. Reject anything else so the
|
||||
# collection stays reviewable (no free-form types accumulating).
|
||||
EventType = Literal[
|
||||
"banner_reconnecting",
|
||||
"banner_unavailable",
|
||||
"lyrics_load_failed",
|
||||
"waveform_slow",
|
||||
"waveform_failed",
|
||||
]
|
||||
|
||||
|
||||
def _get_db():
|
||||
global _db_singleton
|
||||
if _db_singleton is None:
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
_db_singleton = firestore.Client(project="nomadkaraoke")
|
||||
return _db_singleton
|
||||
|
||||
|
||||
class ClientEventPayload(BaseModel):
|
||||
type: EventType
|
||||
url: str = Field("", max_length=2048)
|
||||
job_id: Optional[str] = Field(None, max_length=64)
|
||||
user_email: Optional[str] = Field(None, max_length=320)
|
||||
locale: str = Field("en", max_length=10)
|
||||
release: str = Field("", max_length=64)
|
||||
# Small free-form context (stall age, http status, elapsed ms, probe state…).
|
||||
# Size-capped server-side; values are stored as-is.
|
||||
detail: Optional[dict] = None
|
||||
|
||||
@field_validator("url", "locale", "release")
|
||||
@classmethod
|
||||
def strip(cls, v: str) -> str:
|
||||
return (v or "").strip()
|
||||
|
||||
|
||||
def _capped_detail(detail: Optional[dict]) -> dict[str, Any]:
|
||||
"""Keep detail reviewable: at most 12 keys, scalar-ish values, short strings."""
|
||||
if not isinstance(detail, dict):
|
||||
return {}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in list(detail.items())[:12]:
|
||||
k = str(key)[:40]
|
||||
if isinstance(value, (int, float, bool)) or value is None:
|
||||
out[k] = value
|
||||
else:
|
||||
out[k] = str(value)[:200]
|
||||
return out
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many events")
|
||||
|
||||
user_agent = request.headers.get("user-agent", "")[:1024]
|
||||
if is_bot_user_agent(user_agent):
|
||||
return {"status": "ignored"}
|
||||
|
||||
event = {
|
||||
"type": payload.type,
|
||||
"url": sanitize_url(payload.url),
|
||||
"job_id": payload.job_id,
|
||||
"user_email": payload.user_email,
|
||||
"locale": payload.locale,
|
||||
"release": payload.release,
|
||||
"user_agent": user_agent,
|
||||
"detail": _capped_detail(payload.detail),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
# Sink 1: structured log line — correlate with backend symptoms in Logging.
|
||||
logger.info(
|
||||
"client_event type=%s job_id=%s user=%s url=%s release=%s detail=%s",
|
||||
event["type"],
|
||||
event["job_id"],
|
||||
event["user_email"],
|
||||
event["url"],
|
||||
event["release"],
|
||||
event["detail"],
|
||||
)
|
||||
|
||||
# Sink 2: Firestore — best-effort; telemetry must never error back to users.
|
||||
try:
|
||||
_get_db().collection("client_events").add(event)
|
||||
except Exception:
|
||||
logger.exception("Failed to persist client event (non-fatal)")
|
||||
|
||||
return {"status": "recorded"}
|
||||
@@ -13,6 +13,7 @@ abuse posture identical to the rest of the review surface: you can only warm
|
||||
the shared encoding VM if you already have review access to a real job.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Tuple
|
||||
from fastapi import APIRouter, Depends
|
||||
@@ -56,7 +57,13 @@ async def warmup_encoding_worker(
|
||||
reviewer previews a render. ``job_id`` scopes auth to the job under review.
|
||||
"""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
# ensure_primary_running does Firestore reads + GCE compute-API calls
|
||||
# (instances.get / instances.start) that can take 10s+. Run it off the
|
||||
# event loop: on the single-process server a sync call here froze the
|
||||
# WHOLE instance for ~11s on every review-page open with a cold VM,
|
||||
# stalling that same page's audio/lyrics requests behind it
|
||||
# (2026-09-19, follow-up to the concurrent-load investigation).
|
||||
result = await asyncio.to_thread(manager.ensure_primary_running)
|
||||
if result["started"]:
|
||||
logger.info(f"Started encoding worker VM: {result['vm_name']}")
|
||||
return result
|
||||
@@ -89,7 +96,8 @@ async def heartbeat_encoding_worker(
|
||||
job under review.
|
||||
"""
|
||||
try:
|
||||
manager.update_activity()
|
||||
# Sync Firestore write — keep it off the event loop (see warmup above).
|
||||
await asyncio.to_thread(manager.update_activity)
|
||||
return {"status": "ok"}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update encoding worker heartbeat: {e}")
|
||||
|
||||
@@ -185,6 +185,25 @@ async def trigger_audio_worker(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/auto-approval-eval")
|
||||
async def trigger_auto_approval_eval(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Re-run the auto-approval evaluation on a job parked at AWAITING_REVIEW
|
||||
(admin only). Normally scoring runs from the screens/audio workers; this
|
||||
endpoint lets an admin re-evaluate after conditions change (e.g. a batch
|
||||
job's made_for_you enforcement blocker was lifted). Fail-safe: anything
|
||||
short of fully confident leaves the job in review untouched.
|
||||
"""
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
|
||||
logger.info(f"[job:{job_id}] admin auto-approval eval requested")
|
||||
result = await maybe_auto_complete_review(job_id, trigger="admin_eval")
|
||||
return {"job_id": job_id, **result}
|
||||
|
||||
|
||||
@router.post("/workers/lyrics", response_model=WorkerResponse)
|
||||
async def trigger_lyrics_worker(
|
||||
request: WorkerRequest,
|
||||
@@ -600,6 +619,43 @@ async def process_stale_reviews_endpoint(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/youtube-backfill/run")
|
||||
async def youtube_backfill_run_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
max_updates: Optional[int] = None,
|
||||
dry_run: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Rewrite existing YouTube video descriptions to the current template.
|
||||
|
||||
Called by Cloud Scheduler (daily). Drains a quota-capped batch each run until
|
||||
the whole channel matches the template, emailing progress + a completion note.
|
||||
Optional query params for manual testing: ?max_updates=N&dry_run=true
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
from backend.workers.youtube_description_backfill_worker import run_backfill_sync
|
||||
|
||||
if not get_settings().youtube_backfill_enabled:
|
||||
return {"status": "disabled", "message": "YOUTUBE_BACKFILL_ENABLED is false"}
|
||||
|
||||
logger.info(f"YOUTUBE_BACKFILL starting (max_updates={max_updates}, dry_run={dry_run})")
|
||||
|
||||
async def _process():
|
||||
try:
|
||||
result = await asyncio.to_thread(run_backfill_sync, max_updates, dry_run)
|
||||
logger.info(f"YOUTUBE_BACKFILL complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"YOUTUBE_BACKFILL failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
return {
|
||||
"status": "started",
|
||||
"message": "YouTube description backfill started in background",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/community-daily-pick")
|
||||
async def community_daily_pick_endpoint(
|
||||
http_request: Request,
|
||||
@@ -628,6 +684,30 @@ async def community_daily_pick_endpoint(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/community-requests/reconcile")
|
||||
async def community_requests_reconcile_endpoint(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Reconcile community picks whose video is already live on YouTube but whose
|
||||
request is still ``in_progress`` (publish fan-out never fired for them).
|
||||
|
||||
Idempotent safety net / backfill: advances each to ``published`` and fans out
|
||||
voter emails. Safe to call any time.
|
||||
"""
|
||||
from backend.services.community_publish import reconcile_community_publishes
|
||||
|
||||
logger.info("COMMUNITY_REQUESTS_RECONCILE starting")
|
||||
add_span_attribute("operation", "community_requests_reconcile")
|
||||
try:
|
||||
result = await reconcile_community_publishes()
|
||||
logger.info(f"COMMUNITY_REQUESTS_RECONCILE complete: {result}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.exception(f"COMMUNITY_REQUESTS_RECONCILE failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/community-handoffs")
|
||||
async def community_handoffs_endpoint(
|
||||
http_request: Request,
|
||||
@@ -667,11 +747,27 @@ async def trigger_gdrive_validation_endpoint(
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
# Optional brand code (incident-hardening D2): forwarded so the validator can
|
||||
# check the just-published track's own completeness same-run. expect_cdg says
|
||||
# whether that track produced a CDG (so the validator requires the CDG folder).
|
||||
brand_code = None
|
||||
expect_cdg = False
|
||||
try:
|
||||
body = await http_request.json()
|
||||
if isinstance(body, dict):
|
||||
brand_code = body.get("brand_code")
|
||||
expect_cdg = bool(body.get("expect_cdg", False))
|
||||
except Exception: # noqa: BLE001 - empty/non-JSON body is the normal case
|
||||
brand_code = None
|
||||
expect_cdg = False
|
||||
|
||||
logger.info("GDRIVE_VALIDATION_TRIGGER starting (delayed post-job)")
|
||||
add_span_attribute("operation", "gdrive_validation_trigger")
|
||||
if brand_code:
|
||||
add_span_attribute("brand_code", str(brand_code))
|
||||
|
||||
try:
|
||||
result = trigger_gdrive_validation()
|
||||
result = trigger_gdrive_validation(brand_code=brand_code, expect_cdg=expect_cdg)
|
||||
if result is None:
|
||||
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
|
||||
|
||||
@@ -982,11 +1078,47 @@ async def recover_stuck_jobs(
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
|
||||
|
||||
# --- DOWNLOADING with lyrics done but screens never triggered: lost screens trigger ---
|
||||
# The lyrics worker triggers screen generation once transcription completes
|
||||
# (audio separation is decoupled). If that dispatch is lost — historically a
|
||||
# fire-and-forget task cancelled on Cloud Run Job loop teardown, now awaited,
|
||||
# but a Cloud Tasks enqueue can still fail — the job sits at `downloading` with
|
||||
# lyrics_complete=True and never advances, with no error. Re-trigger is
|
||||
# idempotent (advance_to_screens_if_ready status-guards + the screens worker
|
||||
# no-ops a duplicate). Mirrors the REVIEW_COMPLETE lost-render recovery above.
|
||||
screens_retriggered = []
|
||||
# Bound the scan so a large active DOWNLOADING population can't consume the
|
||||
# request deadline / Firestore reads before the per-tick re-trigger cap kicks
|
||||
# in. DOWNLOADING is a transient processing state (jobs move through in
|
||||
# minutes), so this ceiling is far above any realistic concurrent population.
|
||||
dl_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING.value)
|
||||
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
|
||||
for doc in dl_query:
|
||||
if len(screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
|
||||
break
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if not _prep_screens_stalled(job):
|
||||
continue
|
||||
logger.warning(
|
||||
f"[job:{job_id}] DOWNLOADING stalled >10 min with lyrics complete but "
|
||||
"no screens — re-triggering"
|
||||
)
|
||||
try:
|
||||
if await job_manager.advance_to_screens_if_ready(job_id):
|
||||
screens_retriggered.append(job_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] screens re-trigger failed: {e}")
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)} "
|
||||
f"render_retriggered={len(render_retriggered)}"
|
||||
f"render_retriggered={len(render_retriggered)} "
|
||||
f"screens_retriggered={len(screens_retriggered)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
@@ -1007,11 +1139,45 @@ async def recover_stuck_jobs(
|
||||
"reparked_render_count": len(reparked),
|
||||
"render_retriggered_jobs": render_retriggered,
|
||||
"render_retriggered_count": len(render_retriggered),
|
||||
"screens_retriggered_jobs": screens_retriggered,
|
||||
"screens_retriggered_count": len(screens_retriggered),
|
||||
}
|
||||
|
||||
|
||||
REVIEW_COMPLETE_STALL_SECONDS = 10 * 60 # render normally starts within seconds
|
||||
RENDER_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
|
||||
PREP_SCREENS_STALL_SECONDS = 10 * 60 # screens normally start within seconds of lyrics done
|
||||
SCREENS_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
|
||||
SCREENS_RECOVERY_SCAN_LIMIT = 500 # cap DOWNLOADING docs scanned per tick (transient state)
|
||||
|
||||
|
||||
def _job_updated_age_seconds(job):
|
||||
"""Seconds since a job's ``updated_at``, or None if unavailable/unparseable."""
|
||||
updated_at = getattr(job, "updated_at", None)
|
||||
if updated_at is None:
|
||||
return None
|
||||
from datetime import datetime, timezone as _tz
|
||||
now = datetime.now(_tz.utc)
|
||||
if updated_at.tzinfo is None:
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
return (now - updated_at).total_seconds()
|
||||
except TypeError:
|
||||
return None
|
||||
|
||||
|
||||
def _prep_screens_stalled(job) -> bool:
|
||||
"""True when a DOWNLOADING job has lyrics complete but has sat >10 min without
|
||||
advancing to screen generation — i.e. the screens trigger was lost.
|
||||
|
||||
While audio separation is still running it keeps ``updated_at`` fresh, so this
|
||||
only fires once the job has genuinely gone quiet (both prep workers done, no
|
||||
screens dispatch), which is exactly the orphaned-trigger signature.
|
||||
"""
|
||||
if not (job.state_data or {}).get("lyrics_complete", False):
|
||||
return False
|
||||
age = _job_updated_age_seconds(job)
|
||||
return age is not None and age > PREP_SCREENS_STALL_SECONDS
|
||||
|
||||
|
||||
def _review_complete_stalled(job) -> bool:
|
||||
|
||||
@@ -755,9 +755,18 @@ async def list_jobs(
|
||||
limit=fetch_limit,
|
||||
)
|
||||
|
||||
# Exclude test user jobs (Python-side, same as full mode)
|
||||
# Exclude test user jobs (Python-side, same as full mode).
|
||||
# Never hide the caller's OWN jobs: an admin that is itself a test
|
||||
# account (e.g. the e2e-test-runner the CI canary impersonates) must
|
||||
# still see the jobs it just created in its own "My Jobs" list —
|
||||
# otherwise the happy-path E2E breaks right after job creation.
|
||||
if exclude_test and auth_result.is_admin:
|
||||
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
|
||||
own_email = (auth_result.user_email or "").lower()
|
||||
jobs_dicts = [
|
||||
j for j in jobs_dicts
|
||||
if not is_test_email(j.get('user_email') or "")
|
||||
or (own_email and (j.get('user_email') or "").lower() == own_email)
|
||||
]
|
||||
|
||||
# Apply search filter if provided
|
||||
if search:
|
||||
@@ -782,9 +791,15 @@ async def list_jobs(
|
||||
limit=limit
|
||||
)
|
||||
|
||||
# Filter out test user jobs if exclude_test is True (admin only)
|
||||
# Filter out test user jobs if exclude_test is True (admin only).
|
||||
# Never hide the caller's OWN jobs (see summary-mode note above).
|
||||
if exclude_test and auth_result.is_admin:
|
||||
jobs = [j for j in jobs if not is_test_email(j.user_email or "")]
|
||||
own_email = (auth_result.user_email or "").lower()
|
||||
jobs = [
|
||||
j for j in jobs
|
||||
if not is_test_email(j.user_email or "")
|
||||
or (own_email and (j.user_email or "").lower() == own_email)
|
||||
]
|
||||
|
||||
logger.debug(f"Listed {len(jobs)} jobs for user={auth_result.user_email}, admin={auth_result.is_admin}")
|
||||
return jobs
|
||||
@@ -1667,6 +1682,7 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
"lossless_4k_mkv": " (Final Karaoke Lossless 4k).mkv",
|
||||
"lossy_4k_mp4": " (Final Karaoke Lossy 4k).mp4",
|
||||
"lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
|
||||
"portrait_1080x1920": " (Final Karaoke Portrait 1080x1920).mp4",
|
||||
"cdg_zip": " (Final Karaoke CDG).zip",
|
||||
"txt_zip": " (Final Karaoke TXT).zip",
|
||||
"with_vocals_mp4": " (With Vocals).mp4",
|
||||
|
||||
+392
-103
@@ -13,16 +13,20 @@ Usage:
|
||||
The baseApiUrl includes the job_id, and all endpoints are relative to that.
|
||||
"""
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import logging
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Literal, Optional, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from fastapi.responses import JSONResponse, RedirectResponse, Response
|
||||
from google.cloud.exceptions import NotFound
|
||||
from google.cloud.firestore_v1.field_path import FieldPath
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
@@ -34,10 +38,12 @@ from backend.services.job_logging import job_log_context, JobLogger
|
||||
from backend.services.tracing import create_span, add_span_attribute, add_span_event
|
||||
from backend.services.encoding_service import get_encoding_service
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.utils.stems import vocals_stem_path as _vocals_stem_path
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
|
||||
from pydantic import BaseModel as _PydBaseModel
|
||||
from backend.services.custom_lyrics_service import (
|
||||
@@ -242,7 +248,7 @@ def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_path = os.path.join(temp_dir, local_audio_filename(job.input_media_gcs_path, "audio"))
|
||||
storage.download_file(job.input_media_gcs_path, audio_path)
|
||||
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
|
||||
|
||||
@@ -274,12 +280,65 @@ def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
|
||||
return correction_result, audio_path, output_config
|
||||
|
||||
|
||||
def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
"""Render the full 360p preview locally and upload it to GCS.
|
||||
# At most this many local preview renders at once. The local path runs ffmpeg
|
||||
# ON the 2-vCPU API instance (it's the fallback when GCE preview encoding is
|
||||
# down); unbounded, a GCE outage plus a few users clicking Preview saturates
|
||||
# the instance's CPU, stalls the health probe, and shows everyone the orange
|
||||
# "trouble reaching our servers" banner. Serializing renders keeps the API
|
||||
# responsive — previews just queue a little longer during an encoder outage.
|
||||
_LOCAL_PREVIEW_MAX_CONCURRENCY = max(1, int(os.getenv("LOCAL_PREVIEW_MAX_CONCURRENCY", "1")))
|
||||
_LOCAL_PREVIEW_QUEUE_TIMEOUT_S = int(os.getenv("LOCAL_PREVIEW_QUEUE_TIMEOUT_S", "900"))
|
||||
_local_preview_slots = asyncio.Semaphore(_LOCAL_PREVIEW_MAX_CONCURRENCY)
|
||||
# Dedicated executor: admitted renders never compete with the shared to_thread
|
||||
# pool, and its concurrent.futures-level done callbacks fire when the WORKER
|
||||
# THREAD finishes — the asyncio wrapper future can be "cancelled" while the
|
||||
# thread is still running, so it must not drive the slot release.
|
||||
_local_preview_executor = concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=_LOCAL_PREVIEW_MAX_CONCURRENCY, thread_name_prefix="local-preview"
|
||||
)
|
||||
|
||||
Blocking (downloads + ffmpeg) — call via asyncio.to_thread. Used when GCE
|
||||
preview encoding is disabled and as the fallback when it fails.
|
||||
|
||||
async def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
"""Render the full 360p preview locally (bounded) and upload it to GCS.
|
||||
|
||||
Used when GCE preview encoding is disabled and as the fallback when it
|
||||
fails. Admission happens HERE on the event loop (async semaphore +
|
||||
wait_for) so queued renders wait as cheap coroutines — only an ADMITTED
|
||||
render occupies a thread-pool worker for its blocking downloads + ffmpeg.
|
||||
"""
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
_local_preview_slots.acquire(), timeout=_LOCAL_PREVIEW_QUEUE_TIMEOUT_S
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
raise RuntimeError(
|
||||
"Local preview encoder is busy (waited "
|
||||
f"{_LOCAL_PREVIEW_QUEUE_TIMEOUT_S}s for a slot) — try again shortly"
|
||||
)
|
||||
def _run_render():
|
||||
return _render_preview_locally_unbounded(job, updated_data, is_duet)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
worker_future = _local_preview_executor.submit(_run_render)
|
||||
|
||||
def _release_slot(fut: "concurrent.futures.Future") -> None:
|
||||
# Runs when the WORKER THREAD actually finishes. Releasing from an
|
||||
# async finally (or the asyncio wrapper's callback) would free the slot
|
||||
# the moment the awaiting request is cancelled — while the ffmpeg
|
||||
# render thread is still consuming CPU — letting a second render start
|
||||
# and defeating the concurrency bound.
|
||||
if not fut.cancelled():
|
||||
fut.exception() # mark retrieved when the caller was cancelled/abandoned
|
||||
try:
|
||||
loop.call_soon_threadsafe(_local_preview_slots.release)
|
||||
except RuntimeError:
|
||||
pass # loop already closed (shutdown) — nothing left to bound
|
||||
|
||||
worker_future.add_done_callback(_release_slot)
|
||||
return await asyncio.wrap_future(worker_future)
|
||||
|
||||
|
||||
def _render_preview_locally_unbounded(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -345,7 +404,7 @@ async def _encode_preview_in_background(
|
||||
logger.warning(f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}")
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(_render_preview_locally, job, updated_data, is_duet)
|
||||
await _render_preview_locally(job, updated_data, is_duet)
|
||||
logger.info(f"Job {job_id}: Preview generated locally after GCE failure: {preview_hash}")
|
||||
except Exception as local_error:
|
||||
logger.error(
|
||||
@@ -410,38 +469,49 @@ def _dev_audio_url(job_id: str, gcs_path: Optional[str], base_url: str = "") ->
|
||||
return f"{base_url.rstrip('/')}/api/review/{job_id}/dev-audio?path={quote(gcs_path, safe='')}"
|
||||
|
||||
|
||||
async def _build_instrumental_options(job, storage, request) -> List[Dict[str, Any]]:
|
||||
"""Build the ``instrumental_options`` list (transcoded, freshly-signed OGG URLs).
|
||||
# Maps the public instrumental option id to the stem key in job.file_urls["stems"].
|
||||
# Used both when building instrumental_options and when the byte-proxy endpoint
|
||||
# resolves an option id back to its GCS stem path (server-side, never client-supplied).
|
||||
_INSTRUMENTAL_OPTION_STEMS = {
|
||||
"clean": "instrumental_clean",
|
||||
"with_backing": "instrumental_with_backing",
|
||||
}
|
||||
|
||||
Signed GCS URLs expire (see ``AudioTranscodingService`` — 120 min), so the
|
||||
review payload's baked-in URLs go stale during a long review session. This
|
||||
helper is shared by the combined-review corrections endpoint (initial load)
|
||||
and ``GET /{job_id}/instrumental-urls`` (frontend refresh-on-expiry), so both
|
||||
return the identical shape with URLs signed at call time.
|
||||
|
||||
def _instrumental_proxy_path(job_id: str, option_id: str) -> str:
|
||||
"""Relative same-origin proxy path for an instrumental option's audio bytes.
|
||||
|
||||
Returned as ``instrumental_options[*].audio_url``. The frontend turns this into an
|
||||
absolute, token-authenticated URL (``API_BASE_URL`` + ``?token=``) before using it
|
||||
as an ``<audio>`` src — see ``resolveInstrumentalAudioUrls()`` in ``frontend/lib/api.ts``.
|
||||
Kept RELATIVE because the backend has no trustworthy public base URL behind Cloudflare
|
||||
(``request.base_url`` reports the wrong scheme/host), and a raw absolute-to-the-wrong-host
|
||||
src would break.
|
||||
"""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
return f"/api/review/{job_id}/instrumental-audio/{option_id}"
|
||||
|
||||
transcoding = AudioTranscodingService(storage_service=storage)
|
||||
|
||||
async def _build_instrumental_options(job, request) -> List[Dict[str, Any]]:
|
||||
"""Build the ``instrumental_options`` list (id/label + same-origin audio proxy URL).
|
||||
|
||||
Root-cause fix (2026-09-17, Option B — see docs/archive/2026-09-17-review-fast-full-load-plan.md):
|
||||
the review hot path no longer signs GCS URLs here. Signing went through the IAM
|
||||
signBlob API over the network (~120 s worst-case), which made review loads slow and,
|
||||
when it stalled, took the whole service down. Instead each option's ``audio_url`` is a
|
||||
relative path to the ``GET /{job_id}/instrumental-audio/{option_id}`` byte proxy — no
|
||||
signing, cannot stall, never expires. Shared by the corrections endpoint (initial
|
||||
load) and ``GET /{job_id}/instrumental-urls`` (kept for backwards compatibility).
|
||||
"""
|
||||
stems = job.file_urls.get("stems", {})
|
||||
clean_url = stems.get("instrumental_clean")
|
||||
backing_url = stems.get("instrumental_with_backing")
|
||||
|
||||
signed_urls: Dict[str, Optional[str]] = {}
|
||||
if _dev_audio_proxy_enabled():
|
||||
_base = str(request.base_url)
|
||||
if clean_url:
|
||||
signed_urls["clean"] = _dev_audio_url(job.job_id, clean_url, _base)
|
||||
if backing_url:
|
||||
signed_urls["with_backing"] = _dev_audio_url(job.job_id, backing_url, _base)
|
||||
else:
|
||||
url_tasks = {}
|
||||
if clean_url:
|
||||
url_tasks["clean"] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
|
||||
if backing_url:
|
||||
url_tasks["with_backing"] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
def _audio_url(option_id: str, source_gcs_path: str) -> Optional[str]:
|
||||
# Local dev (no URL-signing creds) keeps its existing byte proxy, which takes the
|
||||
# GCS path directly; prod/default returns the option-scoped proxy path.
|
||||
if _dev_audio_proxy_enabled():
|
||||
return _dev_audio_url(job.job_id, source_gcs_path, str(request.base_url))
|
||||
return _instrumental_proxy_path(job.job_id, option_id)
|
||||
|
||||
instrumental_options: List[Dict[str, Any]] = []
|
||||
if clean_url:
|
||||
@@ -449,14 +519,14 @@ async def _build_instrumental_options(job, storage, request) -> List[Dict[str, A
|
||||
"id": "clean",
|
||||
"label": "Clean Instrumental",
|
||||
"description": "No backing vocals - just the music",
|
||||
"audio_url": signed_urls.get("clean"),
|
||||
"audio_url": _audio_url("clean", clean_url),
|
||||
})
|
||||
if backing_url:
|
||||
instrumental_options.append({
|
||||
"id": "with_backing",
|
||||
"label": "Instrumental with Backing Vocals",
|
||||
"description": "Includes harmonies and background vocals",
|
||||
"audio_url": signed_urls.get("with_backing"),
|
||||
"audio_url": _audio_url("with_backing", backing_url),
|
||||
})
|
||||
return instrumental_options
|
||||
|
||||
@@ -617,7 +687,11 @@ async def get_correction_data(
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
# All Firestore/GCS round-trips in this handler run via to_thread: they're
|
||||
# blocking client-library calls, and on the single-process/single-loop
|
||||
# server anything left on the event loop serializes EVERY in-flight request
|
||||
# behind it under concurrent load (see 2026-09-18 investigation doc).
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -651,7 +725,7 @@ async def get_correction_data(
|
||||
# Try direct path for updated corrections
|
||||
corrections_updated_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if corrections_updated_gcs and storage.file_exists(corrections_updated_gcs):
|
||||
if corrections_updated_gcs and await asyncio.to_thread(storage.file_exists, corrections_updated_gcs):
|
||||
corrections_gcs = corrections_updated_gcs
|
||||
logger.info(f"Job {job_id}: Using updated corrections from previous review")
|
||||
else:
|
||||
@@ -659,7 +733,7 @@ async def get_correction_data(
|
||||
corrections_gcs = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
if not corrections_gcs:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
if not storage.file_exists(corrections_gcs):
|
||||
if not await asyncio.to_thread(storage.file_exists, corrections_gcs):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=t("en", "review.correctionsNotFound")
|
||||
@@ -667,7 +741,7 @@ async def get_correction_data(
|
||||
|
||||
# Download and return corrections data
|
||||
try:
|
||||
corrections_data = storage.download_json(corrections_gcs)
|
||||
corrections_data = await asyncio.to_thread(storage.download_json, corrections_gcs)
|
||||
|
||||
# Add audio hash for the frontend
|
||||
audio_hash = _get_audio_hash(job_id)
|
||||
@@ -684,10 +758,9 @@ async def get_correction_data(
|
||||
}
|
||||
|
||||
# === Add instrumental data for combined review ===
|
||||
# Transcoded signed OGG URLs (freshly signed here; the frontend re-fetches
|
||||
# them via GET /{job_id}/instrumental-urls when they expire mid-review).
|
||||
# Same-origin audio proxy paths (no signing; see _build_instrumental_options).
|
||||
corrections_data['instrumental_options'] = await _build_instrumental_options(
|
||||
job, storage, request
|
||||
job, request
|
||||
)
|
||||
|
||||
# Get backing vocals analysis from state_data (populated by screens_worker)
|
||||
@@ -702,30 +775,31 @@ async def get_correction_data(
|
||||
from backend.services.auto_approval.instrumental import auto_approval_summary
|
||||
corrections_data['auto_approval'] = auto_approval_summary(job, _get_settings())
|
||||
|
||||
# Get waveform URL if available
|
||||
analysis_files = job.file_urls.get('analysis', {})
|
||||
waveform_url = analysis_files.get('backing_vocals_waveform')
|
||||
if waveform_url:
|
||||
corrections_data['backing_vocals_waveform_url'] = (
|
||||
_dev_audio_url(job_id, waveform_url, str(request.base_url)) if _dev_audio_proxy_enabled()
|
||||
else storage.generate_signed_url(waveform_url, expiration_minutes=120)
|
||||
)
|
||||
# NOTE: we intentionally do NOT sign/emit a ``backing_vocals_waveform_url`` here.
|
||||
# The frontend renders the backing-vocals waveform from the Bearer-authenticated
|
||||
# JSON endpoint ``GET /{job_id}/waveform-data`` (amplitudes drawn on a canvas), and
|
||||
# never consumed this field. Signing it was a pure IAM-signBlob round-trip on the
|
||||
# review hot path with no consumer — removed as part of the 2026-09-17 fast-load
|
||||
# re-architecture so ``correction-data`` performs zero signing.
|
||||
|
||||
# Transition to IN_REVIEW if not already (never in replay — read-only)
|
||||
if not replay and job.status == JobStatus.AWAITING_REVIEW:
|
||||
job_manager.transition_to_state(
|
||||
await asyncio.to_thread(
|
||||
job_manager.transition_to_state,
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User opened combined review interface"
|
||||
message="User opened combined review interface",
|
||||
)
|
||||
|
||||
# Replay: attach the reviewer's ordered edit_log so the UI can show the
|
||||
# sequence of actions (AI-accept/reject/manual/timing) beside the final state.
|
||||
if replay:
|
||||
edit_log = _load_edit_log(job, storage)
|
||||
edit_log = await asyncio.to_thread(_load_edit_log, job, storage)
|
||||
post_ai_segments = None
|
||||
try:
|
||||
raw_data = storage.download_json(f"jobs/{job_id}/lyrics/corrections.json")
|
||||
raw_data = await asyncio.to_thread(
|
||||
storage.download_json, f"jobs/{job_id}/lyrics/corrections.json"
|
||||
)
|
||||
post_ai_segments = _reconstruct_post_ai_segments(
|
||||
raw_data.get('corrected_segments', []), edit_log
|
||||
)
|
||||
@@ -753,33 +827,36 @@ async def get_correction_data(
|
||||
@router.get("/{job_id}/audio/vocals")
|
||||
async def get_vocals_audio(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the vocals audio file for playback."""
|
||||
return await _stream_audio(job_id, stem="vocals")
|
||||
return await _stream_audio(job_id, request, stem="vocals")
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
async def get_audio_with_hash(
|
||||
job_id: str,
|
||||
audio_hash: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (with hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
return await _stream_audio(job_id, request)
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/")
|
||||
@router.get("/{job_id}/audio")
|
||||
async def get_audio_no_hash(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (without hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
return await _stream_audio(job_id, request)
|
||||
|
||||
|
||||
async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"] = "input"):
|
||||
async def _stream_audio(job_id: str, request: Optional[Request] = None, stem: Literal["input"] | Literal["vocals"] = "input"):
|
||||
"""
|
||||
Redirect to a signed GCS URL for audio playback in the review interface.
|
||||
|
||||
@@ -790,7 +867,7 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -798,18 +875,7 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
if stem == "input":
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
elif stem == "vocals":
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
# Stem keys vary by separation model. We want the full vocal mix
|
||||
# (lead + backing) so every word can be lined up against the waveform:
|
||||
# - "vocals" : full vocal from a 2-stem split (rare)
|
||||
# - "vocals_clean" : full vocal from the primary vocal/instrumental
|
||||
# split (present on essentially all cloud jobs)
|
||||
# - "lead_vocals" : last-resort fallback (misses backing lines)
|
||||
# Use .get() so a missing key yields a clean 404 below, not a KeyError/500.
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals"):
|
||||
if stems.get(key):
|
||||
audio_gcs_path = stems[key]
|
||||
break
|
||||
audio_gcs_path = _vocals_stem_path(job)
|
||||
if not audio_gcs_path:
|
||||
# Audio separation is decoupled from the lyrics-review critical path, so a
|
||||
# user can open review before the vocal stems have been uploaded (the stem
|
||||
@@ -834,8 +900,13 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
# the (~3 MB) bytes from the API keeps it same-origin to api.* whose
|
||||
# CORS already allows the frontend. <audio> playback (stem="input")
|
||||
# doesn't need CORS, so it keeps the lighter redirect below.
|
||||
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
|
||||
# Cached in the bounded LRU (same as /instrumental-audio) with
|
||||
# single-flight misses, so ten tabs of the same job — or a play after
|
||||
# the waveform decode — share one GCS fetch instead of N.
|
||||
audio_bytes, content_type = await _get_review_audio(audio_gcs_path, transcoding)
|
||||
logger.info(f"Job {job_id}: Proxying {len(audio_bytes)}B vocals audio for waveform")
|
||||
if request is not None:
|
||||
return _ranged_response(request, audio_bytes, content_type)
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
if _dev_audio_proxy_enabled():
|
||||
@@ -859,11 +930,94 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
_DEV_AUDIO_CACHE: Dict[str, Tuple[bytes, str]] = {}
|
||||
|
||||
|
||||
# BOUNDED cache of transcoded review-audio bytes for the PROD byte proxy (Option B).
|
||||
# Serving the ~3 MB OGG through the API means each play/seek would otherwise re-download
|
||||
# the object from GCS; cache a small number of recently-served objects so Range seeks and
|
||||
# repeat plays are cheap. Unlike _DEV_AUDIO_CACHE this is capped by BOTH entry count and
|
||||
# total retained bytes (the transcode-failure fallback can serve a 35+ MB raw FLAC — a
|
||||
# count-only LRU of those would OOM a 2 GiB instance). Keyed by GCS path, guarded by a
|
||||
# lock for thread safety.
|
||||
_REVIEW_AUDIO_CACHE_MAX = int(os.getenv("REVIEW_AUDIO_CACHE_MAX", "16"))
|
||||
_REVIEW_AUDIO_CACHE_MAX_BYTES = int(os.getenv("REVIEW_AUDIO_CACHE_MAX_BYTES", str(192 * 1024 * 1024)))
|
||||
_review_audio_cache: "OrderedDict[str, Tuple[bytes, str]]" = OrderedDict()
|
||||
_review_audio_cache_bytes = 0
|
||||
_review_audio_cache_lock = threading.Lock()
|
||||
|
||||
# Single-flight coordination for cache misses: N tabs of the same job must share ONE
|
||||
# transcode/GCS-download instead of duplicating it N times. Keyed by GCS path; only
|
||||
# ever touched from the event loop (async handlers), so no extra lock is needed.
|
||||
_review_audio_inflight: Dict[str, "asyncio.Future[Tuple[bytes, str]]"] = {}
|
||||
|
||||
|
||||
def _review_audio_cache_get(path: str) -> Optional[Tuple[bytes, str]]:
|
||||
with _review_audio_cache_lock:
|
||||
item = _review_audio_cache.get(path)
|
||||
if item is not None:
|
||||
_review_audio_cache.move_to_end(path) # mark most-recently-used
|
||||
return item
|
||||
|
||||
|
||||
def _review_audio_cache_put(path: str, value: Tuple[bytes, str]) -> None:
|
||||
global _review_audio_cache_bytes
|
||||
size = len(value[0])
|
||||
if size > _REVIEW_AUDIO_CACHE_MAX_BYTES // 4:
|
||||
# One oversized fallback (raw FLAC) must not evict the whole working set.
|
||||
return
|
||||
with _review_audio_cache_lock:
|
||||
old = _review_audio_cache.pop(path, None)
|
||||
if old is not None:
|
||||
_review_audio_cache_bytes -= len(old[0])
|
||||
_review_audio_cache[path] = value
|
||||
_review_audio_cache_bytes += size
|
||||
while _review_audio_cache and (
|
||||
len(_review_audio_cache) > _REVIEW_AUDIO_CACHE_MAX
|
||||
or _review_audio_cache_bytes > _REVIEW_AUDIO_CACHE_MAX_BYTES
|
||||
):
|
||||
_, evicted = _review_audio_cache.popitem(last=False) # least-recently-used
|
||||
_review_audio_cache_bytes -= len(evicted[0])
|
||||
|
||||
|
||||
async def _get_review_audio(source_gcs_path: str, transcoding) -> Tuple[bytes, str]:
|
||||
"""Cached, single-flight fetch of transcoded review-audio bytes.
|
||||
|
||||
Cache hit → served from memory. Miss → exactly one caller runs the
|
||||
transcode/download; concurrent callers for the same path await its result
|
||||
(success and failure are both shared). Used by /audio/vocals and
|
||||
/instrumental-audio.
|
||||
"""
|
||||
cached = _review_audio_cache_get(source_gcs_path)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
inflight = _review_audio_inflight.get(source_gcs_path)
|
||||
if inflight is not None:
|
||||
return await asyncio.shield(inflight)
|
||||
|
||||
future: "asyncio.Future[Tuple[bytes, str]]" = asyncio.get_running_loop().create_future()
|
||||
_review_audio_inflight[source_gcs_path] = future
|
||||
try:
|
||||
value = await transcoding.get_review_audio_bytes_async(source_gcs_path)
|
||||
_review_audio_cache_put(source_gcs_path, value)
|
||||
future.set_result(value)
|
||||
return value
|
||||
except Exception as e:
|
||||
future.set_exception(e)
|
||||
# The originator re-raises; mark the future's exception as observed so
|
||||
# an awaiter-less failure doesn't log "exception was never retrieved".
|
||||
future.exception()
|
||||
raise
|
||||
finally:
|
||||
_review_audio_inflight.pop(source_gcs_path, None)
|
||||
|
||||
|
||||
def _ranged_response(request: Request, data: bytes, content_type: str) -> Response:
|
||||
"""Serve ``data`` honoring an HTTP Range header (206) so <audio> can seek."""
|
||||
total = len(data)
|
||||
range_header = request.headers.get("range")
|
||||
headers = {"Accept-Ranges": "bytes"}
|
||||
# Let the browser reuse review audio across reloads/tabs for a few minutes
|
||||
# instead of re-pulling multi-MB bodies through the API. Short-lived because
|
||||
# audio-edit can replace a stem's bytes at the same URL.
|
||||
headers = {"Accept-Ranges": "bytes", "Cache-Control": "private, max-age=600"}
|
||||
if range_header and range_header.startswith("bytes="):
|
||||
try:
|
||||
spec = range_header.split("=", 1)[1].split(",")[0].strip()
|
||||
@@ -916,6 +1070,54 @@ async def get_dev_audio(job_id: str, path: str, request: Request):
|
||||
raise HTTPException(status_code=500, detail="dev-audio proxy error")
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-audio/{option_id}")
|
||||
async def get_instrumental_audio(
|
||||
job_id: str,
|
||||
option_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
):
|
||||
"""Stream a review instrumental stem's transcoded OGG bytes (same-origin proxy).
|
||||
|
||||
Option B of the fast-review-load re-architecture (2026-09-17): replaces the per-load
|
||||
IAM signBlob round-trip with a same-origin byte proxy, so the review page never depends
|
||||
on URL signing to play audio (signing could stall ~120 s and take the service down).
|
||||
|
||||
Serves the ~3 MB transcoded OGG with HTTP Range support so ``<audio>`` can seek,
|
||||
authenticated by ``require_review_auth`` (the token rides in the query string for
|
||||
raw-media-src use — the same mechanism as ``/audio/vocals``). The stem GCS path is
|
||||
resolved SERVER-SIDE from ``option_id``, so a client can only ever fetch this job's own
|
||||
instrumental stems, never an arbitrary blob.
|
||||
"""
|
||||
stem_key = _INSTRUMENTAL_OPTION_STEMS.get(option_id)
|
||||
if not stem_key:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
job = await asyncio.to_thread(JobManager().get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
source_gcs_path = stems.get(stem_key)
|
||||
if not source_gcs_path:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=StorageService())
|
||||
data, content_type = await _get_review_audio(source_gcs_path, transcoding)
|
||||
logger.info(f"Job {job_id}: Proxying {len(data)}B instrumental audio ({option_id})")
|
||||
return _ranged_response(request, data, content_type)
|
||||
except NotFound:
|
||||
# The stem is referenced in file_urls but its GCS object (and any transcoded
|
||||
# cache) is gone — a genuine 404, not a server error.
|
||||
logger.warning(f"Job {job_id}: instrumental audio object missing for {option_id}")
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: error proxying instrumental audio {option_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
@@ -1049,16 +1251,24 @@ async def complete_review(
|
||||
message=f"Review complete (instrumental: {instrumental_selection}), rendering video"
|
||||
)
|
||||
|
||||
# Trigger render video worker
|
||||
# Trigger the render video worker. AWAIT the dispatch (don't fire-and-forget)
|
||||
# so the Cloud Task / Cloud Run Job dispatch is guaranteed enqueued before we
|
||||
# return — a background asyncio task can be dropped if the Cloud Run instance
|
||||
# is recycled right after the response, stranding the job at REVIEW_COMPLETE.
|
||||
# If the dispatch itself fails we DON'T fail the user's approval: the job is
|
||||
# safely at REVIEW_COMPLETE and the recover-stuck-jobs watchdog re-triggers
|
||||
# render for REVIEW_COMPLETE jobs with no render underway within ~5 min.
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
|
||||
# Run in background, keep reference to prevent garbage collection
|
||||
task = asyncio.create_task(worker_service.trigger_render_video_worker(job_id))
|
||||
_background_tasks.add(task)
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
logger.info(f"Job {job_id}: Combined review complete, triggered render video worker")
|
||||
try:
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
logger.info(f"Job {job_id}: Combined review complete, render video worker triggered")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Job {job_id}: render trigger failed after review completion "
|
||||
f"(watchdog will recover): {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -1707,9 +1917,7 @@ async def generate_preview_video(
|
||||
|
||||
# Local path (GCE preview disabled, or GCE setup failed): render
|
||||
# the full preview synchronously — no cold-start problem, but slow.
|
||||
preview_hash = await asyncio.to_thread(
|
||||
_render_preview_locally, job, updated_data, is_duet
|
||||
)
|
||||
preview_hash = await _render_preview_locally(job, updated_data, is_duet)
|
||||
|
||||
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
@@ -1873,22 +2081,19 @@ async def get_instrumental_urls(
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Return freshly-signed instrumental stem URLs for the combined review.
|
||||
"""Return instrumental stem options (same-origin audio proxy paths) for the review.
|
||||
|
||||
The signed URLs baked into the initial review payload expire after 120 min,
|
||||
and a long review session (or a page reload that rehydrates cached correction
|
||||
data from localStorage) can outlive them — the preview modal's instrumental
|
||||
audio then fails to load (``NS_ERROR_DOM_NETWORK_ERR``). The frontend calls
|
||||
this on an audio load error to swap in a fresh URL and resume playback.
|
||||
Since the 2026-09-17 fast-load re-architecture these are non-expiring proxy paths, so
|
||||
a refresh is no longer strictly needed — but the preview modal still calls this on an
|
||||
audio load error (e.g. a transient network blip) to swap in a fresh URL, and it's a
|
||||
cheap, backwards-compatible way to do so. Returns the same shape as correction-data's
|
||||
``instrumental_options``.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(JobManager().get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
instrumental_options = await _build_instrumental_options(job, storage, request)
|
||||
instrumental_options = await _build_instrumental_options(job, request)
|
||||
return {"instrumental_options": instrumental_options}
|
||||
|
||||
|
||||
@@ -1909,7 +2114,7 @@ async def get_instrumental_analysis(
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -1945,8 +2150,15 @@ async def get_instrumental_analysis(
|
||||
for key, src in audio_url_sources.items() if src
|
||||
}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
# Best-effort per URL (signing is a bounded IAM round-trip): a stall on one
|
||||
# stem yields a null URL the client can retry, not a failed refresh call.
|
||||
results = await asyncio.gather(*url_tasks.values(), return_exceptions=True)
|
||||
for key, res in zip(url_tasks.keys(), results):
|
||||
if isinstance(res, Exception):
|
||||
logger.warning(f"Signing review audio URL failed ({key}): {res}")
|
||||
audio_urls[key] = None
|
||||
else:
|
||||
audio_urls[key] = res
|
||||
|
||||
# Format response to match InstrumentalAnalysis type
|
||||
return {
|
||||
@@ -1969,6 +2181,76 @@ async def get_instrumental_analysis(
|
||||
}
|
||||
|
||||
|
||||
# Bound how many waveform computations/loads can run at once on an instance.
|
||||
# A cache miss decodes a whole audio file (seconds of CPU); before this bound —
|
||||
# and before the compute moved off the event loop — ~10 concurrent review-page
|
||||
# loads could wedge the single uvicorn event loop and take the whole service
|
||||
# down ("no available instance" aborts; see 2026-09-18 investigation doc).
|
||||
# max(1, …): a zero/negative override would otherwise deadlock every request.
|
||||
_WAVEFORM_MAX_CONCURRENCY = max(1, int(os.getenv("REVIEW_WAVEFORM_MAX_CONCURRENCY", "4")))
|
||||
_waveform_semaphore = asyncio.Semaphore(_WAVEFORM_MAX_CONCURRENCY)
|
||||
|
||||
|
||||
@router.get("/{job_id}/vocals-peaks")
|
||||
async def get_vocals_peaks(
|
||||
job_id: str,
|
||||
peaks_per_second: int = 400,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Pre-computed peak envelope of the vocal stem (Waveforms review mode).
|
||||
|
||||
Replaces the frontend's download-and-decode of the whole vocals OGG
|
||||
(~7 MB + WebAudio decode) with a ~150 KB JSON, so the per-segment
|
||||
waveform strips paint sub-second on page load. Served from a persistent
|
||||
GCS cache, pre-computed by screens_worker; a miss computes off the event
|
||||
loop, bounded by the shared waveform semaphore. Returns 202 while audio
|
||||
separation is still producing the stem (frontend polls, mirroring
|
||||
/audio/vocals).
|
||||
|
||||
Response: {peaks_b64 (base64 uint8 per bucket), encoding: "u8",
|
||||
peaks_per_second, duration_seconds}.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
peaks_per_second = max(50, min(peaks_per_second, 1000))
|
||||
|
||||
job = await asyncio.to_thread(JobManager().get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
vocals_path = _vocals_stem_path(job)
|
||||
if not vocals_path:
|
||||
if not job.state_data.get("audio_complete", False):
|
||||
return Response(status_code=202, headers={"Retry-After": "15"})
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
analysis_service = AudioAnalysisService()
|
||||
async with _waveform_semaphore:
|
||||
payload = await asyncio.to_thread(
|
||||
analysis_service.get_vocals_peaks,
|
||||
vocals_path,
|
||||
job_id,
|
||||
peaks_per_second,
|
||||
AudioTranscodingService(),
|
||||
)
|
||||
return JSONResponse(
|
||||
content={
|
||||
"peaks_b64": payload["peaks_b64"],
|
||||
"encoding": payload.get("encoding", "u8"),
|
||||
"peaks_per_second": payload["peaks_per_second"],
|
||||
"duration_seconds": payload["duration_seconds"],
|
||||
},
|
||||
# Immutable per stem path; short-lived like the audio responses.
|
||||
headers={"Cache-Control": "private, max-age=600"},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating vocals peaks: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.waveformGenerationError", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/waveform-data")
|
||||
async def get_waveform_data(
|
||||
job_id: str,
|
||||
@@ -1979,12 +2261,16 @@ async def get_waveform_data(
|
||||
Get waveform amplitude data for client-side rendering.
|
||||
|
||||
Returns amplitude values for drawing the waveform in the frontend.
|
||||
Served from a persistent GCS cache (precomputed by screens_worker before
|
||||
the job reaches review); a miss decodes off the event loop, bounded by
|
||||
``_waveform_semaphore``.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -2001,11 +2287,14 @@ async def get_waveform_data(
|
||||
|
||||
try:
|
||||
analysis_service = AudioAnalysisService()
|
||||
amplitudes, duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=backing_vocals_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
async with _waveform_semaphore:
|
||||
amplitudes, duration = await asyncio.to_thread(
|
||||
analysis_service.get_review_waveform,
|
||||
backing_vocals_path,
|
||||
job_id,
|
||||
num_points,
|
||||
AudioTranscodingService(),
|
||||
)
|
||||
|
||||
return {
|
||||
"amplitudes": amplitudes,
|
||||
|
||||
@@ -340,7 +340,13 @@ async def send_magic_link(
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to send magic link email to {email}")
|
||||
if getattr(email_service, "last_send_suppressed", False):
|
||||
# Benign: the address is Postmark-suppressed (hard bounce / spam /
|
||||
# manual suppression) — typically a junk/placeholder address entered
|
||||
# at the sign-in form. Not an outage, so don't page on it.
|
||||
logger.info(f"Magic link recipient {email} is suppressed by Postmark — skipping send")
|
||||
else:
|
||||
logger.error(f"Failed to send magic link email to {email}")
|
||||
# Don't reveal failure to prevent email enumeration
|
||||
# Still return success
|
||||
|
||||
@@ -363,6 +369,23 @@ async def send_magic_link(
|
||||
)
|
||||
|
||||
|
||||
def _magic_link_redirect_path(purpose) -> "Optional[str]":
|
||||
"""Map a magic-link purpose to a post-login redirect path.
|
||||
|
||||
"requests_board" -> the voting board; "job_review:<job_id>" -> straight to
|
||||
that job's lyrics review (used by outreach one-click links). Unknown or
|
||||
malformed purposes fall through to None (frontend default: /app).
|
||||
"""
|
||||
import re as _re
|
||||
if purpose == "requests_board":
|
||||
return "/requests"
|
||||
if isinstance(purpose, str) and purpose.startswith("job_review:"):
|
||||
job_id = purpose.split(":", 1)[1]
|
||||
if _re.fullmatch(r"[A-Za-z0-9_-]{4,64}", job_id):
|
||||
return f"/app/jobs#/{job_id}/review"
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/auth/verify", response_model=VerifyMagicLinkResponse)
|
||||
async def verify_magic_link(
|
||||
token: str,
|
||||
@@ -513,7 +536,7 @@ async def verify_magic_link(
|
||||
tenant_subdomain=tenant_subdomain,
|
||||
credits_granted=credits_granted,
|
||||
credit_status=credit_status,
|
||||
redirect_path="/requests" if is_board_signin else None,
|
||||
redirect_path=_magic_link_redirect_path(magic_link_purpose),
|
||||
)
|
||||
|
||||
|
||||
@@ -703,7 +726,12 @@ async def resend_magic_link_from_token(
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to resend magic link email to {_mask_email(email)}")
|
||||
if getattr(email_service, "last_send_suppressed", False):
|
||||
logger.info(
|
||||
f"Resend magic link recipient {_mask_email(email)} is suppressed by Postmark — skipping send"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Failed to resend magic link email to {_mask_email(email)}")
|
||||
|
||||
# Stamp the original token so the cooldown applies to subsequent clicks.
|
||||
try:
|
||||
|
||||
+74
-4
@@ -36,7 +36,16 @@ class Settings(BaseSettings):
|
||||
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
|
||||
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
|
||||
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
|
||||
|
||||
|
||||
# KaraokeNerds community catalog: our own daily-refreshed copy of KN's community
|
||||
# (web-only, directly-playable) tracks, written by the authorized `kn-data-sync`
|
||||
# export job. The community-version check reads THIS, never scrapes karaokenerds.com.
|
||||
# Source of truth is BigQuery `karaoke_decide.karaokenerds_community`; the export job
|
||||
# also mirrors it to this gzipped-JSON GCS object, which the backend loads in-process.
|
||||
kn_community_bucket: str = os.getenv("KN_COMMUNITY_BUCKET", "nomadkaraoke-kn-data")
|
||||
kn_community_blob: str = os.getenv("KN_COMMUNITY_BLOB", "community/community-data-latest.json.gz")
|
||||
kn_community_ttl_seconds: int = int(os.getenv("KN_COMMUNITY_TTL_SECONDS", "21600")) # 6h
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
|
||||
@@ -200,6 +209,15 @@ class Settings(BaseSettings):
|
||||
# Default is false - Cloud Tasks is sufficient for most videos (15-20 min).
|
||||
use_cloud_run_jobs_for_video: bool = os.getenv("USE_CLOUD_RUN_JOBS_FOR_VIDEO", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# When enabled AND enable_cloud_tasks is true, the post-review render worker
|
||||
# also runs as a Cloud Run Job (reusing video-encoding-job with an args
|
||||
# override). As a BackgroundTask on the service it was killed by every
|
||||
# deploy rollout that landed mid-render — Cloud Run gives instances only
|
||||
# 10s after SIGTERM, far less than a render takes, so the job froze at
|
||||
# rendering_video until the 45-min stuck-job sweep (incident 2026-09-13,
|
||||
# job 41e06b90; same class as incident 2026-03-08 for the video worker).
|
||||
use_cloud_run_jobs_for_render: bool = os.getenv("USE_CLOUD_RUN_JOBS_FOR_RENDER", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
# GCE Encoding Worker (for high-performance video encoding)
|
||||
# When enabled, video encoding is offloaded to a dedicated C4 GCE instance
|
||||
# with faster CPU (Intel Granite Rapids 3.9 GHz) instead of Cloud Run.
|
||||
@@ -245,6 +263,16 @@ class Settings(BaseSettings):
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
|
||||
# Search retry settings are much lighter than the download defaults above:
|
||||
# search is called synchronously from user-facing requests that sit behind
|
||||
# Cloudflare's ~100s edge timeout, so there's only room for one quick retry
|
||||
# (worst case: 60s timeout + 1s wait + fast cache-hit retry).
|
||||
flacfetch_search_retry_max_attempts: int = int(os.getenv("FLACFETCH_SEARCH_RETRY_MAX_ATTEMPTS", "2"))
|
||||
flacfetch_search_retry_wait: float = float(os.getenv("FLACFETCH_SEARCH_RETRY_WAIT", "1.0")) # seconds
|
||||
# Total budget across all search attempts, kept under Cloudflare's ~100s edge
|
||||
# deadline so callers get a clean FlacfetchServiceError instead of an edge 524.
|
||||
flacfetch_search_total_timeout: float = float(os.getenv("FLACFETCH_SEARCH_TOTAL_TIMEOUT", "95.0")) # seconds
|
||||
|
||||
# Default distribution settings (can be overridden per-request)
|
||||
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
|
||||
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
|
||||
@@ -267,6 +295,8 @@ class Settings(BaseSettings):
|
||||
community_handoff_max_attempts: int = int(os.getenv("COMMUNITY_HANDOFF_MAX_ATTEMPTS", "5"))
|
||||
# Hours an owner has to complete their review before the job is handed off.
|
||||
community_handoff_hours: int = int(os.getenv("COMMUNITY_HANDOFF_HOURS", "24"))
|
||||
# When a flagged pick is "kept on board", how long before it can be re-flagged.
|
||||
community_review_snooze_days: int = int(os.getenv("COMMUNITY_REVIEW_SNOOZE_DAYS", "30"))
|
||||
|
||||
# Private (non-published) track distribution settings
|
||||
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
|
||||
@@ -281,13 +311,53 @@ class Settings(BaseSettings):
|
||||
youtube_quota_safety_margin: int = int(os.getenv("YOUTUBE_QUOTA_SAFETY_MARGIN", "500"))
|
||||
# E2E test bypass key for rate limiting (set via secret in production)
|
||||
e2e_bypass_key: str = os.getenv("E2E_BYPASS_KEY", "")
|
||||
# Canonical YouTube description template. Placeholders ({title}, {artist},
|
||||
# {artist_hashtag}, {brand_code}) are filled by
|
||||
# backend.services.youtube_description.render_youtube_description, which is the
|
||||
# single source of truth shared with the bulk-rewrite tool
|
||||
# (scripts/youtube-descriptions). Keep those two in sync when editing this.
|
||||
default_youtube_description: str = os.getenv(
|
||||
"DEFAULT_YOUTUBE_DESCRIPTION",
|
||||
"Karaoke video created with Nomad Karaoke (https://nomadkaraoke.com)\n\n"
|
||||
"AI-powered vocal separation and synchronized lyrics.\n\n"
|
||||
"#karaoke #music #singing #instrumental #lyrics"
|
||||
'🎤 Sing along to "{title}" by {artist} — a high-quality karaoke version '
|
||||
"using the original song audio with the lead vocals removed and scrolling "
|
||||
"lyrics hand-synced to the music.\n\n"
|
||||
"⬆️ REQUEST THE NEXT NOMAD RELEASE\n"
|
||||
"Vote for the songs you want us to make next — the most-upvoted requests get "
|
||||
"made into karaoke videos and published free, right here on this channel. "
|
||||
"Nothing to buy, no password needed:\n"
|
||||
"👉 https://requests.nomadkaraoke.com\n\n"
|
||||
"▶️ MAKE A VIDEO LIKE THIS FOR ANY SONG\n"
|
||||
"Create studio-quality karaoke videos of ANY song, ready in under an hour:\n"
|
||||
"👉 https://nomadkaraoke.com/r/youtube\n"
|
||||
"Follow that link for 50% off all credit purchases for your first 30 days.\n\n"
|
||||
"🎶 KARAOKE LOVER LINKS\n"
|
||||
"• Nomad Karaoke Community Discord: https://discord.nomadkaraoke.com\n"
|
||||
"• Decide what to sing at karaoke: https://decide.nomadkaraoke.com\n"
|
||||
"• Search all community karaoke tracks: https://karaokenerds.com\n\n"
|
||||
"🔔 Subscribe for new karaoke tracks, and comment to show some love!\n\n"
|
||||
"#karaoke #{artist_hashtag} #instrumental #lyrics #singalong\n"
|
||||
"—\n"
|
||||
"COPYRIGHT: I don't own the rights to the original music; all rights belong "
|
||||
"to the respective copyright holders. If you enjoy the song, please buy the "
|
||||
"original and support the artist. Under §107 of the U.S. Copyright Act 1976, "
|
||||
'allowance is made for "fair use" (criticism, comment, teaching, and '
|
||||
"research).\n\n"
|
||||
"Brand Code: {brand_code}"
|
||||
)
|
||||
|
||||
# YouTube description back-catalogue rewrite (scheduled daily drain worker).
|
||||
# Rewrites existing channel videos to match `default_youtube_description`.
|
||||
# Reusable: whenever the template changes, the worker re-drains the channel.
|
||||
youtube_backfill_enabled: bool = os.getenv("YOUTUBE_BACKFILL_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
# Hard ceiling on updates per daily run (each costs ~50 quota units).
|
||||
youtube_backfill_daily_max_updates: int = int(os.getenv("YOUTUBE_BACKFILL_DAILY_MAX_UPDATES", "150"))
|
||||
# Quota units to leave untouched for the live upload pipeline each day.
|
||||
youtube_backfill_quota_reserve: int = int(os.getenv("YOUTUBE_BACKFILL_QUOTA_RESERVE", "3000"))
|
||||
# Refresh tags too (not just description) when rewriting.
|
||||
youtube_backfill_enrich_tags: bool = os.getenv("YOUTUBE_BACKFILL_ENRICH_TAGS", "true").lower() in ("true", "1", "yes")
|
||||
# Where the daily progress + completion emails are sent.
|
||||
youtube_backfill_report_email: str = os.getenv("YOUTUBE_BACKFILL_REPORT_EMAIL", "andrew@nomadkaraoke.com")
|
||||
|
||||
# Default CDG/TXT generation settings
|
||||
# When True, CDG and TXT packages are generated by default (when a theme is set)
|
||||
# These can be overridden per-request via explicit enable_cdg/enable_txt parameters
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Video IDs to FORCE-rewrite even though the title isn't high-confidence
|
||||
# "Artist - Title (Karaoke)" — e.g. genuine tracks whose "(Karaoke)" suffix was
|
||||
# truncated by YouTube's 100-char title limit.
|
||||
#
|
||||
# Two forms per line ('#' starts a comment):
|
||||
# <id> use the tool's best-effort parsed artist/title
|
||||
# <id> | <Artist> | <Title> override artist/title (for truncated titles)
|
||||
#
|
||||
# --- Genuine tracks rescued from the "review candidates" bucket (2026-09-03) ---
|
||||
|
||||
# Truncated titles restored to full song titles:
|
||||
5zSFKuCEIhs | Los Campesinos! | This Is How You Spell "HAHAHA, We Destroyed the Hopes and Dreams of a Generation of Faux-Romantics"
|
||||
kkT-bZhi9jI | Arctic Monkeys | You Probably Couldn't See for the Lights but You Were Looking Straight at Me
|
||||
|
||||
# Long medley titles parsed fine — no override needed:
|
||||
le347q8nHT4 # Daniel O'Donnell - Medley: Galway Bay, The Mountains Of Mourne, ...
|
||||
3ihDlPse--k # Daniel O'Donnell - Medley: It's a Long Way to Tipperary / ...
|
||||
@@ -0,0 +1,29 @@
|
||||
# Video IDs that should NEVER have their description rewritten by the bulk tool.
|
||||
# One YouTube video ID per line. Everything after a '#' is ignored.
|
||||
#
|
||||
# The "unparseable" videos are already auto-skipped by the classifier; these are
|
||||
# listed explicitly for the record + belt-and-suspenders (so they stay skipped
|
||||
# even if a title changes later).
|
||||
|
||||
# --- Lyrics videos WITH vocals (NOT instrumental karaoke) ---
|
||||
SUkl49w9GPA # buildspace, MAYV - the end (Lyrics Video)
|
||||
jAAhbfmh8Bc # 100 gecs - mememe (Lyrics Video With Vocals)
|
||||
mcZtK8kkx3E # Fleet Foxes - Montezuma (Lyrics / With Vocals)
|
||||
|
||||
# --- Demos / tutorials / screencasts / pitch / channel-explainer (not karaoke) ---
|
||||
VTR3oaqgn0A # Nomad karaoke-gen hosted demo screencast 2026-05-16
|
||||
-dI3r7qXo3A # Nomad Karaoke Generator - Full Tutorial
|
||||
C0Zyy_9V5F8 # Purim Shpiel custom lyrics karaoke tracks production screencast
|
||||
josVDsYwsFM # Nomad Karaoke Lyrics Review Demo (for AudioShake) Screencast
|
||||
NZ8j0uxq6tA # YouTube "Reused content" claim appeal - channel explanation
|
||||
asnwjLyqY4k # Nomad Karaoke production workflow (real time) 2025-02-26
|
||||
dPWyYfjfHvw # Pitch Night - BIC Energy
|
||||
63-Fk3mfZ7Q # Nomad Karaoke Creation Workflow (Normal Speed) 2023-12-19
|
||||
ZsROHgqAVHs # Nomad Karaoke Creation Workflow (MidiCo Tutorial) 2023-12-19
|
||||
|
||||
# --- Unparseable-title non-karaoke (already auto-skipped; explicit for record) ---
|
||||
RLkIEHGwFcU # Nomad Karaoke Generator Quick Demo
|
||||
GJY60IfIHOQ # Nomad Karaoke Generator Demo 2026
|
||||
v1Hox6XMYEw # "YouTube Karaoke just suffered a major loss" (short/commentary)
|
||||
R3eOl1aeq5c # Nomad Karaoke stands with Lemmy Caution (commentary)
|
||||
wHiMti3xLJE # Nomad Karaoke Creation Tutorial / Demo 1 (MidiCo, July 2023)
|
||||
+19
-9
@@ -10,7 +10,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings, validate_production_config
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_admin, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_admin, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, client_events, bulk, parse_titles
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -111,19 +111,28 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown - wait for any active workers to complete before terminating
|
||||
# This prevents Cloud Run from killing workers mid-processing.
|
||||
# Shutdown - best-effort parking of any still-registered workers.
|
||||
#
|
||||
# Cloud Run gen2 default termination grace period is 600s. We wait up to
|
||||
# 480s, leaving ~120s for the cleanup pass below to write Firestore state
|
||||
# before SIGKILL. Without that headroom, render jobs that miss the wait
|
||||
# would sit in `rendering_video` forever waiting for an operator.
|
||||
# Reality check (incident 2026-09-13, job 41e06b90): Cloud Run services
|
||||
# SIGKILL instances ~10 seconds after SIGTERM — NOT the 600s this comment
|
||||
# previously claimed — and uvicorn only runs this lifespan-shutdown code
|
||||
# AFTER all BackgroundTasks have completed ("Waiting for background tasks
|
||||
# to complete"). A long-running worker task therefore keeps uvicorn stuck
|
||||
# in that wait until SIGKILL, and this hook never executes at all. It can
|
||||
# NOT be relied on to protect in-flight renders; that protection comes
|
||||
# from running them as Cloud Run Jobs instead (USE_CLOUD_RUN_JOBS_FOR_RENDER,
|
||||
# mirroring USE_CLOUD_RUN_JOBS_FOR_VIDEO from incident 2026-03-08).
|
||||
#
|
||||
# This hook is kept as a cheap safety net for the legacy flag-off path and
|
||||
# for the narrow case where workers finish right as SIGTERM lands. The wait
|
||||
# is capped well inside the 10s kill window so the parking pass below still
|
||||
# gets a chance to write Firestore state.
|
||||
logger.info("Shutdown requested, checking for active workers...")
|
||||
if worker_registry.has_active_workers():
|
||||
active = worker_registry.get_active_workers()
|
||||
logger.info(f"Active workers found: {active}")
|
||||
logger.info("Waiting for workers to complete (timeout: 480s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=480)
|
||||
logger.info("Waiting for workers to complete (timeout: 5s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=5)
|
||||
if not completed:
|
||||
logger.error(
|
||||
"Shutdown timeout - some workers may not have completed cleanly. "
|
||||
@@ -204,6 +213,7 @@ app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submissio
|
||||
from backend.api.routes import requests_board
|
||||
app.include_router(requests_board.router, prefix="/api") # Public song-request voting board
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(client_events.router, prefix="/api") # Frontend degradation telemetry (banner/unavailable/waveform events)
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
app.include_router(tenant_admin.router) # Admin tenant provisioning (router has /api prefix)
|
||||
app.include_router(tenant_bulk.router) # Tenant bulk-upload filename analysis (router has /api prefix)
|
||||
|
||||
@@ -27,6 +27,14 @@ RequestStatus = Literal[
|
||||
# source="trending_agent"; everything a human submits is "human".
|
||||
RequestSource = Literal["human", "trending_agent"]
|
||||
|
||||
# Existing-community-version review state (set when the daily picker's KaraokeNerds
|
||||
# check finds an existing community karaoke version for a would-be pick):
|
||||
# pending -> flagged, awaiting Andrew's keep/make/reject decision (admin queue)
|
||||
# snoozed -> Andrew chose "keep on board"; not re-flagged until review_snoozed_until
|
||||
# None means never flagged. The request stays votable/visible on the board throughout;
|
||||
# the picker just won't auto-make a flagged (pending, or still-snoozed) request.
|
||||
ReviewState = Literal["pending", "snoozed"]
|
||||
|
||||
|
||||
class SongRequest(BaseModel):
|
||||
"""A single song request on the public board (Firestore: song_requests)."""
|
||||
@@ -71,6 +79,14 @@ class SongRequest(BaseModel):
|
||||
# failures instead of re-emailing everyone (voters_notified is the all-done flag).
|
||||
notified_voters: list[str] = Field(default_factory=list)
|
||||
|
||||
# Existing-community-version review (set by the daily picker's KaraokeNerds check).
|
||||
review_state: Optional[ReviewState] = None
|
||||
# The community versions we found, stored so the admin queue + reject email can
|
||||
# show/link them: {"best_youtube_url": str|None, "tracks": [{"brand_name","youtube_url"}]}.
|
||||
community_versions: Optional[dict] = None
|
||||
community_checked_at: Optional[datetime] = None
|
||||
review_snoozed_until: Optional[datetime] = None
|
||||
|
||||
|
||||
class Vote(BaseModel):
|
||||
"""A single daily vote (Firestore: song_request_votes, doc id = {email}__{date}).
|
||||
|
||||
@@ -12,6 +12,7 @@ import tempfile
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
from karaoke_gen.instrumental_review import (
|
||||
AudioAnalyzer,
|
||||
AnalysisResult,
|
||||
@@ -81,7 +82,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# Run analysis
|
||||
@@ -132,7 +133,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# Run analysis
|
||||
@@ -185,8 +186,8 @@ class AudioAnalysisService:
|
||||
from karaoke_gen.instrumental_review.stem_comparison import compare_stems
|
||||
|
||||
try:
|
||||
local_lead = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
local_vocals = os.path.join(temp_dir, "vocals.flac")
|
||||
local_lead = os.path.join(temp_dir, local_audio_filename(gcs_lead_vocals_path, "lead_vocals"))
|
||||
local_vocals = os.path.join(temp_dir, local_audio_filename(gcs_vocals_path, "vocals"))
|
||||
self.storage_service.download_file(gcs_lead_vocals_path, local_lead)
|
||||
self.storage_service.download_file(gcs_vocals_path, local_vocals)
|
||||
except Exception as e:
|
||||
@@ -231,7 +232,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# Generate waveform data
|
||||
@@ -242,6 +243,171 @@ class AudioAnalysisService:
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
@staticmethod
|
||||
def review_waveform_cache_path(job_id: str, num_points: int) -> str:
|
||||
"""GCS path of the cached review-page waveform JSON for a job."""
|
||||
return f"jobs/{job_id}/review-audio/waveform_review_{num_points}.json"
|
||||
|
||||
def get_review_waveform(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
num_points: int = 1000,
|
||||
transcoding_service=None,
|
||||
) -> tuple[list[float], float]:
|
||||
"""
|
||||
Waveform data for the review page, cached persistently in GCS.
|
||||
|
||||
Decoding a full stem (pydub -> ffmpeg + a pure-Python RMS loop) takes
|
||||
seconds of CPU, so it must only ever happen once per job: results are
|
||||
cached at ``review_waveform_cache_path`` and validated against the
|
||||
source path + num_points (a replaced stem or different resolution
|
||||
recomputes). On a miss, decode the small transcoded review OGG when it
|
||||
exists (~3 MB) instead of the raw stem (~35 MB FLAC).
|
||||
|
||||
The cache upload is best-effort — a failed write still returns the
|
||||
computed data.
|
||||
"""
|
||||
cache_path = self.review_waveform_cache_path(job_id, num_points)
|
||||
cached = self._load_review_waveform_cache(cache_path, gcs_audio_path, num_points)
|
||||
if cached is not None:
|
||||
logger.info(f"[{job_id}] Review waveform cache hit: {cache_path}")
|
||||
return cached
|
||||
|
||||
decode_path = gcs_audio_path
|
||||
if transcoding_service is not None:
|
||||
try:
|
||||
ogg_path = transcoding_service.get_transcoded_cache_path(gcs_audio_path)
|
||||
if self.storage_service.file_exists(ogg_path):
|
||||
decode_path = ogg_path
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Could not resolve transcoded OGG for waveform: {e}")
|
||||
|
||||
amplitudes, duration = self.get_waveform_data(
|
||||
gcs_audio_path=decode_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
|
||||
try:
|
||||
self.storage_service.upload_json(cache_path, {
|
||||
"amplitudes": list(amplitudes),
|
||||
"duration_seconds": duration,
|
||||
"num_points": num_points,
|
||||
# Keyed to the LOGICAL source (the stem path), not decode_path,
|
||||
# so swapping in/out the OGG shortcut never invalidates the cache
|
||||
# but a regenerated stem at a new path does.
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
})
|
||||
logger.info(f"[{job_id}] Review waveform cached at {cache_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to cache review waveform (non-fatal): {e}")
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
def _load_review_waveform_cache(
|
||||
self,
|
||||
cache_gcs_path: str,
|
||||
source_gcs_path: str,
|
||||
num_points: int,
|
||||
) -> Optional[tuple[list[float], float]]:
|
||||
"""Load + validate the review waveform cache; None on any mismatch/error."""
|
||||
try:
|
||||
if not self.storage_service.file_exists(cache_gcs_path):
|
||||
return None
|
||||
data = self.storage_service.download_json(cache_gcs_path)
|
||||
if data.get("source_gcs_path") != source_gcs_path:
|
||||
return None
|
||||
if data.get("num_points") != num_points:
|
||||
return None
|
||||
amplitudes = data.get("amplitudes") or []
|
||||
if not amplitudes:
|
||||
return None
|
||||
return amplitudes, float(data.get("duration_seconds", 0.0))
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load review waveform cache {cache_gcs_path}: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def vocals_peaks_cache_path(job_id: str, peaks_per_second: int) -> str:
|
||||
"""GCS path of the cached vocals peak-envelope JSON for a job."""
|
||||
return f"jobs/{job_id}/review-audio/vocals_peaks_{peaks_per_second}.json"
|
||||
|
||||
def get_vocals_peaks(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
peaks_per_second: int = 400,
|
||||
transcoding_service=None,
|
||||
) -> dict:
|
||||
"""
|
||||
Pre-computed peak envelope of the vocal stem for the review page's
|
||||
Waveforms mode, cached persistently in GCS.
|
||||
|
||||
Returns the serve-ready payload::
|
||||
|
||||
{peaks_b64, encoding: "u8", peaks_per_second, duration_seconds,
|
||||
source_gcs_path}
|
||||
|
||||
``peaks_b64`` is base64 of one uint8 per bucket (max-abs amplitude
|
||||
quantized to 0-255) — ~150 KB for a 5-minute track vs the ~7 MB OGG
|
||||
the frontend previously downloaded and decoded client-side. On a cache
|
||||
miss, decode the small transcoded review OGG when it exists.
|
||||
The cache upload is best-effort.
|
||||
"""
|
||||
import base64
|
||||
|
||||
cache_path = self.vocals_peaks_cache_path(job_id, peaks_per_second)
|
||||
try:
|
||||
if self.storage_service.file_exists(cache_path):
|
||||
data = self.storage_service.download_json(cache_path)
|
||||
if (
|
||||
data.get("source_gcs_path") == gcs_audio_path
|
||||
and data.get("peaks_per_second") == peaks_per_second
|
||||
and data.get("peaks_b64")
|
||||
):
|
||||
logger.info(f"[{job_id}] Vocals peaks cache hit: {cache_path}")
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to load vocals peaks cache: {e}")
|
||||
|
||||
decode_path = gcs_audio_path
|
||||
if transcoding_service is not None:
|
||||
try:
|
||||
ogg_path = transcoding_service.get_transcoded_cache_path(gcs_audio_path)
|
||||
if self.storage_service.file_exists(ogg_path):
|
||||
decode_path = ogg_path
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Could not resolve transcoded OGG for peaks: {e}")
|
||||
|
||||
import numpy as np
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(decode_path, "vocals"))
|
||||
self.storage_service.download_file(decode_path, local_audio_path)
|
||||
peaks, duration = self.waveform_generator.generate_peaks(
|
||||
local_audio_path, peaks_per_second=peaks_per_second
|
||||
)
|
||||
|
||||
quantized = np.clip(np.round(peaks * 255.0), 0, 255).astype(np.uint8)
|
||||
payload = {
|
||||
"peaks_b64": base64.b64encode(quantized.tobytes()).decode("ascii"),
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": peaks_per_second,
|
||||
"duration_seconds": duration,
|
||||
# Keyed to the LOGICAL source (the stem path) so a regenerated stem
|
||||
# at a new path invalidates, while the OGG decode shortcut doesn't.
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
}
|
||||
|
||||
try:
|
||||
self.storage_service.upload_json(cache_path, payload)
|
||||
logger.info(f"[{job_id}] Vocals peaks cached at {cache_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to cache vocals peaks (non-fatal): {e}")
|
||||
|
||||
return payload
|
||||
|
||||
def cache_waveform_data(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
@@ -343,7 +509,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# First run analysis to get segments
|
||||
|
||||
@@ -19,7 +19,8 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.storage_service import SignedUrlTimeout, StorageService
|
||||
from backend.utils.audio_filenames import audio_content_type, local_audio_filename
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -55,6 +56,10 @@ class AudioTranscodingService:
|
||||
filename = Path(source_gcs_path).stem + ".ogg"
|
||||
return f"jobs/{job_id}/review-audio/{filename}"
|
||||
|
||||
def get_transcoded_cache_path(self, source_gcs_path: str) -> str:
|
||||
"""Public accessor for the transcoded-OGG cache path of a source file."""
|
||||
return self._get_cache_path(source_gcs_path)
|
||||
|
||||
def _transcode_and_upload(self, source_gcs_path: str, cache_path: str) -> str:
|
||||
"""
|
||||
Download FLAC from GCS, transcode to OGG Opus, upload to cache path.
|
||||
@@ -63,7 +68,7 @@ class AudioTranscodingService:
|
||||
Raises on failure.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_input = os.path.join(temp_dir, "input.flac")
|
||||
local_input = os.path.join(temp_dir, local_audio_filename(source_gcs_path, "input"))
|
||||
local_output = os.path.join(temp_dir, "output.ogg")
|
||||
|
||||
# Download source
|
||||
@@ -115,6 +120,11 @@ class AudioTranscodingService:
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_gcs_path)
|
||||
return self.storage.generate_signed_url(cache_path, expiration_minutes)
|
||||
except SignedUrlTimeout:
|
||||
# The signing backend (IAM signBlob) is stalling — every fallback below
|
||||
# would sign too and stall identically. Bail immediately so the caller
|
||||
# degrades fast (null audio_url) instead of burning 2-3× the timeout.
|
||||
raise
|
||||
except Exception as e:
|
||||
# Source may be deleted but cache from earlier transcode persists
|
||||
try:
|
||||
@@ -159,7 +169,7 @@ class AudioTranscodingService:
|
||||
return self.storage.download_bytes(cache_path), "audio/ogg"
|
||||
except Exception as e:
|
||||
logger.warning(f"Transcoding failed for {source_gcs_path}, serving source audio: {e}")
|
||||
return self.storage.download_bytes(source_gcs_path), "audio/flac"
|
||||
return self.storage.download_bytes(source_gcs_path), audio_content_type(source_gcs_path)
|
||||
|
||||
async def get_review_audio_bytes_async(self, source_gcs_path: str) -> tuple[bytes, str]:
|
||||
"""Async wrapper around get_review_audio_bytes via asyncio.to_thread."""
|
||||
|
||||
@@ -101,9 +101,19 @@ def _copy_segments(segments: List[Segment]) -> List[Segment]:
|
||||
|
||||
|
||||
def apply_suggestion(
|
||||
segments: List[Segment], suggestion: Suggestion
|
||||
segments: List[Segment],
|
||||
suggestion: Suggestion,
|
||||
undo_out: Optional[Dict[str, Any]] = None,
|
||||
) -> Optional[List[Segment]]:
|
||||
"""Apply one suggestion; returns new segments or None when stale."""
|
||||
"""Apply one suggestion; returns new segments or None when stale.
|
||||
|
||||
When ``undo_out`` is passed, it is populated with enough information to
|
||||
reverse this single suggestion later (mirrors the frontend's
|
||||
``SuggestionUndoInfo`` in ``autoCorrectApply.ts``), so a suggestion applied
|
||||
server-side (pre-apply / auto-approval) can still be undone per-item once
|
||||
the client has this data — independent of any other suggestions applied
|
||||
around it.
|
||||
"""
|
||||
if is_suggestion_stale(segments, suggestion):
|
||||
return None
|
||||
found = _find_segment_with_words(segments, suggestion.get("word_ids") or [])
|
||||
@@ -116,6 +126,7 @@ def apply_suggestion(
|
||||
result = _copy_segments(segments)
|
||||
seg = result[seg_index]
|
||||
words = seg["words"]
|
||||
prev_word_id = words[span_start - 1]["id"] if span_start > 0 else None
|
||||
op = suggestion.get("op")
|
||||
new_text = suggestion.get("new_text") or ""
|
||||
|
||||
@@ -153,18 +164,44 @@ def apply_suggestion(
|
||||
]
|
||||
words[span_end + 1 : span_end + 1] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
if undo_out is not None:
|
||||
undo_out.update(
|
||||
{
|
||||
"op": op,
|
||||
"new_word_ids": [w["id"] for w in new_words],
|
||||
"removed_words": [],
|
||||
"segment_id": seg["id"],
|
||||
"prev_word_id": anchor["id"],
|
||||
"removed_segment": None,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
removed = words[span_start : span_end + 1]
|
||||
removed_snapshot = [dict(w) for w in removed]
|
||||
segment_snapshot = {**seg, "words": [dict(w) for w in words]}
|
||||
|
||||
if op == "delete":
|
||||
del words[span_start : span_start + len(removed)]
|
||||
removed_segment_info = None
|
||||
if not words:
|
||||
removed_segment_info = {"segment": segment_snapshot, "index": seg_index}
|
||||
del result[seg_index]
|
||||
else:
|
||||
seg["text"] = _rebuild_text(words)
|
||||
seg["start_time"] = words[0].get("start_time")
|
||||
seg["end_time"] = words[-1].get("end_time")
|
||||
if undo_out is not None:
|
||||
undo_out.update(
|
||||
{
|
||||
"op": op,
|
||||
"new_word_ids": [],
|
||||
"removed_words": removed_snapshot,
|
||||
"segment_id": segment_snapshot["id"],
|
||||
"prev_word_id": prev_word_id,
|
||||
"removed_segment": removed_segment_info,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
# replace
|
||||
@@ -195,6 +232,17 @@ def apply_suggestion(
|
||||
new_words.append(w)
|
||||
words[span_start : span_start + len(removed)] = new_words
|
||||
seg["text"] = _rebuild_text(words)
|
||||
if undo_out is not None:
|
||||
undo_out.update(
|
||||
{
|
||||
"op": "replace",
|
||||
"new_word_ids": [w["id"] for w in new_words],
|
||||
"removed_words": removed_snapshot,
|
||||
"segment_id": seg["id"],
|
||||
"prev_word_id": prev_word_id,
|
||||
"removed_segment": None,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -203,29 +251,35 @@ def apply_all_suggestions(
|
||||
) -> Dict[str, Any]:
|
||||
"""Accept-all with conflict resolution, mirroring the UI's on-load auto-apply.
|
||||
|
||||
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids"}``.
|
||||
Returns ``{"segments", "applied_ids", "rejected_ids", "stale_ids", "undo_info"}``.
|
||||
``undo_info`` maps each applied suggestion id to its ``SuggestionUndoInfo``-shaped
|
||||
dict, so an applied suggestion can be individually reverted later.
|
||||
"""
|
||||
winners = set(pick_accept_all_winners(suggestions))
|
||||
current = segments
|
||||
applied: List[str] = []
|
||||
rejected: List[str] = []
|
||||
stale: List[str] = []
|
||||
undo_info: Dict[str, Any] = {}
|
||||
for s in suggestions:
|
||||
sid = s.get("id") or ""
|
||||
if sid not in winners:
|
||||
rejected.append(sid)
|
||||
continue
|
||||
result = apply_suggestion(current, s)
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(current, s, undo_out=undo)
|
||||
if result is None:
|
||||
stale.append(sid)
|
||||
continue
|
||||
current = result
|
||||
applied.append(sid)
|
||||
undo_info[sid] = undo
|
||||
return {
|
||||
"segments": current,
|
||||
"applied_ids": applied,
|
||||
"rejected_ids": rejected,
|
||||
"stale_ids": stale,
|
||||
"undo_info": undo_info,
|
||||
}
|
||||
|
||||
|
||||
@@ -261,6 +315,7 @@ def build_applied_segments(
|
||||
"segments": new_segments,
|
||||
"applied_ids": result["applied_ids"],
|
||||
"rejected_ids": result["rejected_ids"],
|
||||
"undo_info": result["undo_info"],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -99,6 +99,10 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
"applied_suggestion_ids": result["applied_ids"],
|
||||
"rejected_suggestion_ids": result["rejected_ids"],
|
||||
"suggestions": ai_suggestions,
|
||||
# Per-suggestion undo info (SuggestionUndoInfo shape) so the review
|
||||
# UI can still revert an individual pre-applied correction even
|
||||
# though it never applied it client-side itself.
|
||||
"undo_info": result["undo_info"],
|
||||
"applied_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
updated["metadata"] = metadata
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Requests-board publish fan-out.
|
||||
|
||||
When a community-pick job goes live on YouTube, its ``song_request`` must advance
|
||||
to ``published`` and every up-voter (other than the owner, who already got the job
|
||||
completion email) should get a "your track is live" email.
|
||||
|
||||
A job can reach YouTube via **two** paths, and both must trigger this:
|
||||
1. the quota-managed ``youtube_upload_queue`` (``youtube_queue_processor``), and
|
||||
2. a direct upload during video-worker distribution (``video_worker``), which
|
||||
never touches that queue.
|
||||
|
||||
Historically only path (1) ran the fan-out, so direct-published community picks
|
||||
(e.g. the first real user request) stayed stuck at ``in_progress`` and their
|
||||
board "Recently made" entry never appeared. This shared helper is called from
|
||||
both paths so the outcome is identical regardless of how the video was published.
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _youtube_url_for_job(job) -> Optional[str]:
|
||||
"""The published YouTube URL for a job, if any, checking both the state_data
|
||||
field (set on the direct-publish path) and the distribution metadata."""
|
||||
if job is None:
|
||||
return None
|
||||
state = getattr(job, "state_data", None) or {}
|
||||
url = state.get("youtube_url")
|
||||
if url:
|
||||
return url
|
||||
meta = getattr(job, "processing_metadata", None) or {}
|
||||
dist = meta.get("distribution") or {}
|
||||
return dist.get("youtube_video_url") or None
|
||||
|
||||
|
||||
async def notify_community_publish(job_id: str, youtube_url: str) -> Optional[str]:
|
||||
"""Advance a community pick to ``published`` and fan out voter emails.
|
||||
|
||||
Idempotent and best-effort: safe to call from both publish paths and to
|
||||
re-run after a partial failure. Marking published is always safe to repeat;
|
||||
voter emails are guarded by the request's ``notified_voters`` /
|
||||
``voters_notified`` flags so no one is emailed twice.
|
||||
|
||||
Returns the request id if this was a community pick, else ``None`` (a normal,
|
||||
non-community job — no-op).
|
||||
"""
|
||||
try:
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
request = service.get_by_job_id(job_id)
|
||||
if request is None:
|
||||
return None # Not a community pick — normal job.
|
||||
|
||||
service.mark_published(request.id, youtube_url)
|
||||
|
||||
if request.voters_notified:
|
||||
return request.id
|
||||
|
||||
# Email up-voters we haven't already reached (retry-safe): exclude the
|
||||
# owner (already got the completion email) and anyone previously notified.
|
||||
owner = (request.owner_email or request.submitted_by or "").lower()
|
||||
already = {v.lower() for v in (request.notified_voters or [])}
|
||||
pending = [
|
||||
v for v in service.list_upvoters(request.id)
|
||||
if v != owner and v not in already
|
||||
]
|
||||
|
||||
from backend.services.job_notification_service import get_job_notification_service
|
||||
notification_service = get_job_notification_service()
|
||||
succeeded = 0
|
||||
for voter in pending:
|
||||
try:
|
||||
ok = await notification_service.send_community_track_live_email(
|
||||
to_email=voter,
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
youtube_url=youtube_url,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed community voter email for job %s / %s", job_id, voter)
|
||||
continue
|
||||
if ok:
|
||||
# Record each success immediately so a crash mid-loop never
|
||||
# re-emails an already-notified voter on the retry.
|
||||
service.add_notified_voters(request.id, [voter])
|
||||
succeeded += 1
|
||||
|
||||
# Only flag "fully notified" when every pending voter was reached — a
|
||||
# partial failure leaves the flag unset so a re-run retries just the misses.
|
||||
if succeeded == len(pending):
|
||||
service.mark_voters_notified(request.id)
|
||||
logger.info(
|
||||
"community pick %s published (job %s): notified %d/%d pending voters",
|
||||
request.id, job_id, succeeded, len(pending),
|
||||
)
|
||||
return request.id
|
||||
except Exception as e:
|
||||
logger.error("Failed community voter fan-out for job %s: %s", job_id, e)
|
||||
return None
|
||||
|
||||
|
||||
async def reconcile_community_publishes() -> Dict[str, Any]:
|
||||
"""Safety net / backfill for the community publish fan-out. Two passes:
|
||||
|
||||
1. Picks stuck at ``in_progress`` whose job is actually live on YouTube — run
|
||||
the publish transition (covers picks published before the fan-out was wired
|
||||
into every path, or any future path that forgets to call it).
|
||||
2. Picks already ``published`` but with ``voters_notified == False`` — a voter
|
||||
send failed (or raised) after the request was marked published, and no other
|
||||
path retries them. Re-run the fan-out (idempotent; only un-notified voters
|
||||
are re-emailed).
|
||||
|
||||
Fully idempotent — safe to call any time.
|
||||
"""
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
|
||||
service = get_song_request_service()
|
||||
job_manager = JobManager()
|
||||
|
||||
scanned = 0
|
||||
published = []
|
||||
|
||||
# Pass 1: in_progress picks whose job is live.
|
||||
for request in service.list_in_progress():
|
||||
scanned += 1
|
||||
if not request.job_id:
|
||||
continue
|
||||
url = _youtube_url_for_job(job_manager.get_job(request.job_id))
|
||||
if not url:
|
||||
continue
|
||||
result_id = await notify_community_publish(request.job_id, url)
|
||||
if result_id:
|
||||
published.append({"request_id": result_id, "job_id": request.job_id, "youtube_url": url})
|
||||
|
||||
# Pass 2: published picks whose voter fan-out never fully completed.
|
||||
retried = 0
|
||||
for request in service.list_published_unnotified():
|
||||
scanned += 1
|
||||
if not request.job_id:
|
||||
continue
|
||||
# Prefer the URL already recorded on the request; fall back to the job.
|
||||
url = request.youtube_url or _youtube_url_for_job(job_manager.get_job(request.job_id))
|
||||
if not url:
|
||||
continue
|
||||
if await notify_community_publish(request.job_id, url):
|
||||
retried += 1
|
||||
|
||||
logger.info(
|
||||
"community publish reconcile: scanned %d, published %d, retried-fanout %d",
|
||||
scanned, len(published), retried,
|
||||
)
|
||||
return {"scanned": scanned, "published": published, "retried_fanout": retried}
|
||||
@@ -104,7 +104,11 @@ class DiscordNotificationService:
|
||||
return True
|
||||
|
||||
self.logger.info(f"Posting message to Discord webhook...")
|
||||
data = {"content": message}
|
||||
# Disable all mentions: message content can include user-supplied text
|
||||
# (artist/title in ops alerts), so an embedded @everyone / <@id> must not
|
||||
# trigger a Discord ping. (CWE-74 — output injection into a downstream
|
||||
# component.)
|
||||
data = {"content": message, "allowed_mentions": {"parse": []}}
|
||||
response = requests.post(url, json=data, timeout=30)
|
||||
response.raise_for_status()
|
||||
self.logger.info("Message posted to Discord successfully")
|
||||
|
||||
@@ -37,6 +37,11 @@ class SendResult(NamedTuple):
|
||||
"""
|
||||
success: bool
|
||||
message_id: Optional[str] = None
|
||||
# True when the send failed specifically because Postmark has the recipient
|
||||
# marked inactive (hard bounce / spam complaint / manual suppression). This
|
||||
# is expected, benign traffic (e.g. someone typing a junk address into the
|
||||
# sign-in form), not an outage — callers log it at INFO, not ERROR.
|
||||
suppressed: bool = False
|
||||
|
||||
|
||||
class EmailProvider(ABC):
|
||||
@@ -176,6 +181,11 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
# Postmark MessageID of the most recent successful send, so the email_log
|
||||
# chokepoint can link a persisted record to its Postmark message.
|
||||
self.last_message_id: Optional[str] = None
|
||||
# True when the most recent send failed because the recipient is
|
||||
# suppressed by Postmark (see SendResult.suppressed). Lets the send
|
||||
# chokepoint / route handlers downgrade the failure log from ERROR to
|
||||
# INFO without threading a richer return type through every caller.
|
||||
self.last_suppressed: bool = False
|
||||
|
||||
def send_email(
|
||||
self,
|
||||
@@ -207,6 +217,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> SendResult:
|
||||
self.last_suppressed = False
|
||||
try:
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
@@ -252,6 +263,18 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
|
||||
try:
|
||||
err = response.json()
|
||||
# ErrorCode 406 (InactiveRecipient) = the address is suppressed
|
||||
# (hard bounce / spam complaint / manual suppression). This is
|
||||
# expected when someone enters a junk/placeholder address at the
|
||||
# sign-in form — it is not an outage, so log it at INFO and flag
|
||||
# it so callers don't raise a scary "failed to send" ERROR.
|
||||
if response.status_code == 422 and err.get("ErrorCode") == 406:
|
||||
self.last_suppressed = True
|
||||
logger.info(
|
||||
f"Postmark skipped suppressed recipient {to_email} "
|
||||
f"(inactive: hard bounce / spam complaint / manual suppression)"
|
||||
)
|
||||
return SendResult(success=False, message_id=None, suppressed=True)
|
||||
logger.error(
|
||||
f"Postmark returned status {response.status_code}: "
|
||||
f"ErrorCode={err.get('ErrorCode')} Message={err.get('Message')}"
|
||||
@@ -311,6 +334,9 @@ class EmailService:
|
||||
self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
|
||||
# After consolidation, buy URL is the same as frontend URL
|
||||
self.buy_url = os.getenv("BUY_URL", self.frontend_url)
|
||||
# Set by _log_and_send: True when the last send failed only because the
|
||||
# recipient is Postmark-suppressed (benign — see SendResult.suppressed).
|
||||
self.last_send_suppressed: bool = False
|
||||
|
||||
def _get_provider(self) -> EmailProvider:
|
||||
"""Get the configured email provider.
|
||||
@@ -414,6 +440,12 @@ class EmailService:
|
||||
from_email_override=from_email_override,
|
||||
)
|
||||
|
||||
# Mirror the provider's suppression flag so route handlers can tell a
|
||||
# benign "recipient suppressed" failure (junk sign-in address) apart
|
||||
# from a real send failure without threading a richer return type
|
||||
# through every send_* method.
|
||||
self.last_send_suppressed = getattr(self.provider, "last_suppressed", False)
|
||||
|
||||
# Only persist genuine outbound mail (Postmark). Console/preview providers
|
||||
# are dev/test only and have no real inbox to reflect.
|
||||
if success and isinstance(self.provider, PostmarkEmailProvider):
|
||||
@@ -1816,6 +1848,40 @@ class EmailService:
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_community_existing_version(
|
||||
self,
|
||||
to_email: str,
|
||||
message_content: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""Notify an up-voter that a requests-board pick was rejected because a good
|
||||
community karaoke version already exists (with a link to it)."""
|
||||
safe_artist = sanitize_filename(artist) if artist else None
|
||||
safe_title = sanitize_filename(title) if title else None
|
||||
if safe_artist and safe_title:
|
||||
subject = t(locale, "emails.communityExistingVersion.subject", artist=safe_artist, title=safe_title)
|
||||
else:
|
||||
subject = t(locale, "emails.communityExistingVersion.subjectFallback")
|
||||
|
||||
extra_styles = """
|
||||
.content {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
"""
|
||||
content = f"""
|
||||
<div class="content">{html.escape(message_content)}</div>
|
||||
"""
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=message_content,
|
||||
)
|
||||
|
||||
def send_made_for_you_order_confirmation(
|
||||
self,
|
||||
to_email: str,
|
||||
|
||||
@@ -10,15 +10,125 @@ can be swapped without changing the orchestration logic.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Any
|
||||
from typing import Dict, List, Optional, Any, TypedDict
|
||||
|
||||
from backend.services.encoding_errors import EncodingJobLostError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GceEncodeResponse(TypedDict, total=False):
|
||||
"""Typed schema for the raw response the GCE encoding worker returns from
|
||||
``encode_videos`` (forwarded up from ``wait_for_completion`` /
|
||||
``submit_encoding_job``).
|
||||
|
||||
This is the *single shared definition* of the encode→publish seam contract:
|
||||
both the producer (``EncodingService.encode_videos``) and the consumer
|
||||
(``GCEEncodingBackend.encode``) annotate against it, so the shape can't
|
||||
silently drift between caller and callee. Mock drift on exactly this shape
|
||||
is what hid NOMAD-1632's Failure B (the "empty output_files" / stale-cache
|
||||
case was never in any test corpus). Golden fixtures under
|
||||
``backend/tests/fixtures/encoding/`` are validated against this schema.
|
||||
|
||||
Keys (``total=False`` — the worker omits most of them on the happy path):
|
||||
- ``status``: terminal/intermediate job state, e.g. ``"complete"``,
|
||||
``"failed"``, ``"running"``, ``"pending"``. ``encode_videos`` normalises a
|
||||
cached hit to ``"complete"``.
|
||||
- ``output_files``: GCS paths to the encoded finals, classified by
|
||||
:func:`classify_encoded_output`. The worker returns a **list**; a few
|
||||
legacy/short-name paths arrive as a ``dict`` keyed by format token, which
|
||||
``encode`` still tolerates. **May be an empty list** on a stale/cached job
|
||||
whose finals were deleted from GCS — a *recoverable* condition, NOT a
|
||||
partial/defective result (see the completeness guard in ``encode``).
|
||||
- ``progress``: 0–100 while running.
|
||||
- ``error``: present when ``status == "failed"``.
|
||||
"""
|
||||
|
||||
status: str
|
||||
output_files: List[str]
|
||||
progress: int
|
||||
error: str
|
||||
|
||||
|
||||
def classify_encoded_output(filename: str) -> Optional[str]:
|
||||
"""Classify a GCE-encoded output file by format, robust to artist/title text.
|
||||
|
||||
GCE finals are named ``<artist> - <title> (<format tag>).<ext>``, e.g.
|
||||
``Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4``. The
|
||||
format is entirely in the trailing parenthetical, so we match on THAT tag only
|
||||
— never the whole filename. Matching the whole filename is what caused the
|
||||
NOMAD-1632 gap: the title "Portrait of Jennie" contains "portrait", so the
|
||||
720p master matched the portrait-video branch (checked before "720p") and was
|
||||
never mapped to ``mp4_720p`` — it published to MP4/ + CDG/ with no 720p, and
|
||||
only the daily GDrive validator caught it. Any song whose artist/title contains
|
||||
a format word ("portrait", "720p", "4k", "lossless", "vocals", …) hit the same
|
||||
class of bug.
|
||||
|
||||
Returns a canonical token or ``None`` if the file isn't a recognised final:
|
||||
``mp4_4k_lossless``, ``mkv_4k``, ``mp4_4k_lossy``, ``mp4_720p``,
|
||||
``portrait_mp4``, ``with_vocals_mp4``, ``title_mov``, ``end_mov``,
|
||||
``cdg_zip``, ``txt_zip``.
|
||||
"""
|
||||
name = os.path.basename(filename)
|
||||
stem, ext = os.path.splitext(name)
|
||||
ext = ext.lower()
|
||||
|
||||
# System-generated short canonical names, e.g. jobs/{id}/finals/lossy_720p_mp4.mp4
|
||||
# (uploaded by _upload_results) and packages/cdg_zip.zip. They carry no artist/title
|
||||
# text, so an exact-stem match is unambiguous — and the redistribution flow reads
|
||||
# these back from GCS. Checked first so the underscore forms don't fall through.
|
||||
# (stem, ext) so a mismatched extension can't slip a stray file into a slot.
|
||||
short_name = {
|
||||
("lossless_4k_mp4", ".mp4"): "mp4_4k_lossless",
|
||||
("lossless_4k_mkv", ".mkv"): "mkv_4k",
|
||||
("lossy_4k_mp4", ".mp4"): "mp4_4k_lossy",
|
||||
("lossy_720p_mp4", ".mp4"): "mp4_720p",
|
||||
("portrait_1080x1920", ".mp4"): "portrait_mp4",
|
||||
("cdg_zip", ".zip"): "cdg_zip",
|
||||
("txt_zip", ".zip"): "txt_zip",
|
||||
}.get((stem.lower(), ext))
|
||||
if short_name:
|
||||
return short_name
|
||||
|
||||
# Otherwise the format tag is the LAST parenthetical group before the extension.
|
||||
# A file without that parenthetical isn't a recognised final. Every branch also
|
||||
# pins the expected extension, so a stray file whose artist/title happens to
|
||||
# contain a format word (e.g. "Artist 720p notes.txt") can't be misclassified
|
||||
# into a slot and then falsely satisfy the completeness guard.
|
||||
match = re.search(r"\(([^()]*)\)[^()]*$", name)
|
||||
if not match:
|
||||
return None
|
||||
tag = match.group(1).lower()
|
||||
|
||||
if "720p" in tag and ext == ".mp4":
|
||||
return "mp4_720p"
|
||||
if ("portrait" in tag or "1080x1920" in tag) and ext == ".mp4":
|
||||
return "portrait_mp4"
|
||||
if "lossless 4k" in tag:
|
||||
if ext == ".mkv":
|
||||
return "mkv_4k"
|
||||
if ext == ".mp4":
|
||||
return "mp4_4k_lossless"
|
||||
return None
|
||||
if "lossy 4k" in tag and ext == ".mp4":
|
||||
return "mp4_4k_lossy"
|
||||
if "with vocals" in tag and ext == ".mp4":
|
||||
return "with_vocals_mp4"
|
||||
if tag == "title" and ext == ".mov":
|
||||
return "title_mov"
|
||||
if tag == "end" and ext == ".mov":
|
||||
return "end_mov"
|
||||
if "cdg" in tag and ext == ".zip":
|
||||
return "cdg_zip"
|
||||
if "txt" in tag and ext == ".zip":
|
||||
return "txt_zip"
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncodingInput:
|
||||
"""
|
||||
@@ -380,34 +490,54 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
# We need dict like: {"mp4_4k_lossless": "path/...", "mp4_720p": "path/..."}
|
||||
if isinstance(raw_output_files, list):
|
||||
output_files = {}
|
||||
# Classify each returned final by its format tag (the trailing
|
||||
# parenthetical), NOT the whole filename — see classify_encoded_output.
|
||||
# Matching the whole filename misfiled the 720p of "Portrait of Jennie"
|
||||
# as the portrait video (NOMAD-1632).
|
||||
for path in raw_output_files:
|
||||
if not isinstance(path, str):
|
||||
continue
|
||||
filename = path.split("/")[-1] if "/" in path else path
|
||||
filename_lower = filename.lower()
|
||||
# Map filename patterns to output format keys
|
||||
# Files are named like "Artist - Title (Final Karaoke Lossless 4k).mp4"
|
||||
if "lossless 4k" in filename_lower:
|
||||
if filename.endswith(".mkv"):
|
||||
output_files["mkv_4k"] = path
|
||||
else:
|
||||
output_files["mp4_4k_lossless"] = path
|
||||
elif "lossy 4k" in filename_lower:
|
||||
output_files["mp4_4k_lossy"] = path
|
||||
elif "portrait" in filename_lower:
|
||||
output_files["portrait_mp4"] = path
|
||||
elif "720p" in filename_lower:
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
elif filename_lower.endswith("(title).mov"):
|
||||
output_files["title_mov"] = path
|
||||
elif filename_lower.endswith("(end).mov"):
|
||||
output_files["end_mov"] = path
|
||||
key = classify_encoded_output(path)
|
||||
if key:
|
||||
output_files[key] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
|
||||
# Completeness guard (defense-in-depth): a worker that returns SOME formats
|
||||
# but not every one we requested — the title-collision mapping bug that
|
||||
# dropped the 720p (NOMAD-1632, fixed above by classify_encoded_output), a
|
||||
# stale-wheel fallback VM, or an output lost before the worker's
|
||||
# glob/upload — must NOT sail through to distribution and publish an
|
||||
# incomplete public release, leaving a sequence gap the daily GDrive
|
||||
# validator only flags ~24h later. Fail loud so the orchestrator errors the
|
||||
# job (retried on a healthy worker) and the alert fires immediately.
|
||||
#
|
||||
# IMPORTANT: only fire on a PARTIAL result. An EMPTY output_files means the
|
||||
# worker returned nothing at all — typically a stale GCE job cache whose
|
||||
# finals were deleted from GCS (admin reset / re-run). That is a normal,
|
||||
# recoverable condition the orchestrator already handles: it downloads zero
|
||||
# files, raises a "stale" RuntimeError from _download_gce_encoded_files, and
|
||||
# re-encodes under a fresh job id. Guarding the empty case here would
|
||||
# short-circuit that recovery and hard-fail real jobs (regression fixed in
|
||||
# v0.222.3).
|
||||
requested_formats = encoding_config.get("formats", [])
|
||||
missing_formats = [f for f in requested_formats if not output_files.get(f)]
|
||||
if output_files and missing_formats:
|
||||
error_message = (
|
||||
f"Encoder returned an incomplete result: missing {missing_formats} "
|
||||
f"(requested {requested_formats}, got {sorted(output_files.keys())}). "
|
||||
"Refusing to publish a partial release."
|
||||
)
|
||||
self.logger.error(f"[job:{job_id}] {error_message}")
|
||||
return EncodingOutput(
|
||||
success=False,
|
||||
error_message=error_message,
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name,
|
||||
)
|
||||
|
||||
return EncodingOutput(
|
||||
success=True,
|
||||
lossless_4k_mp4_path=output_files.get("mp4_4k_lossless"),
|
||||
|
||||
@@ -21,10 +21,15 @@ import os
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator
|
||||
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator, TYPE_CHECKING
|
||||
|
||||
import aiohttp
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Shared seam contract. Type-only import (no runtime cost, no import cycle —
|
||||
# encoding_interface imports encoding_service lazily inside methods).
|
||||
from backend.services.encoding_interface import GceEncodeResponse
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.encoding_errors import (
|
||||
ENCODING_RESTART_FAILURE_CODE,
|
||||
@@ -904,7 +909,7 @@ class EncodingService:
|
||||
output_gcs_path: str,
|
||||
encoding_config: Optional[Dict[str, Any]] = None,
|
||||
progress_callback=None,
|
||||
) -> Dict[str, Any]:
|
||||
) -> "GceEncodeResponse":
|
||||
"""
|
||||
Submit encoding job and wait for completion.
|
||||
|
||||
|
||||
@@ -57,15 +57,51 @@ class FirestoreService:
|
||||
logger.error(f"Error getting job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _is_doc_size_error(exc: Exception) -> bool:
|
||||
"""True when a Firestore write failed the 1MB per-document size limit."""
|
||||
return "maximum allowed size" in str(exc).lower()
|
||||
|
||||
def _update_with_size_recovery(
|
||||
self, doc_ref, updates: Dict[str, Any], job_id: str
|
||||
) -> None:
|
||||
"""
|
||||
Apply ``doc_ref.update(updates)``, self-healing past the 1MB doc limit.
|
||||
|
||||
Old job documents can accumulate a large embedded ``worker_logs`` array
|
||||
(the legacy logging path, superseded by the ``jobs/{id}/logs``
|
||||
subcollection). Once that array pushes a document to ~1MB, EVERY
|
||||
subsequent write — including a customer submitting lyrics corrections —
|
||||
fails with Firestore's "exceeds the maximum allowed size" 400. The
|
||||
embedded array is deprecated dead weight, so drop it and retry once.
|
||||
"""
|
||||
try:
|
||||
doc_ref.update(updates)
|
||||
except Exception as e:
|
||||
# Don't recurse if the caller is itself writing worker_logs, and
|
||||
# only recover from the specific size-limit failure.
|
||||
if 'worker_logs' in updates or not self._is_doc_size_error(e):
|
||||
raise
|
||||
logger.warning(
|
||||
f"Job {job_id}: Firestore write hit the 1MB document limit; "
|
||||
f"clearing the legacy embedded worker_logs array and retrying ({e})"
|
||||
)
|
||||
# Deleting a field only shrinks the document, so this write is safe.
|
||||
doc_ref.update({'worker_logs': firestore.DELETE_FIELD})
|
||||
doc_ref.update(updates)
|
||||
logger.info(
|
||||
f"Job {job_id}: cleared legacy worker_logs; write succeeded on retry"
|
||||
)
|
||||
|
||||
def update_job(self, job_id: str, updates: Dict[str, Any]) -> None:
|
||||
"""Update a job with partial data."""
|
||||
try:
|
||||
doc_ref = self.db.collection(self.collection).document(job_id)
|
||||
|
||||
|
||||
# Add updated_at timestamp
|
||||
updates['updated_at'] = datetime.utcnow()
|
||||
|
||||
doc_ref.update(updates)
|
||||
|
||||
self._update_with_size_recovery(doc_ref, updates, job_id)
|
||||
logger.info(f"Updated job {job_id} in Firestore")
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating job {job_id}: {e}")
|
||||
@@ -107,12 +143,31 @@ class FirestoreService:
|
||||
|
||||
# Add any additional fields
|
||||
updates.update(additional_fields)
|
||||
|
||||
doc_ref.update(updates)
|
||||
|
||||
self._update_with_size_recovery(doc_ref, updates, job_id)
|
||||
logger.info(f"Updated job {job_id} status to {status.value}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating job status {job_id}: {e}")
|
||||
raise
|
||||
|
||||
# Incident-hardening D1: near-real-time alert on ANY transition to FAILED.
|
||||
# The spike-based error monitor is blind to a novel low-volume failure
|
||||
# (rolling_avg==0 → never a spike), so a brand-new error on a couple of
|
||||
# jobs can go unnoticed. This is the universal net. Best-effort: it must
|
||||
# never turn a successful status write into a failure, hence the guard.
|
||||
if status == JobStatus.FAILED:
|
||||
try:
|
||||
from backend.services.ops_alerts import notify_job_failed
|
||||
|
||||
notify_job_failed(
|
||||
db=self.db,
|
||||
collection=self.collection,
|
||||
job_id=job_id,
|
||||
message=message,
|
||||
additional_fields=additional_fields,
|
||||
)
|
||||
except Exception as alert_exc: # noqa: BLE001
|
||||
logger.warning(f"Failure alert for job {job_id} did not send: {alert_exc}")
|
||||
|
||||
def list_jobs(
|
||||
self,
|
||||
@@ -364,18 +419,31 @@ class FirestoreService:
|
||||
|
||||
def append_worker_log(self, job_id: str, log_entry: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Atomically append a log entry to worker_logs using ArrayUnion.
|
||||
Append a log entry to the job's log stream.
|
||||
|
||||
This avoids the race condition of read-modify-write when multiple
|
||||
workers are logging concurrently.
|
||||
|
||||
DEPRECATED: Use append_log_to_subcollection() instead to avoid
|
||||
the 1MB document size limit.
|
||||
DEPRECATED embedded-array behaviour: with USE_LOG_SUBCOLLECTION=false
|
||||
this appends to the ``worker_logs`` array via ArrayUnion (atomic, but
|
||||
subject to the 1MB per-document limit). With the flag on (default) the
|
||||
entry is routed to the ``jobs/{id}/logs`` subcollection instead, so the
|
||||
legacy dict-based callers (job_logging.JobLogger, FirestoreJobLogHandler)
|
||||
stop bloating the embedded array toward that limit.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
log_entry: Log entry dict with timestamp, level, worker, message
|
||||
"""
|
||||
# Route legacy dict-based callers to the subcollection when enabled so
|
||||
# they no longer grow the embedded worker_logs array (which, once near
|
||||
# 1MB, blocks all writes to the job document — including review submits).
|
||||
if settings.use_log_subcollection:
|
||||
entry = WorkerLogEntry.create(
|
||||
job_id=job_id,
|
||||
worker=log_entry.get('worker', 'unknown'),
|
||||
level=log_entry.get('level', 'INFO'),
|
||||
message=log_entry.get('message', ''),
|
||||
)
|
||||
self.append_log_to_subcollection(job_id, entry)
|
||||
return
|
||||
try:
|
||||
doc_ref = self.db.collection(self.collection).document(job_id)
|
||||
doc_ref.update({
|
||||
|
||||
@@ -92,17 +92,21 @@ def should_retry_flacfetch_error(exception: Exception) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
async def with_retry(func, *args, **kwargs):
|
||||
async def with_retry(func, *args, retry_max_attempts=None, retry_min_wait=None, retry_max_wait=None, **kwargs):
|
||||
"""
|
||||
Execute an async function with retry logic using exponential backoff.
|
||||
|
||||
This implementation uses manual retry logic instead of tenacity decorators
|
||||
for better testability and runtime configuration.
|
||||
|
||||
The retry_* keyword-only arguments override the FLACFETCH_RETRY_* settings
|
||||
for callers that need a different retry profile (e.g. search, which sits on
|
||||
a latency-sensitive user-facing path).
|
||||
"""
|
||||
settings = get_settings()
|
||||
max_attempts = settings.flacfetch_retry_max_attempts
|
||||
min_wait = settings.flacfetch_retry_min_wait
|
||||
max_wait = settings.flacfetch_retry_max_wait
|
||||
max_attempts = retry_max_attempts if retry_max_attempts is not None else settings.flacfetch_retry_max_attempts
|
||||
min_wait = retry_min_wait if retry_min_wait is not None else settings.flacfetch_retry_min_wait
|
||||
max_wait = retry_max_wait if retry_max_wait is not None else settings.flacfetch_retry_max_wait
|
||||
|
||||
last_exception = None
|
||||
|
||||
@@ -218,37 +222,65 @@ class FlacfetchClient:
|
||||
|
||||
Returns:
|
||||
Search response dict with search_id and results list
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On search failure
|
||||
FlacfetchServiceError: On search failure (after all retries exhausted)
|
||||
|
||||
Search is idempotent, so transient network errors (e.g. a ReadTimeout
|
||||
while the flacfetch server is busy with an uncached provider sweep) are
|
||||
retried once with a short wait. The retry usually hits the server-side
|
||||
search cache warmed by the first attempt and returns in seconds.
|
||||
|
||||
All attempts share a total time budget kept below Cloudflare's ~100s
|
||||
edge deadline, so a slow retry surfaces as FlacfetchServiceError rather
|
||||
than an opaque edge 524.
|
||||
"""
|
||||
settings = get_settings()
|
||||
total_timeout = settings.flacfetch_search_total_timeout
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "title": title},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
|
||||
if resp.status_code == 404:
|
||||
# No results found - return empty results
|
||||
return {
|
||||
"search_id": None,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"results": [],
|
||||
"results_count": 0,
|
||||
}
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
return await asyncio.wait_for(
|
||||
with_retry(
|
||||
self._search_impl,
|
||||
artist,
|
||||
title,
|
||||
retry_max_attempts=settings.flacfetch_search_retry_max_attempts,
|
||||
retry_min_wait=settings.flacfetch_search_retry_wait,
|
||||
retry_max_wait=settings.flacfetch_search_retry_wait,
|
||||
),
|
||||
timeout=total_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
raise FlacfetchServiceError(
|
||||
f"Search timed out after {total_timeout:.0f}s total (including retries)"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _search_impl(self, artist: str, title: str) -> Dict[str, Any]:
|
||||
"""Implementation of search without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "title": title},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
|
||||
if resp.status_code == 404:
|
||||
# No results found - return empty results
|
||||
return {
|
||||
"search_id": None,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"results": [],
|
||||
"results_count": 0,
|
||||
}
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def download(
|
||||
self,
|
||||
search_id: str,
|
||||
|
||||
@@ -21,6 +21,7 @@ from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .persistence import JobStatePersister
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -305,7 +306,7 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
try:
|
||||
# Download input files
|
||||
ass_path = work_dir / "subtitles.ass"
|
||||
audio_path = work_dir / "audio.flac"
|
||||
audio_path = work_dir / local_audio_filename(request.audio_gcs_path, "audio")
|
||||
|
||||
download_single_file_from_gcs(request.ass_gcs_path, ass_path)
|
||||
jobs[job_id]["progress"] = 20
|
||||
@@ -454,7 +455,7 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
audio_path = work_dir / "audio.flac"
|
||||
audio_path = work_dir / local_audio_filename(request.audio_gcs_path, "audio")
|
||||
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
|
||||
jobs[job_id]["progress"] = 35
|
||||
|
||||
|
||||
@@ -20,12 +20,21 @@ logger = logging.getLogger(__name__)
|
||||
GDRIVE_VALIDATOR_URL = os.environ.get("GDRIVE_VALIDATOR_URL", "")
|
||||
|
||||
|
||||
def trigger_gdrive_validation() -> dict | None:
|
||||
def trigger_gdrive_validation(
|
||||
brand_code: str | None = None, expect_cdg: bool = False
|
||||
) -> dict | None:
|
||||
"""
|
||||
Invoke the GDrive validator Cloud Function.
|
||||
|
||||
Uses the backend service account's OIDC token for authentication.
|
||||
|
||||
Args:
|
||||
brand_code: Optional brand code of the just-published track. When set, the
|
||||
validator additionally verifies this track is present in all expected
|
||||
folders same-run (incident-hardening D2).
|
||||
expect_cdg: Whether the just-published track produced a CDG package (so the
|
||||
validator requires the CDG folder for it). Ignored without brand_code.
|
||||
|
||||
Returns:
|
||||
Parsed JSON response from the function, or None on error.
|
||||
"""
|
||||
@@ -41,6 +50,7 @@ def trigger_gdrive_validation() -> dict | None:
|
||||
response = requests.post(
|
||||
GDRIVE_VALIDATOR_URL,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"brand_code": brand_code, "expect_cdg": expect_cdg} if brand_code else None,
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -1136,49 +1136,58 @@ class JobManager:
|
||||
|
||||
def mark_lyrics_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
Mark lyrics processing as complete and trigger screens if ready.
|
||||
Mark lyrics processing as complete.
|
||||
|
||||
Lyrics completion is the sole gate for screen generation and review.
|
||||
Audio separation runs independently in the background.
|
||||
Lyrics completion is the sole gate for screen generation and review
|
||||
(audio separation runs independently in the background). This ONLY sets
|
||||
the flag — the caller must then ``await advance_to_screens_if_ready()`` so
|
||||
the screens dispatch is durable. A previous fire-and-forget
|
||||
``asyncio.create_task`` trigger was being cancelled when the lyrics Cloud
|
||||
Run Job's event loop tore down, orphaning jobs at ``downloading`` with no
|
||||
error (E2E job-orchestration stall incident, 2026-09).
|
||||
"""
|
||||
self.update_state_data(job_id, 'lyrics_complete', True)
|
||||
|
||||
if self.check_parallel_processing_complete(job_id):
|
||||
logger.info(f"Job {job_id}: Lyrics complete, triggering screens worker")
|
||||
self._trigger_screens_worker(job_id)
|
||||
|
||||
def _trigger_screens_worker(self, job_id: str) -> None:
|
||||
async def advance_to_screens_if_ready(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger screens generation worker.
|
||||
|
||||
Uses WorkerService to make HTTP call to internal API.
|
||||
This must be async, so we use asyncio to create a task.
|
||||
Idempotently trigger the screens worker once lyrics processing is complete.
|
||||
|
||||
Awaited (not fire-and-forget) so the Cloud Task enqueue completes before
|
||||
the calling worker's event loop tears down. Safe to call from BOTH the
|
||||
lyrics worker (primary trigger) and the audio worker (fallback, in case
|
||||
the lyrics trigger was lost): the status guard here plus the screens
|
||||
worker's own idempotency make a double-trigger a harmless no-op.
|
||||
|
||||
Screen generation is gated on LYRICS only (audio separation is decoupled
|
||||
so reviewers can start while it finishes), so this no-ops until lyrics are
|
||||
done, and only fires while the job is still at ``downloading``.
|
||||
|
||||
Returns:
|
||||
True iff a screens dispatch was issued.
|
||||
"""
|
||||
import asyncio
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
return False
|
||||
if not job.state_data.get('lyrics_complete', False):
|
||||
# Lyrics not finished yet — whichever worker finishes lyrics triggers.
|
||||
return False
|
||||
if job.status != JobStatus.DOWNLOADING:
|
||||
# Already advanced past prep (or parked in a special state). Keeps the
|
||||
# audio-worker fallback from re-triggering a job that already reached
|
||||
# screens/review.
|
||||
logger.info(
|
||||
f"Job {job_id}: screens not (re)triggered — status={job.status} "
|
||||
"(expected downloading)"
|
||||
)
|
||||
return False
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
logger.info(f"Job {job_id}: Triggering screens worker")
|
||||
|
||||
# Create async task to trigger worker
|
||||
# This allows us to call async code from sync context
|
||||
async def _trigger():
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_screens_worker(job_id)
|
||||
|
||||
# Create task in event loop
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
if loop.is_running():
|
||||
# If loop is already running, create task
|
||||
asyncio.create_task(_trigger())
|
||||
else:
|
||||
# If no loop, run directly
|
||||
asyncio.run(_trigger())
|
||||
except RuntimeError:
|
||||
# Fallback: just log
|
||||
logger.warning(f"Job {job_id}: Could not trigger screens worker (no event loop)")
|
||||
# TODO: In production, use message queue instead
|
||||
|
||||
logger.info(f"Job {job_id}: lyrics complete — triggering screens worker (awaited)")
|
||||
# Propagate the dispatch result: trigger_screens_worker returns False on a
|
||||
# Cloud Tasks enqueue failure / HTTP error / timeout. Returning False here
|
||||
# keeps recover_stuck_jobs from counting a failed re-trigger against its
|
||||
# per-tick cap (which would delay other stalled jobs), and lets it retry.
|
||||
return await get_worker_service().trigger_screens_worker(job_id)
|
||||
|
||||
def cancel_job(self, job_id: str, reason: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Cancel a job.
|
||||
|
||||
@@ -249,6 +249,33 @@ class JobNotificationService:
|
||||
logger.exception(f"Error sending community-track-live email to {_mask_email(to_email)}: {e}")
|
||||
return False
|
||||
|
||||
async def send_community_existing_version_email(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Notify one up-voter that their request was rejected because a community
|
||||
karaoke version already exists (linking them to it). Best-effort."""
|
||||
if not ENABLE_AUTO_EMAILS:
|
||||
logger.info("Auto emails disabled, skipping community-existing-version notification")
|
||||
return False
|
||||
if not to_email:
|
||||
return False
|
||||
try:
|
||||
user_locale = self._get_user_locale(to_email)
|
||||
message_content = self.template_service.render_community_existing_version(
|
||||
artist=artist, title=title, youtube_url=youtube_url, locale=user_locale,
|
||||
)
|
||||
return self.email_service.send_community_existing_version(
|
||||
to_email=to_email, message_content=message_content,
|
||||
artist=artist, title=title, locale=user_locale,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error sending community-existing-version email to {_mask_email(to_email)}: {e}")
|
||||
return False
|
||||
|
||||
async def send_action_reminder_email(
|
||||
self,
|
||||
job_id: str,
|
||||
|
||||
@@ -1,249 +1,208 @@
|
||||
"""
|
||||
KaraokeNerds community version detection service.
|
||||
|
||||
Scrapes karaokenerds.com to check if a song already has community-approved
|
||||
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
|
||||
Checks whether a song already has community-approved karaoke versions (free,
|
||||
directly-playable, on YouTube). This reads OUR OWN daily-refreshed copy of the
|
||||
KaraokeNerds community catalog — it does NOT scrape or live-query
|
||||
karaokenerds.com. The catalog is populated by the authorized `kn-data-sync`
|
||||
export job (the only thing permitted to hit karaokenerds.com) into BigQuery
|
||||
`karaoke_decide.karaokenerds_community` and mirrored to a gzipped-JSON object in
|
||||
GCS, which this module loads into an in-process index.
|
||||
|
||||
Public API (`check_community_versions` / `check_community_versions_batch`) and
|
||||
its return shapes are unchanged from the previous scraping implementation, so
|
||||
callers and the frontend need no changes.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from google.cloud import storage
|
||||
|
||||
from backend.config import settings
|
||||
from backend.services.kn_brand_names import brand_name_for
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# karaokenerds.com's search silently returns zero results once a query exceeds
|
||||
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
|
||||
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
|
||||
# artist blow past this, so the song is falsely reported as having no community
|
||||
# version. When that happens we retry with the title alone (the highest-signal
|
||||
# term) and keep only results whose artist matches.
|
||||
MAX_RELIABLE_QUERY_TERMS = 10
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
# Extract a YouTube video id from any of KaraokeNerds' stored watch-URL forms
|
||||
# (youtu.be/<id>, /watch?v=<id>, /embed/<id>, /shorts/<id>) so we can emit the
|
||||
# canonical https://www.youtube.com/watch?v=<id> the old scrape produced.
|
||||
_YT_ID_RE = re.compile(
|
||||
r"(?:youtu\.be/|youtube\.com/(?:watch\?(?:[^&]*&)*v=|embed/|shorts/|v/))"
|
||||
r"([A-Za-z0-9_-]{11})"
|
||||
)
|
||||
|
||||
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
def _normalize_youtube_url(watch: str | None) -> str | None:
|
||||
"""Canonicalize a KaraokeNerds watch URL to youtube.com/watch?v=<id>.
|
||||
|
||||
Returns the canonical URL, or the stripped original if no 11-char id can be
|
||||
parsed (never fabricates), or None when empty.
|
||||
"""
|
||||
watch = (watch or "").strip()
|
||||
if not watch:
|
||||
return None
|
||||
m = _YT_ID_RE.search(watch)
|
||||
if m:
|
||||
return f"https://www.youtube.com/watch?v={m.group(1)}"
|
||||
return watch
|
||||
|
||||
# Every row in the community catalog is, by definition, a community/web track, so
|
||||
# entries surfaced from it are always flagged as community versions.
|
||||
_IS_COMMUNITY = True
|
||||
|
||||
# In-process index built from the community export, refreshed on a TTL. Structure:
|
||||
# { "<norm-artist>\x1f<norm-title>": {"title", "artist", "community_tracks": [...]} }
|
||||
_index: dict[str, dict[str, Any]] | None = None
|
||||
_index_expiry: float = 0.0
|
||||
_index_lock = asyncio.Lock()
|
||||
|
||||
# Separator for the (artist, title) match key — a control char that survives
|
||||
# normalization stripping so it can never appear inside a normalized value.
|
||||
_KEY_SEP = "\x1f"
|
||||
|
||||
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
def _match_key(artist: str, title: str) -> str:
|
||||
return f"{normalize_for_match(artist)}{_KEY_SEP}{normalize_for_match(title)}"
|
||||
|
||||
|
||||
def _clean_youtube_url(url: str) -> str:
|
||||
"""Strip playlist params from YouTube URLs, keep just the video URL."""
|
||||
return re.sub(r"&list=[^&]*", "", url)
|
||||
def _build_index(items: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
"""Build the (artist, title) -> song lookup from raw community rows.
|
||||
|
||||
Each raw row carries ``Artist, Title, Brand, Watch`` (YouTube URL). Rows for
|
||||
the same normalized (artist, title) are grouped; their community tracks are
|
||||
deduped by (brand, url).
|
||||
"""
|
||||
index: dict[str, dict[str, Any]] = {}
|
||||
for row in items:
|
||||
artist = (row.get("Artist") or "").strip()
|
||||
title = (row.get("Title") or "").strip()
|
||||
if not artist or not title:
|
||||
continue
|
||||
# The export stores the brand *code* (e.g. "NOMAD"); resolve the human
|
||||
# name for display and keep the code, matching the old scrape's output.
|
||||
brand_code = (row.get("Brand") or "").strip()
|
||||
youtube_url = _normalize_youtube_url(row.get("Watch"))
|
||||
|
||||
key = _match_key(artist, title)
|
||||
song = index.get(key)
|
||||
if song is None:
|
||||
# Keep the first-seen display casing for artist/title.
|
||||
song = {"title": title, "artist": artist, "community_tracks": [], "_seen": set()}
|
||||
index[key] = song
|
||||
|
||||
dedup = (brand_code, youtube_url)
|
||||
if dedup in song["_seen"]:
|
||||
continue
|
||||
song["_seen"].add(dedup)
|
||||
song["community_tracks"].append({
|
||||
"brand_name": brand_name_for(brand_code),
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": _IS_COMMUNITY,
|
||||
})
|
||||
|
||||
# Drop the internal dedup bookkeeping before returning.
|
||||
for song in index.values():
|
||||
song.pop("_seen", None)
|
||||
return index
|
||||
|
||||
|
||||
def _parse_single_track(li) -> dict | None:
|
||||
"""Parse a single track <li> element from karaokenerds search results."""
|
||||
# Brand name: first <a> in the li
|
||||
brand_link = li.find("a")
|
||||
brand_name = brand_link.get_text(strip=True) if brand_link else ""
|
||||
def _load_index() -> dict[str, dict[str, Any]]:
|
||||
"""Download and parse the community export gzip from GCS (blocking)."""
|
||||
client = storage.Client(project=settings.google_cloud_project)
|
||||
bucket = client.bucket(settings.kn_community_bucket)
|
||||
blob = bucket.blob(settings.kn_community_blob)
|
||||
raw = blob.download_as_bytes()
|
||||
data = json.loads(gzip.decompress(raw))
|
||||
if isinstance(data, dict) and "Items" in data:
|
||||
items = data["Items"]
|
||||
elif isinstance(data, list):
|
||||
items = data
|
||||
else:
|
||||
raise ValueError(f"Unexpected community export shape: {type(data).__name__}")
|
||||
index = _build_index(items)
|
||||
logger.info(
|
||||
"Loaded KaraokeNerds community index: %d songs from gs://%s/%s",
|
||||
len(index), settings.kn_community_bucket, settings.kn_community_blob,
|
||||
)
|
||||
return index
|
||||
|
||||
# Brand code: text inside .badge span
|
||||
badge = li.find("span", class_="badge")
|
||||
brand_code = ""
|
||||
if badge:
|
||||
brand_code = badge.get_text(strip=True)
|
||||
|
||||
# YouTube URL: link containing youtube.com
|
||||
youtube_url = None
|
||||
for a in li.find_all("a", href=True):
|
||||
href = a["href"]
|
||||
if "youtube.com" in href:
|
||||
youtube_url = _clean_youtube_url(href)
|
||||
async def _get_index() -> dict[str, dict[str, Any]]:
|
||||
"""Return the community index, refreshing from GCS when the TTL has expired.
|
||||
|
||||
Failures are non-fatal: a stale index keeps serving; if there is no index
|
||||
yet, an empty one is returned (every song reads as "no community version",
|
||||
which keeps tracks selectable — the same fail-open behaviour the scraper had).
|
||||
"""
|
||||
global _index, _index_expiry
|
||||
if _index is not None and time.monotonic() < _index_expiry:
|
||||
return _index
|
||||
|
||||
async with _index_lock:
|
||||
# Re-check after acquiring the lock — another coroutine may have loaded it.
|
||||
if _index is not None and time.monotonic() < _index_expiry:
|
||||
return _index
|
||||
try:
|
||||
fresh = await asyncio.to_thread(_load_index)
|
||||
_index = fresh
|
||||
_index_expiry = time.monotonic() + max(60, settings.kn_community_ttl_seconds)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to load KaraokeNerds community index: %s", e)
|
||||
if _index is None:
|
||||
# No prior data — serve empty until the short retry window elapses.
|
||||
_index = {}
|
||||
# Retry soon whether we're serving empty or a stale index, so an
|
||||
# outage doesn't make every request re-attempt the load immediately.
|
||||
_index_expiry = time.monotonic() + 60
|
||||
return _index
|
||||
|
||||
|
||||
def _lookup(index: dict[str, dict[str, Any]], artist: str, title: str) -> dict:
|
||||
"""Build a check result for one (artist, title) from the index."""
|
||||
song = index.get(_match_key(artist, title))
|
||||
if not song or not song.get("community_tracks"):
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
best_youtube_url = None
|
||||
for track in song["community_tracks"]:
|
||||
if track.get("youtube_url"):
|
||||
best_youtube_url = track["youtube_url"]
|
||||
break
|
||||
|
||||
# Community: presence of img.check
|
||||
is_community = bool(li.find("img", class_="check"))
|
||||
|
||||
if not youtube_url:
|
||||
return None
|
||||
|
||||
return {
|
||||
"brand_name": brand_name,
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": is_community,
|
||||
"has_community": True,
|
||||
"songs": [{
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": song["community_tracks"],
|
||||
}],
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tracks(details_row) -> list[dict]:
|
||||
"""Parse track list items from a details row."""
|
||||
tracks = []
|
||||
for li in details_row.find_all("li", class_="track"):
|
||||
track = _parse_single_track(li)
|
||||
if track:
|
||||
tracks.append(track)
|
||||
return tracks
|
||||
|
||||
|
||||
def parse_results(html: str) -> list[dict]:
|
||||
"""Parse karaokenerds.com search results HTML into structured data."""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
table = soup.find("table")
|
||||
if not table:
|
||||
return []
|
||||
|
||||
tbody = table.find("tbody")
|
||||
if not tbody:
|
||||
return []
|
||||
|
||||
songs = []
|
||||
rows = tbody.find_all("tr", recursive=False)
|
||||
|
||||
i = 0
|
||||
while i < len(rows):
|
||||
row = rows[i]
|
||||
|
||||
# Song rows have class "group"
|
||||
if "group" not in row.get("class", []):
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Extract title and artist from the song row
|
||||
cells = row.find_all("td")
|
||||
if len(cells) < 3:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
title_link = cells[0].find("a")
|
||||
artist_link = cells[1].find("a")
|
||||
title = title_link.get_text(strip=True) if title_link else ""
|
||||
artist = artist_link.get_text(strip=True) if artist_link else ""
|
||||
|
||||
# The next row should be the details row with tracks
|
||||
tracks = []
|
||||
if i + 1 < len(rows):
|
||||
details_row = rows[i + 1]
|
||||
if "details" in details_row.get("class", []):
|
||||
tracks = _parse_tracks(details_row)
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
if title:
|
||||
songs.append({
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": tracks,
|
||||
})
|
||||
|
||||
return songs
|
||||
|
||||
|
||||
async def _search_songs(query: str) -> list[dict] | None:
|
||||
"""Run a single karaokenerds search and parse the results.
|
||||
|
||||
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
|
||||
caller can distinguish "search errored" from "search returned nothing").
|
||||
"""
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
return None
|
||||
return parse_results(resp.text)
|
||||
|
||||
|
||||
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
|
||||
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
|
||||
community_songs: list[dict] = []
|
||||
best_youtube_url: str | None = None
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
return community_songs, best_youtube_url
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
Check if a song has community-approved karaoke versions.
|
||||
|
||||
Returns a dict with:
|
||||
Reads our own community catalog (never karaokenerds.com). Returns a dict with:
|
||||
- has_community: bool
|
||||
- songs: list of matched songs with community tracks
|
||||
- best_youtube_url: URL of the top community version (if any)
|
||||
"""
|
||||
query = f"{artist} {title}"
|
||||
cache_key = f"community:{query.lower().strip()}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
songs = await _search_songs(query)
|
||||
if songs is None:
|
||||
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
|
||||
# site, matching prior behaviour.
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
# karaokenerds chokes on overlong queries and returns nothing. If the
|
||||
# combined "artist title" query was too long AND came back empty, retry with
|
||||
# the title alone, then keep only results whose artist matches (title-only is
|
||||
# broader, so this guards against same-titled songs by other artists).
|
||||
if (
|
||||
not songs
|
||||
and title.strip()
|
||||
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
|
||||
):
|
||||
fallback = await _search_songs(title)
|
||||
if fallback:
|
||||
key_artist = normalize_for_match(artist)
|
||||
songs = [
|
||||
s for s in fallback
|
||||
if normalize_for_match(s.get("artist") or "") == key_artist
|
||||
]
|
||||
|
||||
community_songs, best_youtube_url = _extract_community_songs(songs)
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
"songs": community_songs,
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
artist = (artist or "").strip()
|
||||
title = (title or "").strip()
|
||||
if not artist or not title:
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
index = await _get_index()
|
||||
return _lookup(index, artist, title)
|
||||
|
||||
|
||||
async def check_community_versions_batch(
|
||||
@@ -256,20 +215,20 @@ async def check_community_versions_batch(
|
||||
"brand_count": int, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
|
||||
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
|
||||
uses to render clickable links; ``brands``/``brand_count`` are retained for
|
||||
back-compat. Bounded concurrency keeps us polite to karaokenerds.com; per-song
|
||||
results reuse the existing 1h cache. A failed lookup degrades to
|
||||
``available=False`` (the track simply stays selectable) — never raises.
|
||||
back-compat. Lookups hit our in-process community index (no network per song), so
|
||||
``concurrency`` is accepted for back-compat but no longer meaningful. A missing
|
||||
catalog degrades to ``available=False`` (the track simply stays selectable).
|
||||
"""
|
||||
sem = asyncio.Semaphore(max(1, concurrency))
|
||||
_ = concurrency # retained for call-site compatibility; lookups are in-memory now
|
||||
index = await _get_index()
|
||||
|
||||
async def _one(song: dict) -> dict:
|
||||
def _one(song: dict) -> dict:
|
||||
artist = (song.get("artist") or "").strip()
|
||||
title = (song.get("title") or "").strip()
|
||||
if not artist or not title:
|
||||
return {"artist": artist, "title": title, "available": False,
|
||||
"brands": [], "brand_count": 0, "versions": []}
|
||||
async with sem:
|
||||
res = await check_community_versions(artist, title)
|
||||
res = _lookup(index, artist, title)
|
||||
versions: list[dict] = []
|
||||
versioned_brands: set[str] = set()
|
||||
brands: list[str] = []
|
||||
@@ -294,4 +253,11 @@ async def check_community_versions_batch(
|
||||
"versions": versions,
|
||||
}
|
||||
|
||||
return await asyncio.gather(*[_one(s) for s in songs])
|
||||
return [_one(s) for s in songs]
|
||||
|
||||
|
||||
def _reset_index_for_tests() -> None:
|
||||
"""Clear the module-level cache (used by tests to isolate index state)."""
|
||||
global _index, _index_expiry
|
||||
_index = None
|
||||
_index_expiry = 0.0
|
||||
@@ -0,0 +1,54 @@
|
||||
"""KaraokeNerds brand code -> human display name.
|
||||
|
||||
Our own KaraokeNerds catalog (BigQuery `karaokenerds_community` + the GCS export)
|
||||
stores only the brand *code* (e.g. "NOMAD", "OBSK"). The old live scrape also
|
||||
surfaced the human name ("Nomad Karaoke", "ObsKure Karaoke") which the UI shows.
|
||||
KaraokeNerds exposes no authorized brand-name data source, so this static map
|
||||
(kept in sync with kjbox's version_priority registry, plus the highest-frequency
|
||||
community brands) reproduces those names. Unknown codes fall back to the code —
|
||||
the same graceful degradation the UI already applies.
|
||||
"""
|
||||
|
||||
KN_BRAND_NAMES: dict[str, str] = {
|
||||
# Community brands (mirrors kjbox version_priority.COMMUNITY_BRANDS display names)
|
||||
"CC": "CC Karaoke",
|
||||
"LC": "Lemmy Caution",
|
||||
"FBK": "Funbox Karaoke",
|
||||
"BELLY": "BellySings",
|
||||
"NOMAD": "Nomad Karaoke",
|
||||
"FAKEY": "FakeyOke",
|
||||
"PMK": "Punk Media Karaoke",
|
||||
"OBSK": "ObsKure Karaoke",
|
||||
"SDK": "SNDL Karaoke",
|
||||
"DBK": "Deep Bench Karaoke",
|
||||
# Commercial brands (mirrors version_priority.COMMERCIAL_BRANDS display names)
|
||||
"KV": "Karaoke Version",
|
||||
"SC": "Sound Choice",
|
||||
"SBI": "SBI Karaoke",
|
||||
"SF": "Sunfly",
|
||||
"CB": "Chart Buster",
|
||||
"ZM": "Zoom",
|
||||
"VS": "Vocal Star",
|
||||
"SK": "Sing King",
|
||||
"MR": "Mr. Entertainer",
|
||||
"PT": "Party Tyme",
|
||||
"EK": "Easy Karaoke",
|
||||
# Additional high-frequency community brands (harvested from KaraokeNerds).
|
||||
"IKV": "Imperfekt Karaoke",
|
||||
"ZP": "Zipper Karaoke",
|
||||
"JL311": "Rock Solid Karaoke",
|
||||
"CAR": "Caritas",
|
||||
"MKU": "Mobile Karaoke Unit",
|
||||
"VONAGAM": "Vonagam Karaoke",
|
||||
"GR": "ggnzla RECORDS",
|
||||
"HALJAM": "Hal Jam",
|
||||
"REEKIES": "Reekies Karaoke",
|
||||
"DJS": "DJ Sauly Karaoke",
|
||||
}
|
||||
|
||||
|
||||
def brand_name_for(code: str) -> str:
|
||||
"""Human display name for a KaraokeNerds brand code; the code itself if unknown."""
|
||||
if not code:
|
||||
return ""
|
||||
return KN_BRAND_NAMES.get(code.upper().strip(), code)
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Near-real-time operational alerting (incident-hardening D1 + G1 channel).
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
The production error monitor (``backend/services/error_monitor``) is
|
||||
**spike-based**: a pattern only alerts when its current count exceeds a rolling
|
||||
average by a multiplier *and* clears a minimum-count floor. A brand-new error
|
||||
has ``rolling_avg == 0`` → it is mathematically never a spike, so a novel,
|
||||
low-volume failure is invisible to it. That is exactly how incident NOMAD-1632's
|
||||
follow-on outage (2 jobs failing with a never-before-seen error string) went
|
||||
unnoticed until a human spotted failed jobs in the UI.
|
||||
|
||||
This module is the **universal net**: the moment *any* job transitions to
|
||||
``FAILED`` we emit an immediate Discord alert, independent of the spike detector,
|
||||
de-duplicated by a normalized error signature so a burst collapses into one
|
||||
alert. Novel error signatures always alert regardless of count.
|
||||
|
||||
It also exposes :func:`send_ops_alert`, a generic best-effort sender reused by
|
||||
the publish-completeness shadow invariant (G1).
|
||||
|
||||
Everything here is **best-effort**: any failure to alert is swallowed and
|
||||
logged. It must never raise into — nor add a failure mode to — the status write
|
||||
that triggered it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Secret Manager name of the ops/alert Discord webhook (same channel the startup
|
||||
# credential-validation alert uses — see backend/main.py).
|
||||
_ALERT_WEBHOOK_SECRET = "discord-alert-webhook"
|
||||
|
||||
# Firestore collection used to de-dupe/throttle failure alerts by signature.
|
||||
_DEDUP_COLLECTION = "ops_failure_alerts"
|
||||
|
||||
# Collapse repeat alerts for the same error signature within this window into a
|
||||
# single Discord message (the burst is counted, not re-sent). Override with
|
||||
# FAILURE_ALERT_THROTTLE_MINUTES.
|
||||
_DEFAULT_THROTTLE_MINUTES = 30
|
||||
|
||||
# Environments whose failures we do NOT page on (intentional test/dev failures
|
||||
# would otherwise be noise). Production + unlabeled jobs always alert. Override
|
||||
# with FAILURE_ALERT_SKIP_ENVIRONMENTS (comma-separated).
|
||||
_DEFAULT_SKIP_ENVIRONMENTS = {"test", "development"}
|
||||
|
||||
|
||||
def _is_enabled() -> bool:
|
||||
"""Only alert from a deployed environment.
|
||||
|
||||
Local runs and the test suite have no ``K_SERVICE`` / non-production
|
||||
``ENVIRONMENT`` (see :func:`backend.config.is_production`), so this short
|
||||
circuits before any Secret Manager or Discord call — keeping unit tests
|
||||
silent and fast.
|
||||
"""
|
||||
if os.environ.get("FAILURE_ALERTS_ENABLED", "").lower() in ("1", "true", "yes"):
|
||||
return True
|
||||
try:
|
||||
from backend.config import is_production
|
||||
|
||||
return is_production()
|
||||
except Exception: # noqa: BLE001 - never let config import break a status write
|
||||
return False
|
||||
|
||||
|
||||
def _throttle_minutes() -> int:
|
||||
try:
|
||||
return int(os.environ.get("FAILURE_ALERT_THROTTLE_MINUTES", _DEFAULT_THROTTLE_MINUTES))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_THROTTLE_MINUTES
|
||||
|
||||
|
||||
def _skip_environments() -> set[str]:
|
||||
raw = os.environ.get("FAILURE_ALERT_SKIP_ENVIRONMENTS")
|
||||
if raw is None:
|
||||
return set(_DEFAULT_SKIP_ENVIRONMENTS)
|
||||
return {e.strip().lower() for e in raw.split(",") if e.strip()}
|
||||
|
||||
|
||||
def _get_webhook_url() -> Optional[str]:
|
||||
"""Resolve the ops-alert Discord webhook (cached via settings.get_secret)."""
|
||||
try:
|
||||
from backend.config import settings
|
||||
|
||||
if hasattr(settings, "get_secret"):
|
||||
return settings.get_secret(_ALERT_WEBHOOK_SECRET)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: could not resolve webhook: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def send_ops_alert(message: str) -> bool:
|
||||
"""Post a plaintext ops alert to the Discord alert channel. Best-effort.
|
||||
|
||||
Returns True if the message was sent, False otherwise (disabled, no webhook,
|
||||
or a delivery error). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
logger.debug("ops_alerts: disabled (not a deployed environment); skipping")
|
||||
return False
|
||||
webhook = _get_webhook_url()
|
||||
if not webhook:
|
||||
logger.debug("ops_alerts: no webhook configured; skipping")
|
||||
return False
|
||||
from backend.services.discord_service import get_discord_notification_service
|
||||
|
||||
service = get_discord_notification_service(webhook_url=webhook)
|
||||
return service.post_message(message, webhook_url=webhook)
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: failed to send alert: %s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def _signature(error_message: str) -> str:
|
||||
"""Stable fingerprint for an error string (reuses the error-monitor normalizer)."""
|
||||
try:
|
||||
from backend.services.error_monitor.normalizer import (
|
||||
compute_pattern_hash,
|
||||
normalize_message,
|
||||
)
|
||||
|
||||
return compute_pattern_hash("karaoke-job", normalize_message(error_message or ""))
|
||||
except Exception: # noqa: BLE001
|
||||
# Fallback: hash the raw string so dedup still works if the normalizer
|
||||
# import fails for any reason.
|
||||
import hashlib
|
||||
|
||||
return hashlib.sha256((error_message or "").encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, int, Any]:
|
||||
"""Decide whether to send, WITHOUT yet acknowledging delivery.
|
||||
|
||||
Returns ``(should_send, is_novel, suppressed_since_last, doc_ref)``:
|
||||
* ``should_send`` — emit a Discord alert this time.
|
||||
* ``is_novel`` — we have never seen this signature before.
|
||||
* ``suppressed_since_last`` — how many failures were collapsed (throttled)
|
||||
since the last *successful* alert for this signature.
|
||||
* ``doc_ref`` — the dedup doc, passed to :func:`_mark_alerted` **only after a
|
||||
successful send** so a failed Discord delivery does NOT advance the
|
||||
throttle window (which would suppress the next real failure). ``None`` if
|
||||
Firestore was unreachable.
|
||||
|
||||
This records ``first_seen`` / ``total_count`` (and, when throttled, the
|
||||
suppressed counter) but deliberately does NOT touch ``last_alerted_at`` — that
|
||||
is the delivery acknowledgement, set separately once the alert actually sends.
|
||||
|
||||
Best-effort: on any Firestore error we default to *send* (fail open — an extra
|
||||
alert is far better than a missed outage). NOTE: the ``get()`` + ``update()``
|
||||
are not transactional, so two truly-concurrent failures of the same signature
|
||||
could each send once. That's an acceptable trade (a duplicate alert is
|
||||
harmless; a missed one is not), so we don't pay for a transaction here.
|
||||
"""
|
||||
try:
|
||||
doc_ref = db.collection(_DEDUP_COLLECTION).document(signature)
|
||||
snap = doc_ref.get()
|
||||
now_iso = now.isoformat()
|
||||
if not snap.exists:
|
||||
# Create the record but leave last_alerted_at unset — it's stamped by
|
||||
# _mark_alerted only if the send succeeds.
|
||||
doc_ref.set(
|
||||
{
|
||||
"signature": signature,
|
||||
"first_seen": now_iso,
|
||||
"last_alerted_at": None,
|
||||
"total_count": 1,
|
||||
"alert_count": 0,
|
||||
"suppressed_since_last": 0,
|
||||
}
|
||||
)
|
||||
return True, True, 0, doc_ref
|
||||
|
||||
data = snap.to_dict() or {}
|
||||
last_alerted_raw = data.get("last_alerted_at")
|
||||
within_window = False
|
||||
if last_alerted_raw:
|
||||
try:
|
||||
last_alerted = datetime.fromisoformat(last_alerted_raw)
|
||||
within_window = (now - last_alerted) < timedelta(minutes=_throttle_minutes())
|
||||
except (TypeError, ValueError):
|
||||
within_window = False
|
||||
|
||||
if within_window:
|
||||
# Collapse: count it but don't re-page.
|
||||
doc_ref.update(
|
||||
{
|
||||
"total_count": (data.get("total_count", 0) or 0) + 1,
|
||||
"suppressed_since_last": (data.get("suppressed_since_last", 0) or 0) + 1,
|
||||
}
|
||||
)
|
||||
return False, False, 0, doc_ref
|
||||
|
||||
doc_ref.update({"total_count": (data.get("total_count", 0) or 0) + 1})
|
||||
suppressed = data.get("suppressed_since_last", 0) or 0
|
||||
return True, False, suppressed, doc_ref
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: dedup lookup failed (%s); defaulting to send", exc)
|
||||
return True, False, 0, None
|
||||
|
||||
|
||||
def _mark_alerted(doc_ref: Any, now: datetime) -> None:
|
||||
"""Acknowledge a successful send: advance the throttle window + reset counters.
|
||||
|
||||
Called ONLY after :func:`send_ops_alert` returns True. Best-effort.
|
||||
"""
|
||||
if doc_ref is None:
|
||||
return
|
||||
try:
|
||||
snap = doc_ref.get()
|
||||
data = snap.to_dict() or {} if snap.exists else {}
|
||||
doc_ref.update(
|
||||
{
|
||||
"last_alerted_at": now.isoformat(),
|
||||
"alert_count": (data.get("alert_count", 0) or 0) + 1,
|
||||
"suppressed_since_last": 0,
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
|
||||
|
||||
|
||||
def notify_job_failed(
|
||||
db: Any,
|
||||
collection: str,
|
||||
job_id: str,
|
||||
message: Optional[str] = None,
|
||||
additional_fields: Optional[dict] = None,
|
||||
) -> bool:
|
||||
"""Emit a near-real-time alert for a job that just transitioned to FAILED.
|
||||
|
||||
Invoked from the single status-write chokepoint
|
||||
(:meth:`FirestoreService.update_job_status`). ``db`` is the caller's existing
|
||||
Firestore client (reused to avoid a second client / circular import);
|
||||
``collection`` is the jobs collection so we can enrich the alert with the
|
||||
job's artist/title/environment. Best-effort; never raises.
|
||||
|
||||
Returns True if an alert was sent.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
return False
|
||||
|
||||
# Enrich from the job doc (best-effort). We only just wrote it, so this
|
||||
# is a single extra read on the rare FAILED path.
|
||||
artist = title = environment = brand_code = None
|
||||
error_message = (additional_fields or {}).get("error_message") or message or ""
|
||||
try:
|
||||
snap = db.collection(collection).document(job_id).get()
|
||||
if snap.exists:
|
||||
job = snap.to_dict() or {}
|
||||
artist = job.get("artist")
|
||||
title = job.get("title")
|
||||
meta = job.get("request_metadata") or {}
|
||||
environment = meta.get("environment")
|
||||
state = job.get("state_data") or {}
|
||||
brand_code = state.get("brand_code")
|
||||
if not error_message:
|
||||
error_message = job.get("error_message") or ""
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug("ops_alerts: job enrichment read failed: %s", exc)
|
||||
|
||||
if environment and environment.lower() in _skip_environments():
|
||||
logger.debug("ops_alerts: skipping failure alert for %s env job %s", environment, job_id)
|
||||
return False
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
signature = _signature(error_message)
|
||||
should_send, is_novel, suppressed, doc_ref = _should_alert(db, signature, now)
|
||||
if not should_send:
|
||||
return False
|
||||
|
||||
track = " - ".join(p for p in (artist, title) if p) or "(unknown track)"
|
||||
lines = [
|
||||
"🔴 **Job failed** — near-real-time alert",
|
||||
f"**Job:** `{job_id}`" + (f" ({brand_code})" if brand_code else ""),
|
||||
f"**Track:** {track}",
|
||||
]
|
||||
if environment:
|
||||
lines.append(f"**Env:** {environment}")
|
||||
if is_novel:
|
||||
lines.append("🆕 **First time we've ever seen this error signature.**")
|
||||
elif suppressed:
|
||||
lines.append(f"_(Collapsed {suppressed} earlier occurrence(s) of this signature.)_")
|
||||
err = (error_message or "").strip()
|
||||
if err:
|
||||
if len(err) > 1500:
|
||||
err = err[:1500] + " …[truncated]"
|
||||
lines.append(f"**Error:** ```{err}```")
|
||||
|
||||
sent = send_ops_alert("\n".join(lines))
|
||||
# Only advance the throttle window once delivery actually succeeded — a
|
||||
# failed send must NOT suppress the next occurrence of this signature.
|
||||
if sent:
|
||||
_mark_alerted(doc_ref, now)
|
||||
return sent
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: notify_job_failed failed: %s", exc)
|
||||
return False
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Publish-boundary completeness invariant (incident-hardening G1), shadow-first.
|
||||
|
||||
Incident NOMAD-1632 published a public track to Google Drive **missing its 720p
|
||||
variant** while the pipeline reported success: ``GCEEncodingBackend.encode()``
|
||||
misclassified ``… (Final Karaoke Lossy 720p).mp4`` (title contained "Portrait")
|
||||
so ``mp4_720p`` was never set, and ``upload_to_public_share`` *silently skipped*
|
||||
the ``None`` path. Nothing inline noticed; the daily validator caught it ~24h
|
||||
later.
|
||||
|
||||
This module computes, at the publish boundary, the set of outputs a public
|
||||
GDrive release *should* have shipped and compares it against what was actually
|
||||
distributed (``result.gdrive_files``). The orchestrator logs + alerts on any
|
||||
shortfall **in shadow mode** (never fails the job) — the right altitude for the
|
||||
check (publish-aware of what *should* ship) and the rollout discipline the
|
||||
original fix skipped.
|
||||
|
||||
The compute function is intentionally pure (config + result in, list of missing
|
||||
outputs out) so it is trivially unit-testable and side-effect free.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# gdrive_files keys produced by GDriveService.upload_to_public_share(), mapped to
|
||||
# a human-readable label for alerts.
|
||||
_LOSSY_4K_KEY = "mp4"
|
||||
_720P_KEY = "mp4_720p"
|
||||
_CDG_KEY = "cdg"
|
||||
|
||||
_LABELS = {
|
||||
_LOSSY_4K_KEY: "lossy 4K MP4",
|
||||
_720P_KEY: "720p MP4",
|
||||
_CDG_KEY: "CDG zip",
|
||||
}
|
||||
|
||||
|
||||
def expected_gdrive_outputs(config: Any, result: Any) -> list[str]:
|
||||
"""The gdrive_files keys a public-share release is expected to contain.
|
||||
|
||||
Always the lossy 4K MP4 and the 720p MP4. The CDG zip is expected only when
|
||||
the job actually **produced** a CDG package (``result.final_karaoke_cdg_zip``
|
||||
is set). Keying CDG off ``config.enable_cdg`` alone false-fires on legitimate
|
||||
skips: a lyric-less track (``_lrc_has_lyrics_content()`` False) is packaged
|
||||
without a CDG even when ``enable_cdg`` is True, so the upload omits ``cdg`` by
|
||||
design. Basing the expectation on the produced artifact still catches the real
|
||||
fault we care about — a CDG that WAS made but never distributed.
|
||||
"""
|
||||
expected = [_LOSSY_4K_KEY, _720P_KEY]
|
||||
if getattr(result, "final_karaoke_cdg_zip", None):
|
||||
expected.append(_CDG_KEY)
|
||||
return expected
|
||||
|
||||
|
||||
def compute_publish_shortfall(config: Any, result: Any) -> list[str]:
|
||||
"""Return human-readable labels for expected-but-missing public outputs.
|
||||
|
||||
Empty list == complete (or not a public-share release). Only meaningful for
|
||||
the public GDrive distribution path (``config.gdrive_folder_id`` set); returns
|
||||
``[]`` for any other job so callers can invoke it unconditionally.
|
||||
"""
|
||||
if not getattr(config, "gdrive_folder_id", None):
|
||||
return []
|
||||
|
||||
distributed = getattr(result, "gdrive_files", None) or {}
|
||||
missing: list[str] = []
|
||||
for key in expected_gdrive_outputs(config, result):
|
||||
# A key is satisfied only if present AND truthy (an empty id/url means the
|
||||
# upload didn't actually land).
|
||||
if not distributed.get(key):
|
||||
missing.append(_LABELS.get(key, key))
|
||||
return missing
|
||||
@@ -170,6 +170,15 @@ class SongRequestService:
|
||||
return SongRequest(**doc.to_dict())
|
||||
return None
|
||||
|
||||
def list_all(self) -> list[SongRequest]:
|
||||
"""Every request across all statuses, newest first — the admin history view."""
|
||||
items = [
|
||||
SongRequest(**doc.to_dict())
|
||||
for doc in self.db.collection(REQUESTS_COLLECTION).stream()
|
||||
]
|
||||
items.sort(key=lambda r: r.created_at, reverse=True)
|
||||
return items
|
||||
|
||||
def list_active(self) -> list[SongRequest]:
|
||||
"""Open requests, ranked by net votes desc then oldest-first."""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
@@ -260,13 +269,69 @@ class SongRequestService:
|
||||
# --- picking ---
|
||||
|
||||
def pick_eligible(self) -> Optional[SongRequest]:
|
||||
"""The next request to auto-make: highest net votes, oldest-first tiebreak,
|
||||
skipping community-rejected (net < 0) requests. Source-agnostic — human
|
||||
votes and trending-agent submissions share the same open queue."""
|
||||
"""The single highest-priority auto-makeable request (net votes >= 0, oldest
|
||||
tiebreak), ignoring the community-version review flow. Kept for callers that
|
||||
just want the top request; the daily picker uses list_pick_candidates so it
|
||||
can community-check each candidate in rank order."""
|
||||
candidates = self.list_pick_candidates()
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
def list_pick_candidates(self) -> list[SongRequest]:
|
||||
"""Ranked auto-make candidates: open, net votes >= 0, oldest-first, EXCLUDING
|
||||
requests currently held for existing-community-version review (pending, or
|
||||
snoozed and not yet past their cooldown). The daily picker walks these in
|
||||
order, community-checks each, and makes the first with no existing version."""
|
||||
now = datetime.now(timezone.utc)
|
||||
out: list[SongRequest] = []
|
||||
for req in self.list_active(): # already ranked -vote_count, created_at asc
|
||||
if req.vote_count >= 0:
|
||||
return req
|
||||
return None
|
||||
if req.vote_count < 0:
|
||||
continue
|
||||
if req.review_state == "pending":
|
||||
continue
|
||||
if req.review_state == "snoozed":
|
||||
until = _as_aware(req.review_snoozed_until)
|
||||
if until and until > now:
|
||||
continue # still in its keep-cooldown
|
||||
out.append(req)
|
||||
return out
|
||||
|
||||
def set_review_pending(self, request_id: str, versions: dict) -> bool:
|
||||
"""Flag a request as needing existing-version review. Transactional and
|
||||
idempotent: returns True only the first time it transitions to pending (so
|
||||
the picker emails Andrew about a newly-flagged pick exactly once)."""
|
||||
ref = self.db.collection(REQUESTS_COLLECTION).document(request_id)
|
||||
transaction = self.db.transaction()
|
||||
return _set_review_pending_txn(transaction, ref, versions)
|
||||
|
||||
def list_pending_reviews(self) -> list[SongRequest]:
|
||||
"""Requests flagged pending existing-version review (the admin queue)."""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("review_state", "==", "pending")
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
items = [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
items.sort(key=lambda r: (-r.vote_count, r.created_at))
|
||||
return items
|
||||
|
||||
def snooze_review(self, request_id: str, until: datetime) -> None:
|
||||
"""'Keep on board': clear the pending flag but snooze re-review until `until`."""
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update({
|
||||
"review_state": "snoozed",
|
||||
"review_snoozed_until": until.isoformat(),
|
||||
"updated_at": _now_iso(),
|
||||
})
|
||||
|
||||
def clear_review(self, request_id: str) -> None:
|
||||
"""Clear any review flag (used when admin chooses to make our version anyway)."""
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"review_state": None, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def reject_request(self, request_id: str) -> None:
|
||||
"""Reject a request (admin declined to make it — e.g. a good community
|
||||
version already exists). Removes it from the board and clears review flags."""
|
||||
self.db.collection(REQUESTS_COLLECTION).document(request_id).update(
|
||||
{"status": "rejected", "review_state": None, "updated_at": _now_iso()}
|
||||
)
|
||||
|
||||
def transition_status(
|
||||
self, request_id: str, expected_from: str, new_status: str, **extra
|
||||
@@ -332,6 +397,19 @@ class SongRequestService:
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
return [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
|
||||
def list_published_unnotified(self) -> list[SongRequest]:
|
||||
"""Published picks whose voter fan-out never fully completed
|
||||
(``voters_notified == False``) — e.g. a send failed after the request was
|
||||
already marked published. The reconcile job retries these; the per-voter
|
||||
``notified_voters`` guard keeps it from re-emailing anyone already reached.
|
||||
"""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("status", "==", "published")
|
||||
).where(
|
||||
filter=FieldFilter("voters_notified", "==", False)
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
return [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
|
||||
def list_upvoters(self, request_id: str) -> list[str]:
|
||||
"""Emails that up-voted this request (value > 0), oldest vote first.
|
||||
|
||||
@@ -382,6 +460,29 @@ def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _as_aware(dt: Optional[datetime]) -> Optional[datetime]:
|
||||
"""Coerce a (possibly naive) datetime to UTC-aware for safe comparison."""
|
||||
if dt is None:
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
@firestore.transactional
|
||||
def _set_review_pending_txn(transaction, ref, versions):
|
||||
snap = ref.get(transaction=transaction)
|
||||
if not snap.exists:
|
||||
return False
|
||||
if snap.to_dict().get("review_state") == "pending":
|
||||
return False # already flagged — don't re-notify
|
||||
transaction.update(ref, {
|
||||
"review_state": "pending",
|
||||
"community_versions": versions,
|
||||
"community_checked_at": _now_iso(),
|
||||
"updated_at": _now_iso(),
|
||||
})
|
||||
return True
|
||||
|
||||
|
||||
@firestore.transactional
|
||||
def _transition_status_txn(transaction, ref, expected_from, new_status, extra):
|
||||
snap = ref.get(transaction=transaction)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
Google Cloud Storage operations for file management.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import logging
|
||||
import os
|
||||
import json
|
||||
import threading
|
||||
from typing import Optional, BinaryIO, Any, Dict
|
||||
from pathlib import Path
|
||||
from google.cloud import storage
|
||||
@@ -16,6 +18,39 @@ from backend.config import settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# --- Signed-URL generation hardening (incident 2026-09-17) ---------------------
|
||||
# On Cloud Run we have no private key, so signing goes through the IAM signBlob API
|
||||
# over the network. google-cloud-storage gives that call a ~120s per-attempt
|
||||
# timeout PLUS retries, so a stalled IAM/metadata endpoint hangs the calling worker
|
||||
# thread for minutes. When enough review-page loads (each signs 2-3 audio URLs) hit
|
||||
# a stall at once, the request thread pool is exhausted and the whole service goes
|
||||
# unavailable — exactly what took gen down on 2026-09-17.
|
||||
#
|
||||
# Defense: run every sign on a DEDICATED, bounded thread pool and give it a short
|
||||
# wall-clock budget. A stall then (a) fails fast for the caller instead of hanging,
|
||||
# and (b) is confined to this pool so it can never starve GCS data-plane reads/writes
|
||||
# or the request handlers. Callers treat signing as best-effort (see the review
|
||||
# endpoint's fail-soft handling).
|
||||
SIGNED_URL_TIMEOUT_S = float(os.getenv("SIGNED_URL_TIMEOUT_S", "12"))
|
||||
_SIGNING_MAX_WORKERS = int(os.getenv("SIGNED_URL_MAX_WORKERS", "8"))
|
||||
_SIGNING_EXECUTOR = concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=_SIGNING_MAX_WORKERS,
|
||||
thread_name_prefix="gcs-sign",
|
||||
)
|
||||
# Bounded admission in front of the executor. If every worker is blocked on a stalled
|
||||
# signBlob, the executor's queue is unbounded — a burst of callers would each wait the
|
||||
# full SIGNED_URL_TIMEOUT_S then cancel a still-queued future. Cap total in-flight
|
||||
# (running + queued) so, once saturated, extra callers fail *immediately* instead of
|
||||
# waiting out the budget, and the queue can't grow without bound. Slack above the
|
||||
# worker count absorbs normal bursts (a job-detail load signs ~20 URLs concurrently).
|
||||
_SIGNING_MAX_INFLIGHT = int(os.getenv("SIGNED_URL_MAX_INFLIGHT", str(_SIGNING_MAX_WORKERS * 6)))
|
||||
_SIGNING_SLOTS = threading.BoundedSemaphore(_SIGNING_MAX_INFLIGHT)
|
||||
|
||||
|
||||
class SignedUrlTimeout(Exception):
|
||||
"""A signed-URL generation exceeded ``SIGNED_URL_TIMEOUT_S`` (IAM signBlob stall)."""
|
||||
|
||||
|
||||
class StorageService:
|
||||
"""Service for Google Cloud Storage operations."""
|
||||
|
||||
@@ -177,37 +212,69 @@ class StorageService:
|
||||
logger.info(f"Generated emulator {method} URL for {blob_path} (STORAGE_EMULATOR_HOST set)")
|
||||
return url
|
||||
|
||||
try:
|
||||
def _sign() -> str:
|
||||
"""The actual (blocking, network-bound) signing work.
|
||||
|
||||
Run on the dedicated signing pool with a wall-clock timeout so a stalled
|
||||
IAM signBlob can't hang the caller — see module docstring above.
|
||||
"""
|
||||
blob = self.bucket.blob(blob_path)
|
||||
|
||||
|
||||
# Get default credentials and refresh to ensure we have a valid token
|
||||
credentials, project = google.auth.default()
|
||||
|
||||
|
||||
# Common kwargs for signed URL generation
|
||||
kwargs = {
|
||||
"version": "v4",
|
||||
"expiration": timedelta(minutes=expiration_minutes),
|
||||
"method": method,
|
||||
}
|
||||
|
||||
|
||||
# For PUT requests, we need to specify the content type in headers
|
||||
if method == "PUT" and content_type:
|
||||
kwargs["headers"] = {"Content-Type": content_type}
|
||||
|
||||
|
||||
# Check if we're using compute credentials (Cloud Run/GCE)
|
||||
# These need to use IAM signBlob via service_account_email + access_token
|
||||
if hasattr(credentials, 'service_account_email'):
|
||||
# Refresh credentials to get a valid access token
|
||||
auth_request = requests.Request()
|
||||
credentials.refresh(auth_request)
|
||||
|
||||
|
||||
kwargs["service_account_email"] = credentials.service_account_email
|
||||
kwargs["access_token"] = credentials.token
|
||||
|
||||
url = blob.generate_signed_url(**kwargs)
|
||||
|
||||
|
||||
return blob.generate_signed_url(**kwargs)
|
||||
|
||||
# Bounded admission: refuse immediately when signing is saturated (all workers
|
||||
# stalled + queue full) instead of enqueuing work that would just time out.
|
||||
if not _SIGNING_SLOTS.acquire(blocking=False):
|
||||
logger.error(
|
||||
f"Signing saturated (>{_SIGNING_MAX_INFLIGHT} in flight) — refusing signed "
|
||||
f"{method} URL for {blob_path}; IAM signBlob likely stalled"
|
||||
)
|
||||
raise SignedUrlTimeout(f"Signing saturated for {blob_path}")
|
||||
|
||||
future = _SIGNING_EXECUTOR.submit(_sign)
|
||||
# Release the slot whenever the work settles — success, error, OR cancellation
|
||||
# (cancelling a still-queued future fires done callbacks, so queued-but-abandoned
|
||||
# work frees its slot; a running future frees it only when it actually returns).
|
||||
future.add_done_callback(lambda _f: _SIGNING_SLOTS.release())
|
||||
try:
|
||||
url = future.result(timeout=SIGNED_URL_TIMEOUT_S)
|
||||
logger.info(f"Generated signed {method} URL for {blob_path}")
|
||||
return url
|
||||
except concurrent.futures.TimeoutError:
|
||||
# Don't wait on the leaked thread — it caps itself at the library's own
|
||||
# ~120s timeout and frees its (bounded) pool slot on its own. We bail now.
|
||||
future.cancel()
|
||||
logger.error(
|
||||
f"Timed out (>{SIGNED_URL_TIMEOUT_S:g}s) generating signed {method} URL "
|
||||
f"for {blob_path} — IAM signBlob likely stalled"
|
||||
)
|
||||
raise SignedUrlTimeout(
|
||||
f"Signed URL generation timed out for {blob_path}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
@@ -505,6 +505,35 @@ class TemplateService:
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def render_community_existing_version(
|
||||
self,
|
||||
name: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
youtube_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> str:
|
||||
"""Render the "a version of the song you voted for already exists" email,
|
||||
sent to up-voters when a flagged requests-board pick is rejected in favour
|
||||
of an existing community karaoke version."""
|
||||
ns = "emails.templates.communityExistingVersion"
|
||||
template = f"""{t(locale, f"{ns}.greeting")}
|
||||
|
||||
{t(locale, f"{ns}.body")}
|
||||
{{youtube_url}}
|
||||
|
||||
{t(locale, f"{ns}.callToAction")}
|
||||
|
||||
{t(locale, f"{ns}.signOff")}
|
||||
"""
|
||||
variables = {
|
||||
"name": name or "there",
|
||||
"artist": artist or "Unknown Artist",
|
||||
"title": title or "Unknown Title",
|
||||
"youtube_url": youtube_url or "[link not available]",
|
||||
}
|
||||
return self.render_template(template, variables)
|
||||
|
||||
def upload_template(self, template_name: str, content: str) -> bool:
|
||||
"""
|
||||
Upload a template to GCS.
|
||||
|
||||
@@ -285,6 +285,7 @@ class UserService:
|
||||
self,
|
||||
email: str,
|
||||
expiry_hours: int = 24,
|
||||
purpose: Optional[str] = None,
|
||||
) -> MagicLinkToken:
|
||||
"""
|
||||
Create an admin login token for email-embedded authentication links.
|
||||
@@ -295,6 +296,8 @@ class UserService:
|
||||
Args:
|
||||
email: Admin's email address to authenticate as
|
||||
expiry_hours: Hours until token expires (default: 24, max: 168)
|
||||
purpose: Optional purpose tag (e.g. "job_review:<job_id>") — the
|
||||
verify endpoint maps known purposes to a post-login redirect
|
||||
|
||||
Returns:
|
||||
MagicLinkToken object containing the token
|
||||
@@ -318,6 +321,7 @@ class UserService:
|
||||
token=token,
|
||||
email=email,
|
||||
expires_at=datetime.utcnow() + timedelta(hours=expiry_hours),
|
||||
purpose=purpose,
|
||||
)
|
||||
|
||||
# Save to Firestore (same collection as magic links for unified verification)
|
||||
|
||||
@@ -690,9 +690,25 @@ class WorkerService:
|
||||
return False
|
||||
|
||||
async def trigger_render_video_worker(self, job_id: str) -> bool:
|
||||
"""Trigger render video worker (post-review)."""
|
||||
"""
|
||||
Trigger render video worker (post-review).
|
||||
|
||||
When USE_CLOUD_RUN_JOBS_FOR_RENDER=true and ENABLE_CLOUD_TASKS=true,
|
||||
runs as a Cloud Run Job (reusing video-encoding-job with an args
|
||||
override) so the render orchestration survives Cloud Run Service
|
||||
deployment rollouts. As a BackgroundTask it was killed ~10s after
|
||||
SIGTERM whenever a deploy landed mid-render, freezing the job at
|
||||
rendering_video (incident 2026-09-13, job 41e06b90 — same class as
|
||||
incident 2026-03-08 which migrated the video worker to Cloud Run Jobs).
|
||||
"""
|
||||
self._bump_worker_generation(job_id)
|
||||
self._warmup_encoding_worker(job_id)
|
||||
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_render:
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="video-encoding-job",
|
||||
worker_module="render_video_worker",
|
||||
)
|
||||
return await self.trigger_worker("render-video", job_id)
|
||||
|
||||
def _bump_worker_generation(self, job_id: str) -> None:
|
||||
@@ -807,7 +823,9 @@ class WorkerService:
|
||||
|
||||
async def schedule_gdrive_validation(
|
||||
self,
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS
|
||||
delay_seconds: int = GDRIVE_VALIDATION_DELAY_SECONDS,
|
||||
brand_code: Optional[str] = None,
|
||||
expect_cdg: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
Schedule a delayed GDrive validation check.
|
||||
@@ -817,6 +835,9 @@ class WorkerService:
|
||||
|
||||
Args:
|
||||
delay_seconds: Delay before executing the validation (default: 5 minutes)
|
||||
brand_code: Optional brand code of the just-published track. When set,
|
||||
the validator additionally checks this track is present in all
|
||||
expected folders same-run (incident-hardening D2).
|
||||
|
||||
Returns:
|
||||
True if task was scheduled successfully, False otherwise
|
||||
@@ -864,13 +885,22 @@ class WorkerService:
|
||||
|
||||
dispatch_deadline_seconds = WORKER_DISPATCH_DEADLINES.get("gdrive-validation", 120)
|
||||
|
||||
# Carry the brand code so the validator can check this track's own
|
||||
# completeness same-run (incident-hardening D2). Absent → "{}".
|
||||
# expect_cdg tells the validator whether to require the CDG folder.
|
||||
body_bytes = b"{}"
|
||||
if brand_code:
|
||||
body_bytes = json.dumps(
|
||||
{"brand_code": brand_code, "expect_cdg": expect_cdg}
|
||||
).encode("utf-8")
|
||||
|
||||
# Build task payload
|
||||
task = {
|
||||
"http_request": {
|
||||
"http_method": tasks_v2.HttpMethod.POST,
|
||||
"url": f"{self._base_url}/api/internal/trigger-gdrive-validation",
|
||||
"headers": headers,
|
||||
"body": b"{}",
|
||||
"body": body_bytes,
|
||||
"oidc_token": {
|
||||
"service_account_email": f"karaoke-backend@{project}.iam.gserviceaccount.com",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
"""
|
||||
Shared logic for the YouTube description back-catalogue rewrite.
|
||||
|
||||
Used by BOTH:
|
||||
* the one-off CLI (scripts/youtube-descriptions/youtube_descriptions.py), and
|
||||
* the scheduled daily drain worker (backend/workers/youtube_description_backfill_worker.py)
|
||||
|
||||
so classification, targeting, rendering, and the update-body construction are
|
||||
identical no matter how the rewrite is driven. Rendering itself delegates to
|
||||
backend.services.youtube_description (single source of truth for the template).
|
||||
|
||||
Nothing here talks to the YouTube API — callers pass in already-fetched video
|
||||
snippet dicts (as returned by videos.list items) and act on the results.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.youtube_description import build_youtube_tags, render_youtube_description
|
||||
|
||||
# Data files (skip / force-include lists) ship inside the backend package so they
|
||||
# are available both locally and in the Cloud Run image.
|
||||
_DATA_DIR = Path(__file__).resolve().parent.parent / "data" / "youtube_backfill"
|
||||
SKIP_IDS_PATH = _DATA_DIR / "skip_ids.txt"
|
||||
INCLUDE_IDS_PATH = _DATA_DIR / "include_ids.txt"
|
||||
|
||||
UPDATE_COST = 50 # videos.update quota units
|
||||
DEFAULT_MUSIC_CATEGORY = "10"
|
||||
|
||||
# --- Classification patterns ---
|
||||
# "Artist - Title (Karaoke)" and variants ("(Official Karaoke)", "(Karaoke Version)").
|
||||
KARAOKE_TITLE_RE = re.compile(
|
||||
r"^\s*(?P<artist>.+?)\s*[-–—]\s*(?P<title>.+?)\s*\(\s*[^)]*karaoke[^)]*\)\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
FALLBACK_TITLE_RE = re.compile(r"^\s*(?P<artist>.+?)\s*[-–—]\s*(?P<title>.+?)\s*$")
|
||||
BRAND_CODE_RE = re.compile(r"\bNOMAD(?:NP)?-\d{3,}\b")
|
||||
|
||||
# Description substrings that signal "this is one of our karaoke uploads".
|
||||
KARAOKE_DESC_MARKERS = (
|
||||
"brand code: nomad",
|
||||
"nomadkaraoke.com",
|
||||
"created with nomad karaoke",
|
||||
"vocals removed",
|
||||
"karaoke (instrumental) version",
|
||||
"fiverr.com",
|
||||
"discord.gg/divebar",
|
||||
"discord.nomadkaraoke.com",
|
||||
"karaokenerds.com",
|
||||
"ai-powered vocal separation",
|
||||
)
|
||||
|
||||
# Only these snippet fields are sent back on update (others are read-only or would
|
||||
# be wiped). categoryId + title are required by the API on a snippet update.
|
||||
_MUTABLE_SNIPPET_FIELDS = {
|
||||
"title",
|
||||
"description",
|
||||
"categoryId",
|
||||
"tags",
|
||||
"defaultLanguage",
|
||||
"defaultAudioLanguage",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# List files
|
||||
# ----------------------------------------------------------------------------
|
||||
def _load_id_file(path: Path) -> set:
|
||||
ids = set()
|
||||
if path.exists():
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if line:
|
||||
ids.add(line.split("|", 1)[0].strip())
|
||||
return ids
|
||||
|
||||
|
||||
def load_skip_ids() -> set:
|
||||
return _load_id_file(SKIP_IDS_PATH)
|
||||
|
||||
|
||||
def load_include_overrides() -> Dict[str, Optional[Dict[str, str]]]:
|
||||
"""Parse include_ids.txt.
|
||||
|
||||
Each non-comment line is either a bare video ID, or
|
||||
``<id> | <Artist> | <Title>`` to override the parsed artist/title (used for
|
||||
genuine tracks whose title was truncated on YouTube). Returns a map of
|
||||
id -> {"artist", "song_title"} or None (no override).
|
||||
"""
|
||||
out: Dict[str, Optional[Dict[str, str]]] = {}
|
||||
if not INCLUDE_IDS_PATH.exists():
|
||||
return out
|
||||
for line in INCLUDE_IDS_PATH.read_text(encoding="utf-8").splitlines():
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if not line:
|
||||
continue
|
||||
if "|" in line:
|
||||
parts = [p.strip() for p in line.split("|")]
|
||||
out[parts[0]] = {
|
||||
"artist": parts[1] if len(parts) > 1 else "",
|
||||
"song_title": parts[2] if len(parts) > 2 else "",
|
||||
}
|
||||
else:
|
||||
out[line] = None
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Classification
|
||||
# ----------------------------------------------------------------------------
|
||||
def classify(video: Dict) -> Dict:
|
||||
"""Classify a videos.list item dict. Returns a plain dict of findings."""
|
||||
snip = video.get("snippet", {})
|
||||
title = snip.get("title", "") or ""
|
||||
desc = snip.get("description", "") or ""
|
||||
low_title = title.lower()
|
||||
low_desc = desc.lower()
|
||||
|
||||
brand_match = BRAND_CODE_RE.search(desc)
|
||||
brand_code = brand_match.group(0) if brand_match else None
|
||||
|
||||
has_karaoke_title = "karaoke" in low_title
|
||||
has_marker = any(m in low_desc for m in KARAOKE_DESC_MARKERS)
|
||||
is_karaoke = has_karaoke_title or bool(brand_code) or has_marker
|
||||
|
||||
artist = song_title = None
|
||||
parse_conf = "none"
|
||||
m = KARAOKE_TITLE_RE.match(title)
|
||||
if m:
|
||||
artist = m.group("artist").strip()
|
||||
song_title = m.group("title").strip()
|
||||
parse_conf = "high"
|
||||
elif is_karaoke:
|
||||
m2 = FALLBACK_TITLE_RE.match(title)
|
||||
if m2:
|
||||
artist = m2.group("artist").strip()
|
||||
song_title = m2.group("title").strip()
|
||||
parse_conf = "medium"
|
||||
|
||||
if "ai-powered vocal separation" in low_desc:
|
||||
kind = "terse_new"
|
||||
elif "fiverr.com" in low_desc:
|
||||
kind = "fiverr"
|
||||
elif "brand code: nomad" in low_desc or "nomadkaraoke.com" in low_desc:
|
||||
kind = "nomad_recent"
|
||||
elif is_karaoke:
|
||||
kind = "other_karaoke"
|
||||
else:
|
||||
kind = "non_karaoke"
|
||||
|
||||
# Auto-eligible ONLY at high confidence (title explicitly ends in "(Karaoke)").
|
||||
# The medium fallback sweeps in demos/tutorials/appeals and "lyrics video WITH
|
||||
# vocals" uploads, so those are excluded and surfaced for review instead.
|
||||
eligible = bool(is_karaoke and artist and song_title and parse_conf == "high")
|
||||
|
||||
return {
|
||||
"video_id": video.get("id"),
|
||||
"yt_title": title,
|
||||
"artist": artist,
|
||||
"song_title": song_title,
|
||||
"brand_code": brand_code,
|
||||
"parse_confidence": parse_conf,
|
||||
"kind": kind,
|
||||
"is_karaoke": is_karaoke,
|
||||
"eligible": eligible,
|
||||
"category_id": snip.get("categoryId"),
|
||||
"current_description": desc,
|
||||
}
|
||||
|
||||
|
||||
def render_for(entry: Dict) -> str:
|
||||
return render_youtube_description(
|
||||
artist=entry.get("artist"),
|
||||
title=entry.get("song_title"),
|
||||
brand_code=entry.get("brand_code"),
|
||||
)
|
||||
|
||||
|
||||
def build_entries(
|
||||
videos_by_id: Dict[str, Dict],
|
||||
ordered_ids: List[str],
|
||||
skip_ids: Optional[set] = None,
|
||||
include_overrides: Optional[Dict] = None,
|
||||
) -> List[Dict]:
|
||||
"""Classify every video and decide which are rewrite targets.
|
||||
|
||||
Adds `in_skip_list`, `forced_include`, `target`, and `will_change` to each
|
||||
entry. `will_change` is the authoritative "should we update this" flag: it's
|
||||
True only for a target whose freshly-rendered description actually differs.
|
||||
"""
|
||||
skip_ids = skip_ids if skip_ids is not None else load_skip_ids()
|
||||
include_overrides = include_overrides if include_overrides is not None else load_include_overrides()
|
||||
|
||||
entries: List[Dict] = []
|
||||
for vid in ordered_ids:
|
||||
v = videos_by_id.get(vid)
|
||||
if not v:
|
||||
continue
|
||||
entry = classify(v)
|
||||
entry["in_skip_list"] = vid in skip_ids
|
||||
entry["forced_include"] = vid in include_overrides
|
||||
override = include_overrides.get(vid)
|
||||
if override:
|
||||
if override.get("artist"):
|
||||
entry["artist"] = override["artist"]
|
||||
if override.get("song_title"):
|
||||
entry["song_title"] = override["song_title"]
|
||||
entry["parse_confidence"] = "override"
|
||||
|
||||
is_target = (
|
||||
(entry["eligible"] or entry["forced_include"])
|
||||
and not entry["in_skip_list"]
|
||||
and bool(entry["artist"])
|
||||
and bool(entry["song_title"])
|
||||
)
|
||||
entry["target"] = is_target
|
||||
if is_target:
|
||||
new_desc = render_for(entry)
|
||||
entry["will_change"] = new_desc.strip() != entry["current_description"].strip()
|
||||
else:
|
||||
entry["will_change"] = False
|
||||
entries.append(entry)
|
||||
return entries
|
||||
|
||||
|
||||
def build_update_snippet(current_snippet: Dict, entry: Dict, enrich_tags: bool) -> Dict:
|
||||
"""Build the snippet body for videos.update.
|
||||
|
||||
Copies the existing mutable snippet fields (so title/category/language are
|
||||
preserved), swaps in the new description, and optionally refreshes tags.
|
||||
"""
|
||||
snippet = {k: v for k, v in current_snippet.items() if k in _MUTABLE_SNIPPET_FIELDS}
|
||||
snippet["description"] = render_for(entry)
|
||||
if not snippet.get("categoryId"):
|
||||
snippet["categoryId"] = DEFAULT_MUSIC_CATEGORY
|
||||
if enrich_tags:
|
||||
snippet["tags"] = build_youtube_tags(entry.get("artist"), entry.get("song_title"))
|
||||
return snippet
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# YouTube API helpers (shared by the CLI and the scheduled worker)
|
||||
# ----------------------------------------------------------------------------
|
||||
SCOPES = ["https://www.googleapis.com/auth/youtube"]
|
||||
|
||||
|
||||
def load_credentials_from_secret() -> Optional[Dict]:
|
||||
"""Load the youtube-oauth-credentials dict from Secret Manager (or None)."""
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
return get_youtube_service().get_credentials_dict()
|
||||
|
||||
|
||||
def build_youtube(creds_dict: Dict):
|
||||
"""Build an authorized youtube v3 client from a credentials dict."""
|
||||
from google.auth.transport.requests import Request
|
||||
from google.oauth2.credentials import Credentials
|
||||
from googleapiclient.discovery import build
|
||||
|
||||
creds = Credentials(
|
||||
token=creds_dict.get("token"),
|
||||
refresh_token=creds_dict.get("refresh_token"),
|
||||
token_uri=creds_dict.get("token_uri"),
|
||||
client_id=creds_dict.get("client_id"),
|
||||
client_secret=creds_dict.get("client_secret"),
|
||||
scopes=creds_dict.get("scopes", SCOPES),
|
||||
)
|
||||
if not creds.token or creds.expired:
|
||||
creds.refresh(Request())
|
||||
return build("youtube", "v3", credentials=creds, cache_discovery=False)
|
||||
|
||||
|
||||
def get_uploads_playlist(youtube) -> str:
|
||||
resp = youtube.channels().list(part="contentDetails", mine=True).execute()
|
||||
items = resp.get("items", [])
|
||||
if not items:
|
||||
raise RuntimeError("No channel found for these credentials.")
|
||||
return items[0]["contentDetails"]["relatedPlaylists"]["uploads"]
|
||||
|
||||
|
||||
def iter_all_video_ids(youtube, playlist_id: str) -> List[str]:
|
||||
ids: List[str] = []
|
||||
token = None
|
||||
while True:
|
||||
resp = (
|
||||
youtube.playlistItems()
|
||||
.list(part="contentDetails", playlistId=playlist_id, maxResults=50, pageToken=token)
|
||||
.execute()
|
||||
)
|
||||
for it in resp.get("items", []):
|
||||
ids.append(it["contentDetails"]["videoId"])
|
||||
token = resp.get("nextPageToken")
|
||||
if not token:
|
||||
break
|
||||
return ids
|
||||
|
||||
|
||||
def _chunks(seq: List, n: int):
|
||||
for i in range(0, len(seq), n):
|
||||
yield seq[i : i + n]
|
||||
|
||||
|
||||
def fetch_snippets(youtube, ids: List[str]) -> Dict[str, Dict]:
|
||||
out: Dict[str, Dict] = {}
|
||||
for batch in _chunks(ids, 50):
|
||||
resp = youtube.videos().list(part="snippet,status", id=",".join(batch)).execute()
|
||||
for it in resp.get("items", []):
|
||||
out[it["id"]] = it
|
||||
return out
|
||||
|
||||
|
||||
def fetch_all_channel_entries(youtube) -> Tuple[List[Dict], Dict[str, Dict]]:
|
||||
"""Enumerate the whole channel; return (classified entries, raw videos-by-id).
|
||||
|
||||
Read-only. ~1 quota unit per 50 videos plus a couple for enumeration. The raw
|
||||
videos map is returned too so callers can reuse the already-fetched full
|
||||
snippets when applying updates (no extra reads).
|
||||
"""
|
||||
playlist_id = get_uploads_playlist(youtube)
|
||||
ids = iter_all_video_ids(youtube, playlist_id)
|
||||
videos = fetch_snippets(youtube, ids)
|
||||
return build_entries(videos, ids), videos
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
YouTube description + tags rendering (single source of truth).
|
||||
|
||||
Both the live upload pipeline (video_worker_orchestrator, youtube_queue_processor)
|
||||
and the bulk-rewrite maintenance tool (scripts/youtube-descriptions) render
|
||||
descriptions through this module so on-channel descriptions stay consistent with
|
||||
newly published ones.
|
||||
|
||||
The canonical template lives in ``Settings.default_youtube_description``
|
||||
(``backend/config.py``, overridable via the ``DEFAULT_YOUTUBE_DESCRIPTION`` env
|
||||
var). It may contain these placeholders, all optional:
|
||||
|
||||
{title} - song title
|
||||
{artist} - artist name
|
||||
{artist_hashtag} - artist name reduced to a valid hashtag (e.g. "#Coldplay")
|
||||
{brand_code} - the NOMAD-#### brand code line
|
||||
|
||||
Templates without placeholders still work: legacy/tenant-custom templates that
|
||||
predate placeholders keep the historical behaviour of appending
|
||||
``\n\nBrand Code: <code>`` when a brand code is available.
|
||||
"""
|
||||
import re
|
||||
from typing import List, Optional
|
||||
|
||||
# Total length budget for the YouTube ``tags`` field (API rejects > 500 chars,
|
||||
# counted as the sum of tag lengths plus separators). Stay comfortably under.
|
||||
_MAX_TAGS_TOTAL_CHARS = 460
|
||||
|
||||
|
||||
def hashtagify(text: Optional[str]) -> str:
|
||||
"""Reduce a string to the characters that are valid inside a hashtag.
|
||||
|
||||
Keeps unicode word characters (letters, digits, underscore) and drops
|
||||
everything else, so ``"P!nk"`` -> ``"Pnk"`` and ``"Twenty One Pilots"`` ->
|
||||
``"TwentyOnePilots"``. Returns ``""`` when nothing usable remains.
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^\w]", "", text, flags=re.UNICODE)
|
||||
|
||||
|
||||
def _collapse_blank_lines(text: str) -> str:
|
||||
"""Collapse runs of 3+ newlines down to a blank-line separator."""
|
||||
return re.sub(r"\n{3,}", "\n\n", text)
|
||||
|
||||
|
||||
def render_youtube_description(
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
brand_code: Optional[str] = None,
|
||||
template: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Render a YouTube description from the template + per-video values.
|
||||
|
||||
Args:
|
||||
artist: Artist name (may be empty/unknown).
|
||||
title: Song title (may be empty/unknown).
|
||||
brand_code: NOMAD-#### style code, or falsy to omit the brand-code line.
|
||||
template: Override template. Defaults to
|
||||
``Settings.default_youtube_description``.
|
||||
|
||||
Returns:
|
||||
The fully rendered description string, stripped of trailing whitespace.
|
||||
"""
|
||||
if template is None:
|
||||
# Lazy import to avoid any import-time coupling with config.
|
||||
from backend.config import get_settings
|
||||
|
||||
template = get_settings().default_youtube_description or ""
|
||||
|
||||
result = template
|
||||
|
||||
# Simple token substitution (avoid str.format so stray braces in custom
|
||||
# templates never raise).
|
||||
result = result.replace("{artist}", artist or "")
|
||||
result = result.replace("{title}", title or "")
|
||||
|
||||
artist_tag = hashtagify(artist)
|
||||
if artist_tag:
|
||||
result = result.replace("{artist_hashtag}", artist_tag)
|
||||
else:
|
||||
# Drop the artist hashtag entirely, including a leading separator space.
|
||||
result = result.replace(" #{artist_hashtag}", "")
|
||||
result = result.replace("#{artist_hashtag}", "")
|
||||
result = result.replace("{artist_hashtag}", "")
|
||||
|
||||
if "{brand_code}" in result:
|
||||
if brand_code:
|
||||
result = result.replace("{brand_code}", brand_code)
|
||||
else:
|
||||
# Remove any line carrying the placeholder so we don't leave a
|
||||
# dangling "Brand Code:" label.
|
||||
result = "\n".join(
|
||||
line for line in result.split("\n") if "{brand_code}" not in line
|
||||
)
|
||||
elif brand_code:
|
||||
# Legacy template without a placeholder: preserve historical append.
|
||||
result = f"{result}\n\nBrand Code: {brand_code}"
|
||||
|
||||
return _collapse_blank_lines(result).strip()
|
||||
|
||||
|
||||
def build_youtube_tags(artist: Optional[str], title: Optional[str]) -> List[str]:
|
||||
"""Build a de-duplicated, length-capped YouTube tags list.
|
||||
|
||||
Richer than the historical ``["karaoke", artist, title]`` for discoverability,
|
||||
while respecting YouTube's ~500 char total tags budget.
|
||||
"""
|
||||
artist = (artist or "").strip()
|
||||
title = (title or "").strip()
|
||||
|
||||
candidates = [
|
||||
"karaoke",
|
||||
"instrumental",
|
||||
"lyrics",
|
||||
"karaoke version",
|
||||
"sing along",
|
||||
"backing track",
|
||||
artist,
|
||||
title,
|
||||
f"{artist} karaoke" if artist else "",
|
||||
f"{artist} {title} karaoke" if artist and title else "",
|
||||
]
|
||||
|
||||
tags: List[str] = []
|
||||
seen = set()
|
||||
total = 0
|
||||
for tag in candidates:
|
||||
tag = tag.strip()
|
||||
if not tag:
|
||||
continue
|
||||
key = tag.lower()
|
||||
if key in seen:
|
||||
continue
|
||||
# +1 approximates the separator cost the API counts between tags.
|
||||
cost = len(tag) + 1
|
||||
if total + cost > _MAX_TAGS_TOTAL_CHARS:
|
||||
continue
|
||||
seen.add(key)
|
||||
tags.append(tag)
|
||||
total += cost
|
||||
|
||||
return tags
|
||||
@@ -240,3 +240,61 @@ async def test_list_in_progress_and_stalled(service):
|
||||
service.mark_stalled(a.id)
|
||||
assert service.get_request(a.id).status == "stalled"
|
||||
assert service.list_in_progress() == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Existing-community-version review flow (A/B follow-up)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_pick_candidates_excludes_review_states(service):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
b, _, _, _ = await _submit(service, "o2@x.com", "Artist B", "Song B")
|
||||
c, _, _, _ = await _submit(service, "o3@x.com", "Artist C", "Song C")
|
||||
# Flag A pending; snooze B into the future; C stays clean.
|
||||
service.set_review_pending(a.id, {"best_youtube_url": "https://y/x", "tracks": []})
|
||||
service.snooze_review(b.id, datetime.now(timezone.utc) + timedelta(days=10))
|
||||
ids = [r.id for r in service.list_pick_candidates()]
|
||||
assert c.id in ids
|
||||
assert a.id not in ids # pending
|
||||
assert b.id not in ids # snoozed (future)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_expired_snooze_becomes_pickable_again(service):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.snooze_review(a.id, datetime.now(timezone.utc) - timedelta(days=1)) # already expired
|
||||
assert a.id in [r.id for r in service.list_pick_candidates()]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_set_review_pending_idempotent(service):
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
versions = {"best_youtube_url": "https://y/x", "tracks": [{"brand_name": "Z", "youtube_url": "https://y/x"}]}
|
||||
assert service.set_review_pending(a.id, versions) is True # newly flagged
|
||||
assert service.set_review_pending(a.id, versions) is False # already pending
|
||||
r = service.get_request(a.id)
|
||||
assert r.review_state == "pending" and r.community_versions["best_youtube_url"] == "https://y/x"
|
||||
assert a.id in [x.id for x in service.list_pending_reviews()]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_snooze_clear_and_reject(service):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
a, _, _, _ = await _submit(service, "o1@x.com", "Artist A", "Song A")
|
||||
service.set_review_pending(a.id, {"best_youtube_url": None, "tracks": []})
|
||||
# keep → snoozed, off the pending queue
|
||||
service.snooze_review(a.id, datetime.now(timezone.utc) + timedelta(days=30))
|
||||
assert service.get_request(a.id).review_state == "snoozed"
|
||||
assert service.list_pending_reviews() == []
|
||||
# clear → back to no review flag
|
||||
service.clear_review(a.id)
|
||||
assert service.get_request(a.id).review_state is None
|
||||
# reject → status rejected, off the board
|
||||
service.reject_request(a.id)
|
||||
r = service.get_request(a.id)
|
||||
assert r.status == "rejected" and r.review_state is None
|
||||
assert a.id not in [x.id for x in service.list_active()]
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# GCE encode worker — golden response fixtures
|
||||
|
||||
Real-shaped responses returned by the GCE encoding worker's `encode_videos`
|
||||
(the value `GCEEncodingBackend.encode()` consumes), captured/authored as golden
|
||||
JSON so the encode→publish seam is tested against the *actual* contract rather
|
||||
than hand-authored per-test mocks. Each conforms to the `GceEncodeResponse`
|
||||
TypedDict in `backend/services/encoding_interface.py`.
|
||||
|
||||
| Fixture | Shape | What it exercises |
|
||||
|---|---|---|
|
||||
| `success.json` | `complete`, all 4 requested formats | Happy path. Uses the NOMAD-1632 title ("Portrait of Jennie") so classification must key off the trailing format tag, not the title text. |
|
||||
| `cached.json` | `complete`, full set incl. portrait/with-vocals/title/end/CDG | A cached hit returning every additive final; exercises every classifier branch. |
|
||||
| `empty.json` | `complete`, `output_files: []` | Stale/cached-but-deleted job. Must be treated as **recoverable** (re-encode), NOT a partial/defective result. This shape caused Failure B. |
|
||||
| `partial.json` | `complete`, missing `mp4_720p` | Failure A: the completeness guard must trip and refuse to publish. |
|
||||
| `malformed.json` | `complete`, stray / wrong-extension names | Nothing classifies into a slot → treated as empty (not crash, not mis-slotted). |
|
||||
|
||||
Replayed by `backend/tests/test_encoding_contract.py` (contract test) and driven
|
||||
through the real orchestrator by `TestEncodePublishSeam` in
|
||||
`backend/tests/test_video_worker_orchestrator.py`.
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Portrait 1080x1920).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (With Vocals).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Title).mov",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (End).mov",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke CDG).zip"
|
||||
]
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": []
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/notes.txt",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole 720p demo.txt",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).webm",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/thumbnail.jpg"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4"
|
||||
]
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"status": "complete",
|
||||
"progress": 100,
|
||||
"output_files": [
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4",
|
||||
"gs://nomadkaraoke-media/jobs/NOMAD-1632/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4"
|
||||
]
|
||||
}
|
||||
@@ -158,19 +158,15 @@ class TestParallelProcessingCoordination:
|
||||
# Verify update_job was called to set the lyrics_complete flag
|
||||
job_manager.firestore.update_job.assert_called()
|
||||
|
||||
def test_both_complete_triggers_screens(self, job_manager, mock_firestore_service):
|
||||
"""Test that screens worker is triggered when both complete."""
|
||||
# First call: Job with audio already complete (for update_state_data)
|
||||
# Second call: Job with both complete (for check_parallel_processing_complete)
|
||||
job_audio_only = Job(
|
||||
job_id="test-parallel-003",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True},
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_both_complete_triggers_screens(self, job_manager, mock_firestore_service):
|
||||
"""When lyrics is complete and the job is still DOWNLOADING, advancing
|
||||
triggers the screens worker via an AWAITED (durable) dispatch.
|
||||
|
||||
mark_lyrics_complete now only sets the flag; advance_to_screens_if_ready
|
||||
does the dispatch (the old fire-and-forget trigger was lost on Cloud Run
|
||||
Job loop teardown, orphaning jobs at `downloading`).
|
||||
"""
|
||||
job_both_complete = Job(
|
||||
job_id="test-parallel-003",
|
||||
artist="Test Artist",
|
||||
@@ -180,17 +176,17 @@ class TestParallelProcessingCoordination:
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True, 'lyrics_complete': True},
|
||||
)
|
||||
# Return different jobs on subsequent calls
|
||||
job_manager.firestore.get_job.side_effect = [job_audio_only, job_both_complete]
|
||||
job_manager.firestore.get_job.return_value = job_both_complete
|
||||
job_manager.firestore.update_job.return_value = True
|
||||
|
||||
# Mock the screens worker trigger
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
# Now lyrics completes
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
job_manager.mark_lyrics_complete("test-parallel-003")
|
||||
result = await job_manager.advance_to_screens_if_ready("test-parallel-003")
|
||||
|
||||
# Verify screens worker was triggered (both complete)
|
||||
mock_trigger.assert_called_once_with("test-parallel-003")
|
||||
assert result is True
|
||||
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-parallel-003")
|
||||
|
||||
|
||||
class TestStateTransitionValidation:
|
||||
|
||||
@@ -160,6 +160,70 @@ def test_apply_all_flags_stale() -> None:
|
||||
assert out["applied_ids"] == []
|
||||
|
||||
|
||||
# --- undo_out / undo_info ---
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_replace() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(
|
||||
_segments(), _sug("replace", ["w1"], "was", original_text="am"), undo_out=undo
|
||||
)
|
||||
assert result is not None
|
||||
assert undo["op"] == "replace"
|
||||
assert undo["segment_id"] == "s0"
|
||||
assert undo["prev_word_id"] == "w0"
|
||||
assert undo["removed_words"] == [_word("w1", "am", 0.3, 0.6)]
|
||||
assert undo["new_word_ids"] == [result[0]["words"][1]["id"]]
|
||||
assert undo["removed_segment"] is None
|
||||
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_delete_whole_segment() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w4"]), undo_out=undo)
|
||||
assert result is not None
|
||||
assert undo["op"] == "delete"
|
||||
assert undo["new_word_ids"] == []
|
||||
assert undo["removed_words"] == [_word("w4", "gasoline", 2.0, 2.8)]
|
||||
assert undo["removed_segment"] == {"segment": _segments()[1], "index": 1}
|
||||
|
||||
|
||||
def test_apply_all_suggestions_reports_undo_info_per_applied_id() -> None:
|
||||
out = apply_all_suggestions(_segments(), [_sug("replace", ["w1"], "was", id="a")])
|
||||
assert out["applied_ids"] == ["a"]
|
||||
assert set(out["undo_info"].keys()) == {"a"}
|
||||
assert out["undo_info"]["a"]["op"] == "replace"
|
||||
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_insert_after() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(
|
||||
_segments(), _sug("insert_after", ["w3"], "burning"), undo_out=undo
|
||||
)
|
||||
assert result is not None
|
||||
new_word = result[0]["words"][4]
|
||||
assert undo == {
|
||||
"op": "insert_after",
|
||||
"new_word_ids": [new_word["id"]],
|
||||
"removed_words": [],
|
||||
"segment_id": "s0",
|
||||
"prev_word_id": "w3",
|
||||
"removed_segment": None,
|
||||
}
|
||||
|
||||
|
||||
def test_apply_suggestion_populates_undo_out_for_partial_delete() -> None:
|
||||
undo: Dict[str, Any] = {}
|
||||
result = apply_suggestion(_segments(), _sug("delete", ["w0"]), undo_out=undo)
|
||||
assert result is not None
|
||||
assert undo == {
|
||||
"op": "delete",
|
||||
"new_word_ids": [],
|
||||
"removed_words": [_word("w0", "I", 0.0, 0.3)],
|
||||
"segment_id": "s0",
|
||||
"prev_word_id": None,
|
||||
"removed_segment": None,
|
||||
}
|
||||
|
||||
|
||||
def test_p1_self_conflict_produces_detectable_duplicate() -> None:
|
||||
# Corpus f6439692: overlapping suggestions (conflict_group=null) both add
|
||||
# "you're" -> "fire, you're you're gasoline". The apply engine mirrors the
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Regression: admin endpoints that log the caller must not 500.
|
||||
|
||||
`require_admin` returns an `AuthResult` object (not a tuple). Three admin endpoints
|
||||
logged `auth_data[0]`, which raised `TypeError: 'AuthResult' object is not
|
||||
subscriptable` and returned 500 (prod: POST /jobs/{id}/reset-worker-state on
|
||||
2026-09-15). These endpoints had no test coverage, so the bug shipped. This test
|
||||
locks in the fix (`auth_data.user_email`).
|
||||
"""
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin, AuthResult, UserType
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def _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.dependency_overrides[require_admin] = _mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_reset_worker_state_does_not_500(client):
|
||||
"""POST /jobs/{id}/reset-worker-state must succeed — previously raised
|
||||
TypeError on `auth_data[0]` because require_admin returns an AuthResult."""
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = Mock() # truthy job
|
||||
|
||||
with patch("backend.services.job_manager.JobManager", return_value=mock_jm):
|
||||
resp = client.post("/api/admin/jobs/test-123/reset-worker-state")
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["status"] == "success"
|
||||
# video/render/screens progress states reset
|
||||
assert mock_jm.update_state_data.call_count == 3
|
||||
|
||||
|
||||
def test_clear_all_flacfetch_cache_does_not_500(client):
|
||||
"""DELETE /cache must succeed — same `auth_data[0]` bug on the admin log line."""
|
||||
mock_client = Mock()
|
||||
|
||||
async def _clear():
|
||||
return 7
|
||||
|
||||
mock_client.clear_all_cache = _clear
|
||||
|
||||
with patch("backend.api.routes.admin.get_flacfetch_client", return_value=mock_client):
|
||||
resp = client.delete("/api/admin/cache")
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["deleted_count"] == 7
|
||||
@@ -439,3 +439,40 @@ class TestUpdateJobUserEmailAutoCreate:
|
||||
assert response.status_code == 400
|
||||
assert "valid email" in response.json()["detail"]
|
||||
mock_jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
class TestUpdateJobMadeForYou:
|
||||
"""made_for_you is editable so admin batches can opt jobs out of the
|
||||
stale-review auto-expiry (stale_review_processor skips MFY jobs)."""
|
||||
|
||||
def test_made_for_you_is_editable(self, client, mock_job):
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"made_for_you": True},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "made_for_you" in response.json()["updated_fields"]
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][1]["made_for_you"] is True
|
||||
|
||||
def test_made_for_you_rejects_non_bool(self, client, mock_job):
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"made_for_you": "yes"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "boolean" in response.json()["detail"]
|
||||
mock_jm.update_job.assert_not_called()
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Tests for the admin mint-login-link endpoint and purpose->redirect mapping."""
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.routes.users import _magic_link_redirect_path
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def _mock_admin():
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
|
||||
message="ok", user_email="admin@example.com", is_admin=True)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = _mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
mock_us = Mock()
|
||||
tok = Mock()
|
||||
tok.email = "user@example.com"
|
||||
tok.token = "tok123"
|
||||
tok.expires_at = datetime.utcnow() + timedelta(hours=168)
|
||||
mock_us.create_admin_login_token.return_value = tok
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_us
|
||||
yield TestClient(app), mock_us
|
||||
app.dependency_overrides.pop(get_user_service, None)
|
||||
|
||||
|
||||
class TestMintLoginLink:
|
||||
def test_mints_link_with_purpose(self, client):
|
||||
c, mock_us = client
|
||||
resp = c.post("/api/admin/users/User@Example.com/login-link",
|
||||
json={"expiry_hours": 100, "purpose": "job_review:abc12345"})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "auth/verify?token=tok123" in data["url"]
|
||||
assert data["purpose"] == "job_review:abc12345"
|
||||
mock_us.create_admin_login_token.assert_called_once_with(
|
||||
email="user@example.com", expiry_hours=100, purpose="job_review:abc12345")
|
||||
|
||||
|
||||
class TestMagicLinkRedirectPath:
|
||||
def test_board(self):
|
||||
assert _magic_link_redirect_path("requests_board") == "/requests"
|
||||
|
||||
def test_job_review(self):
|
||||
assert _magic_link_redirect_path("job_review:abc12345") == "/app/jobs#/abc12345/review"
|
||||
|
||||
def test_malformed_job_id_rejected(self):
|
||||
assert _magic_link_redirect_path("job_review:../evil") is None
|
||||
assert _magic_link_redirect_path("job_review:") is None
|
||||
|
||||
def test_none_and_unknown(self):
|
||||
assert _magic_link_redirect_path(None) is None
|
||||
assert _magic_link_redirect_path("something_else") is None
|
||||
@@ -411,3 +411,250 @@ class TestLoadCachedWaveform:
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
|
||||
class TestGetReviewWaveform:
|
||||
"""Persistent GCS cache for the review-page waveform (concurrent-load fix)."""
|
||||
|
||||
def _service(self, mock_storage_class, mock_waveform_class):
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
mock_waveform = Mock()
|
||||
mock_waveform.generate_data_only.return_value = ([0.1, 0.9], 200.0)
|
||||
mock_waveform_class.return_value = mock_waveform
|
||||
return AudioAnalysisService(), mock_storage, mock_waveform
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_hit_skips_decode(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"amplitudes": [0.3, 0.7],
|
||||
"duration_seconds": 123.0,
|
||||
"num_points": 1000,
|
||||
"source_gcs_path": "jobs/j1/stems/backing_vocals.flac",
|
||||
}
|
||||
|
||||
amps, duration = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
|
||||
assert amps == [0.3, 0.7]
|
||||
assert duration == 123.0
|
||||
waveform.generate_data_only.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_miss_computes_and_uploads(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
amps, duration = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
|
||||
assert amps == [0.1, 0.9]
|
||||
assert duration == 200.0
|
||||
waveform.generate_data_only.assert_called_once()
|
||||
storage.upload_json.assert_called_once()
|
||||
cache_path, payload = storage.upload_json.call_args[0]
|
||||
assert cache_path == "jobs/j1/review-audio/waveform_review_1000.json"
|
||||
assert payload["source_gcs_path"] == "jobs/j1/stems/backing_vocals.flac"
|
||||
assert payload["num_points"] == 1000
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_stale_source_recomputes(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""A cache written for an old/replaced stem path must not be served."""
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"amplitudes": [0.3, 0.7],
|
||||
"duration_seconds": 123.0,
|
||||
"num_points": 1000,
|
||||
"source_gcs_path": "jobs/j1/stems/OLD_backing_vocals.flac",
|
||||
}
|
||||
|
||||
amps, _ = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
|
||||
assert amps == [0.1, 0.9] # freshly computed, not the stale cache
|
||||
waveform.generate_data_only.assert_called_once()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_num_points_mismatch_recomputes(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"amplitudes": [0.3, 0.7],
|
||||
"duration_seconds": 123.0,
|
||||
"num_points": 500,
|
||||
"source_gcs_path": "jobs/j1/stems/backing_vocals.flac",
|
||||
}
|
||||
|
||||
_, _ = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
waveform.generate_data_only.assert_called_once()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_prefers_transcoded_ogg_on_miss(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""On a cache miss, decode the small review OGG when it exists."""
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
# Cache JSON absent, transcoded OGG present.
|
||||
storage.file_exists.side_effect = lambda p: p.endswith(".ogg")
|
||||
|
||||
transcoding = Mock()
|
||||
transcoding.get_transcoded_cache_path.return_value = (
|
||||
"jobs/j1/review-audio/backing_vocals.ogg"
|
||||
)
|
||||
|
||||
with patch.object(service, "get_waveform_data", wraps=None) as mock_get:
|
||||
mock_get.return_value = ([0.5], 90.0)
|
||||
service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000, transcoding
|
||||
)
|
||||
assert (
|
||||
mock_get.call_args.kwargs["gcs_audio_path"]
|
||||
== "jobs/j1/review-audio/backing_vocals.ogg"
|
||||
)
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_upload_failure_still_returns_data(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = False
|
||||
storage.upload_json.side_effect = Exception("GCS write denied")
|
||||
|
||||
amps, duration = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
assert amps == [0.1, 0.9]
|
||||
assert duration == 200.0
|
||||
|
||||
|
||||
class TestGetVocalsPeaks:
|
||||
"""Persistent GCS cache of the vocals peak envelope (sub-second strips)."""
|
||||
|
||||
def _service(self, mock_storage_class, mock_waveform_class):
|
||||
import numpy as np
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
mock_waveform = Mock()
|
||||
mock_waveform.generate_peaks.return_value = (
|
||||
np.array([0.0, 0.5, 1.0], dtype=np.float32), 3.0
|
||||
)
|
||||
mock_waveform_class.return_value = mock_waveform
|
||||
return AudioAnalysisService(), mock_storage, mock_waveform
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_hit_skips_decode(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
cached = {
|
||||
"peaks_b64": "AAA=",
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": 400,
|
||||
"duration_seconds": 3.0,
|
||||
"source_gcs_path": "jobs/j1/stems/vocals_clean.flac",
|
||||
}
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = cached
|
||||
|
||||
result = service.get_vocals_peaks("jobs/j1/stems/vocals_clean.flac", "j1", 400)
|
||||
|
||||
assert result == cached
|
||||
waveform.generate_peaks.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_miss_computes_quantizes_and_uploads(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
import base64
|
||||
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
result = service.get_vocals_peaks("jobs/j1/stems/vocals_clean.flac", "j1", 400)
|
||||
|
||||
assert result["encoding"] == "u8"
|
||||
assert result["peaks_per_second"] == 400
|
||||
assert result["duration_seconds"] == 3.0
|
||||
# [0.0, 0.5, 1.0] -> uint8 [0, 128, 255]
|
||||
assert list(base64.b64decode(result["peaks_b64"])) == [0, 128, 255]
|
||||
cache_path, payload = storage.upload_json.call_args[0]
|
||||
assert cache_path == "jobs/j1/review-audio/vocals_peaks_400.json"
|
||||
assert payload == result
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_stale_source_recomputes(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"peaks_b64": "AAA=",
|
||||
"peaks_per_second": 400,
|
||||
"duration_seconds": 3.0,
|
||||
"source_gcs_path": "jobs/j1/stems/OLD.flac",
|
||||
}
|
||||
|
||||
service.get_vocals_peaks("jobs/j1/stems/vocals_clean.flac", "j1", 400)
|
||||
waveform.generate_peaks.assert_called_once()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_prefers_transcoded_ogg_and_survives_upload_failure(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.side_effect = lambda p: p.endswith(".ogg")
|
||||
storage.upload_json.side_effect = Exception("GCS write denied")
|
||||
|
||||
transcoding = Mock()
|
||||
transcoding.get_transcoded_cache_path.return_value = "jobs/j1/review-audio/vocals_clean.ogg"
|
||||
|
||||
result = service.get_vocals_peaks(
|
||||
"jobs/j1/stems/vocals_clean.flac", "j1", 400, transcoding
|
||||
)
|
||||
|
||||
# Decoded from the small OGG, and data still returned despite upload failure
|
||||
downloaded_path = storage.download_file.call_args[0][0]
|
||||
assert downloaded_path == "jobs/j1/review-audio/vocals_clean.ogg"
|
||||
assert result["source_gcs_path"] == "jobs/j1/stems/vocals_clean.flac"
|
||||
@@ -136,6 +136,26 @@ class TestGetReviewAudioUrl:
|
||||
"jobs/abc/review-audio/song.ogg", 120
|
||||
)
|
||||
|
||||
def test_signed_url_timeout_short_circuits_fallbacks(self):
|
||||
"""A signing stall must NOT trigger the FLAC/cache fallbacks (they'd stall too).
|
||||
|
||||
On a cache hit the first sign is the only sign attempted; a SignedUrlTimeout
|
||||
propagates immediately so the caller degrades fast.
|
||||
"""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
from backend.services.storage_service import SignedUrlTimeout
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True # cache hit
|
||||
mock_storage.generate_signed_url.side_effect = SignedUrlTimeout("stalled")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
with pytest.raises(SignedUrlTimeout):
|
||||
service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
# Exactly one sign attempt — no fallback re-signing.
|
||||
assert mock_storage.generate_signed_url.call_count == 1
|
||||
|
||||
def test_falls_back_to_flac_on_error(self):
|
||||
"""On transcoding error with no cache, fall back to original FLAC signed URL."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
@@ -30,24 +30,24 @@ class TestBatchHelper:
|
||||
async def test_batch_maps_community_results(self, monkeypatch):
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
async def fake_single(artist, title):
|
||||
if title == "One More Time":
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [{"community_tracks": [{"brand_name": "KV"}, {"brand_name": "KaraFun"}]}],
|
||||
"best_youtube_url": None,
|
||||
}
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
# Seed the in-process community index (the batch helper reads it directly).
|
||||
# Brand is a CODE in the catalog; brand names resolve for display.
|
||||
rows = [
|
||||
{"Artist": "Daft Punk", "Title": "One More Time", "Brand": "KV", "Watch": ""},
|
||||
{"Artist": "Daft Punk", "Title": "One More Time", "Brand": "OBSK", "Watch": ""},
|
||||
]
|
||||
kn._reset_index_for_tests()
|
||||
monkeypatch.setattr(kn, "_load_index", lambda: kn._build_index(rows))
|
||||
|
||||
monkeypatch.setattr(kn, "check_community_versions", fake_single)
|
||||
out = await kn.check_community_versions_batch(
|
||||
[{"artist": "Daft Punk", "title": "One More Time"},
|
||||
{"artist": "Daft Punk", "title": "Aerodynamic"}]
|
||||
)
|
||||
assert out[0]["available"] is True
|
||||
assert out[0]["brands"] == ["KV", "KaraFun"]
|
||||
assert out[0]["brands"] == ["Karaoke Version", "ObsKure Karaoke"]
|
||||
assert out[1]["available"] is False
|
||||
assert out[1]["brand_count"] == 0
|
||||
kn._reset_index_for_tests()
|
||||
|
||||
|
||||
class TestAvailabilityRoute:
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Tests for POST /api/client-events (degradation telemetry)."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes import client_events
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
app = FastAPI()
|
||||
app.include_router(client_events.router, prefix="/api")
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_limiter_and_db(monkeypatch):
|
||||
monkeypatch.setattr(client_events, "_limiter", client_events.RateLimiter(max_per_minute=30))
|
||||
db = MagicMock()
|
||||
monkeypatch.setattr(client_events, "_db_singleton", db)
|
||||
return db
|
||||
|
||||
|
||||
def _event(**overrides):
|
||||
payload = {
|
||||
"type": "banner_unavailable",
|
||||
"url": "https://gen.nomadkaraoke.com/app/jobs?token=SECRET#/abc123/review",
|
||||
"job_id": "abc123",
|
||||
"locale": "en",
|
||||
"release": "deadbeef",
|
||||
"detail": {"stall_ms": 21000, "probe_ok": False},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
class TestReportClientEvent:
|
||||
def test_valid_event_persists_to_firestore(self, client, fresh_limiter_and_db):
|
||||
resp = client.post("/api/client-events", json=_event())
|
||||
|
||||
assert resp.status_code == 202
|
||||
assert resp.json() == {"status": "recorded"}
|
||||
fresh_limiter_and_db.collection.assert_called_once_with("client_events")
|
||||
(doc,) = fresh_limiter_and_db.collection.return_value.add.call_args[0]
|
||||
assert doc["type"] == "banner_unavailable"
|
||||
assert doc["job_id"] == "abc123"
|
||||
assert doc["detail"] == {"stall_ms": 21000, "probe_ok": False}
|
||||
# Query string (may carry tokens) must be stripped before persisting.
|
||||
assert "SECRET" not in doc["url"]
|
||||
|
||||
def test_unknown_event_type_rejected(self, client):
|
||||
resp = client.post("/api/client-events", json=_event(type="something_else"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
def test_rate_limited(self, client, monkeypatch):
|
||||
monkeypatch.setattr(client_events, "_limiter", client_events.RateLimiter(max_per_minute=2))
|
||||
assert client.post("/api/client-events", json=_event()).status_code == 202
|
||||
assert client.post("/api/client-events", json=_event()).status_code == 202
|
||||
assert client.post("/api/client-events", json=_event()).status_code == 429
|
||||
|
||||
def test_bot_user_agent_ignored(self, client, fresh_limiter_and_db):
|
||||
resp = client.post(
|
||||
"/api/client-events",
|
||||
json=_event(),
|
||||
headers={"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"},
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
assert resp.json() == {"status": "ignored"}
|
||||
fresh_limiter_and_db.collection.assert_not_called()
|
||||
|
||||
def test_firestore_failure_still_returns_202(self, client, fresh_limiter_and_db):
|
||||
fresh_limiter_and_db.collection.return_value.add.side_effect = Exception("firestore down")
|
||||
resp = client.post("/api/client-events", json=_event())
|
||||
assert resp.status_code == 202 # telemetry must never error back to users
|
||||
|
||||
def test_detail_is_capped(self):
|
||||
big = {f"key{i}": "x" * 500 for i in range(30)}
|
||||
capped = client_events._capped_detail(big)
|
||||
assert len(capped) == 12
|
||||
assert all(len(v) <= 200 for v in capped.values())
|
||||
assert client_events._capped_detail(None) == {}
|
||||
assert client_events._capped_detail("not a dict") == {}
|
||||
@@ -148,6 +148,56 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
|
||||
# Verify the returned data is the original
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
|
||||
def test_returns_proxy_audio_urls_and_omits_waveform_without_signing(
|
||||
self, mock_job, original_corrections
|
||||
):
|
||||
"""Root-cause fix (2026-09-17, Option B): the review hot path performs NO URL
|
||||
signing. get_correction_data returns 200 with the lyrics payload, same-origin
|
||||
proxy paths for the instrumental options, and no ``backing_vocals_waveform_url``
|
||||
(the frontend renders the waveform from the JSON /waveform-data endpoint, and
|
||||
never consumed this field). The IAM signBlob round-trip that stalled and took gen
|
||||
down on 2026-09-17 is gone entirely.
|
||||
"""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
|
||||
# Job has both a waveform and instrumental stems, so every former signing path runs.
|
||||
mock_job.file_urls["analysis"] = {
|
||||
"backing_vocals_waveform": "jobs/test-job-123/analysis/backing_vocals_waveform.png"
|
||||
}
|
||||
mock_job.file_urls["stems"] = {
|
||||
"instrumental_clean": "jobs/test-job-123/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/test-job-123/stems/instrumental_with_backing.flac",
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService, \
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False):
|
||||
|
||||
job_manager = MockJobManager.return_value
|
||||
job_manager.get_job.return_value = mock_job
|
||||
|
||||
storage = MockStorageService.return_value
|
||||
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
|
||||
storage.download_json.return_value = original_corrections.copy()
|
||||
|
||||
import asyncio
|
||||
result = asyncio.run(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Endpoint succeeded with the lyrics payload.
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
# Waveform URL is not emitted at all (dead field, no consumer).
|
||||
assert "backing_vocals_waveform_url" not in result
|
||||
# Instrumental options carry same-origin proxy paths (no signing, never expire).
|
||||
opts = {o["id"]: o["audio_url"] for o in result["instrumental_options"]}
|
||||
assert opts == {
|
||||
"clean": "/api/review/test-job-123/instrumental-audio/clean",
|
||||
"with_backing": "/api/review/test-job-123/instrumental-audio/with_backing",
|
||||
}
|
||||
# The critical assertion: the hot path signed nothing.
|
||||
storage.generate_signed_url.assert_not_called()
|
||||
|
||||
def test_checks_direct_gcs_path_when_not_in_file_urls(
|
||||
self, mock_job, updated_corrections
|
||||
):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Unit tests for the daily free-community-track picker orchestration.
|
||||
|
||||
Mocks the service/user/job layers so we exercise run_daily_pick's control flow:
|
||||
kill-switch shadowing, empty board, day-lock idempotency, credit grant, and the
|
||||
grant/job-create idempotency guards. The Firestore-level pieces (claim_day, the
|
||||
transactional transitions) are covered by the emulator tests.
|
||||
Mocks the service/user/job/KaraokeNerds layers so we exercise run_daily_pick's
|
||||
control flow: kill-switch shadowing, empty board, day-lock idempotency, credit
|
||||
grant guards, and the existing-community-version candidate loop (flag dups →
|
||||
make the first clean one). Firestore-level pieces are covered by emulator tests.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
@@ -24,11 +24,19 @@ def _request(**over):
|
||||
return SongRequest(**base)
|
||||
|
||||
|
||||
def _make_service(pick=None, lock=None, claimed_new=True, get_request=None):
|
||||
def _make_service(candidates=None, lock=None, claimed_new=True, registry=None):
|
||||
"""Build a mock SongRequestService.
|
||||
|
||||
candidates: what list_pick_candidates returns (ranked).
|
||||
registry: id -> SongRequest for get_request lookups (defaults to candidates).
|
||||
"""
|
||||
candidates = candidates or []
|
||||
reg = dict(registry) if registry else {r.id: r for r in candidates}
|
||||
svc = MagicMock()
|
||||
svc.claim_day.return_value = (lock or DailyCommunityPick(date="2026-09-03"), claimed_new)
|
||||
svc.pick_eligible.return_value = pick
|
||||
svc.get_request.side_effect = (lambda rid: get_request) if get_request is not None else (lambda rid: pick)
|
||||
svc.list_pick_candidates.return_value = candidates
|
||||
svc.get_request.side_effect = lambda rid: reg.get(rid)
|
||||
svc.set_review_pending.return_value = True # newly flagged
|
||||
return svc
|
||||
|
||||
|
||||
@@ -42,117 +50,153 @@ def _settings(enabled=True):
|
||||
)
|
||||
|
||||
|
||||
def _community(has_map=None):
|
||||
"""AsyncMock for check_community_versions. has_map: artist->bool has_community."""
|
||||
has_map = has_map or {}
|
||||
|
||||
async def _check(artist, title):
|
||||
if has_map.get(artist):
|
||||
return {"has_community": True, "best_youtube_url": "https://youtu.be/x",
|
||||
"songs": [{"community_tracks": [{"brand_name": "Foo", "youtube_url": "https://youtu.be/x"}]}]}
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
return AsyncMock(side_effect=_check)
|
||||
|
||||
|
||||
def _run(svc, settings, community=None, user=None, made=True):
|
||||
"""Context-managed patches; returns the coroutine to await."""
|
||||
community = community or _community()
|
||||
user = user or MagicMock()
|
||||
if user.add_credits.return_value is None or not isinstance(user.add_credits.return_value, tuple):
|
||||
user.add_credits.return_value = (True, 5, "ok")
|
||||
stack = [
|
||||
patch.object(cdp, "get_song_request_service", return_value=svc),
|
||||
patch.object(cdp, "get_settings", return_value=settings),
|
||||
patch.object(cdp, "get_user_service", return_value=user),
|
||||
patch("backend.services.karaokenerds_service.check_community_versions", community),
|
||||
patch.object(cdp, "_email_admin_flagged", MagicMock()),
|
||||
]
|
||||
if made:
|
||||
stack.append(patch.object(cdp, "_create_community_job", return_value="job123"))
|
||||
stack.append(patch.object(cdp, "_search_and_download", new=AsyncMock(return_value=True)))
|
||||
return stack
|
||||
|
||||
|
||||
async def _exec(stack, dry_run=False):
|
||||
for p in stack:
|
||||
p.start()
|
||||
try:
|
||||
return await cdp.run_daily_pick(dry_run=dry_run)
|
||||
finally:
|
||||
for p in reversed(stack):
|
||||
p.stop()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_kill_switch_off_shadows_no_side_effects():
|
||||
svc = _make_service(pick=_request())
|
||||
svc = _make_service(candidates=[_request()])
|
||||
user = MagicMock()
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=False)), \
|
||||
patch.object(cdp, "get_user_service", return_value=user):
|
||||
result = await cdp.run_daily_pick(dry_run=False)
|
||||
assert result["status"] == "shadow"
|
||||
assert result["reason"] == "kill_switch_off"
|
||||
result = await _exec(_run(svc, _settings(enabled=False), user=user, made=False))
|
||||
assert result["status"] == "shadow" and result["reason"] == "kill_switch_off"
|
||||
user.add_credits.assert_not_called()
|
||||
svc.transition_status.assert_not_called()
|
||||
# Shadow must NOT claim the day (else a dry-run would block the real run).
|
||||
svc.claim_day.assert_not_called()
|
||||
svc.update_lock.assert_not_called()
|
||||
svc.set_review_pending.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dry_run_shadows_even_when_enabled():
|
||||
svc = _make_service(pick=_request())
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=MagicMock()):
|
||||
result = await cdp.run_daily_pick(dry_run=True)
|
||||
svc = _make_service(candidates=[_request()])
|
||||
result = await _exec(_run(svc, _settings(enabled=True), made=False), dry_run=True)
|
||||
assert result["status"] == "shadow" and result["reason"] == "dry_run"
|
||||
assert result["request_id"] == "req1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_board_makes_nothing():
|
||||
svc = _make_service(pick=None)
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=MagicMock()):
|
||||
result = await cdp.run_daily_pick()
|
||||
svc = _make_service(candidates=[])
|
||||
result = await _exec(_run(svc, _settings(enabled=True), made=False))
|
||||
assert result["status"] == "empty"
|
||||
assert any(c.kwargs.get("phase") == "empty" for c in svc.update_lock.call_args_list)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_already_resolved_day_is_noop():
|
||||
lock = DailyCommunityPick(date="2026-09-03", phase="done", request_id="req1", job_id="j1")
|
||||
svc = _make_service(lock=lock, claimed_new=False)
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=MagicMock()):
|
||||
result = await cdp.run_daily_pick()
|
||||
svc = _make_service(candidates=[_request()], lock=lock, claimed_new=False)
|
||||
result = await _exec(_run(svc, _settings(enabled=True), made=False))
|
||||
assert result["status"] == "already_done"
|
||||
svc.pick_eligible.assert_not_called()
|
||||
svc.list_pick_candidates.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_success_grants_credit_and_creates_job():
|
||||
req = _request()
|
||||
svc = _make_service(pick=req, get_request=req)
|
||||
svc = _make_service(candidates=[req])
|
||||
user = MagicMock()
|
||||
user.add_credits.return_value = (True, 5, "ok")
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=user), \
|
||||
patch.object(cdp, "_create_community_job", return_value="job123") as mk, \
|
||||
patch.object(cdp, "_search_and_download", new=AsyncMock(return_value=True)):
|
||||
result = await cdp.run_daily_pick()
|
||||
assert result["status"] == "made"
|
||||
assert result["job_id"] == "job123"
|
||||
result = await _exec(_run(svc, _settings(enabled=True), user=user))
|
||||
assert result["status"] == "made" and result["job_id"] == "job123"
|
||||
user.add_credits.assert_called_once()
|
||||
svc.mark_credit_granted.assert_called_once_with("req1")
|
||||
svc.set_job_id.assert_called_once_with("req1", "job123")
|
||||
svc.assign_owner.assert_called_once_with("req1", "owner@x.com")
|
||||
mk.assert_called_once()
|
||||
assert any(c.kwargs.get("phase") == "done" for c in svc.update_lock.call_args_list)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flags_dup_and_makes_next_clean():
|
||||
dup = _request(id="dup", artist="DupArtist", title="Has Version", vote_count=9)
|
||||
clean = _request(id="clean", artist="CleanArtist", title="No Version", vote_count=3)
|
||||
svc = _make_service(candidates=[dup, clean])
|
||||
community = _community({"DupArtist": True}) # only the dup has a community version
|
||||
result = await _exec(_run(svc, _settings(enabled=True), community=community))
|
||||
assert result["status"] == "made" and result["request_id"] == "clean"
|
||||
# The dup was flagged pending; the clean one was made.
|
||||
svc.set_review_pending.assert_called_once()
|
||||
assert svc.set_review_pending.call_args.args[0] == "dup"
|
||||
assert result["flagged"] == ["dup"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_all_dups_makes_nothing_but_flags():
|
||||
a = _request(id="a", artist="A1", title="t", vote_count=9)
|
||||
b = _request(id="b", artist="B1", title="t", vote_count=3)
|
||||
svc = _make_service(candidates=[a, b])
|
||||
community = _community({"A1": True, "B1": True})
|
||||
result = await _exec(_run(svc, _settings(enabled=True), community=community, made=False))
|
||||
assert result["status"] == "empty"
|
||||
assert set(result["flagged"]) == {"a", "b"}
|
||||
assert svc.set_review_pending.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_credit_grant_is_idempotent_on_resume():
|
||||
# Resume: request already flagged as granted → don't grant again.
|
||||
req = _request(community_credit_granted=True, status="queued")
|
||||
svc = _make_service(pick=req, get_request=req)
|
||||
svc = _make_service(candidates=[req])
|
||||
user = MagicMock()
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=user), \
|
||||
patch.object(cdp, "_create_community_job", return_value="job123"), \
|
||||
patch.object(cdp, "_search_and_download", new=AsyncMock(return_value=True)):
|
||||
await cdp.run_daily_pick()
|
||||
await _exec(_run(svc, _settings(enabled=True), user=user))
|
||||
user.add_credits.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_existing_job_not_recreated():
|
||||
req = _request(community_credit_granted=True, job_id="existing", status="in_progress")
|
||||
svc = _make_service(pick=req, get_request=req)
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=MagicMock()), \
|
||||
patch.object(cdp, "_create_community_job", return_value="SHOULD_NOT") as mk, \
|
||||
patch.object(cdp, "_search_and_download", new=AsyncMock(return_value=True)):
|
||||
result = await cdp.run_daily_pick()
|
||||
mk.assert_not_called()
|
||||
assert result["job_id"] == "existing"
|
||||
async def test_resume_finishes_locked_request_without_recheck():
|
||||
# Lock already recorded request_id → resume making it, skip candidate loop.
|
||||
req = _request(id="locked", community_credit_granted=True, job_id="existing", status="in_progress")
|
||||
lock = DailyCommunityPick(date="2026-09-03", phase="job_created", request_id="locked")
|
||||
svc = _make_service(candidates=[], lock=lock, claimed_new=False, registry={"locked": req})
|
||||
community = _community()
|
||||
result = await _exec(_run(svc, _settings(enabled=True), community=community))
|
||||
assert result["status"] == "made" and result["job_id"] == "existing"
|
||||
svc.list_pick_candidates.assert_not_called()
|
||||
community.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_credit_grant_failure_aborts_before_job():
|
||||
req = _request()
|
||||
svc = _make_service(pick=req, get_request=req)
|
||||
svc = _make_service(candidates=[req])
|
||||
user = MagicMock()
|
||||
user.add_credits.return_value = (False, 0, "denied")
|
||||
with patch.object(cdp, "get_song_request_service", return_value=svc), \
|
||||
patch.object(cdp, "get_settings", return_value=_settings(enabled=True)), \
|
||||
patch.object(cdp, "get_user_service", return_value=user), \
|
||||
patch.object(cdp, "_create_community_job", return_value="job123") as mk:
|
||||
result = await cdp.run_daily_pick()
|
||||
with patch.object(cdp, "_create_community_job", return_value="job123") as mk:
|
||||
stack = _run(svc, _settings(enabled=True), user=user, made=False)
|
||||
result = await _exec(stack)
|
||||
assert result["status"] == "error" and result["step"] == "grant_credit"
|
||||
mk.assert_not_called()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Unit tests for the admin community-review action endpoint (make/reject/keep)."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from backend.api.routes.admin import (
|
||||
CommunityReviewActionBody,
|
||||
action_community_review,
|
||||
list_community_requests,
|
||||
)
|
||||
from backend.models.song_request import SongRequest
|
||||
|
||||
|
||||
def _req(**over):
|
||||
base = dict(
|
||||
id="req1", artist="A", title="T", artist_raw="A", title_raw="T",
|
||||
dedupe_key="a|t", submitted_by="owner@x.com", source="human",
|
||||
status="open", vote_count=3, review_state="pending",
|
||||
community_versions={"best_youtube_url": "https://youtu.be/x", "tracks": []},
|
||||
)
|
||||
base.update(over)
|
||||
return SongRequest(**base)
|
||||
|
||||
|
||||
def _settings():
|
||||
return SimpleNamespace(community_review_snooze_days=30)
|
||||
|
||||
|
||||
def _patches(svc, notifier=None, provision=None):
|
||||
ps = [
|
||||
patch("backend.services.song_request_service.get_song_request_service", MagicMock(return_value=svc)),
|
||||
patch("backend.config.get_settings", MagicMock(return_value=_settings())),
|
||||
]
|
||||
if notifier is not None:
|
||||
ps.append(patch("backend.services.job_notification_service.get_job_notification_service",
|
||||
MagicMock(return_value=notifier)))
|
||||
if provision is not None:
|
||||
ps.append(patch("backend.workers.community_daily_pick._provision_and_start", provision))
|
||||
return ps
|
||||
|
||||
|
||||
async def _call(ps, request_id, action):
|
||||
for p in ps:
|
||||
p.start()
|
||||
try:
|
||||
return await action_community_review(
|
||||
request_id, CommunityReviewActionBody(action=action), auth_data=("admin", None, 0)
|
||||
)
|
||||
finally:
|
||||
for p in reversed(ps):
|
||||
p.stop()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_snoozes():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
res = await _call(_patches(svc), "req1", "keep")
|
||||
assert res.status == "snoozed"
|
||||
svc.snooze_review.assert_called_once()
|
||||
assert svc.snooze_review.call_args.args[0] == "req1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_notifies_upvoters():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
svc.list_upvoters.return_value = ["v1@x.com", "v2@x.com"]
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_existing_version_email = AsyncMock(return_value=True)
|
||||
res = await _call(_patches(svc, notifier=notifier), "req1", "reject")
|
||||
assert res.status == "rejected"
|
||||
svc.reject_request.assert_called_once_with("req1")
|
||||
urls = {c.kwargs["youtube_url"] for c in notifier.send_community_existing_version_email.call_args_list}
|
||||
assert urls == {"https://youtu.be/x"}
|
||||
assert notifier.send_community_existing_version_email.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_provisions_job():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
provision = AsyncMock(return_value={"status": "made", "job_id": "j9"})
|
||||
res = await _call(_patches(svc, provision=provision), "req1", "make")
|
||||
assert res.status == "made"
|
||||
svc.clear_review.assert_called_once_with("req1")
|
||||
provision.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_not_pending_returns_404():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req(review_state=None)
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_patches(svc), "req1", "keep")
|
||||
assert exc.value.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_failure_raises_500():
|
||||
svc = MagicMock()
|
||||
svc.get_request.return_value = _req()
|
||||
provision = AsyncMock(return_value={"status": "error", "step": "grant_credit", "message": "denied"})
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_patches(svc, provision=provision), "req1", "make")
|
||||
assert exc.value.status_code == 500
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_community_requests_maps_all_statuses():
|
||||
svc = MagicMock()
|
||||
published = _req(
|
||||
id="pub", status="published", review_state=None,
|
||||
job_id="j-abc12345", youtube_url="https://youtu.be/pub",
|
||||
owner_email="voter@x.com",
|
||||
)
|
||||
open_req = _req(id="op", status="open", review_state=None, job_id=None, youtube_url=None)
|
||||
svc.list_all.return_value = [published, open_req]
|
||||
with patch("backend.services.song_request_service.get_song_request_service",
|
||||
MagicMock(return_value=svc)):
|
||||
res = await list_community_requests(auth_data=("admin", None, 0))
|
||||
assert [r.id for r in res.requests] == ["pub", "op"]
|
||||
pub = res.requests[0]
|
||||
assert pub.status == "published"
|
||||
assert pub.youtube_url == "https://youtu.be/pub"
|
||||
assert pub.owner_email == "voter@x.com"
|
||||
assert pub.created_at is not None # datetime serialized to iso string
|
||||
# Open request carries no job/video links.
|
||||
assert res.requests[1].job_id is None and res.requests[1].youtube_url is None
|
||||
@@ -1,10 +1,14 @@
|
||||
"""Unit tests for the requests-board publish fan-out in the YouTube queue processor."""
|
||||
"""Unit tests for the requests-board publish fan-out (backend.services.community_publish).
|
||||
|
||||
The fan-out fires from BOTH publish paths (youtube_queue_processor and the direct
|
||||
video_worker distribution), so it lives in a shared module and is tested here once.
|
||||
"""
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.song_request import SongRequest
|
||||
from backend.workers import youtube_queue_processor as yqp
|
||||
from backend.services import community_publish as cp
|
||||
|
||||
|
||||
def _req(**over):
|
||||
@@ -34,7 +38,8 @@ async def test_non_community_job_is_ignored():
|
||||
notifier = MagicMock()
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
result = await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
assert result is None
|
||||
svc.mark_published.assert_not_called()
|
||||
|
||||
|
||||
@@ -47,7 +52,8 @@ async def test_publishes_and_fans_out_excluding_owner():
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
result = await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
assert result == "req1"
|
||||
svc.mark_published.assert_called_once_with("req1", "https://youtu.be/x")
|
||||
# Owner excluded (already got the completion email); two voters emailed.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
@@ -69,7 +75,7 @@ async def test_skips_already_notified_voters_and_retries_failures():
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=False) # v3 send fails
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
# Only the un-notified voter (v3) is attempted; v2 skipped.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
assert emailed == {"v3@x.com"}
|
||||
@@ -85,7 +91,97 @@ async def test_already_notified_does_not_resend():
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
svc.mark_published.assert_called_once() # republish (mark) is safe/idempotent
|
||||
notifier.send_community_track_live_email.assert_not_called()
|
||||
svc.mark_voters_notified.assert_not_called()
|
||||
|
||||
|
||||
# --- youtube-url resolution ---------------------------------------------------
|
||||
|
||||
def test_youtube_url_prefers_state_data():
|
||||
job = MagicMock()
|
||||
job.state_data = {"youtube_url": "https://youtu.be/state"}
|
||||
job.processing_metadata = {"distribution": {"youtube_video_url": "https://youtu.be/dist"}}
|
||||
assert cp._youtube_url_for_job(job) == "https://youtu.be/state"
|
||||
|
||||
|
||||
def test_youtube_url_falls_back_to_distribution_metadata():
|
||||
job = MagicMock()
|
||||
job.state_data = {}
|
||||
job.processing_metadata = {"distribution": {"youtube_video_url": "https://youtu.be/dist"}}
|
||||
assert cp._youtube_url_for_job(job) == "https://youtu.be/dist"
|
||||
|
||||
|
||||
def test_youtube_url_none_when_unpublished():
|
||||
job = MagicMock()
|
||||
job.state_data = {}
|
||||
job.processing_metadata = {"distribution": {}}
|
||||
assert cp._youtube_url_for_job(job) is None
|
||||
assert cp._youtube_url_for_job(None) is None
|
||||
|
||||
|
||||
# --- reconcile / backfill -----------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_publishes_live_in_progress_requests():
|
||||
svc = MagicMock()
|
||||
live = _req(id="r-live", job_id="j-live", voters_notified=True)
|
||||
unpub = _req(id="r-unpub", job_id="j-unpub", voters_notified=True)
|
||||
nojob = _req(id="r-nojob", job_id=None)
|
||||
svc.list_in_progress.return_value = [live, unpub, nojob]
|
||||
svc.list_published_unnotified.return_value = []
|
||||
# get_by_job_id (used inside notify_community_publish) resolves the live request.
|
||||
svc.get_by_job_id.side_effect = lambda jid: {"j-live": live}.get(jid)
|
||||
|
||||
live_job = MagicMock(state_data={"youtube_url": "https://youtu.be/live"}, processing_metadata={})
|
||||
unpub_job = MagicMock(state_data={}, processing_metadata={"distribution": {}})
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.side_effect = lambda jid: {"j-live": live_job, "j-unpub": unpub_job}.get(jid)
|
||||
|
||||
with patch.multiple(
|
||||
"backend.services.song_request_service",
|
||||
get_song_request_service=MagicMock(return_value=svc),
|
||||
), patch("backend.services.job_manager.JobManager", MagicMock(return_value=jm)):
|
||||
result = await cp.reconcile_community_publishes()
|
||||
|
||||
assert result["scanned"] == 3
|
||||
published_ids = {p["request_id"] for p in result["published"]}
|
||||
assert published_ids == {"r-live"}
|
||||
assert result["retried_fanout"] == 0
|
||||
svc.mark_published.assert_called_once_with("r-live", "https://youtu.be/live")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_retries_published_but_unnotified_fanout():
|
||||
# A published pick whose voter fan-out never completed is retried using the
|
||||
# URL already on the request (no job lookup needed).
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = []
|
||||
stuck = _req(
|
||||
id="r-stuck", job_id="j-stuck", status="published",
|
||||
youtube_url="https://youtu.be/stuck", voters_notified=False,
|
||||
)
|
||||
svc.list_published_unnotified.return_value = [stuck]
|
||||
svc.get_by_job_id.side_effect = lambda jid: {"j-stuck": stuck}.get(jid)
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com"]
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = None # not needed — request already carries the URL
|
||||
|
||||
with patch.multiple(
|
||||
"backend.services.song_request_service",
|
||||
get_song_request_service=MagicMock(return_value=svc),
|
||||
), patch(
|
||||
"backend.services.job_notification_service.get_job_notification_service",
|
||||
MagicMock(return_value=notifier),
|
||||
), patch("backend.services.job_manager.JobManager", MagicMock(return_value=jm)):
|
||||
result = await cp.reconcile_community_publishes()
|
||||
|
||||
assert result["retried_fanout"] == 1
|
||||
# The un-notified voter (not the owner) gets emailed on the retry.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
assert emailed == {"v2@x.com"}
|
||||
@@ -98,7 +98,7 @@ class TestDiscordNotificationServicePostMessage:
|
||||
assert result is True
|
||||
mock_post.assert_called_once_with(
|
||||
url,
|
||||
json={"content": "Test message"},
|
||||
json={"content": "Test message", "allowed_mentions": {"parse": []}},
|
||||
timeout=30
|
||||
)
|
||||
|
||||
@@ -117,7 +117,7 @@ class TestDiscordNotificationServicePostMessage:
|
||||
assert result is True
|
||||
mock_post.assert_called_once_with(
|
||||
custom_url,
|
||||
json={"content": "Test message"},
|
||||
json={"content": "Test message", "allowed_mentions": {"parse": []}},
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
@@ -155,6 +155,92 @@ class TestPostmarkEmailProvider:
|
||||
|
||||
assert result is False
|
||||
|
||||
def test_suppressed_recipient_flagged_and_not_error(self):
|
||||
"""422 ErrorCode 406 (InactiveRecipient) is benign: SendResult.suppressed
|
||||
is True, provider.last_suppressed is True, and it's logged at INFO not ERROR."""
|
||||
import logging
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._mock_response(
|
||||
422, body={"ErrorCode": 406, "Message": "Inactive recipient"}
|
||||
)
|
||||
with self._capture_logs(logging.ERROR) as errors:
|
||||
result = provider.send_email_detailed(
|
||||
to_email="whatever@example.com",
|
||||
subject="Test",
|
||||
html_content="<p>x</p>",
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
assert result.suppressed is True
|
||||
assert provider.last_suppressed is True
|
||||
# No ERROR-level log for a suppressed recipient (it must not page).
|
||||
assert not errors
|
||||
|
||||
def test_non_suppression_422_is_not_flagged_suppressed(self):
|
||||
"""A 422 with a different ErrorCode (e.g. bad signature) is a real error:
|
||||
suppressed stays False and last_suppressed stays False."""
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._mock_response(
|
||||
422, body={"ErrorCode": 10, "Message": "Invalid API token"}
|
||||
)
|
||||
result = provider.send_email_detailed(
|
||||
to_email="user@example.com",
|
||||
subject="Test",
|
||||
html_content="<p>x</p>",
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
assert result.suppressed is False
|
||||
assert provider.last_suppressed is False
|
||||
|
||||
def test_last_suppressed_reset_on_success(self):
|
||||
"""last_suppressed is cleared on a subsequent successful send."""
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._mock_response(
|
||||
422, body={"ErrorCode": 406, "Message": "Inactive recipient"}
|
||||
)
|
||||
provider.send_email_detailed(
|
||||
to_email="whatever@example.com", subject="s", html_content="<p>x</p>"
|
||||
)
|
||||
assert provider.last_suppressed is True
|
||||
|
||||
mock_post.return_value = self._mock_response(200)
|
||||
provider.send_email_detailed(
|
||||
to_email="ok@example.com", subject="s", html_content="<p>x</p>"
|
||||
)
|
||||
assert provider.last_suppressed is False
|
||||
|
||||
@staticmethod
|
||||
def _capture_logs(level):
|
||||
"""Context manager capturing records at >= level from the email_service logger."""
|
||||
import contextlib
|
||||
import logging
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _cm():
|
||||
logger = logging.getLogger("backend.services.email_service")
|
||||
records: list = []
|
||||
|
||||
class _H(logging.Handler):
|
||||
def emit(self, record):
|
||||
if record.levelno >= level:
|
||||
records.append(record)
|
||||
|
||||
h = _H()
|
||||
logger.addHandler(h)
|
||||
try:
|
||||
yield records
|
||||
finally:
|
||||
logger.removeHandler(h)
|
||||
|
||||
return _cm()
|
||||
|
||||
def test_send_email_request_exception(self):
|
||||
import requests as _requests
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
@@ -189,6 +275,25 @@ class TestEmailServiceProviderSelection:
|
||||
assert isinstance(svc.provider, ConsoleEmailProvider)
|
||||
assert svc.is_configured() is False
|
||||
|
||||
def test_last_send_suppressed_wired_through_send_magic_link(self, monkeypatch):
|
||||
"""A suppressed recipient surfaces on EmailService.last_send_suppressed so
|
||||
route handlers can log it at INFO instead of a scary ERROR."""
|
||||
monkeypatch.setenv("POSTMARK_SERVER_TOKEN", "pm-token")
|
||||
svc = EmailService()
|
||||
|
||||
def _suppressed_response(*args, **kwargs):
|
||||
resp = Mock()
|
||||
resp.status_code = 422
|
||||
resp.json.return_value = {"ErrorCode": 406, "Message": "Inactive recipient"}
|
||||
resp.text = ""
|
||||
return resp
|
||||
|
||||
with patch("backend.services.email_service.requests.post", side_effect=_suppressed_response):
|
||||
sent = svc.send_magic_link("whatever@example.com", "tok123")
|
||||
|
||||
assert sent is False
|
||||
assert svc.last_send_suppressed is True
|
||||
|
||||
|
||||
class TestEmailServiceJobCompletion:
|
||||
"""Tests for job completion email method."""
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Contract test: replay golden GCE worker responses through the real encode path.
|
||||
|
||||
This is the "kill mock drift" backstop (hardening plan P3). Every encoding mock
|
||||
in the suite is hand-authored, and the real "cached / empty" response shape was
|
||||
simply never in the corpus — the textbook cause of NOMAD-1632's Failure B. Here
|
||||
we capture the *real* worker response shapes as golden JSON fixtures
|
||||
(``backend/tests/fixtures/encoding/``) and replay them through the real
|
||||
``classify_encoded_output`` and ``GCEEncodingBackend.encode()`` so the classifier
|
||||
and the completeness guard are exercised against the actual contract.
|
||||
|
||||
Kept lightweight and deterministic: no network, no GCS, no filesystem writes —
|
||||
the only boundary patched is the worker call (``encode_videos``).
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from backend.services.encoding_interface import (
|
||||
GceEncodeResponse,
|
||||
GCEEncodingBackend,
|
||||
EncodingInput,
|
||||
classify_encoded_output,
|
||||
)
|
||||
|
||||
FIXTURES_DIR = Path(__file__).parent / "fixtures" / "encoding"
|
||||
|
||||
# The four formats GCEEncodingBackend.encode() always requests (and the guard
|
||||
# enforces). Keep in sync with encoding_interface.encode().
|
||||
REQUESTED_FORMATS = {"mp4_4k_lossless", "mp4_4k_lossy", "mkv_4k", "mp4_720p"}
|
||||
|
||||
|
||||
def _load(name: str) -> GceEncodeResponse:
|
||||
with open(FIXTURES_DIR / f"{name}.json") as fh:
|
||||
return json.load(fh)
|
||||
|
||||
|
||||
async def _run_encode(response: GceEncodeResponse):
|
||||
"""Drive the REAL encode() with a mocked worker returning ``response``."""
|
||||
backend = GCEEncodingBackend(logger=MagicMock())
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value=response)
|
||||
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/tmp/title.mov",
|
||||
karaoke_video_path="/tmp/karaoke.mkv",
|
||||
instrumental_audio_path="/tmp/audio.flac",
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
options={
|
||||
"job_id": "NOMAD-1632",
|
||||
"input_gcs_path": "gs://bucket/jobs/NOMAD-1632/",
|
||||
"output_gcs_path": "gs://bucket/jobs/NOMAD-1632/finals/",
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"backend.services.encoding_service.get_encoding_service",
|
||||
return_value=mock_service,
|
||||
):
|
||||
return await backend.encode(input_config)
|
||||
|
||||
|
||||
class TestEncodingResponseContract:
|
||||
"""Replay golden fixtures through the real classifier + encode()."""
|
||||
|
||||
ALL_FIXTURES = ["success", "cached", "empty", "partial", "malformed"]
|
||||
|
||||
@pytest.mark.parametrize("name", ALL_FIXTURES)
|
||||
def test_fixture_conforms_to_schema(self, name):
|
||||
"""Every fixture matches the GceEncodeResponse contract keys/types."""
|
||||
data = _load(name)
|
||||
assert set(data).issubset(set(GceEncodeResponse.__annotations__)), (
|
||||
f"{name}.json has keys outside GceEncodeResponse"
|
||||
)
|
||||
assert isinstance(data["status"], str)
|
||||
assert isinstance(data["output_files"], list)
|
||||
assert all(isinstance(p, str) for p in data["output_files"])
|
||||
|
||||
def test_classify_success_fixture(self):
|
||||
"""NOMAD-1632 regression: 'Portrait of Jennie' 720p must NOT misclassify
|
||||
as the portrait video — classification keys off the trailing tag."""
|
||||
files = _load("success")["output_files"]
|
||||
classified = {classify_encoded_output(p) for p in files}
|
||||
assert classified == REQUESTED_FORMATS
|
||||
# The 720p whose TITLE contains 'Portrait' maps to mp4_720p, not portrait_mp4.
|
||||
seven20 = next(p for p in files if "720p" in p)
|
||||
assert classify_encoded_output(seven20) == "mp4_720p"
|
||||
|
||||
def test_classify_cached_fixture_covers_all_branches(self):
|
||||
"""The cached full-set fixture exercises every classifier branch."""
|
||||
files = _load("cached")["output_files"]
|
||||
classified = {classify_encoded_output(p) for p in files}
|
||||
assert classified == REQUESTED_FORMATS | {
|
||||
"portrait_mp4",
|
||||
"with_vocals_mp4",
|
||||
"title_mov",
|
||||
"end_mov",
|
||||
"cdg_zip",
|
||||
}
|
||||
|
||||
def test_classify_malformed_fixture_classified_out(self):
|
||||
"""Stray / wrong-extension names classify to None (no false slotting)."""
|
||||
files = _load("malformed")["output_files"]
|
||||
assert all(classify_encoded_output(p) is None for p in files)
|
||||
# Specifically: a 720p tag with the wrong extension must be rejected.
|
||||
wrong_ext = next(p for p in files if p.endswith(".webm"))
|
||||
assert classify_encoded_output(wrong_ext) is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_success_fixture(self):
|
||||
out = await _run_encode(_load("success"))
|
||||
assert out.success is True
|
||||
assert out.lossy_720p_mp4_path is not None
|
||||
assert set(out.output_files) == REQUESTED_FORMATS
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_cached_fixture(self):
|
||||
out = await _run_encode(_load("cached"))
|
||||
assert out.success is True
|
||||
assert out.portrait_mp4_path is not None
|
||||
assert out.with_vocals_mp4_path is not None
|
||||
assert REQUESTED_FORMATS.issubset(set(out.output_files))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_empty_fixture_is_recoverable(self):
|
||||
"""Empty output_files must NOT trip the guard — it's recoverable
|
||||
(stale cache) and the orchestrator re-encodes. Failure B defense."""
|
||||
out = await _run_encode(_load("empty"))
|
||||
assert out.success is True
|
||||
assert out.output_files == {}
|
||||
assert out.error_message is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_partial_fixture_trips_guard(self):
|
||||
"""Partial (720p missing) must fail loud. Failure A defense."""
|
||||
out = await _run_encode(_load("partial"))
|
||||
assert out.success is False
|
||||
assert "mp4_720p" in out.error_message
|
||||
assert "incomplete" in out.error_message.lower()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_malformed_fixture_treated_as_empty(self):
|
||||
"""Nothing classifies into a slot → treated as empty (no guard trip,
|
||||
no crash), which the orchestrator then recovers from as a stale cache."""
|
||||
out = await _run_encode(_load("malformed"))
|
||||
assert out.success is True
|
||||
assert out.output_files == {}
|
||||
assert out.error_message is None
|
||||
@@ -16,10 +16,62 @@ from backend.services.encoding_interface import (
|
||||
EncodingBackend,
|
||||
LocalEncodingBackend,
|
||||
GCEEncodingBackend,
|
||||
classify_encoded_output,
|
||||
get_encoding_backend,
|
||||
)
|
||||
|
||||
|
||||
class TestClassifyEncodedOutput:
|
||||
"""Format classification must key off the trailing (format) parenthetical only,
|
||||
never the artist/title text — the NOMAD-1632 root cause."""
|
||||
|
||||
def test_720p_of_portrait_titled_song_is_not_misfiled_as_portrait(self):
|
||||
"""Regression for NOMAD-1632: 'Portrait of Jennie' 720p → mp4_720p, NOT portrait."""
|
||||
f = "Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4"
|
||||
assert classify_encoded_output(f) == "mp4_720p"
|
||||
|
||||
def test_real_portrait_video_classifies_as_portrait(self):
|
||||
f = "Nat King Cole - Portrait of Jennie (Final Karaoke Portrait 1080x1920).mp4"
|
||||
assert classify_encoded_output(f) == "portrait_mp4"
|
||||
|
||||
def test_4k_variants_of_portrait_titled_song(self):
|
||||
base = "Nat King Cole - Portrait of Jennie"
|
||||
assert classify_encoded_output(f"{base} (Final Karaoke Lossless 4k).mp4") == "mp4_4k_lossless"
|
||||
assert classify_encoded_output(f"{base} (Final Karaoke Lossless 4k).mkv") == "mkv_4k"
|
||||
assert classify_encoded_output(f"{base} (Final Karaoke Lossy 4k).mp4") == "mp4_4k_lossy"
|
||||
|
||||
def test_title_with_4k_or_720p_words_does_not_leak(self):
|
||||
"""A title literally containing '720p' must not steal the 4k lossy classification."""
|
||||
assert classify_encoded_output("DJ 720p - 4k Dreams (Final Karaoke Lossy 4k).mp4") == "mp4_4k_lossy"
|
||||
assert classify_encoded_output("DJ 720p - 4k Dreams (Final Karaoke Lossy 720p).mp4") == "mp4_720p"
|
||||
|
||||
def test_short_canonical_names(self):
|
||||
assert classify_encoded_output("jobs/x/finals/lossy_720p_mp4.mp4") == "mp4_720p"
|
||||
assert classify_encoded_output("jobs/x/finals/lossy_4k_mp4.mp4") == "mp4_4k_lossy"
|
||||
assert classify_encoded_output("jobs/x/finals/lossless_4k_mkv.mkv") == "mkv_4k"
|
||||
assert classify_encoded_output("jobs/x/finals/portrait_1080x1920.mp4") == "portrait_mp4"
|
||||
assert classify_encoded_output("jobs/x/packages/cdg_zip.zip") == "cdg_zip"
|
||||
assert classify_encoded_output("jobs/x/packages/txt_zip.zip") == "txt_zip"
|
||||
|
||||
def test_screens_and_unknown(self):
|
||||
assert classify_encoded_output("Artist - Title (Title).mov") == "title_mov"
|
||||
assert classify_encoded_output("Artist - Title (End).mov") == "end_mov"
|
||||
assert classify_encoded_output("Artist - Title (Karaoke).mp4") is None
|
||||
|
||||
def test_stray_files_do_not_slip_into_a_format_slot(self):
|
||||
"""Extension is pinned per format, and a file without a format parenthetical
|
||||
is unrecognised — so a stray file whose name merely contains a format word
|
||||
can't be misclassified and then falsely satisfy the completeness guard."""
|
||||
# Format word in the artist/title but wrong extension / no format tag.
|
||||
assert classify_encoded_output("Artist 720p notes.txt") is None
|
||||
assert classify_encoded_output("Artist - 720p Dreams.mp4") is None
|
||||
# Right tag, wrong extension.
|
||||
assert classify_encoded_output("Artist - Title (Final Karaoke Lossy 720p).mkv") is None
|
||||
assert classify_encoded_output("Artist - Title (Final Karaoke Lossless 4k).mov") is None
|
||||
# Short canonical name with a mismatched extension is rejected too.
|
||||
assert classify_encoded_output("jobs/x/finals/lossy_720p_mp4.mkv") is None
|
||||
|
||||
|
||||
class TestEncodingInput:
|
||||
"""Test EncodingInput dataclass."""
|
||||
|
||||
@@ -261,8 +313,12 @@ class TestGCEEncodingBackend:
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
# A healthy worker returns every requested format (see the completeness
|
||||
# guard in GCEEncodingBackend.encode).
|
||||
"output_files": {
|
||||
"mp4_4k_lossless": "gs://bucket/output/lossless.mp4",
|
||||
"mp4_4k_lossy": "gs://bucket/output/lossy.mp4",
|
||||
"mkv_4k": "gs://bucket/output/lossless.mkv",
|
||||
"mp4_720p": "gs://bucket/output/720p.mp4",
|
||||
}
|
||||
})
|
||||
@@ -288,6 +344,130 @@ class TestGCEEncodingBackend:
|
||||
assert output.encoding_backend == "gce"
|
||||
mock_service.encode_videos.assert_called_once()
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_portrait_titled_song_maps_720p(self, mock_get_service):
|
||||
"""Regression for NOMAD-1632: a song titled 'Portrait of Jennie' must still
|
||||
map its 720p to lossy_720p_mp4_path (not silently drop it as the portrait
|
||||
video), so the completeness guard passes and the 720p publishes."""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 4k).mp4",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Lossy 720p).mp4",
|
||||
"jobs/j/finals/Nat King Cole - Portrait of Jennie (Final Karaoke Portrait 1080x1920).mp4",
|
||||
],
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
options={
|
||||
"job_id": "j",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is True
|
||||
assert output.lossy_720p_mp4_path.endswith("(Final Karaoke Lossy 720p).mp4")
|
||||
assert output.portrait_mp4_path.endswith("(Final Karaoke Portrait 1080x1920).mp4")
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_fails_on_incomplete_output(self, mock_get_service):
|
||||
"""A worker that returns fewer formats than requested must fail loud.
|
||||
|
||||
Regression for the NOMAD-1632 MP4-720p sequence gap (2026-09-11): a
|
||||
fallback encoding worker returned the 4K + MKV finals but silently omitted
|
||||
the 720p, and the pipeline published an incomplete public release. Only the
|
||||
daily GDrive validator caught the gap ~24h later. The completeness guard
|
||||
must refuse a partial result so the job errors and is retried instead of
|
||||
publishing a track with no 720p.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
# Worker returned everything EXCEPT the 720p — exactly the NOMAD-1632 case.
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
|
||||
],
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
assert output.success is False
|
||||
assert "mp4_720p" in output.error_message
|
||||
# The formats that DID come back are still reported for debugging.
|
||||
assert output.output_files.get("mp4_4k_lossy")
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_empty_result_does_not_trip_completeness_guard(self, mock_get_service):
|
||||
"""An EMPTY result must NOT hard-fail via the completeness guard.
|
||||
|
||||
Regression for the v0.222.3 outage: a stale GCE job cache returns
|
||||
output_files=[] (finals deleted from GCS on an admin reset / re-run). The
|
||||
orchestrator recovers from this by downloading zero files, raising a
|
||||
"stale" RuntimeError, and re-encoding under a fresh job id. The guard must
|
||||
only fire on a PARTIAL result — an empty result must return success=True so
|
||||
that recovery path runs instead of a hard failure.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(return_value={
|
||||
"status": "cached",
|
||||
"output_files": [],
|
||||
})
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
output = await backend.encode(input_config)
|
||||
|
||||
# Not blocked by the guard: the orchestrator's stale-cache re-encode handles it.
|
||||
assert output.success is True
|
||||
assert output.output_files == {}
|
||||
assert output.lossy_720p_mp4_path is None
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_failure(self, mock_get_service):
|
||||
@@ -353,9 +533,15 @@ class TestGCEEncodingBackend:
|
||||
when GCE worker returns a list instead of a dict.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
# Simulate GCE worker returning a list instead of dict
|
||||
# Simulate GCE worker returning a list instead of dict (with a complete
|
||||
# format set so the completeness guard passes and we isolate list handling).
|
||||
mock_service.encode_videos = AsyncMock(return_value=[
|
||||
{"output_files": {"mp4_4k_lossless": "gs://bucket/output/lossless.mp4"}}
|
||||
{"output_files": {
|
||||
"mp4_4k_lossless": "gs://bucket/output/lossless.mp4",
|
||||
"mp4_4k_lossy": "gs://bucket/output/lossy.mp4",
|
||||
"mkv_4k": "gs://bucket/output/lossless.mkv",
|
||||
"mp4_720p": "gs://bucket/output/720p.mp4",
|
||||
}}
|
||||
])
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
@@ -441,6 +627,9 @@ class TestGCEEncodingBackend:
|
||||
"status": "complete",
|
||||
"output_files": [
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
|
||||
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
|
||||
"jobs/test/finals/Artist - Title (Title).mov",
|
||||
"jobs/test/finals/Artist - Title (End).mov",
|
||||
]
|
||||
|
||||
@@ -1,219 +1,72 @@
|
||||
"""Route tests for the encoding-worker warmup/heartbeat endpoints.
|
||||
|
||||
Regression context (2026-09-19): these handlers called sync manager methods
|
||||
(Firestore + GCE compute API, 10s+) directly in async handlers, freezing the
|
||||
single event loop — every other request on the instance (the same review
|
||||
page's audio/lyrics loads!) stalled behind a cold-VM warmup. They must run
|
||||
their manager work via asyncio.to_thread.
|
||||
"""
|
||||
Unit tests for encoding worker lifecycle endpoints.
|
||||
|
||||
Tests the warmup and heartbeat API endpoints.
|
||||
|
||||
These endpoints are called from the customer-facing lyrics-review page to
|
||||
pre-warm the encoding VM. They are therefore gated on ``require_review_auth``
|
||||
(review access to a specific job), NOT ``require_admin`` — otherwise every
|
||||
non-admin customer 403s and the pre-warm silently never happens (the bug this
|
||||
suite guards against).
|
||||
"""
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import MagicMock
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.api.routes.encoding_worker import router, get_worker_manager
|
||||
from backend.api.dependencies import require_admin, require_review_auth
|
||||
from backend.services.encoding_errors import (
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
)
|
||||
|
||||
JOB_ID = "test-job-123"
|
||||
WARMUP_URL = f"/api/internal/encoding-worker/warmup/{JOB_ID}"
|
||||
HEARTBEAT_URL = f"/api/internal/encoding-worker/heartbeat/{JOB_ID}"
|
||||
from backend.api.routes import encoding_worker
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
|
||||
|
||||
async def fake_review_auth():
|
||||
"""Override for require_review_auth — stands in for a review user.
|
||||
|
||||
Deliberately returns a *non-admin* auth result (auth_type="full") so the
|
||||
tests exercise the review-scoped path, not admin access.
|
||||
"""
|
||||
return (JOB_ID, "full")
|
||||
|
||||
|
||||
class TestWarmupEndpoint:
|
||||
def setup_method(self):
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_warmup_starts_stopped_vm(self):
|
||||
self.mock_manager.ensure_primary_running.return_value = {
|
||||
"started": True,
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["started"] is True
|
||||
assert data["vm_name"] == "encoding-worker-a"
|
||||
|
||||
def test_warmup_already_running(self):
|
||||
self.mock_manager.ensure_primary_running.return_value = {
|
||||
"started": False,
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
|
||||
def test_warmup_handles_error(self):
|
||||
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
|
||||
"VM not found"
|
||||
)
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
assert "error" in response.json()
|
||||
|
||||
def test_warmup_503_start_failure_logged_as_warning(self, caplog):
|
||||
"""A transient 503/start failure must NOT log at ERROR.
|
||||
|
||||
The encoding flow falls back to alternate-zone workers, so this is a
|
||||
self-healing event. Logging it at ERROR trips the production error
|
||||
monitor (severity>=ERROR) and pages us for a non-incident.
|
||||
"""
|
||||
self.mock_manager.ensure_primary_running.side_effect = (
|
||||
EncodingWorkerStartError(
|
||||
"VM encoding-worker-b start failed in us-central1-c: "
|
||||
"503 — SERVICE UNAVAILABLE",
|
||||
vm_name="encoding-worker-b",
|
||||
zone="us-central1-c",
|
||||
)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
warmup_records = [
|
||||
r for r in caplog.records if "warmup failed" in r.getMessage()
|
||||
]
|
||||
assert warmup_records, "expected a warmup-failure log record"
|
||||
assert all(r.levelno == logging.WARNING for r in warmup_records)
|
||||
# And nothing from this endpoint should be at ERROR.
|
||||
assert not [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.ERROR
|
||||
and r.name == "backend.api.routes.encoding_worker"
|
||||
]
|
||||
|
||||
def test_warmup_capacity_error_logged_as_warning(self, caplog):
|
||||
"""Capacity exhaustion is also self-healing → WARNING, not ERROR."""
|
||||
self.mock_manager.ensure_primary_running.side_effect = (
|
||||
EncodingWorkerCapacityError(
|
||||
"VM encoding-worker-b could not be started in us-central1-c: "
|
||||
"ZONE_RESOURCE_POOL_EXHAUSTED",
|
||||
vm_name="encoding-worker-b",
|
||||
zone="us-central1-c",
|
||||
code="ZONE_RESOURCE_POOL_EXHAUSTED",
|
||||
)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert not [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.ERROR
|
||||
and r.name == "backend.api.routes.encoding_worker"
|
||||
]
|
||||
|
||||
def test_warmup_unexpected_error_still_logged_as_error(self, caplog):
|
||||
"""Genuinely unexpected failures must still surface at ERROR."""
|
||||
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
|
||||
"misconfigured service account"
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
error_records = [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.ERROR
|
||||
and r.name == "backend.api.routes.encoding_worker"
|
||||
]
|
||||
assert error_records, "unexpected errors must remain at ERROR severity"
|
||||
|
||||
|
||||
class TestHeartbeatEndpoint:
|
||||
def setup_method(self):
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_heartbeat_updates_activity(self):
|
||||
response = self.client.post(HEARTBEAT_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
self.mock_manager.update_activity.assert_called_once()
|
||||
|
||||
def test_heartbeat_handles_error(self):
|
||||
self.mock_manager.update_activity.side_effect = RuntimeError(
|
||||
"Firestore error"
|
||||
)
|
||||
response = self.client.post(HEARTBEAT_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "error"
|
||||
|
||||
|
||||
class TestReviewAuthGating:
|
||||
"""Regression guard: these endpoints must be review-auth gated, not admin.
|
||||
|
||||
Before this fix they used ``require_admin``, so every non-admin customer on
|
||||
the lyrics-review page got a 403 and the JIT pre-warm never happened.
|
||||
"""
|
||||
|
||||
def test_routes_depend_on_review_auth_not_admin(self):
|
||||
"""The route dependencies reference require_review_auth, never require_admin."""
|
||||
deps = set()
|
||||
for route in router.routes:
|
||||
dependant = getattr(route, "dependant", None)
|
||||
if dependant is None:
|
||||
continue
|
||||
# Flatten the whole dependency tree for the route.
|
||||
stack = list(dependant.dependencies)
|
||||
while stack:
|
||||
d = stack.pop()
|
||||
deps.add(d.call)
|
||||
stack.extend(d.dependencies)
|
||||
assert require_review_auth in deps, (
|
||||
"warmup/heartbeat must be gated on require_review_auth"
|
||||
)
|
||||
assert require_admin not in deps, (
|
||||
"warmup/heartbeat must NOT require admin (regresses pre-warm for "
|
||||
"all non-admin customers)"
|
||||
class TestWarmupHandler:
|
||||
def _run(self, manager):
|
||||
return asyncio.run(
|
||||
encoding_worker.warmup_encoding_worker("job-1", ("admin", "full"), manager)
|
||||
)
|
||||
|
||||
def test_unauthenticated_request_is_rejected(self):
|
||||
"""With real auth (no override, no token), warmup is rejected — not 200/500."""
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
|
||||
client = TestClient(app, raise_server_exceptions=False)
|
||||
response = client.post(WARMUP_URL)
|
||||
# require_review_auth with no credentials raises 401.
|
||||
assert response.status_code == 401
|
||||
def test_success_passthrough(self):
|
||||
manager = MagicMock()
|
||||
manager.ensure_primary_running.return_value = {"started": True, "vm_name": "encoding-worker-a"}
|
||||
assert self._run(manager)["started"] is True
|
||||
|
||||
def test_job_id_is_required_in_path(self):
|
||||
"""The old job-less path no longer exists (404), forcing job scoping."""
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
|
||||
client = TestClient(app)
|
||||
response = client.post("/api/internal/encoding-worker/warmup")
|
||||
assert response.status_code == 404
|
||||
def test_start_error_is_soft(self):
|
||||
manager = MagicMock()
|
||||
manager.ensure_primary_running.side_effect = EncodingWorkerStartError("zone exhausted")
|
||||
result = self._run(manager)
|
||||
assert result["started"] is False
|
||||
assert "zone exhausted" in result["error"]
|
||||
|
||||
def test_slow_manager_does_not_block_event_loop(self):
|
||||
"""The whole point of the fix: a slow warmup must not freeze the loop."""
|
||||
manager = MagicMock()
|
||||
|
||||
def slow_warmup():
|
||||
time.sleep(0.5)
|
||||
return {"started": False}
|
||||
|
||||
manager.ensure_primary_running.side_effect = slow_warmup
|
||||
|
||||
async def scenario():
|
||||
ticks = 0
|
||||
|
||||
async def ticker():
|
||||
nonlocal ticks
|
||||
while True:
|
||||
ticks += 1
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
t = asyncio.create_task(ticker())
|
||||
await encoding_worker.warmup_encoding_worker("job-1", ("admin", "full"), manager)
|
||||
t.cancel()
|
||||
return ticks
|
||||
|
||||
# With the sync-on-loop bug, the ticker would run ~0 times during the
|
||||
# 0.5s warmup; off-loop it keeps ticking throughout.
|
||||
assert asyncio.run(scenario()) >= 5
|
||||
|
||||
|
||||
class TestHeartbeatHandler:
|
||||
def test_ok(self):
|
||||
manager = MagicMock()
|
||||
result = asyncio.run(
|
||||
encoding_worker.heartbeat_encoding_worker("job-1", ("admin", "full"), manager)
|
||||
)
|
||||
assert result == {"status": "ok"}
|
||||
manager.update_activity.assert_called_once()
|
||||
@@ -829,6 +829,150 @@ class TestFlacfetchRetryLogic:
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
|
||||
class TestFlacfetchSearchRetryLogic:
|
||||
"""Test retry logic for flacfetch search (lighter profile than downloads)."""
|
||||
|
||||
@staticmethod
|
||||
def _mock_settings():
|
||||
mock_settings = Mock()
|
||||
# Heavy download retry settings - search must NOT use these
|
||||
mock_settings.flacfetch_retry_max_attempts = 9
|
||||
mock_settings.flacfetch_retry_min_wait = 10.0
|
||||
mock_settings.flacfetch_retry_max_wait = 60.0
|
||||
# Light search retry settings
|
||||
mock_settings.flacfetch_search_retry_max_attempts = 2
|
||||
mock_settings.flacfetch_search_retry_wait = 0.01 # Fast for testing
|
||||
mock_settings.flacfetch_search_total_timeout = 5.0
|
||||
return mock_settings
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_retries_on_read_timeout(self):
|
||||
"""Test search retries on ReadTimeout and succeeds on second attempt."""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"search_id": "s1", "results": [{"index": 0}]}
|
||||
mock_response.raise_for_status = Mock()
|
||||
|
||||
mock_client.post.side_effect = [
|
||||
httpx.ReadTimeout("timed out"),
|
||||
mock_response,
|
||||
]
|
||||
|
||||
result = await client.search("ABBA", "Waterloo")
|
||||
|
||||
assert result["search_id"] == "s1"
|
||||
assert mock_client.post.call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_fails_after_max_attempts(self):
|
||||
"""Test search raises FlacfetchServiceError after exhausting its 2 attempts.
|
||||
|
||||
Also verifies search uses the light search retry settings (2 attempts),
|
||||
not the heavy download settings (9 attempts).
|
||||
"""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_client.post.side_effect = httpx.ReadTimeout("timed out")
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="Search request failed"):
|
||||
await client.search("ABBA", "Waterloo")
|
||||
|
||||
assert mock_client.post.call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_no_retry_on_4xx(self):
|
||||
"""Test search does NOT retry on 4xx client errors (other than 404)."""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 400
|
||||
mock_response.text = "Bad request"
|
||||
mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
|
||||
"Bad request",
|
||||
request=Mock(),
|
||||
response=mock_response,
|
||||
)
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="400"):
|
||||
await client.search("ABBA", "Waterloo")
|
||||
|
||||
assert mock_client.post.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_total_timeout_enforced(self):
|
||||
"""Test the total search budget caps retries below the Cloudflare edge
|
||||
deadline, surfacing a clean FlacfetchServiceError instead of hanging."""
|
||||
mock_settings = self._mock_settings()
|
||||
mock_settings.flacfetch_search_total_timeout = 0.05
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
async def hang(*args, **kwargs):
|
||||
await asyncio.sleep(10)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
mock_client.post.side_effect = hang
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="timed out.*total"):
|
||||
await asyncio.wait_for(client.search("ABBA", "Waterloo"), timeout=2)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_404_returns_empty_without_retry(self):
|
||||
"""Test 404 (no results) still returns empty results, without retrying."""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 404
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
result = await client.search("Unknown", "Nothing")
|
||||
|
||||
assert result["results"] == []
|
||||
assert result["search_id"] is None
|
||||
assert mock_client.post.call_count == 1
|
||||
|
||||
|
||||
class TestFormatHttpxError:
|
||||
"""Test _format_httpx_error helper for descriptive error messages."""
|
||||
|
||||
|
||||
@@ -341,3 +341,26 @@ class TestWorkerIdempotency:
|
||||
data = response.json()
|
||||
assert data["status"] == "not_found"
|
||||
|
||||
|
||||
|
||||
class TestAutoApprovalEval:
|
||||
"""POST /api/internal/jobs/{job_id}/auto-approval-eval — admin re-evaluation."""
|
||||
|
||||
def test_eval_calls_executor_and_returns_outcome(self, client):
|
||||
with patch(
|
||||
'backend.services.auto_approval.executor.maybe_auto_complete_review',
|
||||
new=AsyncMock(return_value={"outcome": "auto_completed"}),
|
||||
) as mock_eval:
|
||||
response = client.post(
|
||||
"/api/internal/jobs/test123/auto-approval-eval",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["job_id"] == "test123"
|
||||
assert data["outcome"] == "auto_completed"
|
||||
mock_eval.assert_awaited_once_with("test123", trigger="admin_eval")
|
||||
|
||||
def test_eval_requires_admin(self, client):
|
||||
response = client.post("/api/internal/jobs/test123/auto-approval-eval")
|
||||
assert response.status_code == 401
|
||||
@@ -1,263 +1,169 @@
|
||||
"""
|
||||
Tests for the karaokenerds service — HTML parsing, community detection, YouTube URL cleanup.
|
||||
Tests for the karaokenerds service.
|
||||
|
||||
Ported from kjbox/kj-controller/tests/unit/test_karaoke_nerds.py.
|
||||
The service reads our OWN daily-refreshed copy of the KaraokeNerds community
|
||||
catalog (a gzipped-JSON export in GCS, populated by the authorized `kn-data-sync`
|
||||
job) into an in-process index — it never scrapes or live-queries karaokenerds.com.
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import karaokenerds_service as svc
|
||||
from backend.services.karaokenerds_service import (
|
||||
parse_results,
|
||||
_clean_youtube_url,
|
||||
_parse_single_track,
|
||||
_build_index,
|
||||
_normalize_youtube_url,
|
||||
check_community_versions,
|
||||
check_community_versions_batch,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
|
||||
# --- YouTube URL cleanup ---
|
||||
# Rows mirror the community export shape: Artist, Title, Brand (a CODE), Watch.
|
||||
ROWS = [
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/aaaaaaaaaaa"},
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "OBSK",
|
||||
"Watch": "https://youtu.be/bbbbbbbbbbb"},
|
||||
# Exact duplicate (brand + url) — must collapse.
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/aaaaaaaaaaa"},
|
||||
{"Artist": "ABBA", "Title": "Dancing Queen", "Brand": "SDK",
|
||||
"Watch": "https://youtu.be/ddddddddddd"},
|
||||
# Accents + ampersand exercise the normalized match key.
|
||||
{"Artist": "Beyoncé", "Title": "Crazy in Love", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/ccccccccccc"},
|
||||
{"Artist": "Hall & Oates", "Title": "Rich Girl", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/rrrrrrrrrrr"},
|
||||
# Unknown brand code -> name falls back to the code.
|
||||
{"Artist": "Some Band", "Title": "Obscure", "Brand": "ZZTOP7",
|
||||
"Watch": "https://youtu.be/eeeeeeeeeee"},
|
||||
# Missing artist/title rows are skipped.
|
||||
{"Artist": "", "Title": "No Artist", "Brand": "X", "Watch": "https://youtu.be/fffffffffff"},
|
||||
]
|
||||
|
||||
|
||||
def test_clean_youtube_url_strips_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest123&index=1"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123&index=1"
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_index(monkeypatch):
|
||||
"""Isolate the module cache and back `_get_index` with the sample catalog."""
|
||||
svc._reset_index_for_tests()
|
||||
monkeypatch.setattr(svc, "_load_index", lambda: _build_index(ROWS))
|
||||
yield
|
||||
svc._reset_index_for_tests()
|
||||
|
||||
|
||||
def test_clean_youtube_url_no_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
# --- YouTube URL normalization ---
|
||||
|
||||
|
||||
def test_clean_youtube_url_list_at_end():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
@pytest.mark.parametrize("raw,expected", [
|
||||
("https://youtu.be/dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PLx", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/embed/dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("", None),
|
||||
("not a url", "not a url"), # unparseable -> returned as-is, never fabricated
|
||||
])
|
||||
def test_normalize_youtube_url(raw, expected):
|
||||
assert _normalize_youtube_url(raw) == expected
|
||||
|
||||
|
||||
# --- Single track parsing ---
|
||||
# --- Index building ---
|
||||
|
||||
|
||||
TRACK_HTML_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=mrZRURcb1cM&list=PLtest" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=xyz789" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_YOUTUBE = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">Some Brand</a>
|
||||
<div class="ml-auto">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">
|
||||
<span class="badge badge-primary badge-pill">AB</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
def test_build_index_groups_and_dedupes():
|
||||
index = _build_index(ROWS)
|
||||
dreams = index[svc._match_key("Fleetwood Mac", "Dreams")]
|
||||
# Two distinct brands; the exact-duplicate row is collapsed.
|
||||
assert len(dreams["community_tracks"]) == 2
|
||||
codes = {t["brand_code"] for t in dreams["community_tracks"]}
|
||||
names = {t["brand_name"] for t in dreams["community_tracks"]}
|
||||
assert codes == {"NOMAD", "OBSK"}
|
||||
assert names == {"Nomad Karaoke", "ObsKure Karaoke"}
|
||||
assert all(t["is_community"] is True for t in dreams["community_tracks"])
|
||||
# youtu.be URLs are canonicalized to watch?v=.
|
||||
assert all(t["youtube_url"].startswith("https://www.youtube.com/watch?v=")
|
||||
for t in dreams["community_tracks"])
|
||||
|
||||
|
||||
def test_parse_single_track_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Karaoke Version"
|
||||
assert track["brand_code"] == "KV"
|
||||
assert track["is_community"] is True
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
# List param should be stripped
|
||||
assert "&list=" not in track["youtube_url"]
|
||||
def test_build_index_unknown_brand_name_falls_back_to_code():
|
||||
index = _build_index(ROWS)
|
||||
song = index[svc._match_key("Some Band", "Obscure")]
|
||||
tr = song["community_tracks"][0]
|
||||
assert tr["brand_code"] == "ZZTOP7"
|
||||
assert tr["brand_name"] == "ZZTOP7"
|
||||
|
||||
|
||||
def test_parse_single_track_no_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Sunfly"
|
||||
assert track["brand_code"] == "SF"
|
||||
assert track["is_community"] is False
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
def test_build_index_skips_rows_without_artist_or_title():
|
||||
index = _build_index(ROWS)
|
||||
assert svc._match_key("", "No Artist") not in index
|
||||
|
||||
|
||||
def test_parse_single_track_no_youtube_returns_none():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_YOUTUBE, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is None
|
||||
|
||||
|
||||
# --- Full results parsing ---
|
||||
|
||||
|
||||
FULL_RESULTS_HTML = """
|
||||
<table>
|
||||
<tbody>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/Dreams/Fleetwood-Mac/">Dreams</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">2 Brands >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=community1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=noncommunity1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/The-Chain/Fleetwood-Mac/">The Chain</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">1 Brand >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">Karafun</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=chain1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">
|
||||
<span class="badge badge-primary badge-pill">KFN</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
"""
|
||||
|
||||
|
||||
def test_parse_results_full():
|
||||
songs = parse_results(FULL_RESULTS_HTML)
|
||||
assert len(songs) == 2
|
||||
|
||||
# First song: Dreams
|
||||
assert songs[0]["title"] == "Dreams"
|
||||
assert songs[0]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[0]["tracks"]) == 2
|
||||
|
||||
# First track is community
|
||||
assert songs[0]["tracks"][0]["is_community"] is True
|
||||
assert songs[0]["tracks"][0]["brand_code"] == "KV"
|
||||
|
||||
# Second track is not community
|
||||
assert songs[0]["tracks"][1]["is_community"] is False
|
||||
assert songs[0]["tracks"][1]["brand_code"] == "SF"
|
||||
|
||||
# Second song: The Chain
|
||||
assert songs[1]["title"] == "The Chain"
|
||||
assert songs[1]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[1]["tracks"]) == 1
|
||||
assert songs[1]["tracks"][0]["is_community"] is False
|
||||
|
||||
|
||||
def test_parse_results_empty_html():
|
||||
assert parse_results("") == []
|
||||
assert parse_results("<html></html>") == []
|
||||
assert parse_results("<table></table>") == []
|
||||
|
||||
|
||||
def test_parse_results_no_table():
|
||||
assert parse_results("<div>No results</div>") == []
|
||||
|
||||
|
||||
# --- Batch availability: per-version data with YouTube URLs (Bulk Mode) ---
|
||||
# --- check_community_versions ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_returns_versions_with_urls_deduped_by_brand(monkeypatch):
|
||||
"""Each result carries `versions: [{brand, url}]` (community only), deduped by
|
||||
brand keeping the first URL, alongside the existing brands/brand_count."""
|
||||
async def test_match_returns_community_with_best_url():
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is True
|
||||
assert result["best_youtube_url"] == "https://www.youtube.com/watch?v=aaaaaaaaaaa"
|
||||
assert len(result["songs"]) == 1
|
||||
assert result["songs"][0]["title"] == "Dreams"
|
||||
assert result["songs"][0]["artist"] == "Fleetwood Mac"
|
||||
|
||||
async def fake_check(artist, title):
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [
|
||||
{
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"community_tracks": [
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=aaa", "is_community": True},
|
||||
{"brand_name": "Nomad Karaoke", "brand_code": "NK",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=bbb", "is_community": True},
|
||||
# Duplicate brand — should be collapsed, keeping the first URL.
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=ccc", "is_community": True},
|
||||
],
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=aaa",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service.check_community_versions", fake_check
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_is_case_and_whitespace_insensitive():
|
||||
result = await check_community_versions(" fleetwood MAC ", "dreams")
|
||||
assert result["has_community"] is True
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": "ABBA", "title": "Dancing Queen"}]
|
||||
)
|
||||
|
||||
assert len(results) == 1
|
||||
r = results[0]
|
||||
assert r["available"] is True
|
||||
assert r["versions"] == [
|
||||
{"brand": "SNDL Karaoke", "url": "https://www.youtube.com/watch?v=aaa"},
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=bbb"},
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_folds_accents():
|
||||
result = await check_community_versions("Beyonce", "Crazy in Love")
|
||||
assert result["has_community"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_treats_ampersand_as_and():
|
||||
# "&" folds to "and", so "Hall and Oates" matches "Hall & Oates".
|
||||
result = await check_community_versions("Hall and Oates", "Rich Girl")
|
||||
assert result["has_community"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_match_returns_false():
|
||||
result = await check_community_versions("Nonexistent Artist", "No Such Song")
|
||||
assert result == {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blank_input_returns_false_without_lookup():
|
||||
assert (await check_community_versions("", "Dreams"))["has_community"] is False
|
||||
assert (await check_community_versions("ABBA", ""))["has_community"] is False
|
||||
|
||||
|
||||
# --- Batch (Bulk Mode) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_returns_versions_deduped_by_brand():
|
||||
results = await check_community_versions_batch([
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
{"artist": "Nope", "title": "Missing"},
|
||||
])
|
||||
assert len(results) == 2
|
||||
|
||||
dreams = results[0]
|
||||
assert dreams["available"] is True
|
||||
assert dreams["brands"] == ["Nomad Karaoke", "ObsKure Karaoke"]
|
||||
assert dreams["brand_count"] == 2
|
||||
assert dreams["versions"] == [
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=aaaaaaaaaaa"},
|
||||
{"brand": "ObsKure Karaoke", "url": "https://www.youtube.com/watch?v=bbbbbbbbbbb"},
|
||||
]
|
||||
# Back-compat retained.
|
||||
assert r["brands"] == ["SNDL Karaoke", "Nomad Karaoke"]
|
||||
assert r["brand_count"] == 2
|
||||
|
||||
assert results[1]["available"] is False
|
||||
assert results[1]["versions"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -267,110 +173,63 @@ async def test_batch_empty_song_has_empty_versions():
|
||||
assert results[0]["versions"] == []
|
||||
|
||||
|
||||
# --- check_community_versions: overlong-query fallback (KaraokeNerds term cap) ---
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_preserves_input_order():
|
||||
order = [
|
||||
{"artist": "ABBA", "title": "Dancing Queen"},
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
{"artist": "Beyonce", "title": "Crazy in Love"},
|
||||
]
|
||||
results = await check_community_versions_batch(order)
|
||||
assert [r["title"] for r in results] == ["Dancing Queen", "Dreams", "Crazy in Love"]
|
||||
assert all(r["available"] for r in results)
|
||||
|
||||
|
||||
def _community_song(title, artist, brand="Nomad Karaoke", url="https://youtu.be/x"):
|
||||
return {
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": [
|
||||
{"brand_name": brand, "brand_code": "NK", "youtube_url": url, "is_community": True}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_community_cache():
|
||||
"""check_community_versions caches in-process; isolate each test."""
|
||||
from backend.services import karaokenerds_service as svc
|
||||
svc._cache.clear()
|
||||
yield
|
||||
svc._cache.clear()
|
||||
# --- Loading + resilience ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_overlong_query_falls_back_to_title_only(monkeypatch):
|
||||
"""An overlong "artist title" query that returns nothing retries title-only
|
||||
and matches by artist (the ABBA 'I Do, I Do, I Do, I Do, I Do' bug)."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
async def test_load_index_parses_gzipped_items(monkeypatch):
|
||||
"""`_load_index` decompresses the GCS gzip and reads the `Items` array."""
|
||||
payload = gzip.compress(json.dumps({"Items": ROWS}).encode())
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
if query == f"ABBA {title}":
|
||||
return [] # combined query is too long -> KaraokeNerds returns nothing
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
return []
|
||||
class _Blob:
|
||||
def download_as_bytes(self):
|
||||
return payload
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
class _Bucket:
|
||||
def blob(self, _name):
|
||||
return _Blob()
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
class _Client:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def bucket(self, _name):
|
||||
return _Bucket()
|
||||
|
||||
monkeypatch.setattr(svc.storage, "Client", _Client)
|
||||
# Restore the real loader (the autouse fixture stubbed it) so it runs against
|
||||
# the mocked GCS client above.
|
||||
monkeypatch.setattr(svc, "_load_index", _real_load_index)
|
||||
svc._reset_index_for_tests()
|
||||
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is True
|
||||
assert result["songs"][0]["artist"] == "ABBA"
|
||||
assert calls == [f"ABBA {title}", title] # combined first, then title-only fallback
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_filters_out_wrong_artist(monkeypatch):
|
||||
"""Title-only fallback is broader, so same-titled songs by other artists
|
||||
must be discarded — no false positive."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
|
||||
async def fake_search(query):
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "Some Other Band")]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
async def test_load_failure_is_fail_open(monkeypatch):
|
||||
"""If the export can't be loaded, every song reads as no-community (fail-open)."""
|
||||
def _boom():
|
||||
raise RuntimeError("GCS unavailable")
|
||||
|
||||
svc._reset_index_for_tests()
|
||||
monkeypatch.setattr(svc, "_load_index", _boom)
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is False
|
||||
assert result["songs"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_empty_query_does_not_fall_back(monkeypatch):
|
||||
"""A short query that legitimately returns nothing must NOT trigger a second
|
||||
request (avoids doubling load for songs with no community version)."""
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", "Dancing Queen")
|
||||
|
||||
assert result["has_community"] is False
|
||||
assert calls == ["ABBA Dancing Queen"] # no fallback request
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nonempty_combined_result_skips_fallback(monkeypatch):
|
||||
"""If the combined query returns results, never fall back even when long."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
assert result["has_community"] is True
|
||||
assert calls == [f"ABBA {title}"] # only the combined query ran
|
||||
# `_real_load_index` is the unpatched module function, captured at import time so
|
||||
# the gzip-parsing test can call it after the autouse fixture stubs `_load_index`.
|
||||
_real_load_index = svc._load_index
|
||||
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
Regression tests for list_jobs' exclude_test filter and the caller's own jobs.
|
||||
|
||||
An admin account that is *itself* a test account (the e2e-test-runner the CI
|
||||
canary impersonates) must still see the jobs it just created in its own
|
||||
"My Jobs" list. The exclude_test filter hides test-account jobs from admin
|
||||
dashboards, but it must never hide the CALLER's own jobs — otherwise the
|
||||
happy-path E2E breaks immediately after creating its job (STEP 5: the new job
|
||||
card never appears in Recent Jobs).
|
||||
"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.api.routes.jobs import list_jobs
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
|
||||
E2E_RUNNER = "e2e-test-runner@nomadkaraoke.com"
|
||||
|
||||
JOBS = [
|
||||
{"job_id": "own1", "user_email": E2E_RUNNER}, # caller's own (test acct)
|
||||
{"job_id": "othertest", "user_email": "x@inbox.testmail.app"}, # other test acct
|
||||
{"job_id": "real", "user_email": "real@example.com"}, # real user
|
||||
]
|
||||
|
||||
|
||||
def _admin(email: str) -> AuthResult:
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=0,
|
||||
message="",
|
||||
user_email=email,
|
||||
is_admin=True,
|
||||
tenant_id="",
|
||||
)
|
||||
|
||||
|
||||
async def _call_summary(auth: AuthResult):
|
||||
request = MagicMock()
|
||||
with patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"), \
|
||||
patch("backend.api.routes.jobs.get_tenant_from_request", return_value=""), \
|
||||
patch("backend.api.routes.jobs.job_manager") as mock_jm:
|
||||
# Return a fresh copy each call so pruning doesn't mutate shared state.
|
||||
mock_jm.list_jobs_summary.return_value = [dict(j) for j in JOBS]
|
||||
return await list_jobs(request, fields="summary", auth_result=auth)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_e2e_runner_sees_its_own_jobs():
|
||||
"""The e2e-test-runner admin must still see its own test-account jobs."""
|
||||
result = await _call_summary(_admin(E2E_RUNNER))
|
||||
ids = {j["job_id"] for j in result}
|
||||
assert "own1" in ids # caller's own job kept
|
||||
assert "real" in ids # real job kept
|
||||
assert "othertest" not in ids # OTHER test-account job still hidden
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regular_admin_still_hides_all_test_jobs():
|
||||
"""A normal admin (not a test account) still has all test jobs filtered out."""
|
||||
result = await _call_summary(_admin("andrew@nomadkaraoke.com"))
|
||||
ids = {j["job_id"] for j in result}
|
||||
assert "real" in ids
|
||||
assert "own1" not in ids # e2e-test-runner jobs hidden from real admin
|
||||
assert "othertest" not in ids # testmail jobs hidden
|
||||
@@ -11,7 +11,7 @@ Covers:
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from unittest.mock import Mock, patch, MagicMock, AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -58,8 +58,10 @@ class TestPipelineDecoupling:
|
||||
|
||||
New behavior:
|
||||
- check_parallel_processing_complete() only checks lyrics_complete
|
||||
- mark_audio_complete() sets flag but does NOT trigger screens
|
||||
- mark_lyrics_complete() triggers screens on its own (no audio gate)
|
||||
- mark_audio_complete() / mark_lyrics_complete() only set their flag
|
||||
- advance_to_screens_if_ready() does the AWAITED, idempotent screens dispatch,
|
||||
gated on lyrics_complete + status==DOWNLOADING (durability fix: the old
|
||||
fire-and-forget trigger was lost on Cloud Run Job loop teardown).
|
||||
"""
|
||||
|
||||
def test_check_parallel_only_requires_lyrics(self, job_manager, mock_firestore_service):
|
||||
@@ -83,76 +85,86 @@ class TestPipelineDecoupling:
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is False
|
||||
|
||||
def test_mark_audio_complete_does_not_trigger_screens(self, job_manager, mock_firestore_service):
|
||||
"""Critical: audio completion must NOT trigger screens worker."""
|
||||
def test_mark_audio_complete_only_sets_flag(self, job_manager, mock_firestore_service):
|
||||
"""mark_audio_complete only persists the flag; it never triggers screens
|
||||
itself (the audio worker calls advance_to_screens_if_ready as a fallback)."""
|
||||
job = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
# Flag persisted via a dot-path state_data write.
|
||||
assert mock_firestore_service.update_job.called
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_without_audio(self, job_manager, mock_firestore_service):
|
||||
"""Critical: lyrics completion triggers screens even if audio isn't done."""
|
||||
# After update_state_data sets lyrics_complete, get_job returns updated state
|
||||
job_after_update = _make_job(state_data={"audio_complete": False, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
def test_mark_lyrics_complete_only_sets_flag(self, job_manager, mock_firestore_service):
|
||||
"""mark_lyrics_complete only persists the flag; the durable AWAITED dispatch
|
||||
is advance_to_screens_if_ready (called by the worker)."""
|
||||
job = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
assert mock_firestore_service.update_job.called
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_with_audio(self, job_manager, mock_firestore_service):
|
||||
"""Lyrics completion triggers screens when audio is already done too."""
|
||||
job_after_update = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_triggers_screens_when_lyrics_done(self, job_manager, mock_firestore_service):
|
||||
"""lyrics_complete + status DOWNLOADING → screens dispatched (awaited)."""
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
def test_ordering_audio_first_then_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""Typical flow: audio finishes first, then lyrics triggers screens."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
assert result is True
|
||||
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-001")
|
||||
|
||||
# Audio completes first — get_job returns state without lyrics_complete
|
||||
job_audio_only = _make_job(state_data={"audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_audio_only
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_noop_when_lyrics_not_done(self, job_manager, mock_firestore_service):
|
||||
"""No screens trigger until lyrics complete, even if audio is done."""
|
||||
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
# Now lyrics completes — get_job returns state with both flags
|
||||
job_both = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
assert result is False
|
||||
mock_ws.trigger_screens_worker.assert_not_called()
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_is_idempotent_when_already_advanced(self, job_manager, mock_firestore_service):
|
||||
"""Idempotency: once the job has advanced past DOWNLOADING, a second call
|
||||
(e.g. the audio-worker fallback) must NOT re-dispatch screens."""
|
||||
job = _make_job(state_data={"lyrics_complete": True}, status=JobStatus.AWAITING_REVIEW)
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
def test_ordering_lyrics_first_then_audio(self, job_manager, mock_firestore_service):
|
||||
"""Less common: lyrics finishes first, triggers screens immediately."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
# Lyrics completes first — get_job returns state with lyrics_complete
|
||||
job_lyrics_only = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_lyrics_only
|
||||
assert result is False
|
||||
mock_ws.trigger_screens_worker.assert_not_called()
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
@pytest.mark.asyncio
|
||||
async def test_audio_fallback_recovers_lost_lyrics_trigger(self, job_manager, mock_firestore_service):
|
||||
"""The exact incident: lyrics finished (flag set) but its screens dispatch
|
||||
was lost, leaving the job at DOWNLOADING. The audio worker finishing later
|
||||
calls advance_to_screens_if_ready and rescues it."""
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": True},
|
||||
status=JobStatus.DOWNLOADING)
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
# Audio completes later — should NOT trigger screens again
|
||||
job_both = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
assert result is True
|
||||
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-001")
|
||||
|
||||
|
||||
# ==================== P0: Preset Configuration ====================
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Unit tests for near-real-time failure alerting (incident-hardening D1).
|
||||
|
||||
Covers the universal-net behaviour the spike-based error monitor can't provide:
|
||||
novel error signatures always alert, repeats within the window collapse, test/dev
|
||||
failures are skipped, and — critically — nothing here ever raises into the status
|
||||
write that triggers it.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import ops_alerts
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In-memory Firestore test double
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _FakeSnap:
|
||||
def __init__(self, data):
|
||||
self._data = data
|
||||
self.exists = data is not None
|
||||
|
||||
def to_dict(self):
|
||||
return dict(self._data) if self._data is not None else None
|
||||
|
||||
|
||||
class _FakeDoc:
|
||||
def __init__(self, store, key):
|
||||
self._store = store
|
||||
self._key = key
|
||||
|
||||
def get(self):
|
||||
return _FakeSnap(self._store.get(self._key))
|
||||
|
||||
def set(self, data):
|
||||
self._store[self._key] = dict(data)
|
||||
|
||||
def update(self, data):
|
||||
self._store.setdefault(self._key, {}).update(data)
|
||||
|
||||
|
||||
class _FakeCollection:
|
||||
def __init__(self, store):
|
||||
self._store = store
|
||||
|
||||
def document(self, doc_id):
|
||||
return _FakeDoc(self._store, doc_id)
|
||||
|
||||
|
||||
class FakeFirestore:
|
||||
"""Mimics the subset of google.cloud.firestore.Client used by ops_alerts."""
|
||||
|
||||
def __init__(self, jobs=None):
|
||||
self._collections = {}
|
||||
# Seed the jobs collection so enrichment reads succeed.
|
||||
jobs_store = {}
|
||||
for job_id, doc in (jobs or {}).items():
|
||||
jobs_store[job_id] = doc
|
||||
self._collections["jobs"] = jobs_store
|
||||
|
||||
def collection(self, name):
|
||||
return _FakeCollection(self._collections.setdefault(name, {}))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def enabled(monkeypatch):
|
||||
monkeypatch.setenv("FAILURE_ALERTS_ENABLED", "true")
|
||||
# Deterministic throttle window for tests.
|
||||
monkeypatch.setenv("FAILURE_ALERT_THROTTLE_MINUTES", "30")
|
||||
monkeypatch.delenv("FAILURE_ALERT_SKIP_ENVIRONMENTS", raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def captured(monkeypatch):
|
||||
"""Capture send_ops_alert calls instead of hitting Discord."""
|
||||
sent = []
|
||||
monkeypatch.setattr(ops_alerts, "send_ops_alert", lambda msg: sent.append(msg) or True)
|
||||
return sent
|
||||
|
||||
|
||||
def _job(environment="production", artist="A", title="B", brand="NOMAD-1632", error_message="boom"):
|
||||
return {
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"request_metadata": {"environment": environment},
|
||||
"state_data": {"brand_code": brand},
|
||||
"error_message": error_message,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# send_ops_alert gating
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_send_ops_alert_disabled_returns_false(monkeypatch):
|
||||
monkeypatch.delenv("FAILURE_ALERTS_ENABLED", raising=False)
|
||||
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: False)
|
||||
assert ops_alerts.send_ops_alert("hi") is False
|
||||
|
||||
|
||||
def test_send_ops_alert_no_webhook_returns_false(monkeypatch):
|
||||
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: True)
|
||||
monkeypatch.setattr(ops_alerts, "_get_webhook_url", lambda: None)
|
||||
assert ops_alerts.send_ops_alert("hi") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# notify_job_failed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_novel_signature_alerts(enabled, captured):
|
||||
db = FakeFirestore(jobs={"job-1": _job(error_message="never seen this")})
|
||||
sent = ops_alerts.notify_job_failed(db, "jobs", "job-1", message="never seen this")
|
||||
assert sent is True
|
||||
assert len(captured) == 1
|
||||
assert "First time" in captured[0]
|
||||
assert "job-1" in captured[0]
|
||||
|
||||
|
||||
def test_repeat_within_window_is_suppressed(enabled, captured):
|
||||
db = FakeFirestore(jobs={
|
||||
"job-1": _job(),
|
||||
"job-2": _job(),
|
||||
})
|
||||
# Same error string -> same signature.
|
||||
ops_alerts.notify_job_failed(db, "jobs", "job-1", additional_fields={"error_message": "same err"})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "job-2", additional_fields={"error_message": "same err"})
|
||||
assert len(captured) == 1 # second collapsed
|
||||
|
||||
|
||||
def test_distinct_signatures_each_alert(enabled, captured):
|
||||
db = FakeFirestore(jobs={"j1": _job(), "j2": _job()})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "j1", additional_fields={"error_message": "error one"})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "j2", additional_fields={"error_message": "totally different"})
|
||||
assert len(captured) == 2
|
||||
|
||||
|
||||
def test_test_environment_skipped(enabled, captured):
|
||||
db = FakeFirestore(jobs={"job-t": _job(environment="test")})
|
||||
sent = ops_alerts.notify_job_failed(db, "jobs", "job-t", message="boom")
|
||||
assert sent is False
|
||||
assert captured == []
|
||||
|
||||
|
||||
def test_disabled_environment_no_alert(monkeypatch, captured):
|
||||
monkeypatch.delenv("FAILURE_ALERTS_ENABLED", raising=False)
|
||||
monkeypatch.setattr(ops_alerts, "_is_enabled", lambda: False)
|
||||
db = FakeFirestore(jobs={"job-1": _job()})
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", message="boom") is False
|
||||
assert captured == []
|
||||
|
||||
|
||||
def test_best_effort_never_raises_on_broken_db(enabled, captured):
|
||||
class BrokenDB:
|
||||
def collection(self, name):
|
||||
raise RuntimeError("firestore exploded")
|
||||
|
||||
# Must not propagate. Enrichment + dedup both fail, so it fails OPEN and
|
||||
# still sends (missing a real outage is worse than an unenriched alert).
|
||||
result = ops_alerts.notify_job_failed(BrokenDB(), "jobs", "job-x", message="boom")
|
||||
assert result is True
|
||||
assert len(captured) == 1
|
||||
|
||||
|
||||
def test_fail_open_when_dedup_read_errors(enabled, captured, monkeypatch):
|
||||
"""If the dedup lookup fails we should still alert (missing an outage is worse)."""
|
||||
db = FakeFirestore(jobs={"job-1": _job()})
|
||||
monkeypatch.setattr(ops_alerts, "_should_alert", lambda *a, **k: (True, False, 0, None))
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", message="boom") is True
|
||||
assert len(captured) == 1
|
||||
|
||||
|
||||
def test_failed_delivery_does_not_suppress_next(enabled, monkeypatch):
|
||||
"""A failed Discord send must NOT advance the throttle window."""
|
||||
db = FakeFirestore(jobs={"job-1": _job(), "job-2": _job()})
|
||||
calls = []
|
||||
|
||||
def flaky_send(msg):
|
||||
calls.append(msg)
|
||||
return len(calls) > 1 # first send fails, second succeeds
|
||||
|
||||
monkeypatch.setattr(ops_alerts, "send_ops_alert", flaky_send)
|
||||
# First failure: send attempted but delivery fails → not acked.
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", additional_fields={"error_message": "same err"}) is False
|
||||
# Second failure, same signature, within window: because the first never
|
||||
# acked, this must still be attempted (not throttled away) and now succeed.
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-2", additional_fields={"error_message": "same err"}) is True
|
||||
assert len(calls) == 2
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Unit tests for the publish-boundary completeness invariant (incident-hardening G1).
|
||||
|
||||
These pin the exact behaviour that closes the NOMAD-1632 silent-partial class: a
|
||||
public GDrive release missing its 720p variant (or any expected output) must be
|
||||
reported as a shortfall, while a complete release — and any non-public job —
|
||||
reports nothing.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from backend.services.publish_completeness import (
|
||||
compute_publish_shortfall,
|
||||
expected_gdrive_outputs,
|
||||
)
|
||||
|
||||
|
||||
def _config(gdrive_folder_id="folder-1", enable_cdg=True):
|
||||
return SimpleNamespace(
|
||||
gdrive_folder_id=gdrive_folder_id,
|
||||
enable_cdg=enable_cdg,
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
)
|
||||
|
||||
|
||||
def _result(gdrive_files, cdg_produced=True):
|
||||
"""A result whose CDG was produced by default (final_karaoke_cdg_zip set)."""
|
||||
return SimpleNamespace(
|
||||
gdrive_files=gdrive_files,
|
||||
brand_code="NOMAD-1632",
|
||||
final_karaoke_cdg_zip=("/tmp/x.zip" if cdg_produced else None),
|
||||
)
|
||||
|
||||
|
||||
class TestExpectedOutputs:
|
||||
def test_cdg_produced_expects_all_three(self):
|
||||
res = _result({}, cdg_produced=True)
|
||||
assert expected_gdrive_outputs(_config(enable_cdg=True), res) == ["mp4", "mp4_720p", "cdg"]
|
||||
|
||||
def test_cdg_not_produced_expects_two(self):
|
||||
res = _result({}, cdg_produced=False)
|
||||
assert expected_gdrive_outputs(_config(enable_cdg=True), res) == ["mp4", "mp4_720p"]
|
||||
|
||||
|
||||
class TestComputePublishShortfall:
|
||||
def test_complete_release_no_shortfall(self):
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2", "cdg": "id3"})
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_missing_720p_is_the_incident(self):
|
||||
"""The NOMAD-1632 case: 4K + CDG shipped, 720p silently skipped."""
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "cdg": "id3"})
|
||||
assert compute_publish_shortfall(cfg, res) == ["720p MP4"]
|
||||
|
||||
def test_missing_cdg_when_produced(self):
|
||||
"""CDG was produced but not distributed → real shortfall."""
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2"}, cdg_produced=True)
|
||||
assert compute_publish_shortfall(cfg, res) == ["CDG zip"]
|
||||
|
||||
def test_lyricless_skip_does_not_require_cdg(self):
|
||||
"""enable_cdg True but no CDG produced (lyric-less track) → no false alarm."""
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2"}, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_cdg_not_expected_when_disabled(self):
|
||||
cfg = _config(enable_cdg=False)
|
||||
res = _result({"mp4": "id1", "mp4_720p": "id2"}, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_empty_distribution_lists_all_expected(self):
|
||||
cfg = _config(enable_cdg=True)
|
||||
res = _result({}, cdg_produced=True)
|
||||
assert compute_publish_shortfall(cfg, res) == ["lossy 4K MP4", "720p MP4", "CDG zip"]
|
||||
|
||||
def test_empty_string_id_counts_as_missing(self):
|
||||
cfg = _config(enable_cdg=False)
|
||||
res = _result({"mp4": "id1", "mp4_720p": ""}, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == ["720p MP4"]
|
||||
|
||||
def test_non_public_job_never_flags(self):
|
||||
"""No gdrive_folder_id → not a public-share release → always clean."""
|
||||
cfg = _config(gdrive_folder_id=None, enable_cdg=True)
|
||||
res = _result({})
|
||||
assert compute_publish_shortfall(cfg, res) == []
|
||||
|
||||
def test_none_gdrive_files_is_safe(self):
|
||||
cfg = _config(enable_cdg=False)
|
||||
res = _result(None, cdg_produced=False)
|
||||
assert compute_publish_shortfall(cfg, res) == ["lossy 4K MP4", "720p MP4"]
|
||||
@@ -55,7 +55,8 @@ def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=No
|
||||
)
|
||||
|
||||
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None, jobs=None):
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None,
|
||||
downloading_prep=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 4 status queries.
|
||||
|
||||
downloading/rendering/review_complete use .where().stream(); pending uses
|
||||
@@ -68,8 +69,11 @@ def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=
|
||||
where.stream.side_effect = [
|
||||
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
|
||||
]
|
||||
# One .limit().stream() call: download_pending_retry
|
||||
where.limit.return_value.stream.return_value = iter(pending or [])
|
||||
# Two .limit().stream() calls in order: download_pending_retry, then downloading
|
||||
# (lost-screens-trigger sweep, bounded by SCREENS_RECOVERY_SCAN_LIMIT)
|
||||
where.limit.return_value.stream.side_effect = [
|
||||
iter(pending or []), iter(downloading_prep or []),
|
||||
]
|
||||
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
return mock_jm
|
||||
@@ -177,6 +181,41 @@ def test_fresh_render_not_reparked(client):
|
||||
mock_jm = _mock_jm(rendering=[_doc("r2", JobStatus.RENDERING_VIDEO)], jobs={"r2": job})
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["reparked_render_count"] == 0
|
||||
|
||||
|
||||
def test_stuck_downloading_with_lyrics_done_retriggers_screens(client):
|
||||
"""A job stuck at DOWNLOADING >10 min with lyrics_complete=True (a lost screens
|
||||
trigger) is re-advanced to screen generation."""
|
||||
job = _job("s1", JobStatus.DOWNLOADING, minutes_stale=15)
|
||||
job.state_data["lyrics_complete"] = True
|
||||
mock_jm = _mock_jm(downloading_prep=[_doc("s1", JobStatus.DOWNLOADING)], jobs={"s1": job})
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
resp, _ = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["screens_retriggered_jobs"] == ["s1"]
|
||||
mock_jm.advance_to_screens_if_ready.assert_awaited_once_with("s1")
|
||||
|
||||
|
||||
def test_fresh_downloading_not_retriggered(client):
|
||||
"""A DOWNLOADING job updated 2 min ago (audio still separating) is NOT re-triggered."""
|
||||
job = _job("s2", JobStatus.DOWNLOADING, minutes_stale=2)
|
||||
job.state_data["lyrics_complete"] = True
|
||||
mock_jm = _mock_jm(downloading_prep=[_doc("s2", JobStatus.DOWNLOADING)], jobs={"s2": job})
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["screens_retriggered_count"] == 0
|
||||
mock_jm.advance_to_screens_if_ready.assert_not_awaited()
|
||||
|
||||
|
||||
def test_downloading_without_lyrics_not_retriggered(client):
|
||||
"""A DOWNLOADING job stale >10 min but WITHOUT lyrics_complete is still
|
||||
legitimately processing (download/separate/transcribe) — not re-triggered."""
|
||||
job = _job("s3", JobStatus.DOWNLOADING, minutes_stale=15) # no lyrics_complete
|
||||
mock_jm = _mock_jm(downloading_prep=[_doc("s3", JobStatus.DOWNLOADING)], jobs={"s3": job})
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["screens_retriggered_count"] == 0
|
||||
mock_jm.advance_to_screens_if_ready.assert_not_awaited()
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
Tests for the render video worker CLI entry point (Cloud Run Jobs execution).
|
||||
|
||||
The render worker runs as a Cloud Run Job (video-encoding-job with an args
|
||||
override) so it survives Cloud Run Service deployment rollouts — as a
|
||||
BackgroundTask it was killed ~10s after SIGTERM whenever a deploy landed
|
||||
mid-render (incident 2026-09-13, job 41e06b90).
|
||||
|
||||
Exit-code contract (deliberately different from video_worker): the Cloud Run
|
||||
Job template has max_retries=2 and process_render_video handles every expected
|
||||
failure internally (park / fail_job / supersede-discard). A clean return —
|
||||
True OR False — must exit 0 so Cloud Run never re-runs the worker against a
|
||||
job that already moved to a non-render state. Only an escaped exception
|
||||
(crash before state was handled) exits 1 to request a Cloud Run retry.
|
||||
"""
|
||||
import sys
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers.render_video_worker import main
|
||||
|
||||
|
||||
def _run_main_with_args(job_id="job123"):
|
||||
return patch.object(sys, "argv", ["render_video_worker", "--job-id", job_id])
|
||||
|
||||
|
||||
class TestRenderVideoWorkerCli:
|
||||
def test_main_exits_zero_on_success(self):
|
||||
with _run_main_with_args(), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=AsyncMock(return_value=True)):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
assert exc_info.value.code == 0
|
||||
|
||||
def test_main_exits_zero_on_handled_failure(self):
|
||||
"""False means the worker already parked/failed/superseded the job —
|
||||
a Cloud Run retry would re-enter a job in a non-render state."""
|
||||
with _run_main_with_args(), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=AsyncMock(return_value=False)):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
assert exc_info.value.code == 0
|
||||
|
||||
def test_main_exits_nonzero_on_crash(self):
|
||||
"""An escaped exception means job state was NOT handled — exit 1 so
|
||||
Cloud Run's max_retries can re-run the worker."""
|
||||
with _run_main_with_args(), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=AsyncMock(side_effect=RuntimeError("boom"))):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
assert exc_info.value.code == 1
|
||||
|
||||
def test_main_passes_job_id(self):
|
||||
mock_worker = AsyncMock(return_value=True)
|
||||
with _run_main_with_args("abc999"), \
|
||||
patch("backend.workers.render_video_worker.process_render_video",
|
||||
new=mock_worker):
|
||||
with pytest.raises(SystemExit):
|
||||
main()
|
||||
mock_worker.assert_awaited_once_with("abc999")
|
||||
|
||||
def test_main_requires_job_id(self):
|
||||
with patch.object(sys, "argv", ["render_video_worker"]):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
main()
|
||||
# argparse exits 2 on missing required argument
|
||||
assert exc_info.value.code == 2
|
||||
@@ -104,6 +104,9 @@ class TestIsDuetPropagation:
|
||||
job.style_assets = {}
|
||||
job.prep_only = False
|
||||
job.subtitle_offset_ms = 0
|
||||
# Real dispatch state — the worker itself transitions to
|
||||
# RENDERING_VIDEO (and skips jobs already in it / terminal).
|
||||
job.status = JobStatus.REVIEW_COMPLETE
|
||||
return job
|
||||
|
||||
def test_is_duet_true_passed_to_output_config_local_path(self):
|
||||
|
||||
@@ -23,7 +23,11 @@ from backend.models.job import JobStatus
|
||||
from backend.workers.registry import worker_registry
|
||||
|
||||
|
||||
def _build_minimal_job(status=JobStatus.RENDERING_VIDEO):
|
||||
def _build_minimal_job(status=JobStatus.REVIEW_COMPLETE):
|
||||
# Default matches the real entry state: the worker is dispatched with the
|
||||
# job in REVIEW_COMPLETE and transitions to RENDERING_VIDEO itself. A job
|
||||
# already in RENDERING_VIDEO at entry is skipped by the worker-side
|
||||
# idempotency gate (duplicate trigger / Cloud Run Job retry protection).
|
||||
job = MagicMock()
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
@@ -61,7 +65,15 @@ async def test_worker_registers_and_unregisters_on_success():
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = job
|
||||
mock_job_manager.transition_to_state.return_value = True
|
||||
|
||||
# Mirror real transitions on the shared mock so the supersession fence's
|
||||
# mid-render re-reads see RENDERING_VIDEO (a frozen REVIEW_COMPLETE would
|
||||
# read as "status reset" and discard the render).
|
||||
def _transition(job_id=None, new_status=None, **kwargs):
|
||||
job.status = new_status
|
||||
return True
|
||||
|
||||
mock_job_manager.transition_to_state.side_effect = _transition
|
||||
|
||||
mock_encoding_service = MagicMock()
|
||||
mock_encoding_service.is_enabled = True
|
||||
@@ -226,3 +238,56 @@ def test_park_active_render_jobs_continues_after_per_job_failure():
|
||||
|
||||
# The successful job should still have been parked
|
||||
assert parked == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_skips_job_in_terminal_state():
|
||||
"""A stale/duplicate trigger for a finished job must never resurrect it.
|
||||
|
||||
The Cloud Run Job dispatch path bypasses the HTTP endpoint's
|
||||
_check_worker_idempotency guard, so the worker enforces this itself.
|
||||
"""
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = _build_minimal_job(JobStatus.COMPLETE)
|
||||
|
||||
with patch.object(rvw, "JobManager", return_value=mock_job_manager), \
|
||||
patch.object(rvw, "StorageService"), \
|
||||
patch.object(rvw, "get_settings"), \
|
||||
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(rvw, "setup_job_logging", return_value=MagicMock()):
|
||||
result = await rvw.process_render_video("done-job")
|
||||
|
||||
assert result is False
|
||||
# Must not touch job state at all
|
||||
mock_job_manager.transition_to_state.assert_not_called()
|
||||
mock_job_manager.fail_job.assert_not_called()
|
||||
mock_job_manager.update_state_data.assert_not_called()
|
||||
# And must not leak a registry entry
|
||||
assert worker_registry.get_active_workers() == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_skips_job_already_rendering():
|
||||
"""Re-entry on a job already in RENDERING_VIDEO (duplicate trigger, or a
|
||||
Cloud Run Job max_retries re-run after a crash) must be a clean no-op —
|
||||
NOT a hard fail via the same-state InvalidStateTransition path. A live
|
||||
render must not be disrupted; a dead one is recovered by the
|
||||
rendering_video_stuck sweep."""
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = _build_minimal_job(JobStatus.RENDERING_VIDEO)
|
||||
|
||||
with patch.object(rvw, "JobManager", return_value=mock_job_manager), \
|
||||
patch.object(rvw, "StorageService"), \
|
||||
patch.object(rvw, "get_settings"), \
|
||||
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(rvw, "setup_job_logging", return_value=MagicMock()):
|
||||
result = await rvw.process_render_video("mid-render-job")
|
||||
|
||||
assert result is False
|
||||
mock_job_manager.transition_to_state.assert_not_called()
|
||||
mock_job_manager.fail_job.assert_not_called()
|
||||
assert worker_registry.get_active_workers() == {}
|
||||
@@ -770,6 +770,9 @@ class TestSummaryEndpoint:
|
||||
{'job_id': '1', 'user_email': 'real@example.com'},
|
||||
{'job_id': '2', 'user_email': 'test@inbox.testmail.app'},
|
||||
{'job_id': '3', 'user_email': None},
|
||||
# The persistent account impersonated by the CI canary + daily E2E
|
||||
# runs. Its jobs must be filtered out of the admin dashboard too.
|
||||
{'job_id': '4', 'user_email': 'e2e-test-runner@nomadkaraoke.com'},
|
||||
]
|
||||
|
||||
filtered = [j for j in job_dicts if not is_test_email(j.get('user_email') or "")]
|
||||
|
||||
@@ -314,12 +314,12 @@ class TestAddLyricsRejectionHandling:
|
||||
|
||||
|
||||
class TestInstrumentalUrlsRefresh:
|
||||
"""GET /{job_id}/instrumental-urls re-signs the stem URLs on demand.
|
||||
"""GET /{job_id}/instrumental-urls returns same-origin audio proxy paths.
|
||||
|
||||
The signed URLs baked into the initial review payload expire after 120 min;
|
||||
a long review session (or a reload that rehydrates cached correction data)
|
||||
outlives them and the preview modal's overlaid audio fails to load. This
|
||||
endpoint hands the frontend a freshly-signed batch to swap in.
|
||||
Since the 2026-09-17 fast-load re-architecture (Option B) the review hot path no
|
||||
longer signs GCS URLs. Each option's ``audio_url`` is a RELATIVE proxy path to
|
||||
``/{job_id}/instrumental-audio/{option_id}`` (served as bytes, no signing, never
|
||||
expires). The frontend turns it into an absolute token URL before use.
|
||||
"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -334,7 +334,7 @@ class TestInstrumentalUrlsRefresh:
|
||||
yield
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
def test_returns_freshly_signed_options_for_both_stems(self, test_client):
|
||||
def test_returns_proxy_paths_for_both_stems(self, test_client):
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "job1"
|
||||
mock_job.file_urls = {
|
||||
@@ -344,22 +344,17 @@ class TestInstrumentalUrlsRefresh:
|
||||
}
|
||||
}
|
||||
|
||||
async def fake_sign(src, expiration_minutes=120):
|
||||
return f"https://signed/{src}?fresh=1"
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async",
|
||||
side_effect=fake_sign):
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False):
|
||||
mock_jm.return_value.get_job.return_value = mock_job
|
||||
response = test_client.get("/api/review/job1/instrumental-urls")
|
||||
|
||||
assert response.status_code == 200
|
||||
options = response.json()["instrumental_options"]
|
||||
ids = {o["id"]: o["audio_url"] for o in options}
|
||||
assert ids["clean"].endswith("instrumental_clean.flac?fresh=1")
|
||||
assert ids["with_backing"].endswith("instrumental_with_backing.flac?fresh=1")
|
||||
assert ids["clean"] == "/api/review/job1/instrumental-audio/clean"
|
||||
assert ids["with_backing"] == "/api/review/job1/instrumental-audio/with_backing"
|
||||
|
||||
def test_omits_stems_that_do_not_exist(self, test_client):
|
||||
mock_job = MagicMock()
|
||||
@@ -368,14 +363,9 @@ class TestInstrumentalUrlsRefresh:
|
||||
"stems": {"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac"}
|
||||
}
|
||||
|
||||
async def fake_sign(src, expiration_minutes=120):
|
||||
return f"https://signed/{src}"
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async",
|
||||
side_effect=fake_sign):
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False):
|
||||
mock_jm.return_value.get_job.return_value = mock_job
|
||||
response = test_client.get("/api/review/job1/instrumental-urls")
|
||||
|
||||
@@ -383,6 +373,29 @@ class TestInstrumentalUrlsRefresh:
|
||||
options = response.json()["instrumental_options"]
|
||||
assert [o["id"] for o in options] == ["clean"]
|
||||
|
||||
def test_does_not_sign_urls_on_hot_path(self, test_client):
|
||||
"""The root-cause fix: building instrumental options must perform NO URL signing
|
||||
(the IAM signBlob round-trip is what stalled and took gen down on 2026-09-17)."""
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "job1"
|
||||
mock_job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/job1/stems/instrumental_with_backing.flac",
|
||||
}
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService") as mock_storage, \
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async") as mock_sign_async:
|
||||
mock_jm.return_value.get_job.return_value = mock_job
|
||||
response = test_client.get("/api/review/job1/instrumental-urls")
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_sign_async.assert_not_called()
|
||||
mock_storage.return_value.generate_signed_url.assert_not_called()
|
||||
|
||||
def test_missing_job_returns_404(self, test_client):
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
@@ -391,6 +404,122 @@ class TestInstrumentalUrlsRefresh:
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestInstrumentalAudioProxy:
|
||||
"""GET /{job_id}/instrumental-audio/{option_id} — same-origin byte proxy.
|
||||
|
||||
Option B of the 2026-09-17 fast-load re-architecture: serves the transcoded OGG
|
||||
bytes with HTTP Range support instead of a signed GCS URL, so playback never depends
|
||||
on IAM signBlob. The stem GCS path is resolved server-side from the option id.
|
||||
"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def auth_overrides(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_audio_cache(self):
|
||||
# The proxy caches bytes per GCS path at module scope; clear it so a prior
|
||||
# test's stubbed bytes don't leak into the next test's assertions.
|
||||
from backend.api.routes import review as review_module
|
||||
review_module._review_audio_cache.clear()
|
||||
yield
|
||||
review_module._review_audio_cache.clear()
|
||||
|
||||
def _mock_job(self):
|
||||
job = MagicMock()
|
||||
job.job_id = "job1"
|
||||
job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/job1/stems/instrumental_with_backing.flac",
|
||||
}
|
||||
}
|
||||
return job
|
||||
|
||||
def test_streams_transcoded_bytes(self, test_client):
|
||||
audio = b"OggS" + b"\x00" * 100
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(return_value=(audio, "audio/ogg"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "audio/ogg"
|
||||
assert response.headers["accept-ranges"] == "bytes"
|
||||
assert response.content == audio
|
||||
|
||||
def test_supports_range_requests(self, test_client):
|
||||
audio = bytes(range(50)) * 4 # 200 deterministic bytes
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(return_value=(audio, "audio/ogg"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get(
|
||||
"/api/review/job1/instrumental-audio/clean",
|
||||
headers={"Range": "bytes=10-19"},
|
||||
)
|
||||
|
||||
assert response.status_code == 206
|
||||
assert response.headers["content-range"] == f"bytes 10-19/{len(audio)}"
|
||||
assert response.content == audio[10:20]
|
||||
|
||||
def test_unknown_option_id_returns_404(self, test_client):
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/bogus")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_missing_stem_returns_404(self, test_client):
|
||||
job = MagicMock()
|
||||
job.job_id = "job1"
|
||||
job.file_urls = {"stems": {"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac"}}
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
mock_jm.return_value.get_job.return_value = job
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/with_backing")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_missing_job_returns_404(self, test_client):
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
mock_jm.return_value.get_job.return_value = None
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_deleted_gcs_object_returns_404_not_500(self, test_client):
|
||||
from google.cloud.exceptions import NotFound
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(side_effect=NotFound("gone"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_does_not_sign_urls(self, test_client):
|
||||
audio = b"OggS"
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService") as mock_storage, \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(return_value=(audio, "audio/ogg"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
assert response.status_code == 200
|
||||
mock_storage.return_value.generate_signed_url.assert_not_called()
|
||||
|
||||
|
||||
class TestReviewResubmissionClearsWorkerProgress:
|
||||
"""Tests for ensuring review submission clears worker progress keys.
|
||||
|
||||
@@ -1318,7 +1447,11 @@ class TestGetVocalsAudio:
|
||||
|
||||
def _call(self, stems, audio_complete=True):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _stream_audio
|
||||
from backend.api.routes.review import _stream_audio, _review_audio_cache
|
||||
|
||||
# Vocals bytes are LRU-cached module-wide; clear so each test asserts a
|
||||
# fresh fetch rather than a hit on a previous test's identical path.
|
||||
_review_audio_cache.clear()
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
@@ -1692,7 +1825,7 @@ class TestEncodePreviewInBackground:
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(return_value="h1")
|
||||
local_render = AsyncMock(return_value="h1")
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
local_render.assert_called_once()
|
||||
storage.upload_json.assert_not_called()
|
||||
@@ -1703,9 +1836,378 @@ class TestEncodePreviewInBackground:
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(side_effect=RuntimeError("ffmpeg died"))
|
||||
local_render = AsyncMock(side_effect=RuntimeError("ffmpeg died"))
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
storage.upload_json.assert_called_once_with(
|
||||
"jobs/job-bg/previews/h1.error.json",
|
||||
{"error": "ffmpeg died"},
|
||||
)
|
||||
|
||||
|
||||
class TestVocalsCacheRangeAndHeaders:
|
||||
"""Concurrent-load fixes on the vocals byte proxy: LRU cache, Range, Cache-Control."""
|
||||
|
||||
def _make_request(self, headers=None):
|
||||
req = MagicMock()
|
||||
req.headers = headers or {}
|
||||
return req
|
||||
|
||||
def _run(self, request=None, path="jobs/j/stems/vocals_clean.flac", clear_cache=True):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _stream_audio, _review_audio_cache
|
||||
|
||||
if clear_cache:
|
||||
_review_audio_cache.clear()
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
job.file_urls = {"stems": {"vocals_clean": path}}
|
||||
job.state_data = {"audio_complete": True}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
transcoding = MagicMock()
|
||||
transcoding.get_review_audio_bytes_async = AsyncMock(
|
||||
return_value=(b"0123456789", "audio/ogg")
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=transcoding,
|
||||
):
|
||||
resp = asyncio.run(_stream_audio("j", request, stem="vocals"))
|
||||
return resp, transcoding
|
||||
|
||||
def test_second_fetch_served_from_lru_cache(self):
|
||||
"""Ten tabs of one job must not each re-download the stem from GCS."""
|
||||
_, first = self._run()
|
||||
first.get_review_audio_bytes_async.assert_awaited_once()
|
||||
|
||||
resp, second = self._run(clear_cache=False)
|
||||
second.get_review_audio_bytes_async.assert_not_awaited()
|
||||
assert resp.body == b"0123456789"
|
||||
|
||||
def test_range_request_returns_206_partial(self):
|
||||
req = self._make_request({"range": "bytes=2-5"})
|
||||
resp, _ = self._run(request=req)
|
||||
|
||||
assert resp.status_code == 206
|
||||
assert resp.body == b"2345"
|
||||
assert resp.headers["Content-Range"] == "bytes 2-5/10"
|
||||
assert resp.headers["Accept-Ranges"] == "bytes"
|
||||
|
||||
def test_full_response_has_cache_control(self):
|
||||
req = self._make_request({})
|
||||
resp, _ = self._run(request=req)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert "max-age" in resp.headers.get("Cache-Control", "")
|
||||
|
||||
def test_no_request_still_returns_full_body(self):
|
||||
"""Callers without a Request object (legacy path) keep working."""
|
||||
resp, _ = self._run(request=None)
|
||||
assert resp.status_code == 200
|
||||
assert resp.body == b"0123456789"
|
||||
|
||||
|
||||
class TestWaveformDataEndpointCache:
|
||||
"""/waveform-data must serve via the persistent cache path, off the event loop."""
|
||||
|
||||
def _run(self, stems=None):
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_waveform_data
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
if stems is None:
|
||||
stems = {"backing_vocals": "jobs/j/stems/backing_vocals.flac"}
|
||||
job.file_urls = {"stems": stems}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
analysis = MagicMock()
|
||||
analysis.get_review_waveform.return_value = ([0.4, 0.8], 150.0)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_analysis_service.AudioAnalysisService",
|
||||
return_value=analysis,
|
||||
), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=MagicMock(),
|
||||
):
|
||||
result = asyncio.run(
|
||||
get_waveform_data("j", num_points=1000, auth_info=("admin", "full"))
|
||||
)
|
||||
return result, analysis
|
||||
|
||||
def test_serves_cached_review_waveform(self):
|
||||
result, analysis = self._run()
|
||||
|
||||
analysis.get_review_waveform.assert_called_once()
|
||||
args = analysis.get_review_waveform.call_args[0]
|
||||
assert args[0] == "jobs/j/stems/backing_vocals.flac"
|
||||
assert args[1] == "j"
|
||||
assert args[2] == 1000
|
||||
assert result["amplitudes"] == [0.4, 0.8]
|
||||
assert result["duration_seconds"] == 150.0
|
||||
assert result["duration"] == 150.0
|
||||
|
||||
def test_falls_back_to_input_audio_without_backing_stem(self):
|
||||
_, analysis = self._run(stems={})
|
||||
assert analysis.get_review_waveform.call_args[0][0] == "jobs/j/input.flac"
|
||||
|
||||
|
||||
class TestReviewAudioSingleFlightAndByteCap:
|
||||
"""CodeRabbit follow-ups on #1024: coalesce concurrent misses; bound cache bytes."""
|
||||
|
||||
def test_concurrent_misses_share_one_fetch(self):
|
||||
import asyncio
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
class SlowTranscoding:
|
||||
async def get_review_audio_bytes_async(self, path):
|
||||
calls["n"] += 1
|
||||
await asyncio.sleep(0.05)
|
||||
return (b"shared-bytes", "audio/ogg")
|
||||
|
||||
async def scenario():
|
||||
t = SlowTranscoding()
|
||||
results = await asyncio.gather(
|
||||
*[review_module._get_review_audio("jobs/j/stems/v.flac", t) for _ in range(5)]
|
||||
)
|
||||
return results
|
||||
|
||||
results = asyncio.run(scenario())
|
||||
assert calls["n"] == 1 # five concurrent callers, one fetch
|
||||
assert all(r == (b"shared-bytes", "audio/ogg") for r in results)
|
||||
|
||||
def test_failure_is_shared_and_next_call_retries(self):
|
||||
import asyncio
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
class FlakyTranscoding:
|
||||
async def get_review_audio_bytes_async(self, path):
|
||||
calls["n"] += 1
|
||||
await asyncio.sleep(0.02)
|
||||
if calls["n"] == 1:
|
||||
raise RuntimeError("GCS blip")
|
||||
return (b"ok", "audio/ogg")
|
||||
|
||||
async def scenario():
|
||||
t = FlakyTranscoding()
|
||||
first = await asyncio.gather(
|
||||
*[review_module._get_review_audio("jobs/j/stems/v.flac", t) for _ in range(3)],
|
||||
return_exceptions=True,
|
||||
)
|
||||
assert all(isinstance(r, RuntimeError) for r in first)
|
||||
# In-flight entry must be gone — a fresh call retries and succeeds.
|
||||
return await review_module._get_review_audio("jobs/j/stems/v.flac", t)
|
||||
|
||||
result = asyncio.run(scenario())
|
||||
assert result == (b"ok", "audio/ogg")
|
||||
assert calls["n"] == 2
|
||||
|
||||
def test_oversized_entry_not_cached(self, monkeypatch):
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
monkeypatch.setattr(review_module, "_REVIEW_AUDIO_CACHE_MAX_BYTES", 100)
|
||||
|
||||
# > max_bytes // 4 → skipped (one giant fallback FLAC must not evict all)
|
||||
review_module._review_audio_cache_put("big", (b"x" * 50, "audio/flac"))
|
||||
assert "big" not in review_module._review_audio_cache
|
||||
|
||||
def test_byte_cap_evicts_lru(self, monkeypatch):
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
review_module._review_audio_cache_bytes = 0
|
||||
monkeypatch.setattr(review_module, "_REVIEW_AUDIO_CACHE_MAX_BYTES", 100)
|
||||
|
||||
for key in ("a", "b", "c", "d", "e"):
|
||||
review_module._review_audio_cache_put(key, (b"x" * 25, "audio/ogg"))
|
||||
|
||||
# 5 × 25B = 125B > 100B cap → oldest evicted, total back under the cap.
|
||||
assert "a" not in review_module._review_audio_cache
|
||||
assert review_module._review_audio_cache_bytes <= 100
|
||||
assert set(review_module._review_audio_cache) == {"b", "c", "d", "e"}
|
||||
|
||||
|
||||
class TestLocalPreviewRenderBound:
|
||||
"""The local preview ffmpeg fallback must be bounded so a GCE outage plus a
|
||||
few concurrent Preview clicks can't saturate the API instance's CPU.
|
||||
Admission is an async semaphore on the event loop (waiters are cheap
|
||||
coroutines, not parked executor threads)."""
|
||||
|
||||
def test_serializes_and_times_out_admission(self, monkeypatch):
|
||||
import asyncio
|
||||
import threading
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
monkeypatch.setattr(review_module, "_LOCAL_PREVIEW_QUEUE_TIMEOUT_S", 0.2)
|
||||
monkeypatch.setattr(review_module, "_local_preview_slots", asyncio.Semaphore(1))
|
||||
|
||||
started = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def slow_render(job, updated_data, is_duet):
|
||||
started.set()
|
||||
release.wait(timeout=5)
|
||||
return "hash"
|
||||
|
||||
monkeypatch.setattr(review_module, "_render_preview_locally_unbounded", slow_render)
|
||||
|
||||
async def scenario():
|
||||
first = asyncio.create_task(
|
||||
review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
)
|
||||
await asyncio.to_thread(started.wait, 5)
|
||||
|
||||
# Slot held by the first render — the second caller's admission wait
|
||||
# times out fast instead of piling more ffmpeg onto the instance.
|
||||
with pytest.raises(RuntimeError, match="busy"):
|
||||
await review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
|
||||
release.set()
|
||||
assert await first == "hash"
|
||||
|
||||
# Slot released — a fresh render is admitted immediately.
|
||||
monkeypatch.setattr(
|
||||
review_module, "_render_preview_locally_unbounded",
|
||||
lambda job, updated_data, is_duet: "hash2",
|
||||
)
|
||||
assert await review_module._render_preview_locally(MagicMock(), {}, False) == "hash2"
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_cancelled_caller_does_not_free_slot_while_render_runs(self, monkeypatch):
|
||||
"""Cancelling the awaiting request must NOT release the slot while the
|
||||
ffmpeg worker thread is still running — otherwise a second render can
|
||||
start and defeat the concurrency bound."""
|
||||
import asyncio
|
||||
import threading
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
monkeypatch.setattr(review_module, "_LOCAL_PREVIEW_QUEUE_TIMEOUT_S", 0.2)
|
||||
monkeypatch.setattr(review_module, "_local_preview_slots", asyncio.Semaphore(1))
|
||||
|
||||
started = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def slow_render(job, updated_data, is_duet):
|
||||
started.set()
|
||||
release.wait(timeout=5)
|
||||
return "hash"
|
||||
|
||||
monkeypatch.setattr(review_module, "_render_preview_locally_unbounded", slow_render)
|
||||
|
||||
async def scenario():
|
||||
first = asyncio.create_task(
|
||||
review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
)
|
||||
await asyncio.to_thread(started.wait, 5)
|
||||
|
||||
first.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await first
|
||||
|
||||
# Worker thread is still rendering — the slot must still be held.
|
||||
with pytest.raises(RuntimeError, match="busy"):
|
||||
await review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
|
||||
# Worker finishes → done-callback releases the slot.
|
||||
release.set()
|
||||
for _ in range(50):
|
||||
if not review_module._local_preview_slots.locked():
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
monkeypatch.setattr(
|
||||
review_module, "_render_preview_locally_unbounded",
|
||||
lambda job, updated_data, is_duet: "hash2",
|
||||
)
|
||||
assert await review_module._render_preview_locally(MagicMock(), {}, False) == "hash2"
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
class TestVocalsPeaksEndpoint:
|
||||
"""/vocals-peaks serves the precomputed envelope (sub-second strips)."""
|
||||
|
||||
def _run(self, stems=None, audio_complete=True, pps=400):
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_vocals_peaks
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
if stems is None:
|
||||
stems = {"vocals_clean": "jobs/j/stems/vocals_clean.flac"}
|
||||
job.file_urls = {"stems": stems}
|
||||
job.state_data = {"audio_complete": audio_complete}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
analysis = MagicMock()
|
||||
analysis.get_vocals_peaks.return_value = {
|
||||
"peaks_b64": "AAECAw==",
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": 400,
|
||||
"duration_seconds": 12.5,
|
||||
"source_gcs_path": "jobs/j/stems/vocals_clean.flac",
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_analysis_service.AudioAnalysisService",
|
||||
return_value=analysis,
|
||||
), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=MagicMock(),
|
||||
):
|
||||
resp = asyncio.run(
|
||||
get_vocals_peaks("j", peaks_per_second=pps, auth_info=("admin", "full"))
|
||||
)
|
||||
return resp, analysis
|
||||
|
||||
def test_serves_payload_with_cache_headers(self):
|
||||
import json as jsonlib
|
||||
|
||||
resp, analysis = self._run()
|
||||
|
||||
assert resp.status_code == 200
|
||||
body = jsonlib.loads(resp.body)
|
||||
assert body["peaks_b64"] == "AAECAw=="
|
||||
assert body["encoding"] == "u8"
|
||||
assert body["duration_seconds"] == 12.5
|
||||
assert "max-age" in resp.headers.get("Cache-Control", "")
|
||||
args = analysis.get_vocals_peaks.call_args[0]
|
||||
assert args[0] == "jobs/j/stems/vocals_clean.flac"
|
||||
assert args[1] == "j"
|
||||
assert args[2] == 400
|
||||
|
||||
def test_clamps_peaks_per_second(self):
|
||||
_, analysis = self._run(pps=999999)
|
||||
assert analysis.get_vocals_peaks.call_args[0][2] == 1000
|
||||
|
||||
def test_202_while_separation_running(self):
|
||||
resp, analysis = self._run(stems={}, audio_complete=False)
|
||||
assert resp.status_code == 202
|
||||
assert resp.headers.get("Retry-After") == "15"
|
||||
analysis.get_vocals_peaks.assert_not_called()
|
||||
|
||||
def test_404_when_stem_will_never_exist(self):
|
||||
from fastapi import HTTPException
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._run(stems={}, audio_complete=True)
|
||||
assert exc_info.value.status_code == 404
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Screens worker idempotency.
|
||||
|
||||
The screens worker can be dispatched more than once — the lyrics worker (primary
|
||||
trigger) and the audio worker (fallback trigger) may both fire it, and Cloud Tasks
|
||||
can redeliver. A duplicate dispatch that arrives once the job has advanced past the
|
||||
pre-screens stage must no-op rather than re-run the (now invalid)
|
||||
GENERATING_SCREENS transition and regenerate screens.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
def _job(status):
|
||||
return Job(
|
||||
job_id="dup-1", artist="A", title="B", status=status,
|
||||
created_at=datetime.now(timezone.utc), updated_at=datetime.now(timezone.utc),
|
||||
state_data={"lyrics_complete": True, "audio_complete": True},
|
||||
)
|
||||
|
||||
|
||||
def _patched(screens_worker, mock_jm):
|
||||
return (
|
||||
patch.object(screens_worker, "JobManager", return_value=mock_jm),
|
||||
patch.object(screens_worker, "StorageService"),
|
||||
patch.object(screens_worker, "get_settings"),
|
||||
patch.object(screens_worker, "create_job_logger"),
|
||||
patch.object(screens_worker, "setup_job_logging"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", [
|
||||
JobStatus.GENERATING_SCREENS,
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.COMPLETE,
|
||||
])
|
||||
async def test_generate_screens_noops_when_already_advanced(status):
|
||||
from backend.workers import screens_worker
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = _job(status)
|
||||
|
||||
p1, p2, p3, p4, p5 = _patched(screens_worker, mock_jm)
|
||||
with p1, p2, p3, p4, p5:
|
||||
result = await screens_worker.generate_screens("dup-1")
|
||||
|
||||
assert result is True
|
||||
# Duplicate dispatch must NOT perform the (invalid) GENERATING_SCREENS transition.
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_screens_proceeds_from_downloading():
|
||||
"""A first, legitimate dispatch (status DOWNLOADING) passes the idempotency
|
||||
guard and proceeds to validate prerequisites."""
|
||||
from backend.workers import screens_worker
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = _job(JobStatus.DOWNLOADING)
|
||||
|
||||
p1, p2, p3, p4, p5 = _patched(screens_worker, mock_jm)
|
||||
with p1, p2, p3, p4, p5, \
|
||||
patch.object(screens_worker, "_validate_prerequisites", return_value=False) as mock_val:
|
||||
result = await screens_worker.generate_screens("dup-1")
|
||||
|
||||
# Guard passed → prerequisites were checked (stubbed False to stop early before work).
|
||||
mock_val.assert_called_once()
|
||||
assert result is False
|
||||
@@ -512,6 +512,82 @@ class TestWorkerService:
|
||||
assert "--job-id" in str(override_args)
|
||||
assert "test123" in str(override_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_render_video_worker_routes_to_cloud_run_job(self):
|
||||
"""Test that render worker routes to Cloud Run Jobs when enabled.
|
||||
|
||||
When USE_CLOUD_RUN_JOBS_FOR_RENDER=true and ENABLE_CLOUD_TASKS=true,
|
||||
trigger_render_video_worker should dispatch a Cloud Run Job (reusing
|
||||
video-encoding-job with a render_video_worker args override) instead
|
||||
of posting to the internal HTTP endpoint. As a BackgroundTask on the
|
||||
service, the render poll was killed ~10s after SIGTERM whenever a
|
||||
deploy rollout landed mid-render, freezing the job at rendering_video
|
||||
(see incident 2026-09-13, job 41e06b90).
|
||||
"""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_render = True
|
||||
|
||||
mock_jobs_client = MagicMock()
|
||||
mock_operation = MagicMock()
|
||||
mock_operation.metadata = "test-metadata"
|
||||
mock_jobs_client.run_job.return_value = mock_operation
|
||||
|
||||
mock_run_v2 = MagicMock()
|
||||
mock_run_v2.JobsClient.return_value = mock_jobs_client
|
||||
mock_run_v2.RunJobRequest = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides = MagicMock()
|
||||
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
|
||||
|
||||
import google.cloud
|
||||
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
|
||||
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
|
||||
service = WorkerService()
|
||||
result = await service.trigger_render_video_worker("test456")
|
||||
|
||||
assert result is True
|
||||
mock_jobs_client.run_job.assert_called_once()
|
||||
|
||||
# Reuses the video-encoding-job Cloud Run Job resource
|
||||
call_args = mock_run_v2.RunJobRequest.call_args
|
||||
assert call_args is not None
|
||||
assert "video-encoding-job" in str(call_args)
|
||||
|
||||
# But overrides the module to the render worker with the job id
|
||||
override_args = mock_run_v2.RunJobRequest.Overrides.ContainerOverride.call_args
|
||||
assert "backend.workers.render_video_worker" in str(override_args)
|
||||
assert "--job-id" in str(override_args)
|
||||
assert "test456" in str(override_args)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trigger_render_video_worker_flag_off_uses_legacy_path(self):
|
||||
"""With USE_CLOUD_RUN_JOBS_FOR_RENDER off, the legacy Cloud Tasks /
|
||||
HTTP path is used and no Cloud Run Job is dispatched (rollback path)."""
|
||||
from backend.services.worker_service import WorkerService, reset_worker_service
|
||||
reset_worker_service()
|
||||
|
||||
with patch('backend.services.worker_service.get_settings') as mock_settings:
|
||||
mock_settings.return_value.admin_tokens = "test-token"
|
||||
mock_settings.return_value.google_cloud_project = "test-project"
|
||||
mock_settings.return_value.enable_cloud_tasks = True
|
||||
mock_settings.return_value.gcp_region = "us-central1"
|
||||
mock_settings.return_value.use_cloud_run_jobs_for_render = False
|
||||
|
||||
service = WorkerService()
|
||||
with patch.object(service, '_trigger_worker_cloud_run_job', new=AsyncMock()) as mock_crj, \
|
||||
patch.object(service, 'trigger_worker', new=AsyncMock(return_value=True)) as mock_legacy:
|
||||
result = await service.trigger_render_video_worker("test789")
|
||||
|
||||
assert result is True
|
||||
mock_crj.assert_not_called()
|
||||
mock_legacy.assert_called_once_with("render-video", "test789")
|
||||
|
||||
|
||||
class TestWorkerServiceWarmup:
|
||||
"""Test encoding worker warmup in trigger methods."""
|
||||
@@ -825,12 +901,56 @@ class TestFirestoreService:
|
||||
|
||||
assert job is None
|
||||
|
||||
def test_failed_status_triggers_failure_alert(self):
|
||||
"""Incident-hardening D1: a transition to FAILED fires the failure alert."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
mock_collection = MagicMock()
|
||||
mock_client.collection.return_value = mock_collection
|
||||
mock_collection.document.return_value = MagicMock()
|
||||
|
||||
firestore_service = FirestoreService()
|
||||
with patch('backend.services.ops_alerts.notify_job_failed') as mock_notify:
|
||||
firestore_service.update_job_status("job1", JobStatus.FAILED, message="boom")
|
||||
mock_notify.assert_called_once()
|
||||
# Reuses the caller's client + collection (no second Firestore client).
|
||||
_, kwargs = mock_notify.call_args
|
||||
assert kwargs["job_id"] == "job1"
|
||||
assert kwargs["db"] is mock_client
|
||||
|
||||
def test_non_failed_status_does_not_alert(self):
|
||||
"""A normal status transition must NOT fire the failure alert."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
mock_client.collection.return_value.document.return_value = MagicMock()
|
||||
|
||||
firestore_service = FirestoreService()
|
||||
with patch('backend.services.ops_alerts.notify_job_failed') as mock_notify:
|
||||
firestore_service.update_job_status("job1", JobStatus.COMPLETE, message="done")
|
||||
mock_notify.assert_not_called()
|
||||
|
||||
def test_failure_alert_error_does_not_break_status_write(self):
|
||||
"""If the alerter raises, the status write must still succeed (best-effort)."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
mock_doc_ref = MagicMock()
|
||||
mock_client.collection.return_value.document.return_value = mock_doc_ref
|
||||
|
||||
firestore_service = FirestoreService()
|
||||
with patch('backend.services.ops_alerts.notify_job_failed', side_effect=RuntimeError("x")):
|
||||
# Should not raise.
|
||||
firestore_service.update_job_status("job1", JobStatus.FAILED, message="boom")
|
||||
mock_doc_ref.update.assert_called_once()
|
||||
|
||||
def test_update_job(self):
|
||||
"""Test updating a job in Firestore."""
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_client = MagicMock()
|
||||
mock_firestore.Client.return_value = mock_client
|
||||
|
||||
|
||||
mock_collection = MagicMock()
|
||||
mock_client.collection.return_value = mock_collection
|
||||
|
||||
|
||||
@@ -550,6 +550,108 @@ class TestStorageServiceSignedUrls:
|
||||
|
||||
|
||||
|
||||
class TestStorageServiceSigningTimeout:
|
||||
"""A stalled IAM signBlob must fail fast, not hang the caller (incident 2026-09-17)."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_emulator_env(self, monkeypatch):
|
||||
# In CI STORAGE_EMULATOR_HOST is set, which would divert signing into the
|
||||
# emulator URL fallback and never exercise the timeout/executor path.
|
||||
monkeypatch.delenv("STORAGE_EMULATOR_HOST", raising=False)
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_signing_raises_signed_url_timeout_when_stalled(
|
||||
self, mock_settings, mock_client_class, monkeypatch
|
||||
):
|
||||
import threading
|
||||
import time
|
||||
|
||||
from backend.services.storage_service import SignedUrlTimeout, StorageService
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
|
||||
# Simulate a stalled signBlob: block until released, well past the timeout.
|
||||
release = threading.Event()
|
||||
|
||||
def _hang(*_args, **_kwargs):
|
||||
release.wait(timeout=5)
|
||||
return "https://storage.googleapis.com/never-returned-in-time"
|
||||
|
||||
mock_blob = Mock()
|
||||
mock_blob.generate_signed_url.side_effect = _hang
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
|
||||
# Tiny budget so the test is fast.
|
||||
monkeypatch.setattr("backend.services.storage_service.SIGNED_URL_TIMEOUT_S", 0.2)
|
||||
|
||||
try:
|
||||
with patch("google.auth.default") as mock_auth_default:
|
||||
mock_auth_default.return_value = (Mock(spec=[]), "test-project")
|
||||
started = time.monotonic()
|
||||
with pytest.raises(SignedUrlTimeout):
|
||||
StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
elapsed = time.monotonic() - started
|
||||
finally:
|
||||
release.set() # let the leaked signing thread finish cleanly
|
||||
|
||||
# Must bail near the budget, not wait for the underlying stall.
|
||||
assert elapsed < 2.0, f"signing did not fail fast (took {elapsed:.2f}s)"
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_signing_refuses_immediately_when_saturated(
|
||||
self, mock_settings, mock_client_class, monkeypatch
|
||||
):
|
||||
"""When admission is saturated, refuse at submit time — don't enqueue/wait."""
|
||||
import threading
|
||||
|
||||
from backend.services.storage_service import SignedUrlTimeout, StorageService
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_blob = Mock()
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
|
||||
# Fully-acquired semaphore = no free admission slots.
|
||||
full = threading.BoundedSemaphore(1)
|
||||
assert full.acquire(blocking=False)
|
||||
monkeypatch.setattr("backend.services.storage_service._SIGNING_SLOTS", full)
|
||||
|
||||
with patch("google.auth.default") as mock_auth_default:
|
||||
mock_auth_default.return_value = (Mock(spec=[]), "test-project")
|
||||
with pytest.raises(SignedUrlTimeout):
|
||||
StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
|
||||
# Refused before any signing work was attempted.
|
||||
mock_blob.generate_signed_url.assert_not_called()
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_signing_returns_url_normally(self, mock_settings, mock_client_class):
|
||||
"""Sanity: the executor path still returns a normal (fast) signed URL."""
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_blob = Mock()
|
||||
mock_blob.generate_signed_url.return_value = "https://storage.googleapis.com/ok"
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
|
||||
with patch("google.auth.default") as mock_auth_default:
|
||||
mock_auth_default.return_value = (Mock(spec=[]), "test-project")
|
||||
url = StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
|
||||
assert url == "https://storage.googleapis.com/ok"
|
||||
|
||||
|
||||
class TestStorageServiceEmulatorUrls:
|
||||
"""Test emulator URL fallback when STORAGE_EMULATOR_HOST is set (local dev)."""
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Unit tests for backend.utils.test_data email classification helpers."""
|
||||
|
||||
from backend.utils.test_data import (
|
||||
is_test_email,
|
||||
is_internal_email,
|
||||
is_internal_or_test_email,
|
||||
)
|
||||
|
||||
|
||||
class TestIsTestEmail:
|
||||
def test_testmail_domain_is_test(self):
|
||||
assert is_test_email("k1l43.test-123@inbox.testmail.app") is True
|
||||
|
||||
def test_e2e_test_runner_account_is_test(self):
|
||||
# Persistent account impersonated by the CI canary + daily E2E runs.
|
||||
assert is_test_email("e2e-test-runner@nomadkaraoke.com") is True
|
||||
|
||||
def test_e2e_test_runner_is_case_insensitive(self):
|
||||
assert is_test_email("E2E-Test-Runner@NomadKaraoke.com") is True
|
||||
|
||||
def test_regular_team_account_is_not_test(self):
|
||||
# Other @nomadkaraoke.com accounts are internal, not test data.
|
||||
assert is_test_email("andrew@nomadkaraoke.com") is False
|
||||
|
||||
def test_real_user_is_not_test(self):
|
||||
assert is_test_email("real@example.com") is False
|
||||
|
||||
def test_empty_is_not_test(self):
|
||||
assert is_test_email("") is False
|
||||
assert is_test_email(None) is False
|
||||
|
||||
|
||||
class TestIsInternalEmail:
|
||||
def test_nomadkaraoke_is_internal(self):
|
||||
assert is_internal_email("andrew@nomadkaraoke.com") is True
|
||||
|
||||
def test_e2e_runner_is_also_internal_domain(self):
|
||||
# It lives on the internal domain; is_internal stays True. The point of
|
||||
# the TEST_EMAIL_ADDRESSES entry is that is_test_email ALSO returns True
|
||||
# so the admin dashboard's exclude_test filter hides it.
|
||||
assert is_internal_email("e2e-test-runner@nomadkaraoke.com") is True
|
||||
|
||||
def test_real_user_is_not_internal(self):
|
||||
assert is_internal_email("real@example.com") is False
|
||||
|
||||
|
||||
class TestIsInternalOrTestEmail:
|
||||
def test_e2e_runner_matches(self):
|
||||
assert is_internal_or_test_email("e2e-test-runner@nomadkaraoke.com") is True
|
||||
|
||||
def test_real_user_does_not_match(self):
|
||||
assert is_internal_or_test_email("real@example.com") is False
|
||||
@@ -2182,3 +2182,178 @@ class TestRedistributeModeProgress:
|
||||
|
||||
jm.transition_to_state.assert_called_once()
|
||||
jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
class TestEncodePublishSeam:
|
||||
"""Composed integration test of the encode→publish seam (hardening plan T1).
|
||||
|
||||
Both NOMAD-1632 bugs lived in the boundary between ``GCEEncodingBackend.encode()``
|
||||
and the orchestrator's ``_run_encoding`` / ``_download_gce_encoded_files``, yet
|
||||
NO existing test composes those two real layers — the stale-cache test mocks the
|
||||
*entire* backend, so the real classifier and completeness guard never run inside
|
||||
an orchestrator test. These tests wire the **real** backend to the **real**
|
||||
orchestrator and patch only the network boundary (the worker's ``encode_videos``
|
||||
call) and storage (GCS download), replaying the golden fixtures from
|
||||
``backend/tests/fixtures/encoding/``.
|
||||
|
||||
Asserted shapes:
|
||||
- empty → guard must NOT trip → 0 downloads → "stale" RuntimeError →
|
||||
re-encode recovers (Failure B path).
|
||||
- partial → completeness guard trips → job fails loud (Failure A defense).
|
||||
- complete → success, all result attrs populated with local paths.
|
||||
- malformed → classified out → treated as empty (no mis-slotting, no crash) →
|
||||
recovered via the same stale path.
|
||||
"""
|
||||
|
||||
FIXTURES_DIR = (
|
||||
os.path.join(os.path.dirname(__file__), "fixtures", "encoding")
|
||||
)
|
||||
|
||||
def _load_fixture(self, name):
|
||||
import json
|
||||
with open(os.path.join(self.FIXTURES_DIR, f"{name}.json")) as fh:
|
||||
return json.load(fh)
|
||||
|
||||
def _make_config(self, temp_dir):
|
||||
return OrchestratorConfig(
|
||||
job_id="test-job",
|
||||
artist="Nat King Cole",
|
||||
title="Portrait of Jennie",
|
||||
title_video_path=os.path.join(temp_dir, "title.mov"),
|
||||
karaoke_video_path=os.path.join(temp_dir, "karaoke.mkv"),
|
||||
instrumental_audio_path=os.path.join(temp_dir, "audio.flac"),
|
||||
output_dir=temp_dir,
|
||||
encoding_backend="gce", # exercise the REAL GCEEncodingBackend
|
||||
)
|
||||
|
||||
def _make_storage(self):
|
||||
"""Storage mock: no custom-instrumental staging; downloads write a file."""
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.list_files = MagicMock(return_value=[])
|
||||
|
||||
def _download(gcs_path, local_path):
|
||||
with open(local_path, "w") as f:
|
||||
f.write("fake encoded bytes")
|
||||
|
||||
mock_storage.download_file = MagicMock(side_effect=_download)
|
||||
return mock_storage
|
||||
|
||||
def _patch_worker(self, *, side_effect=None, return_value=None):
|
||||
"""Patch ONLY the network boundary: the GCE worker's encode_videos.
|
||||
|
||||
Returns (context_manager, mock_service). The real backend, real
|
||||
classifier, real completeness guard and real orchestrator all run.
|
||||
"""
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(
|
||||
side_effect=side_effect, return_value=return_value
|
||||
)
|
||||
cm = patch(
|
||||
"backend.services.encoding_service.get_encoding_service",
|
||||
return_value=mock_service,
|
||||
)
|
||||
return cm, mock_service
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_output_recovers_via_reencode(self):
|
||||
"""Failure B: empty output_files is recoverable, NOT a guard failure.
|
||||
|
||||
Real encode() must return success (guard does not fire on empty) →
|
||||
orchestrator downloads 0 files → raises the 'stale' RuntimeError →
|
||||
re-encodes under a fresh job id → recovers.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=self._make_storage()
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
side_effect=[self._load_fixture("empty"), self._load_fixture("success")]
|
||||
)
|
||||
with cm:
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
# encode() ran twice: empty (recoverable) then the fresh re-encode.
|
||||
assert mock_service.encode_videos.call_count == 2
|
||||
# The retry used a fresh suffixed worker job id.
|
||||
retry_job_id = mock_service.encode_videos.call_args_list[1].kwargs["job_id"]
|
||||
assert retry_job_id.startswith("test-job_retry_")
|
||||
# Recovered: results point at downloaded local files.
|
||||
assert orchestrator.result.final_video is not None
|
||||
assert orchestrator.result.final_video.startswith(temp_dir)
|
||||
assert orchestrator.result.final_video_720p is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_partial_output_fails_loud(self):
|
||||
"""Failure A defense: a partial result (720p missing) trips the guard and
|
||||
fails the job loudly rather than publishing an incomplete release."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=self._make_storage()
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
return_value=self._load_fixture("partial")
|
||||
)
|
||||
with cm:
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
msg = str(exc_info.value)
|
||||
assert "incomplete" in msg.lower()
|
||||
assert "mp4_720p" in msg
|
||||
# No retry — a partial result is a defect, not a recoverable empty.
|
||||
assert mock_service.encode_videos.call_count == 1
|
||||
# Nothing was published / downloaded.
|
||||
assert orchestrator.result.final_video is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_complete_output_populates_all_results(self):
|
||||
"""Happy path: all four formats present → success, all attrs populated
|
||||
with local downloaded paths. Uses the NOMAD-1632 title to prove the
|
||||
720p whose title contains 'Portrait' maps correctly."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
storage = self._make_storage()
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=storage
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
return_value=self._load_fixture("success")
|
||||
)
|
||||
with cm:
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
assert mock_service.encode_videos.call_count == 1
|
||||
for attr in (
|
||||
"final_video",
|
||||
"final_video_mkv",
|
||||
"final_video_lossy",
|
||||
"final_video_720p",
|
||||
):
|
||||
val = getattr(orchestrator.result, attr)
|
||||
assert val is not None, f"{attr} not populated"
|
||||
assert val.startswith(temp_dir), f"{attr} not a downloaded local path"
|
||||
assert storage.download_file.called
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_malformed_output_treated_as_empty(self):
|
||||
"""Malformed names (stray / wrong-extension) classify to nothing, so the
|
||||
guard must NOT mis-fire or mis-slot — the result is treated as empty.
|
||||
With persistently malformed output, that surfaces as the recoverable
|
||||
'stale' RuntimeError (handled, not a crash)."""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
orchestrator = VideoWorkerOrchestrator(
|
||||
self._make_config(temp_dir), storage=self._make_storage()
|
||||
)
|
||||
cm, mock_service = self._patch_worker(
|
||||
side_effect=[
|
||||
self._load_fixture("malformed"),
|
||||
self._load_fixture("malformed"),
|
||||
]
|
||||
)
|
||||
with cm:
|
||||
with pytest.raises(RuntimeError, match="stale"):
|
||||
await orchestrator._run_encoding()
|
||||
|
||||
# Classified-out → empty → recoverable path attempted (re-encode),
|
||||
# which with still-malformed output raises the stale signal again.
|
||||
assert mock_service.encode_videos.call_count == 2
|
||||
assert orchestrator.result.final_video is None
|
||||
@@ -507,3 +507,130 @@ class TestWorkerLogEntryEdgeCases:
|
||||
# Should be ~30 days from now
|
||||
expected = datetime.now(timezone.utc) + timedelta(days=30)
|
||||
assert abs((entry.ttl_expiry - expected).total_seconds()) < 10
|
||||
|
||||
|
||||
class TestDocSizeRecovery:
|
||||
"""Self-healing when a job document hits Firestore's 1MB size limit.
|
||||
|
||||
A large legacy embedded ``worker_logs`` array (superseded by the logs
|
||||
subcollection) can push an old job document to ~1MB, after which EVERY
|
||||
write — including a customer submitting lyrics corrections — fails with
|
||||
Firestore's "exceeds the maximum allowed size" 400. update_job /
|
||||
update_job_status drop the deprecated array and retry once.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self, mock_db):
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_firestore.Client.return_value = mock_db
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
service = FirestoreService()
|
||||
service.db = mock_db
|
||||
return service
|
||||
|
||||
@staticmethod
|
||||
def _size_error():
|
||||
return Exception(
|
||||
"400 Document 'projects/nomadkaraoke/databases/(default)/documents/"
|
||||
"jobs/d93747cd' cannot be written because its size (1,048,592 bytes) "
|
||||
"exceeds the maximum allowed size of 1,048,576 bytes."
|
||||
)
|
||||
|
||||
def test_update_job_recovers_by_clearing_worker_logs(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
# payload write fails (too big), worker_logs delete succeeds, retry succeeds
|
||||
doc_ref.update.side_effect = [self._size_error(), None, None]
|
||||
|
||||
firestore_service.update_job(
|
||||
"d93747cd", {"state_data.corrected_lyrics": {"corrected_segment_count": 5}}
|
||||
)
|
||||
|
||||
assert doc_ref.update.call_count == 3
|
||||
# Second write clears the legacy embedded worker_logs array
|
||||
delete_payload = doc_ref.update.call_args_list[1][0][0]
|
||||
assert "worker_logs" in delete_payload
|
||||
# Third write re-applies the caller's original field
|
||||
retry_payload = doc_ref.update.call_args_list[2][0][0]
|
||||
assert "state_data.corrected_lyrics" in retry_payload
|
||||
|
||||
def test_update_job_reraises_non_size_errors(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
doc_ref.update.side_effect = Exception("PERMISSION_DENIED")
|
||||
|
||||
with pytest.raises(Exception, match="PERMISSION_DENIED"):
|
||||
firestore_service.update_job("j", {"foo": "bar"})
|
||||
# No recovery attempt for unrelated errors
|
||||
assert doc_ref.update.call_count == 1
|
||||
|
||||
def test_worker_logs_write_does_not_recurse(self, firestore_service, mock_db):
|
||||
"""A write that is itself setting worker_logs must not self-clear+retry."""
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
doc_ref.update.side_effect = self._size_error()
|
||||
|
||||
with pytest.raises(Exception, match="maximum allowed size"):
|
||||
firestore_service.update_job("j", {"worker_logs": ["x"]})
|
||||
assert doc_ref.update.call_count == 1
|
||||
|
||||
def test_update_job_status_recovers_by_clearing_worker_logs(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
doc_ref.update.side_effect = [self._size_error(), None, None]
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
firestore_service.update_job_status("d93747cd", JobStatus.IN_REVIEW)
|
||||
|
||||
assert doc_ref.update.call_count == 3
|
||||
delete_payload = doc_ref.update.call_args_list[1][0][0]
|
||||
assert "worker_logs" in delete_payload
|
||||
|
||||
|
||||
class TestAppendWorkerLogRouting:
|
||||
"""Legacy dict-based append_worker_log must respect the subcollection flag
|
||||
so it stops bloating the embedded worker_logs array."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self, mock_db):
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_firestore.Client.return_value = mock_db
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
service = FirestoreService()
|
||||
service.db = mock_db
|
||||
return service
|
||||
|
||||
def test_routes_to_subcollection_when_flag_on(self, firestore_service):
|
||||
with patch('backend.services.firestore_service.settings') as mock_settings:
|
||||
mock_settings.use_log_subcollection = True
|
||||
with patch.object(firestore_service, 'append_log_to_subcollection') as mock_sub:
|
||||
firestore_service.append_worker_log(
|
||||
"job123",
|
||||
{"timestamp": "t", "worker": "review", "level": "INFO", "message": "hi"},
|
||||
)
|
||||
mock_sub.assert_called_once()
|
||||
entry = mock_sub.call_args[0][1]
|
||||
assert entry.worker == "review"
|
||||
assert entry.level == "INFO"
|
||||
assert entry.message == "hi"
|
||||
|
||||
def test_uses_embedded_array_when_flag_off(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
with patch('backend.services.firestore_service.settings') as mock_settings:
|
||||
mock_settings.use_log_subcollection = False
|
||||
with patch.object(firestore_service, 'append_log_to_subcollection') as mock_sub:
|
||||
firestore_service.append_worker_log(
|
||||
"job123",
|
||||
{"timestamp": "t", "worker": "review", "level": "INFO", "message": "hi"},
|
||||
)
|
||||
mock_sub.assert_not_called()
|
||||
doc_ref.update.assert_called_once()
|
||||
@@ -123,7 +123,11 @@ def test_bump_worker_generation_is_best_effort():
|
||||
# render worker (GCE path) supersession behaviour
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _render_job(generation=1):
|
||||
def _render_job(generation=1, status=JobStatus.RENDERING_VIDEO):
|
||||
# Entry snapshots (job_start) must use REVIEW_COMPLETE — the real dispatch
|
||||
# state. A job already in RENDERING_VIDEO at entry is skipped by the
|
||||
# worker-side idempotency gate (duplicate trigger / CRJ retry protection).
|
||||
# Mid-render re-read snapshots (job_after) stay RENDERING_VIDEO.
|
||||
job = MagicMock()
|
||||
job.artist = "John Maus"
|
||||
job.title = "The Fear"
|
||||
@@ -134,7 +138,7 @@ def _render_job(generation=1):
|
||||
job.prep_only = False
|
||||
job.state_data = {"worker_generation": generation, "is_duet": False}
|
||||
job.file_urls = {}
|
||||
job.status = JobStatus.RENDERING_VIDEO
|
||||
job.status = status
|
||||
return job
|
||||
|
||||
|
||||
@@ -187,7 +191,7 @@ async def _run_gce_render(job_start, job_after, transition_side_effect=None):
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_superseded_by_status_reset_does_not_fail_job():
|
||||
"""Admin reset moved the job to awaiting_review mid-render → discard, don't fail."""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1)
|
||||
job_after.status = "awaiting_review" # reset out from under the render
|
||||
|
||||
@@ -207,7 +211,7 @@ async def test_render_superseded_by_status_reset_does_not_fail_job():
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_superseded_by_generation_bump_does_not_fail_job():
|
||||
"""A newer render was triggered (generation bumped) → discard the stale run."""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=2) # newer run took over
|
||||
|
||||
result, jm = await _run_gce_render(job_start, job_after)
|
||||
@@ -225,7 +229,7 @@ async def test_invalid_terminal_transition_is_graceful_when_superseded():
|
||||
reset moved the job to awaiting_review). The worker must bail gracefully,
|
||||
exactly reproducing and fixing the 7f457087 incident.
|
||||
"""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1)
|
||||
job_after.status = "awaiting_review" # reset confirmed on re-read in the handler
|
||||
|
||||
@@ -252,7 +256,7 @@ async def test_invalid_transition_when_not_superseded_still_fails():
|
||||
workflow defect — it must still fail the job (loudly) rather than be silently
|
||||
swallowed and leave the job stuck. Guards against over-broad error suppression.
|
||||
"""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1) # same gen + still rendering_video => NOT superseded
|
||||
|
||||
invalid = InvalidStateTransitionError(
|
||||
@@ -272,7 +276,7 @@ async def test_progress_callback_skips_update_when_superseded():
|
||||
"""A stale render's progress ticks must not drag a reset job's progress bar."""
|
||||
from backend.workers import render_video_worker as rvw
|
||||
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
superseded = _render_job(generation=2) # reset bumped the fence mid-render
|
||||
|
||||
jm = MagicMock()
|
||||
@@ -318,7 +322,7 @@ async def test_progress_callback_skips_update_when_superseded():
|
||||
@pytest.mark.asyncio
|
||||
async def test_normal_render_still_completes():
|
||||
"""Un-superseded render must still write outputs and transition to INSTRUMENTAL_SELECTED."""
|
||||
job_start = _render_job(generation=1)
|
||||
job_start = _render_job(generation=1, status=JobStatus.REVIEW_COMPLETE)
|
||||
job_after = _render_job(generation=1) # same gen, still rendering_video
|
||||
|
||||
result, jm = await _run_gce_render(job_start, job_after)
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Tests for the shared YouTube back-catalogue rewrite logic."""
|
||||
import pytest
|
||||
|
||||
from backend.services import youtube_backfill as bf
|
||||
|
||||
|
||||
def _video(title, description="", category_id="10", vid="vid123"):
|
||||
return {"id": vid, "snippet": {"title": title, "description": description, "categoryId": category_id}}
|
||||
|
||||
|
||||
class TestClassify:
|
||||
def test_standard_karaoke_title_with_brand_code(self):
|
||||
c = bf.classify(_video(
|
||||
"Coldplay - Yellow (Karaoke)",
|
||||
"Karaoke video created with Nomad Karaoke\n\nBrand Code: NOMAD-1603",
|
||||
))
|
||||
assert c["is_karaoke"] and c["eligible"]
|
||||
assert c["artist"] == "Coldplay" and c["song_title"] == "Yellow"
|
||||
assert c["brand_code"] == "NOMAD-1603"
|
||||
assert c["parse_confidence"] == "high"
|
||||
|
||||
def test_official_karaoke_version_suffix(self):
|
||||
c = bf.classify(_video("Adele - Hello (Official Karaoke Version)"))
|
||||
assert c["eligible"] and c["artist"] == "Adele" and c["song_title"] == "Hello"
|
||||
|
||||
def test_fiverr_era_video_is_eligible(self):
|
||||
c = bf.classify(_video(
|
||||
"Queen - Bohemian Rhapsody (Karaoke)",
|
||||
"This is a karaoke (instrumental) version...\nhttps://www.fiverr.com/share/j2aLvm",
|
||||
))
|
||||
assert c["kind"] == "fiverr" and c["eligible"]
|
||||
|
||||
def test_terse_new_template_detected(self):
|
||||
c = bf.classify(_video(
|
||||
"Taylor Swift - Cruel Summer (Karaoke)",
|
||||
"AI-powered vocal separation and synchronized lyrics.\n\nBrand Code: NOMAD-0009",
|
||||
))
|
||||
assert c["kind"] == "terse_new" and c["eligible"]
|
||||
assert c["brand_code"] == "NOMAD-0009"
|
||||
|
||||
def test_npbrand_code_parsed(self):
|
||||
c = bf.classify(_video("Artist - Song (Karaoke)", "Brand Code: NOMADNP-0042"))
|
||||
assert c["brand_code"] == "NOMADNP-0042"
|
||||
|
||||
def test_no_brand_code_still_eligible(self):
|
||||
c = bf.classify(_video("Oasis - Wonderwall (Karaoke)", "some description"))
|
||||
assert c["eligible"] and c["brand_code"] is None
|
||||
|
||||
def test_non_karaoke_tutorial_is_skipped(self):
|
||||
c = bf.classify(_video("Channel Trailer", "Welcome to my channel"))
|
||||
assert not c["is_karaoke"] and not c["eligible"] and c["kind"] == "non_karaoke"
|
||||
|
||||
def test_karaoke_word_but_unparseable_title_not_eligible(self):
|
||||
c = bf.classify(_video("How I Make Karaoke Videos With AI"))
|
||||
assert c["is_karaoke"] and not c["eligible"] and c["parse_confidence"] == "none"
|
||||
|
||||
def test_medium_confidence_hyphenated_not_auto_eligible(self):
|
||||
c = bf.classify(_video('YouTube "Reused content" appeal - Nomad Karaoke Explanation'))
|
||||
assert c["is_karaoke"] and c["parse_confidence"] == "medium" and not c["eligible"]
|
||||
|
||||
def test_endash_separator_supported(self):
|
||||
c = bf.classify(_video("Beyoncé – Halo (Karaoke)"))
|
||||
assert c["eligible"] and c["artist"] == "Beyoncé" and c["song_title"] == "Halo"
|
||||
|
||||
|
||||
class TestBuildEntries:
|
||||
def test_targets_and_skip_and_override(self):
|
||||
videos = {
|
||||
"a": _video("Coldplay - Yellow (Karaoke)", "Brand Code: NOMAD-1603", vid="a"),
|
||||
"b": _video("How I Make Karaoke Videos", vid="b"), # medium, not eligible
|
||||
"c": _video("Some Artist - Some Song (Karaoke)", "old desc", vid="c"),
|
||||
}
|
||||
order = ["a", "b", "c"]
|
||||
entries = bf.build_entries(
|
||||
videos, order,
|
||||
skip_ids={"c"}, # skip the otherwise-eligible one
|
||||
include_overrides={"b": {"artist": "The Band", "song_title": "The Tune"}},
|
||||
)
|
||||
by = {e["video_id"]: e for e in entries}
|
||||
assert by["a"]["target"] and by["a"]["will_change"]
|
||||
# 'b' force-included with overridden artist/title
|
||||
assert by["b"]["forced_include"] and by["b"]["target"]
|
||||
assert by["b"]["artist"] == "The Band" and by["b"]["song_title"] == "The Tune"
|
||||
assert by["b"]["parse_confidence"] == "override"
|
||||
# 'c' skipped -> not a target
|
||||
assert by["c"]["in_skip_list"] and not by["c"]["target"]
|
||||
|
||||
def test_will_change_false_when_already_current(self):
|
||||
from backend.services.youtube_description import render_youtube_description
|
||||
# Brand code must be the real 4-digit form so classify re-extracts it and
|
||||
# render_for reproduces the identical description.
|
||||
current = render_youtube_description(artist="Coldplay", title="Yellow", brand_code="NOMAD-1603")
|
||||
v = _video("Coldplay - Yellow (Karaoke)", current, vid="x")
|
||||
entries = bf.build_entries({"x": v}, ["x"], skip_ids=set(), include_overrides={})
|
||||
assert entries[0]["target"]
|
||||
assert entries[0]["brand_code"] == "NOMAD-1603"
|
||||
assert entries[0]["will_change"] is False
|
||||
|
||||
|
||||
class TestBuildUpdateSnippet:
|
||||
def test_preserves_title_category_and_swaps_description(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)", "Brand Code: NOMAD-1603"))
|
||||
current = {"title": "Coldplay - Yellow (Karaoke)", "categoryId": "10",
|
||||
"tags": ["old", "tags"], "description": "old"}
|
||||
body = bf.build_update_snippet(current, entry, enrich_tags=False)
|
||||
assert body["title"] == "Coldplay - Yellow (Karaoke)"
|
||||
assert body["categoryId"] == "10"
|
||||
assert body["tags"] == ["old", "tags"] # preserved
|
||||
assert "nomadkaraoke.com/r/youtube" in body["description"]
|
||||
assert "AI" not in body["description"]
|
||||
|
||||
def test_enrich_tags_replaces_tags(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)"))
|
||||
current = {"title": "Coldplay - Yellow (Karaoke)", "categoryId": "10", "tags": ["old"]}
|
||||
body = bf.build_update_snippet(current, entry, enrich_tags=True)
|
||||
assert "karaoke" in body["tags"]
|
||||
assert "Coldplay" in body["tags"]
|
||||
assert body["tags"] != ["old"]
|
||||
|
||||
def test_missing_category_defaults_to_music(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)"))
|
||||
body = bf.build_update_snippet({"title": "x"}, entry, enrich_tags=False)
|
||||
assert body["categoryId"] == bf.DEFAULT_MUSIC_CATEGORY
|
||||
|
||||
def test_readonly_fields_dropped(self):
|
||||
entry = bf.classify(_video("Coldplay - Yellow (Karaoke)"))
|
||||
current = {"title": "t", "categoryId": "10", "channelId": "UC...", "publishedAt": "2020"}
|
||||
body = bf.build_update_snippet(current, entry, enrich_tags=False)
|
||||
assert "channelId" not in body and "publishedAt" not in body
|
||||
|
||||
|
||||
class TestListLoaders:
|
||||
def test_skip_ids_parses_comments_and_pipe(self, tmp_path, monkeypatch):
|
||||
f = tmp_path / "skip_ids.txt"
|
||||
f.write_text("# c\nabc123 # note\nDEF456 | Artist | Title\n\n", encoding="utf-8")
|
||||
monkeypatch.setattr(bf, "SKIP_IDS_PATH", f)
|
||||
assert bf.load_skip_ids() == {"abc123", "DEF456"}
|
||||
|
||||
def test_include_overrides_bare_and_override(self, tmp_path, monkeypatch):
|
||||
f = tmp_path / "include_ids.txt"
|
||||
f.write_text("bare1 # x\nov1 | The Band | The Song\n", encoding="utf-8")
|
||||
monkeypatch.setattr(bf, "INCLUDE_IDS_PATH", f)
|
||||
out = bf.load_include_overrides()
|
||||
assert out["bare1"] is None
|
||||
assert out["ov1"] == {"artist": "The Band", "song_title": "The Song"}
|
||||
|
||||
def test_real_data_files_load(self):
|
||||
# The committed lists should parse and contain the curated decisions.
|
||||
skip = bf.load_skip_ids()
|
||||
inc = bf.load_include_overrides()
|
||||
assert "jAAhbfmh8Bc" in skip # a lyrics-with-vocals video
|
||||
assert "5zSFKuCEIhs" in inc # Los Campesinos! force-include
|
||||
assert inc["5zSFKuCEIhs"]["artist"] == "Los Campesinos!"
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Tests for the shared YouTube description/tags renderer."""
|
||||
import pytest
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.youtube_description import (
|
||||
build_youtube_tags,
|
||||
hashtagify,
|
||||
render_youtube_description,
|
||||
)
|
||||
|
||||
|
||||
class TestHashtagify:
|
||||
def test_strips_punctuation_and_spaces(self):
|
||||
assert hashtagify("Twenty One Pilots") == "TwentyOnePilots"
|
||||
assert hashtagify("P!nk") == "Pnk"
|
||||
assert hashtagify("AC/DC") == "ACDC"
|
||||
|
||||
def test_empty_or_symbol_only_returns_empty(self):
|
||||
assert hashtagify("") == ""
|
||||
assert hashtagify(None) == ""
|
||||
assert hashtagify("!!!") == ""
|
||||
|
||||
def test_keeps_unicode_letters(self):
|
||||
assert hashtagify("Beyoncé") == "Beyoncé"
|
||||
|
||||
|
||||
class TestRenderDefaultTemplate:
|
||||
"""Renders against the real canonical template from config."""
|
||||
|
||||
def _render(self, **kwargs):
|
||||
return render_youtube_description(**kwargs)
|
||||
|
||||
def test_fills_all_placeholders(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code="NOMAD-1603")
|
||||
assert "Yellow" in out
|
||||
assert "Coldplay" in out
|
||||
assert "#Coldplay" in out
|
||||
assert "Brand Code: NOMAD-1603" in out
|
||||
assert "https://nomadkaraoke.com/r/youtube" in out
|
||||
|
||||
def test_no_leftover_placeholders(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code="NOMAD-1603")
|
||||
for token in ("{artist}", "{title}", "{artist_hashtag}", "{brand_code}"):
|
||||
assert token not in out
|
||||
|
||||
def test_removes_ai_framing(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code="NOMAD-1")
|
||||
assert "AI" not in out
|
||||
assert "AI-powered" not in out
|
||||
|
||||
def test_omits_brand_code_line_when_absent(self):
|
||||
out = self._render(artist="Coldplay", title="Yellow", brand_code=None)
|
||||
assert "Brand Code" not in out
|
||||
assert "{brand_code}" not in out
|
||||
# No dangling blank block at the end.
|
||||
assert not out.endswith("\n")
|
||||
|
||||
def test_drops_artist_hashtag_when_unrenderable(self):
|
||||
out = self._render(artist="!!!", title="Song", brand_code="NOMAD-2")
|
||||
# No stray empty hashtag left behind.
|
||||
assert "# " not in out
|
||||
assert "#{artist_hashtag}" not in out
|
||||
assert "#karaoke #instrumental" in out
|
||||
|
||||
def test_config_default_is_the_canonical_template(self):
|
||||
# Guard: the config default must carry the placeholders the renderer expects.
|
||||
tpl = get_settings().default_youtube_description
|
||||
assert "{title}" in tpl and "{artist}" in tpl
|
||||
assert "{brand_code}" in tpl
|
||||
assert "nomadkaraoke.com/r/youtube" in tpl
|
||||
|
||||
|
||||
class TestRenderLegacyTemplate:
|
||||
def test_template_without_placeholders_appends_brand_code(self):
|
||||
legacy = "Karaoke video created with Nomad Karaoke.\n\n#karaoke"
|
||||
out = render_youtube_description(
|
||||
artist="Coldplay", title="Yellow", brand_code="NOMAD-1603", template=legacy
|
||||
)
|
||||
assert out.endswith("Brand Code: NOMAD-1603")
|
||||
assert out.startswith("Karaoke video created with Nomad Karaoke.")
|
||||
|
||||
def test_template_without_placeholders_no_brand_code(self):
|
||||
legacy = "Karaoke video created with Nomad Karaoke.\n\n#karaoke"
|
||||
out = render_youtube_description(
|
||||
artist="Coldplay", title="Yellow", brand_code=None, template=legacy
|
||||
)
|
||||
assert "Brand Code" not in out
|
||||
|
||||
|
||||
class TestBuildTags:
|
||||
def test_includes_core_and_song_specific_tags(self):
|
||||
tags = build_youtube_tags("Coldplay", "Yellow")
|
||||
assert "karaoke" in tags
|
||||
assert "Coldplay" in tags
|
||||
assert "Yellow" in tags
|
||||
assert "Coldplay karaoke" in tags
|
||||
|
||||
def test_deduplicates_case_insensitively(self):
|
||||
# An artist literally named "Karaoke" must not duplicate the core tag.
|
||||
tags = build_youtube_tags("karaoke", "Test")
|
||||
assert sum(1 for t in tags if t.lower() == "karaoke") == 1
|
||||
|
||||
def test_skips_empty_artist_title(self):
|
||||
tags = build_youtube_tags("", "")
|
||||
assert "" not in tags
|
||||
assert "karaoke" in tags
|
||||
|
||||
def test_respects_total_length_budget(self):
|
||||
tags = build_youtube_tags("A" * 300, "B" * 300)
|
||||
total = sum(len(t) + 1 for t in tags)
|
||||
assert total <= 460
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Tests for the scheduled YouTube description backfill worker."""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.youtube_description import render_youtube_description
|
||||
from backend.workers import youtube_description_backfill_worker as worker
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Fakes
|
||||
# ----------------------------------------------------------------------------
|
||||
class FakeDocRef:
|
||||
def __init__(self, data=None):
|
||||
self.data = data
|
||||
self.set_calls = []
|
||||
|
||||
def get(self):
|
||||
m = MagicMock()
|
||||
m.exists = self.data is not None
|
||||
m.to_dict.return_value = dict(self.data) if self.data else {}
|
||||
return m
|
||||
|
||||
def set(self, d):
|
||||
self.data = dict(d)
|
||||
self.set_calls.append(dict(d))
|
||||
|
||||
|
||||
def _fake_db(ref):
|
||||
db = MagicMock()
|
||||
db.collection.return_value.document.return_value = ref
|
||||
return db
|
||||
|
||||
|
||||
def _fake_settings(**overrides):
|
||||
base = dict(
|
||||
youtube_backfill_enabled=True,
|
||||
default_youtube_description="TEMPLATE-V1 {title} {artist} {brand_code}",
|
||||
youtube_backfill_quota_reserve=3000,
|
||||
youtube_backfill_daily_max_updates=150,
|
||||
youtube_backfill_enrich_tags=True,
|
||||
youtube_backfill_report_email="andrew@nomadkaraoke.com",
|
||||
)
|
||||
base.update(overrides)
|
||||
return SimpleNamespace(**base)
|
||||
|
||||
|
||||
def _entry(vid, will_change=True, target=True):
|
||||
return {
|
||||
"video_id": vid,
|
||||
"yt_title": f"Artist - {vid} (Karaoke)",
|
||||
"artist": "Artist",
|
||||
"song_title": vid,
|
||||
"brand_code": "NOMAD-1603",
|
||||
"parse_confidence": "high",
|
||||
"kind": "terse_new",
|
||||
"is_karaoke": True,
|
||||
"eligible": True,
|
||||
"category_id": "10",
|
||||
"current_description": "old description",
|
||||
"target": target,
|
||||
"will_change": will_change,
|
||||
"in_skip_list": False,
|
||||
"forced_include": False,
|
||||
}
|
||||
|
||||
|
||||
def _videos(vids):
|
||||
return {v: {"id": v, "snippet": {"title": f"Artist - {v} (Karaoke)", "categoryId": "10",
|
||||
"description": "old description", "tags": ["old"]}} for v in vids}
|
||||
|
||||
|
||||
class _Ctx:
|
||||
"""Bundle of patches; returns handles for assertions."""
|
||||
|
||||
def __init__(self, entries, videos, settings=None, quota_remaining=100000):
|
||||
self.entries = entries
|
||||
self.videos = videos
|
||||
self.settings = settings or _fake_settings()
|
||||
self.ref = FakeDocRef()
|
||||
self.youtube = MagicMock()
|
||||
self.youtube.videos.return_value.update.return_value.execute.return_value = {}
|
||||
self.quota = MagicMock()
|
||||
self.quota.get_quota_stats.return_value = {"units_remaining": quota_remaining}
|
||||
self.email = MagicMock()
|
||||
|
||||
def __enter__(self):
|
||||
self._patches = [
|
||||
patch.object(worker, "get_settings", return_value=self.settings),
|
||||
patch.object(worker.bf, "load_credentials_from_secret", return_value={"refresh_token": "x"}),
|
||||
patch.object(worker.bf, "build_youtube", return_value=self.youtube),
|
||||
patch.object(worker.bf, "fetch_all_channel_entries", return_value=(self.entries, self.videos)),
|
||||
patch.object(worker, "get_firestore_client", return_value=_fake_db(self.ref)),
|
||||
patch.object(worker, "get_youtube_quota_service", return_value=self.quota),
|
||||
patch.object(worker, "_email_service", return_value=self.email),
|
||||
]
|
||||
for p in self._patches:
|
||||
p.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
for p in self._patches:
|
||||
p.stop()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ----------------------------------------------------------------------------
|
||||
def test_disabled_short_circuits():
|
||||
with _Ctx([], {}, settings=_fake_settings(youtube_backfill_enabled=False)) as ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["status"] == "disabled"
|
||||
ctx.youtube.videos.assert_not_called()
|
||||
|
||||
|
||||
def test_full_drain_updates_all_and_sends_completion():
|
||||
vids = ["a", "b", "c"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
with _Ctx(entries, _videos(vids)) as ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["updated"] == 3
|
||||
assert result["pending_after"] == 0
|
||||
assert result["completed"] is True
|
||||
# 3 videos.update calls
|
||||
assert ctx.youtube.videos.return_value.update.call_count == 3
|
||||
# completion email sent, subject mentions complete
|
||||
subj = ctx.email.send_email.call_args.kwargs["subject"]
|
||||
assert "complete" in subj.lower()
|
||||
# state persisted with completed_notified
|
||||
assert ctx.ref.data["completed_notified"] is True
|
||||
assert ctx.ref.data["completed"] is True
|
||||
|
||||
|
||||
def test_budget_cap_partial_and_progress_email():
|
||||
vids = ["a", "b", "c"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
with _Ctx(entries, _videos(vids)) as ctx:
|
||||
result = worker.run_backfill_sync(max_updates=2)
|
||||
assert result["updated"] == 2
|
||||
assert result["pending_after"] == 1
|
||||
assert result["completed"] is False
|
||||
subj = ctx.email.send_email.call_args.kwargs["subject"]
|
||||
assert "remaining" in subj.lower()
|
||||
assert ctx.ref.data.get("completed_notified") in (None, False)
|
||||
|
||||
|
||||
def test_quota_reserve_blocks_updates():
|
||||
vids = ["a", "b"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
# remaining barely above reserve -> budget 0
|
||||
with _Ctx(entries, _videos(vids), quota_remaining=3010) as ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["budget"] == 0
|
||||
assert result["updated"] == 0
|
||||
ctx.youtube.videos.return_value.update.assert_not_called()
|
||||
|
||||
|
||||
def test_dry_run_makes_no_changes():
|
||||
vids = ["a", "b"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
with _Ctx(entries, _videos(vids)) as ctx:
|
||||
result = worker.run_backfill_sync(dry_run=True)
|
||||
assert result["dry_run"] is True
|
||||
ctx.youtube.videos.return_value.update.assert_not_called()
|
||||
ctx.email.send_email.assert_not_called()
|
||||
assert ctx.ref.set_calls == [] # no state persisted on dry run
|
||||
|
||||
|
||||
def test_nothing_pending_already_notified_no_email():
|
||||
# Channel already fully drained and previously notified.
|
||||
entries = [_entry("a", will_change=False)]
|
||||
ctx = _Ctx(entries, _videos(["a"]))
|
||||
ctx.ref = FakeDocRef({
|
||||
"template_fingerprint": worker._template_fingerprint(ctx.settings),
|
||||
"completed": True,
|
||||
"completed_notified": True,
|
||||
"cycle_index": 1,
|
||||
})
|
||||
with ctx:
|
||||
result = worker.run_backfill_sync()
|
||||
assert result["updated"] == 0
|
||||
assert result["completed"] is True
|
||||
ctx.email.send_email.assert_not_called()
|
||||
|
||||
|
||||
def test_template_change_starts_new_cycle():
|
||||
entries = [_entry("a", will_change=False)]
|
||||
ctx = _Ctx(entries, _videos(["a"]))
|
||||
# Prior state has a DIFFERENT fingerprint -> new cycle should bump cycle_index.
|
||||
ctx.ref = FakeDocRef({
|
||||
"template_fingerprint": "STALEFINGERPRINT",
|
||||
"completed": True,
|
||||
"completed_notified": True,
|
||||
"cycle_index": 2,
|
||||
})
|
||||
with ctx:
|
||||
worker.run_backfill_sync()
|
||||
assert ctx.ref.data["cycle_index"] == 3
|
||||
assert ctx.ref.data["template_fingerprint"] == worker._template_fingerprint(ctx.settings)
|
||||
|
||||
|
||||
def test_quota_exceeded_stops_run():
|
||||
vids = ["a", "b", "c"]
|
||||
entries = [_entry(v) for v in vids]
|
||||
ctx = _Ctx(entries, _videos(vids))
|
||||
# First update ok, second raises quotaExceeded.
|
||||
calls = {"n": 0}
|
||||
|
||||
def _exec():
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise RuntimeError("quotaExceeded: The request cannot be completed")
|
||||
return {}
|
||||
|
||||
with ctx:
|
||||
ctx.youtube.videos.return_value.update.return_value.execute.side_effect = _exec
|
||||
result = worker.run_backfill_sync()
|
||||
# 1 success, stopped on the 2nd (quota) before doing the 3rd
|
||||
assert result["updated"] == 1
|
||||
assert result["completed"] is False
|
||||
@@ -347,11 +347,21 @@
|
||||
"body": "Great news — \"{artist} - {title}\", a karaoke track you voted for on the Nomad Karaoke requests board, is now live on YouTube:",
|
||||
"callToAction": "Want to pick the next free track? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Thanks for voting!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"greeting": "Hi {name},",
|
||||
"body": "Good news — a karaoke version of \"{artist} - {title}\" (which you voted for on the Nomad Karaoke requests board) already exists online, so we won't be re-making it. Here's a version you can use right now:",
|
||||
"callToAction": "Want to help pick the next FREE track we make? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Happy singing!\n-Andrew"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} is live on YouTube! 🎉",
|
||||
"subjectFallback": "A track you voted for is now live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "A karaoke version of {artist} - {title} already exists",
|
||||
"subjectFallback": "A karaoke version of the song you requested already exists"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "هل ترغب في اختيار المقطع المجاني التالي؟ صوّت عبر https://requests.nomadkaraoke.com",
|
||||
"greeting": "مرحباً {name}،",
|
||||
"signOff": "شكراً لتصويتك!\n- أندرو"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "أخبار سارة — توجد بالفعل نسخة كاريوكي لأغنية \"{artist} - {title}\" (التي قمت بالتصويت لها في لوحة طلبات Nomad Karaoke) متاحة على الإنترنت، لذا لن نقوم بإعادة إنتاجها. إليك نسخة يمكنك استخدامها الآن:",
|
||||
"callToAction": "هل ترغب في المساعدة في اختيار الأغنية المجانية التالية التي سنقوم بإنتاجها؟ صوّت عبر https://requests.nomadkaraoke.com",
|
||||
"signOff": "غناء ممتع!\n-أندرو",
|
||||
"greeting": "مرحباً {name}،"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} متاح الآن على YouTube! 🎉",
|
||||
"subjectFallback": "المقطع الذي صوّت له متاح الآن!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "توجد بالفعل نسخة كاريوكي لأغنية {artist} - {title}",
|
||||
"subjectFallback": "توجد بالفعل نسخة كاريوكي للأغنية التي طلبتها"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Vols triar la propera pista gratuïta? Vota a https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hola {name},",
|
||||
"signOff": "Gràcies per votar!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Bones notícies — ja existeix a internet una versió de karaoke de \"{artist} - {title}\" (que vas votar al tauler de peticions de Nomad Karaoke), així que no la tornarem a fer. Aquí tens una versió que pots utilitzar ara mateix:",
|
||||
"callToAction": "Vols ajudar a triar la següent pista GRATUÏTA que farem? Vota a https://requests.nomadkaraoke.com",
|
||||
"signOff": "Que gaudeixis cantant!\n-Andrew",
|
||||
"greeting": "Hola {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} ja està disponible a YouTube! 🎉",
|
||||
"subjectFallback": "Una pista que vas votar ja està disponible!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Ja existeix una versió de karaoke de {artist} - {title}",
|
||||
"subjectFallback": "Ja existeix una versió de karaoke de la cançó que has demanat"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Chceš vybrat další skladbu zdarma? Hlasuj na https://requests.nomadkaraoke.com",
|
||||
"greeting": "Ahoj {name},",
|
||||
"signOff": "Díky za hlasování!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Máme dobrou zprávu — karaoke verze \"{artist} - {title}\" (která dostala tvůj hlas na nástěnce přání Nomad Karaoke) už na internetu existuje, takže ji nebudeme vytvářet znovu. Tady je verze, kterou můžeš rovnou použít:",
|
||||
"callToAction": "Chceš pomoct vybrat další písničku, kterou vytvoříme ZDARMA? Hlasuj na https://requests.nomadkaraoke.com",
|
||||
"signOff": "Příjemné zpívání!\n-Andrew",
|
||||
"greeting": "Ahoj {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} je nyní na YouTube! 🎉",
|
||||
"subjectFallback": "Skladba, pro kterou jsi hlasoval/a, je nyní online!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Karaoke verze {artist} - {title} už existuje",
|
||||
"subjectFallback": "Karaoke verze požadované písničky už existuje"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Vil du være med til at vælge det næste gratis nummer? Stem på https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hej {name},",
|
||||
"signOff": "Tak for din stemme!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Gode nyheder — en karaoke-version af \"{artist} - {title}\" (som du stemte på på Nomad Karaokes ønsketavle) findes allerede online, så vi kommer ikke til at lave en ny version. Her er en version, du kan bruge med det samme:",
|
||||
"callToAction": "Vil du hjælpe med at vælge det næste GRATIS nummer, vi laver? Stem på https://requests.nomadkaraoke.com",
|
||||
"signOff": "God sanglyst!\n-Andrew",
|
||||
"greeting": "Hej {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} er live på YouTube! 🎉",
|
||||
"subjectFallback": "Et nummer, du har stemt på, er nu live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "En karaoke-version af {artist} - {title} findes allerede",
|
||||
"subjectFallback": "En karaoke-version af den sang, du efterspurgte, findes allerede"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Möchtest du den nächsten kostenlosen Track auswählen? Stimme ab unter https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hallo {name},",
|
||||
"signOff": "Danke fürs Abstimmen!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Gute Nachrichten — eine Karaoke-Version von \"{artist} - {title}\" (für die du auf dem Nomad Karaoke Wunsch-Board abgestimmt hast) existiert bereits online, daher werden wir sie nicht neu erstellen. Hier ist eine Version, die du sofort nutzen kannst:",
|
||||
"callToAction": "Möchtest du mitentscheiden, welchen KOSTENLOSEN Track wir als Nächstes erstellen? Stimme ab unter https://requests.nomadkaraoke.com",
|
||||
"signOff": "Viel Spaß beim Singen!\n-Andrew",
|
||||
"greeting": "Hallo {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} ist live auf YouTube! 🎉",
|
||||
"subjectFallback": "Ein Track, für den du abgestimmt hast, ist jetzt live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Eine Karaoke-Version von {artist} - {title} existiert bereits",
|
||||
"subjectFallback": "Eine Karaoke-Version deines gewünschten Songs existiert bereits"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Θέλεις να επιλέξεις το επόμενο δωρεάν κομμάτι; Ψήφισε στο https://requests.nomadkaraoke.com",
|
||||
"greeting": "Γεια σου {name},",
|
||||
"signOff": "Ευχαριστώ που ψήφισες!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Καλά νέα — μια έκδοση καραόκε του \"{artist} - {title}\" (για το οποίο ψήφισες στον πίνακα αιτημάτων του Nomad Karaoke) υπάρχει ήδη στο διαδίκτυο, οπότε δεν θα τη φτιάξουμε από την αρχή. Ορίστε μια έκδοση που μπορείς να χρησιμοποιήσεις αμέσως:",
|
||||
"callToAction": "Θέλεις να βοηθήσεις στην επιλογή του επόμενου ΔΩΡΕΑΝ κομματιού που θα φτιάξουμε; Ψήφισε στο https://requests.nomadkaraoke.com",
|
||||
"signOff": "Καλό τραγούδι!\n-Andrew",
|
||||
"greeting": "Γεια σου {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} είναι διαθέσιμο στο YouTube! 🎉",
|
||||
"subjectFallback": "Ένα κομμάτι που ψήφισες είναι πλέον διαθέσιμο!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Μια έκδοση καραόκε του {artist} - {title} υπάρχει ήδη",
|
||||
"subjectFallback": "Μια έκδοση καραόκε του τραγουδιού που ζήτησες υπάρχει ήδη"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"body": "Great news — \"{artist} - {title}\", a karaoke track you voted for on the Nomad Karaoke requests board, is now live on YouTube:",
|
||||
"callToAction": "Want to pick the next free track? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Thanks for voting!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"greeting": "Hi {name},",
|
||||
"body": "Good news — a karaoke version of \"{artist} - {title}\" (which you voted for on the Nomad Karaoke requests board) already exists online, so we won't be re-making it. Here's a version you can use right now:",
|
||||
"callToAction": "Want to help pick the next FREE track we make? Vote at https://requests.nomadkaraoke.com",
|
||||
"signOff": "Happy singing!\n-Andrew"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} is live on YouTube! 🎉",
|
||||
"subjectFallback": "A track you voted for is now live!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "A karaoke version of {artist} - {title} already exists",
|
||||
"subjectFallback": "A karaoke version of the song you requested already exists"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "¿Quieres elegir la próxima pista gratuita? Vota en https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hola {name},",
|
||||
"signOff": "¡Gracias por votar!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Buenas noticias: ya existe en línea una versión de karaoke de \"{artist} - {title}\" (por la que votaste en el tablero de solicitudes de Nomad Karaoke), así que no haremos una nueva versión. Aquí tienes una versión que puedes usar ahora mismo:",
|
||||
"callToAction": "¿Quieres ayudar a elegir la próxima pista GRATUITA que hagamos? Vota en https://requests.nomadkaraoke.com",
|
||||
"signOff": "¡Que disfrutes cantando!\n-Andrew",
|
||||
"greeting": "Hola {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "¡{artist} - {title} ya está disponible en YouTube! 🎉",
|
||||
"subjectFallback": "¡Una pista por la que votaste ya está disponible!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Ya existe una versión de karaoke de {artist} - {title}",
|
||||
"subjectFallback": "Ya existe una versión de karaoke de la canción que solicitaste"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Haluatko valita seuraavan ilmaisen kappaleen? Äänestä osoitteessa https://requests.nomadkaraoke.com",
|
||||
"greeting": "Hei {name},",
|
||||
"signOff": "Kiitos äänestämisestä!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Hyviä uutisia — karaokeversio kappaleesta \"{artist} - {title}\" (jota äänestit Nomad Karaoke -toivetaululla) löytyy jo verkosta, joten emme tee siitä uutta versiota. Tässä on versio, jota voit käyttää heti:",
|
||||
"callToAction": "Haluatko auttaa valitsemaan seuraavan ILMAISEN kappaleen, jonka teemme? Äänestä osoitteessa https://requests.nomadkaraoke.com",
|
||||
"signOff": "Mukavia lauluhetkiä!\n-Andrew",
|
||||
"greeting": "Hei {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} on nyt YouTubessa! 🎉",
|
||||
"subjectFallback": "Äänestämäsi kappale on nyt julkaistu!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Karaokeversio kappaleesta {artist} - {title} on jo olemassa",
|
||||
"subjectFallback": "Karaokeversio pyytämästäsi kappaleesta on jo olemassa"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "Tu veux choisir le prochain titre gratuit ? Vote sur https://requests.nomadkaraoke.com",
|
||||
"greeting": "Salut {name},",
|
||||
"signOff": "Merci d'avoir voté !\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "Bonne nouvelle ! Une version karaoké de \"{artist} - {title}\" (pour laquelle tu as voté sur la liste des demandes de Nomad Karaoke) existe déjà en ligne, nous n'allons donc pas la recréer. Voici une version que tu peux utiliser dès maintenant :",
|
||||
"callToAction": "Tu veux aider à choisir le prochain titre GRATUIT que nous créerons ? Vote sur https://requests.nomadkaraoke.com",
|
||||
"signOff": "Bon karaoké !\n-Andrew",
|
||||
"greeting": "Salut {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} est en ligne sur YouTube ! 🎉",
|
||||
"subjectFallback": "Un titre pour lequel tu as voté est maintenant en ligne !"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "Une version karaoké de {artist} - {title} existe déjà",
|
||||
"subjectFallback": "Une version karaoké de la chanson que tu as demandée existe déjà"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "רוצה לבחור את השיר החינמי הבא? אפשר להצביע בכתובת https://requests.nomadkaraoke.com",
|
||||
"greeting": "היי {name},",
|
||||
"signOff": "תודה על ההצבעה!\n- אנדרו"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "חדשות טובות — גרסת קריוקי של \"{artist} - {title}\" (שהצבעתם עבורה בלוח הבקשות של Nomad Karaoke) כבר קיימת ברשת, אז לא ניצור אותה מחדש. הנה גרסה שתוכלו להשתמש בה כבר עכשיו:",
|
||||
"callToAction": "רוצים לעזור לבחור את הרצועה החינמית הבאה שניצור? הצביעו ב-https://requests.nomadkaraoke.com",
|
||||
"signOff": "שירה מהנה!\n-Andrew",
|
||||
"greeting": "היי {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} עלה ל-YouTube! 🎉",
|
||||
"subjectFallback": "שיר שהצבעת עבורו עלה לאוויר!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "גרסת קריוקי של {artist} - {title} כבר קיימת",
|
||||
"subjectFallback": "גרסת קריוקי של השיר שביקשתם כבר קיימת"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,11 +347,21 @@
|
||||
"callToAction": "क्या तुम अगला फ्री ट्रैक चुनना चाहते हो? https://requests.nomadkaraoke.com पर वोट करो",
|
||||
"greeting": "हाय {name},",
|
||||
"signOff": "वोट करने के लिए धन्यवाद!\n-Andrew"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"body": "अच्छी ख़बर — \"{artist} - {title}\" का कराओके वर्ज़न (जिसके लिए तुमने Nomad Karaoke रिक्वेस्ट बोर्ड पर वोट किया था) ऑनलाइन पहले से ही मौजूद है, इसलिए हम इसे दोबारा नहीं बनाएंगे। यहाँ एक वर्ज़न है जिसका तुम अभी इस्तेमाल कर सकते हो:",
|
||||
"callToAction": "क्या तुम हमारा अगला मुफ़्त (FREE) ट्रैक चुनने में मदद करना चाहते हो? https://requests.nomadkaraoke.com पर वोट करो",
|
||||
"signOff": "गाने का आनंद लो!\n-Andrew",
|
||||
"greeting": "हाय {name},"
|
||||
}
|
||||
},
|
||||
"communityTrackLive": {
|
||||
"subject": "{artist} - {title} YouTube पर लाइव है! 🎉",
|
||||
"subjectFallback": "जिस ट्रैक के लिए तुमने वोट किया था, वह अब लाइव है!"
|
||||
},
|
||||
"communityExistingVersion": {
|
||||
"subject": "{artist} - {title} का कराओके वर्ज़न पहले से मौजूद है",
|
||||
"subjectFallback": "तुमने जिस गाने की रिक्वेस्ट की थी, उसका कराओके वर्ज़न पहले से मौजूद है"
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user