mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
Compare commits
No files matched your search
@@ -1106,6 +1106,13 @@ jobs:
|
||||
GPU_REPOSITORY: karaoke-backend-gpu
|
||||
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
|
||||
GPU_APP_IMAGE_NAME: karaoke-backend
|
||||
# CPU app image copy for the latency-critical CPU jobs (audio-download,
|
||||
# lyrics-transcription, bulk-search) in us-east4, where Cloud Run Jobs start
|
||||
# in ~15s instead of 2-5 min. Lives in the existing us-east4 repo so the jobs
|
||||
# pull same-region; only changed app layers cross regions on each push.
|
||||
CPU_JOBS_REGISTRY: us-east4-docker.pkg.dev
|
||||
CPU_JOBS_REPOSITORY: karaoke-backend-gpu
|
||||
CPU_JOBS_IMAGE_NAME: karaoke-backend-cpu
|
||||
steps:
|
||||
- name: Check disk space (aggressive for Docker builds)
|
||||
run: |
|
||||
@@ -1859,12 +1866,32 @@ jobs:
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:latest
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
# Registry cache for app layers
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
- name: Pre-import CPU image for us-east4 jobs
|
||||
# A new image digest costs a one-time ~2.5 min "Container image import" on
|
||||
# its FIRST execution in a region (measured 2026-09-29); later executions
|
||||
# of any job using that digest start in ~8s. audio-download-job runs
|
||||
# :latest (just pushed), so a no-op execution now performs the import
|
||||
# while the service deploy + smoke test run, instead of on the first
|
||||
# customer download. Async on purpose: the import overlaps the rest of
|
||||
# the deploy. Non-fatal: worst case the first download pays the import.
|
||||
run: |
|
||||
gcloud run jobs execute audio-download-job \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--args="python,-c,pass" \
|
||||
--async \
|
||||
--quiet \
|
||||
|| echo "::warning::us-east4 CPU image pre-import execution failed to start (non-fatal)"
|
||||
|
||||
# ============================================
|
||||
# GPU Image Build (for audio worker with L4 GPU)
|
||||
# Same pattern as base image: hash check → rebuild if needed.
|
||||
@@ -2125,19 +2152,22 @@ jobs:
|
||||
# daily E2E run 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 }}"
|
||||
CPU_JOBS_IMAGE="${{ env.CPU_JOBS_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.CPU_JOBS_REPOSITORY }}/${{ env.CPU_JOBS_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
echo "📦 Updating Cloud Run Jobs..."
|
||||
|
||||
# Video encoding job (CPU, us-central1)
|
||||
# Video encoding job (CPU, us-east4; also runs render_video_worker)
|
||||
gcloud run jobs update video-encoding-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
--image "$CPU_JOBS_IMAGE" \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
# Lyrics transcription job (CPU, us-east4 — see CPU_JOBS_REGION in
|
||||
# backend/config.py). The us-east4 job is created by Pulumi, so
|
||||
# `pulumi up` must run BEFORE merging a change that introduces it. audio-download-job and bulk-search-job track the
|
||||
# :latest tag pushed above, so they need no update here.
|
||||
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
|
||||
# ("Invalid secret path ... in annotation") because this job's existing
|
||||
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
|
||||
@@ -2147,8 +2177,8 @@ jobs:
|
||||
# doc); until then the proactive flag stays unset and the worker's
|
||||
# _run_proactive_auto_correct() returns early (no-op).
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
--image "$CPU_JOBS_IMAGE" \
|
||||
--region us-east4 \
|
||||
--project ${{ env.PROJECT_ID }} \
|
||||
--quiet
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PROJECT: karaoke-gen
|
||||
KEEP_DAYS: "60"
|
||||
KEEP_DAYS: "30"
|
||||
# Only nag once the project crosses this watermark — pruning holds it at
|
||||
# ~4-7 GB, and there are always old releases to consolidate, so without a
|
||||
# threshold this would open an issue every month for no real reason. 7 GB
|
||||
|
||||
@@ -432,8 +432,14 @@ def _prepare_theme_for_job(
|
||||
color_overrides=color_overrides_model
|
||||
)
|
||||
|
||||
# Get YouTube description template if available
|
||||
youtube_desc = theme_service.get_youtube_description(theme_id)
|
||||
# Settings.default_youtube_description is the single source of truth for
|
||||
# YouTube descriptions. A theme's legacy youtube_description.txt is only a
|
||||
# fallback when no canonical template is configured — otherwise it silently
|
||||
# overrode the template on every themed job (the nomad theme's copy was stale
|
||||
# Fiverr text, which the daily description-backfill worker then had to undo).
|
||||
youtube_desc = None
|
||||
if not get_settings().default_youtube_description:
|
||||
youtube_desc = theme_service.get_youtube_description(theme_id)
|
||||
|
||||
logger.info(f"Prepared theme '{theme_id}' for job {job_id}")
|
||||
|
||||
@@ -1127,6 +1133,69 @@ async def _validate_audio_durations(
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
|
||||
# Conforming decodes both files and runs ffmpeg in the API process (2Gi, /tmp is
|
||||
# in-memory); cap how many run at once per instance.
|
||||
_CONFORM_SEMAPHORE = asyncio.Semaphore(2)
|
||||
|
||||
|
||||
def _conform_mismatched_instrumental_sync(
|
||||
storage: StorageService,
|
||||
job_id: str,
|
||||
audio_gcs_path: str,
|
||||
instrumental_gcs_path: str,
|
||||
) -> Optional[Tuple[str, Dict[str, Any]]]:
|
||||
from backend.services.instrumental_conform import InstrumentalConformError, conform_instrumental
|
||||
|
||||
temp_dir = tempfile.mkdtemp(prefix="instrumental_conform_")
|
||||
try:
|
||||
audio_local = os.path.join(temp_dir, "audio" + Path(audio_gcs_path).suffix)
|
||||
instrumental_local = os.path.join(temp_dir, "instrumental" + Path(instrumental_gcs_path).suffix)
|
||||
out_local = os.path.join(temp_dir, "conformed.flac")
|
||||
storage.download_file(audio_gcs_path, audio_local)
|
||||
storage.download_file(instrumental_gcs_path, instrumental_local)
|
||||
try:
|
||||
result = conform_instrumental(audio_local, instrumental_local, out_local)
|
||||
except InstrumentalConformError as e:
|
||||
if not e.mismatch:
|
||||
raise
|
||||
logger.warning(f"Job {job_id}: instrumental could not be conformed: {e}")
|
||||
return None
|
||||
conformed_gcs_path = f"uploads/{job_id}/conformed/existing_instrumental.flac"
|
||||
storage.upload_file(out_local, conformed_gcs_path)
|
||||
return conformed_gcs_path, {**result.to_dict(), "original_gcs_path": instrumental_gcs_path}
|
||||
finally:
|
||||
import shutil
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
|
||||
async def _conform_mismatched_instrumental(
|
||||
storage: StorageService,
|
||||
job_id: str,
|
||||
audio_gcs_path: str,
|
||||
instrumental_gcs_path: str,
|
||||
locale: str = "en",
|
||||
) -> Optional[Tuple[str, Dict[str, Any]]]:
|
||||
"""Line the instrumental up with the mix and fit it to the mix's length.
|
||||
|
||||
Returns (conformed GCS path, adjustment details), or None when the files
|
||||
don't line up (almost certainly the wrong instrumental). The original upload
|
||||
is kept; the conformed copy lives outside the ``audio/`` prefix so it's never
|
||||
mistaken for the mixed audio. Infrastructure failures (GCS, ffmpeg crash)
|
||||
raise a retryable 503 rather than cancelling the job as a "wrong file".
|
||||
"""
|
||||
async with _CONFORM_SEMAPHORE:
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
_conform_mismatched_instrumental_sync, storage, job_id, audio_gcs_path, instrumental_gcs_path
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: conforming instrumental failed unexpectedly: {e}", exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=t(locale, "jobs.instrumentalConformUnavailable"),
|
||||
) from e
|
||||
|
||||
|
||||
def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
|
||||
"""Generate the GCS path for a file based on its type."""
|
||||
ext = Path(filename).suffix.lower()
|
||||
@@ -1538,28 +1607,40 @@ async def mark_uploads_complete(
|
||||
storage_service, audio_gcs_path, instrumental_gcs_path
|
||||
)
|
||||
if not duration_valid:
|
||||
# Cancel (refunds the credit) so the job isn't stranded PENDING
|
||||
# with uploaded files — the stale-upload sweep skips those.
|
||||
job_manager.cancel_job(
|
||||
job_id,
|
||||
reason=(
|
||||
f"Instrumental duration ({instrumental_duration:.2f}s) does not match "
|
||||
f"audio duration ({audio_duration:.2f}s)"
|
||||
),
|
||||
# Different edits of the same song (extra count-in, longer or
|
||||
# shorter outro) are lined up with the mix automatically; only a
|
||||
# file that doesn't correlate with the mix at all is rejected.
|
||||
conform = await _conform_mismatched_instrumental(
|
||||
storage_service, job_id, audio_gcs_path, instrumental_gcs_path, locale
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"error": "duration_mismatch",
|
||||
"message": t(locale, "jobs.uploadDurationMismatchCancelled",
|
||||
instrumental_duration=f"{instrumental_duration:.1f}",
|
||||
audio_duration=f"{audio_duration:.1f}"),
|
||||
"audio_duration": audio_duration,
|
||||
"instrumental_duration": instrumental_duration,
|
||||
"difference": abs(audio_duration - instrumental_duration),
|
||||
}
|
||||
)
|
||||
logger.info(f"Duration validation passed: audio={audio_duration:.2f}s, instrumental={instrumental_duration:.2f}s")
|
||||
if conform is None:
|
||||
# Cancel (refunds the credit) so the job isn't stranded PENDING
|
||||
# with uploaded files — the stale-upload sweep skips those.
|
||||
job_manager.cancel_job(
|
||||
job_id,
|
||||
reason=(
|
||||
f"Instrumental duration ({instrumental_duration:.2f}s) does not match "
|
||||
f"audio duration ({audio_duration:.2f}s) and could not be aligned"
|
||||
),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"error": "duration_mismatch",
|
||||
"message": t(locale, "jobs.uploadDurationMismatchCancelled",
|
||||
instrumental_duration=f"{instrumental_duration:.1f}",
|
||||
audio_duration=f"{audio_duration:.1f}"),
|
||||
"audio_duration": audio_duration,
|
||||
"instrumental_duration": instrumental_duration,
|
||||
"difference": abs(audio_duration - instrumental_duration),
|
||||
}
|
||||
)
|
||||
conformed_path, conform_info = conform
|
||||
update_data['existing_instrumental_gcs_path'] = conformed_path
|
||||
job_manager.update_state_data(job_id, 'instrumental_conformed', conform_info)
|
||||
logger.info(f"Job {job_id}: conformed instrumental to mix length: {conform_info}")
|
||||
else:
|
||||
logger.info(f"Duration validation passed: audio={audio_duration:.2f}s, instrumental={instrumental_duration:.2f}s")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
|
||||
+145
-1
@@ -30,6 +30,7 @@ from backend.models.requests import (
|
||||
CompleteReviewRequest,
|
||||
CreateCustomInstrumentalRequest,
|
||||
)
|
||||
from backend.services.audio_download_limits import KEEP_TRYING_STATE_KEY
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.tempo_label import apply_tempo_to_title
|
||||
from backend.services.worker_service import get_worker_service
|
||||
@@ -2014,16 +2015,27 @@ async def cancel_job(
|
||||
}
|
||||
|
||||
|
||||
class RetryJobRequest(BaseModel):
|
||||
"""Optional body for POST /jobs/{id}/retry."""
|
||||
# For a stalled torrent download: wait up to an hour (instead of the default
|
||||
# 20 minutes) for the file's seeder to come back online.
|
||||
keep_trying: bool = False
|
||||
|
||||
|
||||
@router.post("/{job_id}/retry")
|
||||
async def retry_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: Optional[RetryJobRequest] = None,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Retry a failed or cancelled job from the last successful checkpoint.
|
||||
|
||||
Body (optional): ``{"keep_trying": true}`` retries a stalled audio download
|
||||
with the extended (1 hour) stall budget.
|
||||
|
||||
This endpoint allows resuming jobs that failed or were cancelled during:
|
||||
- Audio processing (re-runs from beginning if input audio exists)
|
||||
- Video generation (re-runs video worker)
|
||||
@@ -2068,6 +2080,28 @@ async def retry_job(
|
||||
# Check what state exists to determine retry point
|
||||
file_urls = job.file_urls or {}
|
||||
state_data = job.state_data or {}
|
||||
|
||||
# A theme re-render that failed before its new screens were made: re-run
|
||||
# the re-render (not the generic ladder below, which could send the job
|
||||
# back to review). Once screens exist, the render/video branches below
|
||||
# resume it correctly.
|
||||
theme_rerender = state_data.get('theme_rerender') or {}
|
||||
if (theme_rerender.get('theme_id') and original_status == JobStatus.FAILED
|
||||
and not _has_title_screen(file_urls)):
|
||||
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
|
||||
try:
|
||||
await ThemeRerenderService(job_manager).start(
|
||||
job, theme_id=theme_rerender['theme_id'],
|
||||
requested_by=auth_result.user_email or "unknown",
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
return {
|
||||
"status": "success",
|
||||
"job_status": "lyrics_complete",
|
||||
"message": "Job retry: re-running the theme re-render",
|
||||
"retry_stage": "theme_rerender",
|
||||
}
|
||||
|
||||
# If we have a video with vocals and instrumental selection, retry video generation
|
||||
if (file_urls.get('videos', {}).get('with_vocals') and
|
||||
@@ -2266,6 +2300,8 @@ async def retry_job(
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
})
|
||||
keep_trying = bool(body and body.keep_trying)
|
||||
job_manager.update_state_data(job_id, KEEP_TRYING_STATE_KEY, keep_trying or None)
|
||||
|
||||
# Reset to DOWNLOADING_AUDIO state
|
||||
if not job_manager.transition_to_state(
|
||||
@@ -2281,7 +2317,9 @@ async def retry_job(
|
||||
|
||||
# Trigger audio download via Cloud Run Job (runs to completion,
|
||||
# immune to HTTP instance termination)
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
triggered = await worker_service.trigger_audio_download_worker(
|
||||
job_id, keep_trying=keep_trying
|
||||
)
|
||||
if not triggered:
|
||||
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
|
||||
raise HTTPException(
|
||||
@@ -2293,6 +2331,7 @@ async def retry_job(
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading_audio",
|
||||
"keep_trying": keep_trying,
|
||||
"message": f"Job retry started: re-downloading from {job.source_name}",
|
||||
"retry_stage": "audio_download"
|
||||
}
|
||||
@@ -2311,6 +2350,53 @@ async def retry_job(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{job_id}/choose-different-audio")
|
||||
async def choose_different_audio(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Reopen audio selection for a job whose audio download failed.
|
||||
|
||||
Moves a FAILED job (error stage ``audio_download``) back to
|
||||
AWAITING_AUDIO_SELECTION using its cached search results, so the owner can
|
||||
pick another source (e.g. the Spotify version when the only torrent seeder
|
||||
is offline) via the usual Select Audio dialog.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
if job.status != JobStatus.FAILED or (job.error_details or {}).get('stage') != 'audio_download':
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Only jobs whose audio download failed can choose different audio",
|
||||
)
|
||||
if _is_auto_retry_pending(job.state_data):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="An automatic retry is already in progress. Please wait a few minutes."
|
||||
)
|
||||
if not (job.state_data or {}).get('audio_search_results'):
|
||||
raise HTTPException(status_code=400, detail="No saved audio search results for this job")
|
||||
|
||||
job_manager.update_job(job_id, {'error_message': None, 'error_details': None})
|
||||
job_manager.update_state_data(job_id, KEEP_TRYING_STATE_KEY, None)
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message="Choosing different audio after a failed download",
|
||||
):
|
||||
raise HTTPException(status_code=500, detail="Failed to reopen audio selection")
|
||||
|
||||
logger.info(f"Job {job_id}: reopened audio selection after failed download")
|
||||
return {"status": "success", "job_id": job_id, "job_status": "awaiting_audio_selection"}
|
||||
|
||||
|
||||
@router.get("/{job_id}/logs")
|
||||
async def get_worker_logs(
|
||||
job_id: str,
|
||||
@@ -2898,6 +2984,64 @@ async def change_visibility(
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Re-render With Current Theme Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@router.post("/{job_id}/rerender")
|
||||
async def rerender_with_current_theme(
|
||||
job_id: str,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Re-render a finished tenant track with the tenant's current theme.
|
||||
|
||||
Regenerates title/end screens, the lyrics video, final encodes and CDG/TXT
|
||||
packages from the already-reviewed lyrics and instrumental selection — no
|
||||
review step. Used after a tenant edits their theme. Free (tenant jobs are
|
||||
never charged); only the job owner (still on the tenant allowlist) or an
|
||||
admin may trigger it.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
from backend.services.tenant_admin_service import _theme_id_for
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderError,
|
||||
ThemeRerenderService,
|
||||
validate_rerender,
|
||||
)
|
||||
|
||||
reason = validate_rerender(job)
|
||||
if reason:
|
||||
raise HTTPException(status_code=400, detail=reason)
|
||||
|
||||
tenant = get_tenant_service().get_tenant_config(job.tenant_id)
|
||||
if tenant is None or not tenant.is_active:
|
||||
raise HTTPException(status_code=400, detail="This track's portal is no longer active.")
|
||||
# Re-rendering is free work, so (like tenant billing) require the caller to
|
||||
# still be on the tenant's allowlist — X-Tenant-ID alone proves nothing.
|
||||
if not auth_result.is_admin and not tenant.is_email_allowed(auth_result.user_email or ""):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
|
||||
|
||||
theme_id = _theme_id_for(tenant)
|
||||
try:
|
||||
await ThemeRerenderService(job_manager).start(
|
||||
job, theme_id=theme_id, requested_by=auth_result.user_email or "unknown"
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
|
||||
return {"status": "processing", "job_id": job_id, "theme_id": theme_id}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Duration Confirmation Endpoint
|
||||
# =============================================================================
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
Tenant self-service theme editor API (``/api/tenant/theme``).
|
||||
|
||||
Any user allowed on a tenant's portal can view, preview and save that tenant's
|
||||
theme. Tenant context comes from the request (subdomain or the client-controlled
|
||||
``X-Tenant-ID`` header), so every endpoint re-checks membership against the
|
||||
tenant's allowlist (admins always pass) — a header alone grants nothing.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from pydantic import BaseModel, Field, constr
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.models.tenant import TenantConfig
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.tenant_admin_service import TenantValidationError
|
||||
from backend.services.tenant_theme_service import (
|
||||
ThemeNotEditableError,
|
||||
ThemeNotFoundError,
|
||||
get_theme_for_editor,
|
||||
prepare_preview_styles,
|
||||
save_tenant_theme,
|
||||
store_uploaded_asset,
|
||||
)
|
||||
from backend.services.theme_preview_service import ThemePreviewError, render_theme_preview
|
||||
from backend.services.tenant_admin_service import _theme_id_for
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/tenant/theme", tags=["tenant-theme"])
|
||||
|
||||
MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
||||
|
||||
# Previews run ffmpeg/PIL on the API instance — bound concurrency like the review
|
||||
# preview path so a burst of edits can't starve request handling.
|
||||
_PREVIEW_SEMAPHORE = asyncio.Semaphore(2)
|
||||
_PREVIEW_EXECUTOR = ThreadPoolExecutor(max_workers=2, thread_name_prefix="theme-preview")
|
||||
PREVIEW_TIMEOUT_S = 45
|
||||
|
||||
|
||||
def require_tenant_member(
|
||||
request: Request, auth_result: AuthResult = Depends(require_auth)
|
||||
) -> TenantConfig:
|
||||
"""The request's tenant, iff the authenticated user is allowed on it."""
|
||||
config = get_tenant_config_from_request(request)
|
||||
if config is None or not config.is_active:
|
||||
raise HTTPException(status_code=404, detail="Theme editing is only available on a tenant portal.")
|
||||
if auth_result.tenant_id and auth_result.tenant_id != config.id:
|
||||
raise HTTPException(status_code=403, detail="Your sign-in belongs to a different portal.")
|
||||
if not auth_result.user_email or not config.is_email_allowed(auth_result.user_email):
|
||||
raise HTTPException(status_code=403, detail="You don't have access to this portal's theme.")
|
||||
return config
|
||||
|
||||
|
||||
def _raise_http(exc: TenantValidationError) -> None:
|
||||
if isinstance(exc, ThemeNotFoundError):
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
if isinstance(exc, ThemeNotEditableError):
|
||||
raise HTTPException(status_code=403, detail=str(exc))
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
class ThemeResponse(BaseModel):
|
||||
theme_id: str
|
||||
style_params: Dict[str, Any]
|
||||
images: List[str]
|
||||
fonts: List[str]
|
||||
|
||||
|
||||
class PreviewSample(BaseModel):
|
||||
artist: str = Field("Artist Name", max_length=80)
|
||||
title: str = Field("Song Title", max_length=80)
|
||||
lyrics: Optional[List[constr(max_length=120)]] = Field(None, max_length=4)
|
||||
|
||||
|
||||
class PreviewRequest(BaseModel):
|
||||
style_params: Dict[str, Any]
|
||||
sample: PreviewSample = Field(default_factory=PreviewSample)
|
||||
|
||||
|
||||
class PreviewResponse(BaseModel):
|
||||
title_card: str # data:image/jpeg;base64,...
|
||||
karaoke_frame: str
|
||||
|
||||
|
||||
class SaveRequest(BaseModel):
|
||||
style_params: Dict[str, Any]
|
||||
|
||||
|
||||
class AssetResponse(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
@router.get("", response_model=ThemeResponse)
|
||||
def get_theme(config: TenantConfig = Depends(require_tenant_member)):
|
||||
try:
|
||||
return ThemeResponse(**get_theme_for_editor(config))
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
|
||||
|
||||
@router.post("/assets", response_model=AssetResponse)
|
||||
async def upload_asset(file: UploadFile = File(...), config: TenantConfig = Depends(require_tenant_member)):
|
||||
# Read in chunks and stop as soon as the limit is exceeded, so an oversized
|
||||
# upload never gets materialised in memory in full.
|
||||
chunks, size = [], 0
|
||||
while True:
|
||||
chunk = await file.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
if size > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=400, detail="The file is too large (max 15 MB).")
|
||||
chunks.append(chunk)
|
||||
data = b"".join(chunks)
|
||||
if not data:
|
||||
raise HTTPException(status_code=400, detail="The file is empty.")
|
||||
try:
|
||||
name = await run_in_threadpool(store_uploaded_asset, config, file.filename or "asset", data)
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
return AssetResponse(name=name)
|
||||
|
||||
|
||||
@router.post("/preview", response_model=PreviewResponse)
|
||||
async def preview_theme(body: PreviewRequest, config: TenantConfig = Depends(require_tenant_member)):
|
||||
try:
|
||||
styles = await run_in_threadpool(prepare_preview_styles, config, body.style_params)
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
await _PREVIEW_SEMAPHORE.acquire()
|
||||
future = loop.run_in_executor(
|
||||
_PREVIEW_EXECUTOR,
|
||||
lambda: render_theme_preview(
|
||||
_theme_id_for(config),
|
||||
styles,
|
||||
artist=body.sample.artist,
|
||||
title=body.sample.title,
|
||||
lyrics=body.sample.lyrics,
|
||||
),
|
||||
)
|
||||
# The slot is released only when the render really finishes — a timed-out
|
||||
# render keeps running in its thread, so releasing early would let a burst
|
||||
# queue unbounded work behind it.
|
||||
future.add_done_callback(lambda _f: _PREVIEW_SEMAPHORE.release())
|
||||
try:
|
||||
images = await asyncio.wait_for(asyncio.shield(future), timeout=PREVIEW_TIMEOUT_S)
|
||||
except ThemePreviewError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc))
|
||||
except asyncio.TimeoutError:
|
||||
raise HTTPException(status_code=504, detail="The preview took too long to render. Try again.")
|
||||
return PreviewResponse(**images.as_data_urls())
|
||||
|
||||
|
||||
@router.put("", response_model=ThemeResponse)
|
||||
def save_theme(body: SaveRequest, config: TenantConfig = Depends(require_tenant_member)):
|
||||
try:
|
||||
save_tenant_theme(config, body.style_params)
|
||||
return ThemeResponse(**get_theme_for_editor(config))
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
@@ -365,7 +365,9 @@ async def send_magic_link(
|
||||
# will be ready and verification will be instant.
|
||||
# Skip for test emails — they get auto-granted without evaluation.
|
||||
# Skip for board sign-in — it never grants a welcome credit, so there's nothing to eval.
|
||||
if existing_user is None and not is_test_email(email) and not is_board_signin:
|
||||
# Skip for tenant portals — tenant users are billed under a separate agreement and
|
||||
# never get consumer welcome credits.
|
||||
if existing_user is None and not is_test_email(email) and not is_board_signin and not tenant_id:
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, email),
|
||||
@@ -571,14 +573,16 @@ async def verify_magic_link(
|
||||
# Board sign-in grants NO welcome credit — it's identity only. The credit is granted
|
||||
# later, when the user converts via the "make it yourself now" flow (claim endpoint),
|
||||
# or when their requested track gets picked (Phase 2).
|
||||
# Tenant portal sign-ins never touch consumer credits (no eval, no denial/welcome
|
||||
# emails, no credit interstitial) — tenants have a separate commercial agreement.
|
||||
result = complete_verified_login(
|
||||
user,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
is_first_login=is_first_login,
|
||||
precomputed_eval=precomputed_eval,
|
||||
grant_welcome_credit=magic_link_purpose != "requests_board",
|
||||
referral_code=referral_code,
|
||||
grant_welcome_credit=magic_link_purpose != "requests_board" and not magic_link_tenant_id,
|
||||
referral_code=referral_code if not magic_link_tenant_id else None,
|
||||
locale=locale if has_accept_language else None,
|
||||
ui_locale=get_full_locale_from_request(http_request),
|
||||
ip_address=ip_address,
|
||||
|
||||
@@ -205,6 +205,16 @@ class Settings(BaseSettings):
|
||||
# must still enqueue to the real queue location — building queue paths from
|
||||
# gcp_region 404s from those workers ("Queue does not exist").
|
||||
cloud_tasks_region: str = os.getenv("CLOUD_TASKS_REGION", "us-central1")
|
||||
# Region of the latency-critical CPU Cloud Run Jobs (audio-download-job,
|
||||
# lyrics-transcription-job, bulk-search-job, video-encoding-job). Cloud Run
|
||||
# Jobs in us-central1 queue 2-5 min before the container starts (measured
|
||||
# 2026-09-28 with a tiny sample image: us-central1 4-5 min vs us-east4 8-19s),
|
||||
# independent of image size or CPU. video-encoding-job reads ~0.3 GB/run from
|
||||
# the us-central1 bucket cross-region (~$1.60/mo, 2026-09-29 model). Rollback:
|
||||
# recreate the jobs in us-central1 via Pulumi, then set CPU_JOBS_REGION on the
|
||||
# service AND the jobs (see docs/TROUBLESHOOTING.md). Deliberately separate from gcp_region,
|
||||
# which these workers use for other resources (queues, encoding VM zones).
|
||||
cpu_jobs_region: str = os.getenv("CPU_JOBS_REGION", "us-east4")
|
||||
|
||||
# Cloud Run Jobs (for long-running video encoding)
|
||||
# When enabled AND enable_cloud_tasks is true, video worker uses Cloud Run Jobs
|
||||
|
||||
+2
-1
@@ -12,7 +12,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, client_events, 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, tenant_theme, 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
|
||||
@@ -245,6 +245,7 @@ app.include_router(kjbox.router, prefix="/api") # kjbox partner API: singer ema
|
||||
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)
|
||||
app.include_router(tenant_theme.router) # Tenant self-service theme editor (router has /api prefix)
|
||||
|
||||
|
||||
# Exception handlers
|
||||
|
||||
@@ -203,6 +203,7 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
JobStatus.AWAITING_REVIEW, # Retry from combined review
|
||||
JobStatus.RENDER_PENDING_CAPACITY, # Operator parks a stale-failed job for auto-retry
|
||||
JobStatus.AWAITING_AUDIO_SELECTION, # Choose different audio after a failed download
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
|
||||
@@ -175,7 +175,8 @@ class TenantConfig(BaseModel):
|
||||
"""Check if an email address may sign in to this tenant's portal.
|
||||
|
||||
- Nomad Karaoke admins (admin email domain) can always sign in.
|
||||
- No allowlist at all (no domains, no emails) = open portal.
|
||||
- No allowlist at all (no domains, no emails) = admins only. Tenant jobs
|
||||
are free of consumer credits, so a portal must never be open to anyone.
|
||||
- Otherwise only an ``allowed_emails`` entry or a matching domain is
|
||||
allowed. (``require_email_domain`` is vestigial: any non-empty
|
||||
allowlist is always enforced.)
|
||||
@@ -189,7 +190,7 @@ class TenantConfig(BaseModel):
|
||||
allowed_emails = [e.strip().lower() for e in self.auth.allowed_emails]
|
||||
domains = self.auth.allowed_email_domains
|
||||
if not allowed_emails and not domains:
|
||||
return True
|
||||
return False
|
||||
|
||||
if email_lower in allowed_emails:
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Time budgets for the audio-download Cloud Run Job (torrent stall handling).
|
||||
|
||||
A torrent whose only seeder is intermittently offline can sit at 0 peers for a
|
||||
while and then complete in seconds. flacfetch aborts a download after
|
||||
``max_stall_seconds`` with no progress; the worker then fails the job with
|
||||
error code ``audio_download_stalled`` and the user chooses "Keep trying" (a
|
||||
longer stall budget) or different audio — there is no silent auto-retry.
|
||||
|
||||
The worker's wait and the Cloud Run execution timeout are derived from the stall
|
||||
budget so they always leave room for the download itself plus the GCS upload.
|
||||
"""
|
||||
|
||||
# First attempt: wait this long with no progress before asking the user.
|
||||
STALL_SECONDS_DEFAULT = 20 * 60
|
||||
# "Keep trying": wait up to another hour (flacfetch caps a request at 3600s).
|
||||
STALL_SECONDS_KEEP_TRYING = 60 * 60
|
||||
|
||||
# Once data flows the stall clock resets; allow this much active download time
|
||||
# on top of the stall budget before the worker gives up waiting.
|
||||
_ACTIVE_DOWNLOAD_ALLOWANCE_SECONDS = 20 * 60
|
||||
# Headroom between the worker's wait and the Cloud Run task timeout, for the GCS
|
||||
# upload + state transition (so the worker fails gracefully, never SIGKILLed).
|
||||
_TASK_HEADROOM_SECONDS = 5 * 60
|
||||
|
||||
# While waiting on a torrent, the worker writes progress to the job this often.
|
||||
# Must stay well under the recover-stuck-jobs "no update for 10 min" threshold
|
||||
# (job_health_service: downloading_audio_stuck), or a live wait gets parked.
|
||||
HEARTBEAT_INTERVAL_SECONDS = 2 * 60
|
||||
|
||||
# Firestore state_data flag set by /retry {keep_trying: true}.
|
||||
KEEP_TRYING_STATE_KEY = "audio_download_keep_trying"
|
||||
|
||||
# error_details.code for a stalled download (read by the job card).
|
||||
STALLED_ERROR_CODE = "audio_download_stalled"
|
||||
|
||||
|
||||
def stall_seconds(keep_trying: bool) -> int:
|
||||
return STALL_SECONDS_KEEP_TRYING if keep_trying else STALL_SECONDS_DEFAULT
|
||||
|
||||
|
||||
def torrent_wait_timeout_seconds(keep_trying: bool) -> int:
|
||||
return stall_seconds(keep_trying) + _ACTIVE_DOWNLOAD_ALLOWANCE_SECONDS
|
||||
|
||||
|
||||
def task_timeout_seconds(keep_trying: bool) -> int:
|
||||
"""Cloud Run execution timeout override for audio-download-job."""
|
||||
return torrent_wait_timeout_seconds(keep_trying) + _TASK_HEADROOM_SECONDS
|
||||
@@ -96,15 +96,16 @@ def _encode_flac(samples: np.ndarray, out_path: str, sample_rate: int = SAMPLE_R
|
||||
|
||||
|
||||
def find_offset(mix: np.ndarray, inst: np.ndarray, max_lag: int,
|
||||
window: int = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE)) -> int:
|
||||
window: int = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE),
|
||||
start_fraction: float = 0.25) -> int:
|
||||
"""Lag (samples) that best aligns inst to mix: mix[n] ≈ inst[n - lag].
|
||||
|
||||
Correlates a `window`-sample excerpt of the mix (from a quarter of the way
|
||||
in, past intros) against the matching instrumental span ±max_lag, so memory
|
||||
and time are independent of track length.
|
||||
Correlates a `window`-sample excerpt of the mix (by default from a quarter
|
||||
of the way in, past intros) against the matching instrumental span
|
||||
±max_lag, so memory and time are independent of track length.
|
||||
"""
|
||||
window = max(1, min(window, len(mix)))
|
||||
start = min(len(mix) // 4, len(mix) - window)
|
||||
start = min(int(len(mix) * start_fraction), len(mix) - window)
|
||||
excerpt = mix[start: start + window].astype(np.float64)
|
||||
|
||||
# Instrumental span covering every candidate lag, zero-padded where it runs
|
||||
|
||||
@@ -254,7 +254,8 @@ class FirestoreService:
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'updated_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'error_message', 'error_details.code', 'error_details.stage',
|
||||
'error_details.stall_minutes', 'error_details.keep_trying', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'made_for_you', 'customer_email', 'locale',
|
||||
'url', 'filename', 'existing_instrumental_gcs_path',
|
||||
'audio_search_artist', 'audio_search_title',
|
||||
|
||||
@@ -44,6 +44,21 @@ class FlacfetchServiceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FlacfetchDownloadStalledError(FlacfetchServiceError):
|
||||
"""A torrent made no progress for the whole stall ceiling (typically its only
|
||||
seeder is offline). Recoverable by waiting longer or picking other audio, so
|
||||
callers surface it to the user instead of auto-retrying the same torrent."""
|
||||
pass
|
||||
|
||||
|
||||
def _is_stall_failure(status: Dict[str, Any]) -> bool:
|
||||
"""flacfetch >= 0.31 reports error_code='torrent_stalled'; older versions only
|
||||
the message ("Torrent download stalled for 600s ...")."""
|
||||
if status.get("error_code") == "torrent_stalled":
|
||||
return True
|
||||
return "download stalled for" in str(status.get("error") or "").lower()
|
||||
|
||||
|
||||
def _format_httpx_error(e: Exception) -> str:
|
||||
"""
|
||||
Format an httpx exception into a descriptive error string.
|
||||
@@ -287,6 +302,7 @@ class FlacfetchClient:
|
||||
result_index: int,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading an audio file.
|
||||
@@ -299,6 +315,8 @@ class FlacfetchClient:
|
||||
result_index: Index of result to download
|
||||
output_filename: Optional custom filename (without extension)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
max_stall_seconds: Torrents only — abort after this long with no progress
|
||||
(overrides flacfetch's default ceiling)
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
@@ -307,7 +325,9 @@ class FlacfetchClient:
|
||||
FlacfetchServiceError: On download start failure (after all retries exhausted)
|
||||
"""
|
||||
try:
|
||||
return await with_retry(self._download_impl, search_id, result_index, output_filename, gcs_path)
|
||||
return await with_retry(
|
||||
self._download_impl, search_id, result_index, output_filename, gcs_path, max_stall_seconds
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
@@ -319,6 +339,7 @@ class FlacfetchClient:
|
||||
result_index: int,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Implementation of download without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -331,6 +352,8 @@ class FlacfetchClient:
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
if max_stall_seconds:
|
||||
payload["max_stall_seconds"] = max_stall_seconds
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download",
|
||||
@@ -351,6 +374,7 @@ class FlacfetchClient:
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading directly by source ID (no prior search required).
|
||||
@@ -368,6 +392,8 @@ class FlacfetchClient:
|
||||
target_file: For torrents, specific file to extract
|
||||
download_url: For YouTube/Spotify, direct URL (optional)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
max_stall_seconds: Torrents only — abort after this long with no progress
|
||||
(overrides flacfetch's default ceiling)
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
@@ -378,7 +404,8 @@ class FlacfetchClient:
|
||||
try:
|
||||
return await with_retry(
|
||||
self._download_by_id_impl,
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path,
|
||||
max_stall_seconds,
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {_format_httpx_error(e)}")
|
||||
@@ -393,6 +420,7 @@ class FlacfetchClient:
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Implementation of download_by_id without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -409,6 +437,8 @@ class FlacfetchClient:
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
if max_stall_seconds:
|
||||
payload["max_stall_seconds"] = max_stall_seconds
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
@@ -518,6 +548,8 @@ class FlacfetchClient:
|
||||
return status
|
||||
elif download_status == "failed":
|
||||
error = status.get("error", "Unknown error")
|
||||
if _is_stall_failure(status):
|
||||
raise FlacfetchDownloadStalledError(f"Download failed: {error}")
|
||||
raise FlacfetchServiceError(f"Download failed: {error}")
|
||||
elif download_status == "cancelled":
|
||||
raise FlacfetchServiceError("Download was cancelled")
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Line a user-supplied instrumental up with its mix when their lengths differ.
|
||||
|
||||
Artists often export the instrumental with a different edit from the mix: extra
|
||||
count-in, a longer or shorter outro. Lyrics are timed against the mix, so the
|
||||
instrumental must start at the same moment and run the same length. Rather than
|
||||
reject the job, we find the start offset by cross-correlation (the same method
|
||||
as derived_vocals), then trim/pad the start and trim (with a fade) or pad the
|
||||
end so it matches the mix exactly. Files that don't correlate at all are almost
|
||||
certainly the wrong pairing and are still rejected, as are files whose offset
|
||||
changes between early and late in the song (an edit in the middle).
|
||||
|
||||
Runs in the API request (uploads-complete), so it decodes a bounded mono copy
|
||||
for alignment and does the actual edit with one ffmpeg pass on the original.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
from dataclasses import dataclass, asdict
|
||||
|
||||
import numpy as np
|
||||
|
||||
from backend.services.derived_vocals import (
|
||||
SAMPLE_RATE,
|
||||
DerivedVocalsError,
|
||||
_decode_mono,
|
||||
find_offset,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Count-ins / intros can add several seconds; search well past that.
|
||||
MAX_LAG_SECONDS = 15.0
|
||||
ALIGN_WINDOW_SECONDS = 60.0
|
||||
# Pearson correlation of mix vs aligned instrumental. Same-master pairs score
|
||||
# ~0.75-0.85 (the vocals are the only difference); unrelated files score ~0.01.
|
||||
MIN_CORRELATION = 0.3
|
||||
# Fade applied when the instrumental's extra outro is cut at the mix's end.
|
||||
END_FADE_SECONDS = 2.0
|
||||
# Offsets measured early and late in the song must agree this closely; a bigger
|
||||
# difference means an edit in the middle (removed bar, longer bridge), which a
|
||||
# single start/end fix can't correct.
|
||||
MAX_OFFSET_DRIFT_SECONDS = 0.02
|
||||
# Where the two alignment excerpts start, as a fraction of the mix length.
|
||||
ALIGN_POINTS = (0.25, 0.75)
|
||||
# How close the conformed file must land to the mix length.
|
||||
LENGTH_TOLERANCE_SECONDS = 0.05
|
||||
FFMPEG_TIMEOUT_SECONDS = 180
|
||||
|
||||
|
||||
class InstrumentalConformError(RuntimeError):
|
||||
"""Conforming failed. ``mismatch`` is True when the files themselves don't
|
||||
line up (wrong file / mid-song edit) — a reason to reject the upload — and
|
||||
False for processing failures (ffmpeg crash/timeout), which are retryable."""
|
||||
|
||||
def __init__(self, message: str, mismatch: bool = False):
|
||||
super().__init__(message)
|
||||
self.mismatch = mismatch
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConformResult:
|
||||
mix_duration: float
|
||||
original_duration: float
|
||||
# > 0: instrumental had this much extra audio at the start (trimmed).
|
||||
# < 0: instrumental started late by this much (silence added).
|
||||
start_trimmed_seconds: float
|
||||
# > 0: extra outro cut (with a fade). < 0: silence padded at the end.
|
||||
end_trimmed_seconds: float
|
||||
correlation: float
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {k: round(v, 3) + 0.0 for k, v in asdict(self).items()}
|
||||
|
||||
|
||||
def _probe_duration(path: str) -> float:
|
||||
out = subprocess.run(
|
||||
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", path],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60, check=True,
|
||||
).stdout
|
||||
return float(json.loads(out)["format"]["duration"])
|
||||
|
||||
|
||||
def _aligned_correlation(mix: np.ndarray, inst: np.ndarray, lag: int, window: int,
|
||||
start_fraction: float = 0.25) -> float:
|
||||
"""Pearson correlation of a mix excerpt vs the instrumental shifted by lag."""
|
||||
window = max(1, min(window, len(mix)))
|
||||
start = min(int(len(mix) * start_fraction), len(mix) - window)
|
||||
excerpt = mix[start: start + window].astype(np.float64)
|
||||
shifted = np.zeros(window, dtype=np.float64)
|
||||
lo = start - lag
|
||||
src_lo, src_hi = max(0, lo), min(len(inst), lo + window)
|
||||
if src_hi > src_lo:
|
||||
shifted[src_lo - lo: src_hi - lo] = inst[src_lo:src_hi]
|
||||
if not excerpt.std() or not shifted.std():
|
||||
return 0.0
|
||||
return float(np.corrcoef(excerpt, shifted)[0, 1])
|
||||
|
||||
|
||||
def build_filter(lag_seconds: float, original_duration: float, mix_duration: float) -> str:
|
||||
"""ffmpeg -af chain moving the instrumental by lag and fitting it to mix_duration.
|
||||
|
||||
lag follows find_offset: mix[t] ≈ inst[t - lag], so a negative lag means the
|
||||
instrumental has extra audio at the start.
|
||||
"""
|
||||
filters = []
|
||||
if lag_seconds < 0:
|
||||
filters.append(f"atrim=start={-lag_seconds:.6f},asetpts=PTS-STARTPTS")
|
||||
elif lag_seconds > 0:
|
||||
filters.append(f"adelay=delays={lag_seconds * 1000:.3f}:all=1")
|
||||
shifted_duration = original_duration + lag_seconds
|
||||
if shifted_duration > mix_duration + LENGTH_TOLERANCE_SECONDS:
|
||||
fade = min(END_FADE_SECONDS, mix_duration / 10)
|
||||
filters.append(f"afade=t=out:st={mix_duration - fade:.6f}:d={fade:.6f}")
|
||||
else:
|
||||
filters.append(f"apad=whole_dur={mix_duration:.6f}")
|
||||
filters.append(f"atrim=end={mix_duration:.6f}")
|
||||
return ",".join(filters)
|
||||
|
||||
|
||||
def conform_instrumental(mix_path: str, instrumental_path: str, out_path: str) -> ConformResult:
|
||||
"""Write an instrumental aligned to, and exactly as long as, the mix (FLAC).
|
||||
|
||||
Raises InstrumentalConformError when the files don't line up.
|
||||
"""
|
||||
try:
|
||||
mix = _decode_mono(mix_path)
|
||||
inst = _decode_mono(instrumental_path)
|
||||
except DerivedVocalsError as e:
|
||||
# Too long / undecodable input fails the same way every time: reject it
|
||||
# rather than hand back a retryable error.
|
||||
raise InstrumentalConformError(str(e), mismatch=True) from e
|
||||
|
||||
# Measure the offset early and late in the song. One constant shift is all
|
||||
# this can fix, so the two must agree and both must be a genuine match.
|
||||
window = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE)
|
||||
max_lag = int(MAX_LAG_SECONDS * SAMPLE_RATE)
|
||||
lags, correlations = [], []
|
||||
for fraction in ALIGN_POINTS:
|
||||
point_lag = find_offset(mix, inst, max_lag, window, start_fraction=fraction)
|
||||
lags.append(point_lag)
|
||||
correlations.append(_aligned_correlation(mix, inst, point_lag, window, start_fraction=fraction))
|
||||
correlation = min(correlations)
|
||||
if correlation < MIN_CORRELATION:
|
||||
raise InstrumentalConformError(
|
||||
f"instrumental doesn't match the mix (correlation {correlation:.2f})", mismatch=True
|
||||
)
|
||||
drift = abs(lags[1] - lags[0]) / SAMPLE_RATE
|
||||
if drift > MAX_OFFSET_DRIFT_SECONDS:
|
||||
raise InstrumentalConformError(
|
||||
f"instrumental is edited differently mid-song (offset {lags[0] / SAMPLE_RATE:+.3f}s early "
|
||||
f"vs {lags[1] / SAMPLE_RATE:+.3f}s late)", mismatch=True
|
||||
)
|
||||
lag = lags[0]
|
||||
|
||||
mix_duration = _probe_duration(mix_path)
|
||||
original_duration = _probe_duration(instrumental_path)
|
||||
lag_seconds = lag / SAMPLE_RATE
|
||||
af = build_filter(lag_seconds, original_duration, mix_duration)
|
||||
try:
|
||||
subprocess.run(
|
||||
["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", instrumental_path,
|
||||
"-af", af, "-c:a", "flac", out_path],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
timeout=FFMPEG_TIMEOUT_SECONDS, check=True,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
stderr = (e.stderr or b"").decode(errors="replace").strip()[-500:]
|
||||
raise InstrumentalConformError(f"ffmpeg failed: {stderr}") from e
|
||||
except subprocess.TimeoutExpired as e:
|
||||
raise InstrumentalConformError("ffmpeg timed out conforming instrumental") from e
|
||||
|
||||
result_duration = _probe_duration(out_path)
|
||||
if abs(result_duration - mix_duration) > LENGTH_TOLERANCE_SECONDS:
|
||||
raise InstrumentalConformError(
|
||||
f"conformed instrumental is {result_duration:.2f}s, expected {mix_duration:.2f}s"
|
||||
)
|
||||
|
||||
result = ConformResult(
|
||||
mix_duration=mix_duration,
|
||||
original_duration=original_duration,
|
||||
start_trimmed_seconds=-lag_seconds,
|
||||
end_trimmed_seconds=(original_duration + lag_seconds) - mix_duration,
|
||||
correlation=correlation,
|
||||
)
|
||||
logger.info(f"Conformed instrumental: {result.to_dict()} (filter: {af})")
|
||||
return result
|
||||
@@ -54,6 +54,26 @@ class JobManager:
|
||||
self.firestore = FirestoreService()
|
||||
self.storage = StorageService()
|
||||
|
||||
@staticmethod
|
||||
def _is_tenant_billed(tenant_id: Optional[str], user_email: Optional[str]) -> bool:
|
||||
"""True if this job is billed to a tenant (not consumer credits).
|
||||
|
||||
The tenant context can come from the client-controlled X-Tenant-ID
|
||||
header, so a tenant id alone is NOT proof of membership: the user must
|
||||
be allowed on that tenant's portal (its email/domain allowlist; an empty
|
||||
allowlist admits admins only). Otherwise the job is charged normally.
|
||||
"""
|
||||
if not tenant_id or not user_email:
|
||||
return False
|
||||
try:
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
|
||||
config = get_tenant_service().get_tenant_config(tenant_id)
|
||||
except Exception:
|
||||
logger.exception(f"Tenant lookup failed for {tenant_id}; charging consumer credits")
|
||||
return False
|
||||
return bool(config and config.is_active and config.is_email_allowed(user_email))
|
||||
|
||||
def create_job(self, job_create: JobCreate, is_admin: bool = False) -> Job:
|
||||
"""
|
||||
Create a new job with initial state PENDING.
|
||||
@@ -68,9 +88,15 @@ class JobManager:
|
||||
Raises:
|
||||
ValueError: If theme_id is not provided (all jobs require a theme)
|
||||
"""
|
||||
# Check credits (skip for admins)
|
||||
# Check credits (skip for admins, and for tenant-portal jobs: tenants are
|
||||
# billed under a separate commercial agreement, never consumer credits)
|
||||
credits_to_charge = job_create.credits
|
||||
if job_create.user_email and not is_admin:
|
||||
charge_credits = (
|
||||
bool(job_create.user_email)
|
||||
and not is_admin
|
||||
and not self._is_tenant_billed(job_create.tenant_id, job_create.user_email)
|
||||
)
|
||||
if charge_credits:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
credits_available = user_service.check_credits(job_create.user_email)
|
||||
@@ -149,12 +175,12 @@ class JobManager:
|
||||
"created_from": job_create.request_metadata.get("created_from", "unknown"),
|
||||
},
|
||||
# Record how many credits were charged for this job (authoritative running total).
|
||||
# When charging is bypassed (admin / no user_email), set credits_charged=0 and
|
||||
# payment_bypassed=True so duration reconciliation short-circuits without pausing,
|
||||
# charging, or refunding.
|
||||
# When charging is bypassed (admin / no user_email / tenant portal), set
|
||||
# credits_charged=0 and payment_bypassed=True so duration reconciliation
|
||||
# short-circuits without pausing, charging, or refunding.
|
||||
state_data=(
|
||||
{"credits_charged": 0, "payment_bypassed": True}
|
||||
if (is_admin or not job_create.user_email)
|
||||
if not charge_credits
|
||||
else {"credits_charged": credits_to_charge}
|
||||
),
|
||||
)
|
||||
@@ -163,7 +189,7 @@ class JobManager:
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
# Deduct credits atomically (after job is persisted so we have job_id for transaction record)
|
||||
if job_create.user_email and not is_admin:
|
||||
if charge_credits:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
success, _remaining, deduct_msg = user_service.deduct_credits(
|
||||
|
||||
@@ -225,6 +225,20 @@ def _mark_alerted(doc_ref: Any, now: datetime) -> None:
|
||||
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
|
||||
|
||||
|
||||
def _retry_pending(state_data: dict) -> bool:
|
||||
"""True if state_data.cloud_run_retry_pending is set and unexpired."""
|
||||
pending = (state_data or {}).get("cloud_run_retry_pending")
|
||||
if not isinstance(pending, dict) or not pending.get("expires_at"):
|
||||
return False
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(str(pending["expires_at"]).replace("Z", "+00:00"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
return expires_at > datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def notify_job_failed(
|
||||
db: Any,
|
||||
collection: str,
|
||||
@@ -249,6 +263,8 @@ def notify_job_failed(
|
||||
# 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
|
||||
retry_pending = False
|
||||
error_code = None
|
||||
error_message = (additional_fields or {}).get("error_message") or message or ""
|
||||
try:
|
||||
snap = db.collection(collection).document(job_id).get()
|
||||
@@ -260,6 +276,8 @@ def notify_job_failed(
|
||||
environment = meta.get("environment")
|
||||
state = job.get("state_data") or {}
|
||||
brand_code = state.get("brand_code")
|
||||
retry_pending = _retry_pending(state)
|
||||
error_code = (job.get("error_details") or {}).get("code")
|
||||
if not error_message:
|
||||
error_message = job.get("error_message") or ""
|
||||
except Exception as exc: # noqa: BLE001
|
||||
@@ -269,6 +287,13 @@ def notify_job_failed(
|
||||
logger.debug("ops_alerts: skipping failure alert for %s env job %s", environment, job_id)
|
||||
return False
|
||||
|
||||
# A Cloud Run auto-retry is already queued: this failure is transient
|
||||
# from the user's view (they see "Retrying automatically…"). If the final
|
||||
# attempt also fails, it clears the marker first and alerts then.
|
||||
if retry_pending:
|
||||
logger.info("ops_alerts: skipping failure alert for job %s (auto-retry pending)", 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)
|
||||
@@ -276,8 +301,13 @@ def notify_job_failed(
|
||||
return False
|
||||
|
||||
track = " - ".join(p for p in (artist, title) if p) or "(unknown track)"
|
||||
headline = (
|
||||
"🟠 **Audio download stalled** — waiting for the user to keep trying or pick other audio"
|
||||
if error_code == "audio_download_stalled"
|
||||
else "🔴 **Job failed** — near-real-time alert"
|
||||
)
|
||||
lines = [
|
||||
"🔴 **Job failed** — near-real-time alert",
|
||||
headline,
|
||||
f"**Job:** `{job_id}`" + (f" ({brand_code})" if brand_code else ""),
|
||||
f"**Track:** {track}",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
"""
|
||||
Tenant self-service theme editing (used by /api/tenant/theme).
|
||||
|
||||
Tenant users edit their own tenant's theme, so their input is untrusted and is
|
||||
validated more strictly than the admin console's:
|
||||
|
||||
- every asset field must be a bare basename that exists in the theme's assets
|
||||
(or, for the font, a bundled karaoke_gen font) — no absolute/gs:// paths;
|
||||
- the font is kept consistent with the render pipeline, which downloads ONE font
|
||||
asset (``intro.font``) and applies it to intro/karaoke/end/cdg: all four fields
|
||||
are set to it, ``karaoke.font`` is set to the family name libass matches, and a
|
||||
bundled font is copied into the theme's assets on save so render jobs find it;
|
||||
- ASS style keys ``build_karaoke_styles`` needs without defaults are filled in;
|
||||
- numeric layout values are bounded.
|
||||
|
||||
Uploads are stored content-addressed (``<stem>-<sha8>.<ext>``) so an upload can
|
||||
never overwrite an asset that saved themes / existing jobs reference.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from backend.services.storage_service import NO_STORE_CACHE_CONTROL, StorageService
|
||||
from backend.services.tenant_admin_service import (
|
||||
IMAGE_CONTENT_TYPES,
|
||||
TenantValidationError,
|
||||
_content_type_for,
|
||||
_safe_asset_name,
|
||||
_theme_id_for,
|
||||
_validate_style_params,
|
||||
update_tenant,
|
||||
)
|
||||
from backend.services.theme_preview_service import BUNDLED_FONTS_DIR, bundled_fonts, font_family_name
|
||||
from backend.services.theme_service import THEMES_PREFIX
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FONT_CONTENT_TYPES = {"ttf": "font/ttf", "otf": "font/otf"}
|
||||
MAX_IMAGE_SIDE = 8000 # 4K backgrounds are 3840x2160; this leaves headroom
|
||||
MAX_IMAGE_PIXELS = 40_000_000 # decoded size bound (PIL only errors at ~179 MP)
|
||||
UPLOAD_EXTENSIONS = set(IMAGE_CONTENT_TYPES) | set(FONT_CONTENT_TYPES)
|
||||
|
||||
# (section, field) pairs that hold image asset basenames.
|
||||
# (existing_image is not editable: neither the preview nor production resolves it.)
|
||||
IMAGE_FIELDS = (
|
||||
("intro", "background_image"),
|
||||
("karaoke", "background_image"),
|
||||
("end", "background_image"),
|
||||
("cdg", "instrumental_background"),
|
||||
("cdg", "title_screen_background"),
|
||||
("cdg", "outro_background"),
|
||||
)
|
||||
FONT_FIELDS = (("intro", "font"), ("karaoke", "font_path"), ("end", "font"), ("cdg", "font_path"))
|
||||
|
||||
DEFAULT_FONT = "AvenirNext-Bold.ttf" # bundled; used when a draft names no font
|
||||
|
||||
# Every key lyrics_transcriber.output.ass.style.build_karaoke_styles reads without a
|
||||
# default — a theme missing one previews fine but crashes every real render.
|
||||
REQUIRED_KARAOKE_KEYS = (
|
||||
"font", "ass_name", "primary_color", "secondary_color", "outline_color", "back_color",
|
||||
"bold", "italic", "underline", "strike_out", "scale_x", "scale_y", "spacing", "angle",
|
||||
"border_style", "outline", "shadow", "margin_l", "margin_r", "margin_v", "encoding",
|
||||
)
|
||||
|
||||
# Free-text values written verbatim into the ASS header / style line.
|
||||
ASS_TEXT_FIELDS = (("karaoke", "font"), ("karaoke", "ass_name"))
|
||||
_ASS_UNSAFE = re.compile(r"[,\r\n{}\\]")
|
||||
|
||||
NUMERIC_BOUNDS = {
|
||||
("karaoke", "scale_x"): (10, 400),
|
||||
("karaoke", "scale_y"): (10, 400),
|
||||
("karaoke", "spacing"): (-50, 200),
|
||||
("karaoke", "angle"): (-360, 360),
|
||||
("karaoke", "border_style"): (1, 4),
|
||||
("karaoke", "margin_l"): (0, 3840),
|
||||
("karaoke", "margin_r"): (0, 3840),
|
||||
("karaoke", "margin_v"): (0, 2160),
|
||||
("karaoke", "encoding"): (0, 255),
|
||||
("karaoke", "font_size"): (40, 600),
|
||||
("karaoke", "top_padding"): (0, 2000),
|
||||
("karaoke", "max_line_length"): (10, 80),
|
||||
("karaoke", "outline"): (0, 20),
|
||||
("karaoke", "shadow"): (0, 20),
|
||||
("intro", "video_duration"): (1, 30),
|
||||
("end", "video_duration"): (1, 30),
|
||||
}
|
||||
|
||||
_HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
|
||||
_RGBA = re.compile(r"^\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*$")
|
||||
HEX_COLOR_FIELDS = (
|
||||
("intro", "background_color"), ("intro", "title_color"), ("intro", "artist_color"), ("intro", "extra_text_color"),
|
||||
("end", "background_color"), ("end", "title_color"), ("end", "artist_color"), ("end", "extra_text_color"),
|
||||
("karaoke", "background_color"),
|
||||
)
|
||||
RGBA_COLOR_FIELDS = (
|
||||
("karaoke", "primary_color"), ("karaoke", "secondary_color"),
|
||||
("karaoke", "outline_color"), ("karaoke", "back_color"),
|
||||
)
|
||||
REGION_FIELDS = (
|
||||
("intro", "title_region"), ("intro", "artist_region"), ("intro", "extra_text_region"),
|
||||
("end", "title_region"), ("end", "artist_region"), ("end", "extra_text_region"),
|
||||
)
|
||||
|
||||
|
||||
def _theme_assets(storage: StorageService, theme_id: str) -> List[str]:
|
||||
return sorted(
|
||||
p.rsplit("/", 1)[-1]
|
||||
for p in storage.list_files(f"{THEMES_PREFIX}/{theme_id}/assets/")
|
||||
if p.rsplit("/", 1)[-1]
|
||||
)
|
||||
|
||||
|
||||
def _basename_only(value: object, where: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise TenantValidationError(f"{where} must be a file name.")
|
||||
name = value.strip()
|
||||
if "/" in name or "\\" in name or name.startswith(".") or ":" in name:
|
||||
raise TenantValidationError(f"{where} must be one of your theme's uploaded files, not a path.")
|
||||
return name
|
||||
|
||||
|
||||
def _check_region(value: object, where: str) -> None:
|
||||
if value is None:
|
||||
return
|
||||
try:
|
||||
x, y, w, h = (int(float(p)) for p in str(value).split(","))
|
||||
except (ValueError, OverflowError) as exc:
|
||||
raise TenantValidationError(f"{where} must be 'x, y, width, height'.") from exc
|
||||
if min(x, y) < 0 or w <= 0 or h <= 0 or x + w > 3840 or y + h > 2160:
|
||||
raise TenantValidationError(f"{where} must fit inside the 3840x2160 frame.")
|
||||
|
||||
|
||||
def sanitize_style_params(
|
||||
style_params: object, *, available_assets: List[str]
|
||||
) -> Tuple[Dict, Optional[str]]:
|
||||
"""Validate + normalise tenant-supplied style_params.
|
||||
|
||||
Returns (clean_style_params, font_basename). Raises TenantValidationError.
|
||||
"""
|
||||
styles = copy.deepcopy(_validate_style_params(style_params))
|
||||
for section in ("intro", "karaoke", "end", "cdg"):
|
||||
styles.setdefault(section, {})
|
||||
|
||||
assets = set(available_assets)
|
||||
fonts_ok = assets | set(bundled_fonts())
|
||||
|
||||
for section in ("intro", "end"):
|
||||
if "existing_image" in styles[section]:
|
||||
styles[section]["existing_image"] = None
|
||||
|
||||
for section, field in IMAGE_FIELDS:
|
||||
value = styles[section].get(field)
|
||||
if value in (None, ""):
|
||||
if field in styles[section]:
|
||||
styles[section][field] = None
|
||||
continue
|
||||
name = _basename_only(value, f"{section}.{field}")
|
||||
if name not in assets:
|
||||
raise TenantValidationError(f"{section}.{field} '{name}' hasn't been uploaded to this theme.")
|
||||
styles[section][field] = name
|
||||
|
||||
# One font for every section (the render pipeline applies intro.font everywhere).
|
||||
# Always set, so no section can keep a path of its own (e.g. an absolute
|
||||
# karaoke.font_path would otherwise reach the ffmpeg fontsdir / libass).
|
||||
font = _basename_only(styles["intro"].get("font") or DEFAULT_FONT, "intro.font")
|
||||
if font not in fonts_ok:
|
||||
raise TenantValidationError(f"Font '{font}' isn't available — upload it or pick a built-in font.")
|
||||
for section, field in FONT_FIELDS:
|
||||
styles[section][field] = font
|
||||
|
||||
from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE
|
||||
|
||||
for key in REQUIRED_KARAOKE_KEYS:
|
||||
if styles["karaoke"].get(key) is None:
|
||||
styles["karaoke"][key] = DEFAULT_KARAOKE_STYLE[key]
|
||||
for section, field in ASS_TEXT_FIELDS:
|
||||
value = styles[section].get(field)
|
||||
if not isinstance(value, str) or not value.strip() or len(value) > 80 or _ASS_UNSAFE.search(value):
|
||||
raise TenantValidationError(f"{section}.{field} must be a short name without commas or line breaks.")
|
||||
|
||||
singers = styles["karaoke"].get("singers")
|
||||
if singers is not None:
|
||||
if not isinstance(singers, dict) or not all(isinstance(v, dict) for v in singers.values()):
|
||||
raise TenantValidationError("karaoke.singers must map singer keys to colour settings.")
|
||||
for key, colours in singers.items():
|
||||
for name, value in colours.items():
|
||||
if name.endswith("_color") and (
|
||||
not _RGBA.match(str(value)) or any(int(p) > 255 for p in str(value).split(","))
|
||||
):
|
||||
raise TenantValidationError(f"karaoke.singers.{key}.{name} must be 'r, g, b, a' (0-255).")
|
||||
|
||||
for (section, field), (lo, hi) in NUMERIC_BOUNDS.items():
|
||||
if field in styles[section] and styles[section][field] is not None:
|
||||
value = styles[section][field]
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not lo <= value <= hi:
|
||||
raise TenantValidationError(f"{section}.{field} must be a number between {lo} and {hi}.")
|
||||
|
||||
for section, field in HEX_COLOR_FIELDS:
|
||||
value = styles[section].get(field)
|
||||
if value is not None and not _HEX.match(str(value)):
|
||||
raise TenantValidationError(f"{section}.{field} must be a colour like #ff5bb8.")
|
||||
for section, field in RGBA_COLOR_FIELDS:
|
||||
value = styles[section].get(field)
|
||||
if value is not None:
|
||||
if not _RGBA.match(str(value)) or any(int(p) > 255 for p in str(value).split(",")):
|
||||
raise TenantValidationError(f"{section}.{field} must be 'r, g, b, a' (0-255).")
|
||||
for section, field in REGION_FIELDS:
|
||||
_check_region(styles[section].get(field), f"{section}.{field}")
|
||||
|
||||
return styles, font
|
||||
|
||||
|
||||
def _font_local_path(storage: StorageService, theme_id: str, font: str, workdir: str) -> str:
|
||||
blob_path = f"{THEMES_PREFIX}/{theme_id}/assets/{font}"
|
||||
if storage.file_exists(blob_path):
|
||||
local = os.path.join(workdir, font)
|
||||
storage.download_file(blob_path, local)
|
||||
return local
|
||||
return os.path.join(BUNDLED_FONTS_DIR, font)
|
||||
|
||||
|
||||
class ThemeNotEditableError(TenantValidationError):
|
||||
"""The tenant uses a shared/default theme it may not modify."""
|
||||
|
||||
|
||||
def _editable_theme_id(config) -> str:
|
||||
"""Tenants may only edit their own 1:1 theme (the one the admin console
|
||||
creates, named after the tenant) — never a shared or default theme."""
|
||||
theme_id = _theme_id_for(config)
|
||||
if theme_id != config.id:
|
||||
raise ThemeNotEditableError(
|
||||
"This portal uses a shared theme, so it can't be edited here. Contact Nomad Karaoke."
|
||||
)
|
||||
return theme_id
|
||||
|
||||
|
||||
class ThemeNotFoundError(TenantValidationError):
|
||||
"""The tenant's theme files are missing."""
|
||||
|
||||
|
||||
def get_theme_for_editor(config, storage: Optional[StorageService] = None) -> Dict[str, object]:
|
||||
storage = storage or StorageService()
|
||||
theme_id = _editable_theme_id(config)
|
||||
try:
|
||||
style_params = storage.download_json(f"{THEMES_PREFIX}/{theme_id}/style_params.json")
|
||||
except Exception as exc:
|
||||
raise ThemeNotFoundError("This portal's theme couldn't be found. Contact Nomad Karaoke.") from exc
|
||||
assets = _theme_assets(storage, theme_id)
|
||||
fonts = sorted(set(bundled_fonts()) | {a for a in assets if a.lower().endswith((".ttf", ".otf"))})
|
||||
images = [a for a in assets if a.rsplit(".", 1)[-1].lower() in IMAGE_CONTENT_TYPES]
|
||||
return {"theme_id": theme_id, "style_params": style_params, "images": images, "fonts": fonts}
|
||||
|
||||
|
||||
def store_uploaded_asset(
|
||||
config, filename: str, data: bytes, storage: Optional[StorageService] = None
|
||||
) -> str:
|
||||
"""Store an uploaded image/font content-addressed; return its basename."""
|
||||
storage = storage or StorageService()
|
||||
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
||||
if ext not in UPLOAD_EXTENSIONS:
|
||||
raise TenantValidationError("Upload a PNG, JPG, GIF or WEBP image, or a TTF/OTF font.")
|
||||
if ext in FONT_CONTENT_TYPES:
|
||||
# Must be a real font PIL/libass can load.
|
||||
from PIL import ImageFont
|
||||
|
||||
try:
|
||||
ImageFont.truetype(io.BytesIO(data), 20)
|
||||
except Exception as exc:
|
||||
raise TenantValidationError("That font file couldn't be read.") from exc
|
||||
else:
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
width, height = img.size
|
||||
img.verify()
|
||||
except Exception as exc:
|
||||
raise TenantValidationError("That image file couldn't be read.") from exc
|
||||
if width > MAX_IMAGE_SIDE or height > MAX_IMAGE_SIDE or width * height > MAX_IMAGE_PIXELS:
|
||||
raise TenantValidationError(
|
||||
f"That image is too large ({width}x{height}). Use up to {MAX_IMAGE_SIDE}x{MAX_IMAGE_SIDE} pixels."
|
||||
)
|
||||
|
||||
stem = _safe_asset_name(filename).rsplit(".", 1)[0][:60] or "asset"
|
||||
digest = hashlib.sha256(data).hexdigest()[:8]
|
||||
name = f"{stem}-{digest}.{ext}"
|
||||
theme_id = _editable_theme_id(config)
|
||||
content_type = FONT_CONTENT_TYPES.get(ext) or _content_type_for(ext)
|
||||
storage.upload_fileobj(
|
||||
io.BytesIO(data),
|
||||
f"{THEMES_PREFIX}/{theme_id}/assets/{name}",
|
||||
content_type=content_type,
|
||||
cache_control=NO_STORE_CACHE_CONTROL,
|
||||
)
|
||||
return name
|
||||
|
||||
|
||||
def prepare_preview_styles(config, style_params: object, storage: Optional[StorageService] = None) -> Dict:
|
||||
storage = storage or StorageService()
|
||||
theme_id = _editable_theme_id(config)
|
||||
styles, _font = sanitize_style_params(style_params, available_assets=_theme_assets(storage, theme_id))
|
||||
return styles
|
||||
|
||||
|
||||
def save_tenant_theme(config, style_params: object, storage: Optional[StorageService] = None) -> Dict:
|
||||
"""Validate, finalise (font family / bundled font copy) and save the theme."""
|
||||
storage = storage or StorageService()
|
||||
theme_id = _editable_theme_id(config)
|
||||
styles, font = sanitize_style_params(style_params, available_assets=_theme_assets(storage, theme_id))
|
||||
|
||||
assets: Dict[str, Tuple[bytes, str]] = {}
|
||||
with tempfile.TemporaryDirectory() as workdir:
|
||||
local = _font_local_path(storage, theme_id, font, workdir)
|
||||
try:
|
||||
styles["karaoke"]["font"] = font_family_name(local)
|
||||
except Exception as exc:
|
||||
raise TenantValidationError(f"Font '{font}' couldn't be read.") from exc
|
||||
if not storage.file_exists(f"{THEMES_PREFIX}/{theme_id}/assets/{font}"):
|
||||
# Bundled font: copy into the theme so render jobs download it.
|
||||
with open(local, "rb") as fh:
|
||||
assets[font] = (fh.read(), font.rsplit(".", 1)[-1])
|
||||
|
||||
update_tenant(config.id, style_params=styles, assets=assets or None, storage=storage)
|
||||
logger.info(f"Tenant '{config.id}' saved theme '{theme_id}' (font={font})")
|
||||
return styles
|
||||
@@ -0,0 +1,414 @@
|
||||
"""
|
||||
Exact previews of a (draft) theme: the real title card and one karaoke-video frame.
|
||||
|
||||
Used by the tenant theme editor. Both images come from the SAME renderers production
|
||||
uses, fed the draft ``style_params`` exactly the way a render job would see them:
|
||||
|
||||
- **Title card**: ``karaoke_gen.video_generator.VideoGenerator.create_title_video``
|
||||
with ``intro_video_duration=0`` (PNG only — what ``screens_worker`` does on Cloud Run).
|
||||
- **Karaoke frame**: ``SegmentResizer`` → ``SubtitlesGenerator.generate_ass`` (the
|
||||
generator's 4K layout: ``font_size`` default 250, ``line_height = font_size``,
|
||||
``max_line_length`` default 36) → one frame burned with the same ffmpeg ``ass``
|
||||
filter + background handling as ``lyrics_transcriber.output.video.VideoGenerator``,
|
||||
at a moment when the second line is part-way sung (sung = primary colour).
|
||||
|
||||
Theme assets are resolved like ``style_loader.update_asset_paths``: background images
|
||||
per section, and the single ``font`` asset (``intro.font``) applied to
|
||||
intro.font / karaoke.font_path / end.font / cdg.font_path.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_service import THEMES_PREFIX
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PREVIEW_WIDTH = 1280 # output thumbnails are 1280x720 JPEGs
|
||||
VIDEO_RES = (3840, 2160) # production karaoke render resolution ("4k")
|
||||
DEFAULT_FONT_SIZE = 250 # OutputGenerator._get_video_params default for 4k
|
||||
DEFAULT_MAX_LINE_LENGTH = 36 # OutputConfig.default_max_line_length
|
||||
FFMPEG_TIMEOUT_S = 30
|
||||
|
||||
# Required ASS style keys build_karaoke_styles reads without defaults.
|
||||
_REQUIRED_KARAOKE_KEYS = ("underline", "strike_out", "angle", "encoding", "ass_name")
|
||||
|
||||
BUNDLED_FONTS_DIR = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
"karaoke_gen",
|
||||
"resources",
|
||||
)
|
||||
FONT_EXTENSIONS = (".ttf", ".otf")
|
||||
|
||||
DEFAULT_SAMPLE_LYRICS = [
|
||||
"Every night I sing along",
|
||||
"Lights go down and here's my song",
|
||||
"Hold the mic and take the stage",
|
||||
"Turn the page, turn the page",
|
||||
]
|
||||
|
||||
|
||||
class ThemePreviewError(RuntimeError):
|
||||
"""A preview couldn't be rendered (bad theme, missing asset, ffmpeg failure)."""
|
||||
|
||||
|
||||
def bundled_fonts() -> List[str]:
|
||||
"""Font files shipped with karaoke_gen (usable by any theme)."""
|
||||
try:
|
||||
return sorted(f for f in os.listdir(BUNDLED_FONTS_DIR) if f.lower().endswith(FONT_EXTENSIONS))
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def font_family_name(font_file: str) -> str:
|
||||
"""The name libass matches for a font file (e.g. 'Avenir Next Bold')."""
|
||||
from PIL import ImageFont
|
||||
|
||||
family, style = ImageFont.truetype(font_file, 20).getname()
|
||||
family = (family or "").strip()
|
||||
style = (style or "").strip()
|
||||
if style and style.lower() not in ("regular", "normal", "book", "roman"):
|
||||
return f"{family} {style}"
|
||||
return family
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreviewImages:
|
||||
title_card: bytes # JPEG
|
||||
karaoke_frame: bytes # JPEG
|
||||
|
||||
def as_data_urls(self) -> Dict[str, str]:
|
||||
enc = lambda b: "data:image/jpeg;base64," + base64.b64encode(b).decode() # noqa: E731
|
||||
return {"title_card": enc(self.title_card), "karaoke_frame": enc(self.karaoke_frame)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Asset resolution (mirrors theme_service.prepare_job_style + style_loader)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_BG_FIELDS = (("intro", "background_image"), ("karaoke", "background_image"), ("end", "background_image"))
|
||||
_FONT_TARGETS = (("intro", "font"), ("karaoke", "font_path"), ("end", "font"), ("cdg", "font_path"))
|
||||
|
||||
_download_lock = threading.Lock()
|
||||
|
||||
# Cloud Run's /tmp is in-memory: keep both on-disk caches bounded.
|
||||
ASSET_CACHE_ROOT = os.path.join(tempfile.gettempdir(), "theme-preview-assets")
|
||||
BG_CACHE_ROOT = os.path.join(tempfile.gettempdir(), "theme-preview-bg")
|
||||
ASSET_CACHE_MAX_BYTES = 300 * 1024 * 1024
|
||||
BG_CACHE_MAX_BYTES = 300 * 1024 * 1024
|
||||
|
||||
|
||||
def _cache_dir(theme_id: str) -> str:
|
||||
path = os.path.join(ASSET_CACHE_ROOT, theme_id)
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _evict(root: str, max_bytes: int, keep: str = "") -> None:
|
||||
"""Delete least-recently-used files under root until it fits in max_bytes."""
|
||||
files = []
|
||||
for dirpath, _dirs, names in os.walk(root):
|
||||
for name in names:
|
||||
path = os.path.join(dirpath, name)
|
||||
try:
|
||||
st = os.stat(path)
|
||||
except OSError:
|
||||
continue
|
||||
files.append((st.st_atime, st.st_size, path))
|
||||
total = sum(size for _t, size, _p in files)
|
||||
for _atime, size, path in sorted(files):
|
||||
if total <= max_bytes:
|
||||
break
|
||||
if path == keep:
|
||||
continue
|
||||
try:
|
||||
os.remove(path)
|
||||
total -= size
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _local_theme_asset(storage: StorageService, theme_id: str, basename: str) -> Optional[str]:
|
||||
"""Download themes/<id>/assets/<basename> into a per-generation cache; None if absent."""
|
||||
blob = storage.bucket.get_blob(f"{THEMES_PREFIX}/{theme_id}/assets/{basename}")
|
||||
if blob is None:
|
||||
return None
|
||||
gen_dir = os.path.join(_cache_dir(theme_id), str(blob.generation))
|
||||
local = os.path.join(gen_dir, basename)
|
||||
with _download_lock:
|
||||
if not os.path.isfile(local):
|
||||
os.makedirs(gen_dir, exist_ok=True)
|
||||
# Download to a temp name + atomic rename: a failed download must
|
||||
# never leave a partial file that later looks cached.
|
||||
partial = f"{local}.part-{os.getpid()}-{threading.get_ident()}"
|
||||
try:
|
||||
blob.download_to_filename(partial)
|
||||
os.replace(partial, local)
|
||||
finally:
|
||||
if os.path.exists(partial):
|
||||
os.remove(partial)
|
||||
_evict(ASSET_CACHE_ROOT, ASSET_CACHE_MAX_BYTES, keep=local)
|
||||
return local
|
||||
|
||||
|
||||
def resolve_assets(
|
||||
style_params: Dict, theme_id: str, storage: Optional[StorageService] = None
|
||||
) -> Dict:
|
||||
"""Return a deep copy of style_params with asset basenames replaced by local paths.
|
||||
|
||||
Backgrounds resolve from the theme's GCS assets. The font resolves from the
|
||||
theme's assets, else from bundled fonts (a bundled font is copied into the
|
||||
theme on save, so production resolves it the same way).
|
||||
"""
|
||||
storage = storage or StorageService()
|
||||
styles = copy.deepcopy(style_params)
|
||||
|
||||
for section, field in _BG_FIELDS:
|
||||
value = (styles.get(section) or {}).get(field)
|
||||
if not value:
|
||||
continue
|
||||
local = _local_theme_asset(storage, theme_id, os.path.basename(value))
|
||||
if not local:
|
||||
raise ThemePreviewError(f"Background image '{value}' ({section}) was not found in the theme's assets.")
|
||||
styles[section][field] = local
|
||||
|
||||
font = (styles.get("intro") or {}).get("font")
|
||||
if font:
|
||||
base = os.path.basename(font)
|
||||
local = _local_theme_asset(storage, theme_id, base)
|
||||
if not local and base in bundled_fonts():
|
||||
local = os.path.join(BUNDLED_FONTS_DIR, base)
|
||||
if not local:
|
||||
raise ThemePreviewError(f"Font '{font}' was not found in the theme's assets.")
|
||||
for section, field in _FONT_TARGETS:
|
||||
if isinstance(styles.get(section), dict):
|
||||
styles[section][field] = local
|
||||
# libass selects by family name — same value save_tenant_theme persists.
|
||||
if isinstance(styles.get("karaoke"), dict):
|
||||
try:
|
||||
styles["karaoke"]["font"] = font_family_name(local)
|
||||
except Exception as exc:
|
||||
raise ThemePreviewError(f"Font '{font}' couldn't be read.") from exc
|
||||
return styles
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Renderers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _to_jpeg(png_path: str) -> bytes:
|
||||
with Image.open(png_path) as img:
|
||||
img = img.convert("RGB")
|
||||
height = round(img.height * PREVIEW_WIDTH / img.width)
|
||||
img = img.resize((PREVIEW_WIDTH, height), Image.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "JPEG", quality=85)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
|
||||
"""Title card exactly as screens_worker renders it (PNG via PIL, no video)."""
|
||||
from karaoke_gen.style_loader import DEFAULT_INTRO_STYLE
|
||||
from karaoke_gen.video_generator import VideoGenerator
|
||||
|
||||
fmt = {**DEFAULT_INTRO_STYLE, **(styles.get("intro") or {})}
|
||||
generator = VideoGenerator(
|
||||
logger=logger,
|
||||
ffmpeg_base_command="ffmpeg -hide_banner -nostats -loglevel error",
|
||||
render_bounding_boxes=False,
|
||||
output_png=True,
|
||||
output_jpg=False,
|
||||
)
|
||||
noext = os.path.join(workdir, "title")
|
||||
try:
|
||||
generator.create_title_video(
|
||||
artist=artist,
|
||||
title=title,
|
||||
format=fmt,
|
||||
output_image_filepath_noext=noext,
|
||||
output_video_filepath=os.path.join(workdir, "title.mov"),
|
||||
existing_title_image=fmt.get("existing_image"),
|
||||
intro_video_duration=0,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise ThemePreviewError(f"Title card render failed: {exc}") from exc
|
||||
return _to_jpeg(f"{noext}.png")
|
||||
|
||||
|
||||
def _sample_segments(lines: List[str]):
|
||||
"""Evenly-timed segments: line i starts at 2+3i s, words spread over 2.5 s.
|
||||
|
||||
Starts < 10 s and gaps < 10 s so SectionDetector adds no intro/instrumental.
|
||||
"""
|
||||
from karaoke_gen.lyrics_transcriber.types import LyricsSegment, Word
|
||||
|
||||
segments = []
|
||||
for i, text in enumerate(lines):
|
||||
words_text = text.split() or ["…"]
|
||||
start = 2.0 + 3.0 * i
|
||||
step = 2.5 / len(words_text)
|
||||
words = [
|
||||
Word(id=f"w{i}-{j}", text=w, start_time=start + j * step, end_time=start + (j + 1) * step - 0.05)
|
||||
for j, w in enumerate(words_text)
|
||||
]
|
||||
segments.append(
|
||||
LyricsSegment(id=f"s{i}", text=" ".join(words_text), words=words, start_time=start, end_time=start + 2.5)
|
||||
)
|
||||
return segments
|
||||
|
||||
|
||||
class _FrameRenderer:
|
||||
"""Borrow lyrics VideoGenerator's background + ASS filter handling without its
|
||||
__init__ (which probes for NVENC via nvidia-smi — pointless for one frame)."""
|
||||
|
||||
def __init__(self, styles: Dict, cache_dir: str):
|
||||
from karaoke_gen.lyrics_transcriber.output.video import VideoGenerator as LyricsVideoGenerator
|
||||
|
||||
gen = LyricsVideoGenerator.__new__(LyricsVideoGenerator)
|
||||
gen.output_dir = cache_dir
|
||||
gen.cache_dir = cache_dir
|
||||
gen.video_resolution = VIDEO_RES
|
||||
gen.styles = styles
|
||||
gen.logger = logger
|
||||
karaoke = styles.get("karaoke", {})
|
||||
gen.background_image = karaoke.get("background_image")
|
||||
gen.background_color = karaoke.get("background_color", "black")
|
||||
if gen.background_image and not os.path.isfile(gen.background_image):
|
||||
raise ThemePreviewError(f"Karaoke background image not found: {gen.background_image}")
|
||||
self.gen = gen
|
||||
|
||||
def _resized_background(self, path: str) -> str:
|
||||
"""Production's 4K scale+pad of the background, cached per source file."""
|
||||
st = os.stat(path)
|
||||
key = hashlib.sha1(f"{path}:{st.st_size}:{st.st_mtime_ns}".encode()).hexdigest()[:16]
|
||||
cached = os.path.join(BG_CACHE_ROOT, f"{key}.png")
|
||||
if os.path.isfile(cached):
|
||||
return cached
|
||||
os.makedirs(BG_CACHE_ROOT, exist_ok=True)
|
||||
resized = self.gen._resize_background_image(path)
|
||||
if resized == path:
|
||||
return path
|
||||
os.replace(resized, cached)
|
||||
_evict(BG_CACHE_ROOT, BG_CACHE_MAX_BYTES, keep=cached)
|
||||
return cached
|
||||
|
||||
def frame(self, ass_path: str, at_seconds: float, out_png: str) -> None:
|
||||
w, h = VIDEO_RES
|
||||
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-r", "30"]
|
||||
if self.gen.background_image:
|
||||
cmd += ["-loop", "1", "-i", self._resized_background(self.gen.background_image)]
|
||||
else:
|
||||
cmd += ["-f", "lavfi", "-i", f"color=c={self.gen.background_color}:s={w}x{h}:r=30"]
|
||||
try:
|
||||
ass_filter = self.gen._build_ass_filter(ass_path)
|
||||
except FileNotFoundError as exc:
|
||||
raise ThemePreviewError(str(exc)) from exc
|
||||
# Shift the single input frame's timestamp to `at_seconds` so libass renders
|
||||
# that moment directly (output-side -ss would render every 4K frame up to it).
|
||||
# Downscale inside the same pass (encoding a 4K PNG is most of the cost).
|
||||
vf = f"setpts=PTS+{at_seconds:.3f}/TB,{ass_filter},scale={PREVIEW_WIDTH}:-2:flags=lanczos"
|
||||
cmd += ["-vf", vf, "-frames:v", "1", "-y", out_png]
|
||||
try:
|
||||
subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=FFMPEG_TIMEOUT_S)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise ThemePreviewError(f"Karaoke frame render failed: {exc.stderr[-500:]}") from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise ThemePreviewError("Karaoke frame render timed out") from exc
|
||||
|
||||
|
||||
def render_karaoke_frame(styles: Dict, lines: List[str], workdir: str) -> bytes:
|
||||
"""One frame of the karaoke video with the first line about half sung."""
|
||||
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
|
||||
from karaoke_gen.lyrics_transcriber.output.subtitles import SubtitlesGenerator
|
||||
from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE
|
||||
|
||||
karaoke = dict(styles.get("karaoke") or {})
|
||||
# build_karaoke_styles reads these without defaults; fill so a sparse theme previews.
|
||||
for key in _REQUIRED_KARAOKE_KEYS:
|
||||
karaoke.setdefault(key, DEFAULT_KARAOKE_STYLE[key])
|
||||
styles = {**styles, "karaoke": karaoke}
|
||||
|
||||
font_size = karaoke.get("font_size", DEFAULT_FONT_SIZE)
|
||||
max_line_length = karaoke.get("max_line_length", DEFAULT_MAX_LINE_LENGTH)
|
||||
segments = SegmentResizer(max_line_length=max_line_length, logger=logger).resize_segments(
|
||||
_sample_segments(lines)
|
||||
)
|
||||
subtitles = SubtitlesGenerator(
|
||||
output_dir=workdir,
|
||||
video_resolution=VIDEO_RES,
|
||||
font_size=font_size,
|
||||
line_height=font_size,
|
||||
styles=styles,
|
||||
logger=logger,
|
||||
)
|
||||
try:
|
||||
ass_path = subtitles.generate_ass(segments, "preview", None) # no audio: duration from segments
|
||||
except Exception as exc:
|
||||
raise ThemePreviewError(f"Lyrics layout failed: {exc}") from exc
|
||||
|
||||
first = segments[0]
|
||||
at = first.start_time + (first.end_time - first.start_time) * 0.5
|
||||
out_png = os.path.join(workdir, "karaoke.png")
|
||||
_FrameRenderer(styles, workdir).frame(ass_path, at, out_png)
|
||||
return _to_jpeg(out_png)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public entry point (+ small cache for identical drafts)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_CACHE: "OrderedDict[str, PreviewImages]" = OrderedDict()
|
||||
_CACHE_MAX = 32
|
||||
_cache_lock = threading.Lock()
|
||||
|
||||
|
||||
def render_theme_preview(
|
||||
theme_id: str,
|
||||
style_params: Dict,
|
||||
*,
|
||||
artist: str = "Artist Name",
|
||||
title: str = "Song Title",
|
||||
lyrics: Optional[List[str]] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
) -> PreviewImages:
|
||||
lines = [ln.strip() for ln in (lyrics or DEFAULT_SAMPLE_LYRICS) if ln and ln.strip()][:4] or DEFAULT_SAMPLE_LYRICS
|
||||
key = hashlib.sha256(
|
||||
repr((theme_id, sorted_repr(style_params), artist, title, lines)).encode()
|
||||
).hexdigest()
|
||||
with _cache_lock:
|
||||
if key in _CACHE:
|
||||
_CACHE.move_to_end(key)
|
||||
return _CACHE[key]
|
||||
|
||||
styles = resolve_assets(style_params, theme_id, storage)
|
||||
with tempfile.TemporaryDirectory(prefix="theme-preview-") as workdir:
|
||||
result = PreviewImages(
|
||||
title_card=render_title_card(styles, artist, title, workdir),
|
||||
karaoke_frame=render_karaoke_frame(styles, lines, workdir),
|
||||
)
|
||||
with _cache_lock:
|
||||
_CACHE[key] = result
|
||||
while len(_CACHE) > _CACHE_MAX:
|
||||
_CACHE.popitem(last=False)
|
||||
return result
|
||||
|
||||
|
||||
def sorted_repr(value) -> str:
|
||||
"""Stable repr for hashing nested dicts."""
|
||||
import json
|
||||
|
||||
return json.dumps(value, sort_keys=True, default=str)
|
||||
@@ -0,0 +1,213 @@
|
||||
"""
|
||||
Re-render a completed tenant job with the tenant's CURRENT theme.
|
||||
|
||||
Tenant users can edit their theme at any time, but a job snapshots the theme's
|
||||
style at creation (``jobs/{id}/style/style_params.json`` + ``style_assets``), so
|
||||
existing videos keep the old look. This service re-snapshots the current theme
|
||||
onto the job and re-runs everything downstream of review — title/end screens,
|
||||
the lyrics video, final encodes and CDG/TXT packages — reusing the job's
|
||||
reviewed lyrics (corrections_updated.json) and instrumental selection, so the
|
||||
user never goes back through review.
|
||||
|
||||
Mechanism (same as VisibilityChangeService.change_to_public): move the job to
|
||||
LYRICS_COMPLETE with ``state_data.regen_restore_status = "review_complete"`` and
|
||||
trigger the screens worker. The screens worker regenerates the screens with the
|
||||
new style, restores REVIEW_COMPLETE and triggers the render worker, which renders
|
||||
from the existing corrections; the video worker then re-encodes and completes.
|
||||
|
||||
Scope is deliberately narrow: tenant jobs with no external distribution
|
||||
(YouTube/Dropbox/GDrive) — re-rendering a distributed job would need the
|
||||
delete/redistribute dance the visibility flow does, which tenants don't use.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Screens + lyrics video are regenerated; stale copies must go so the encoder
|
||||
# can't reuse them (it prefers an existing screens/*.mov over the new PNG).
|
||||
# Old title/end MOVs in finals/ are removed separately (see _delete_stale_artifacts).
|
||||
_REGENERATED_ARTIFACTS = [
|
||||
"screens/title.mov",
|
||||
"screens/title.jpg",
|
||||
"screens/title.png",
|
||||
"screens/end.mov",
|
||||
"screens/end.jpg",
|
||||
"screens/end.png",
|
||||
"videos/with_vocals.mkv",
|
||||
"videos/with_vocals.mov",
|
||||
]
|
||||
|
||||
|
||||
class RerenderError(Exception):
|
||||
"""Re-render request rejected; ``status_code`` maps to the HTTP response."""
|
||||
|
||||
def __init__(self, message: str, status_code: int = 400):
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class RerenderConflictError(RerenderError):
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message, status_code=409)
|
||||
|
||||
|
||||
def _claimable_statuses(job) -> set:
|
||||
"""COMPLETE, plus FAILED when the failure was a re-render (so it can be retried)."""
|
||||
statuses = {JobStatus.COMPLETE.value}
|
||||
if (job.state_data or {}).get("theme_rerender"):
|
||||
statuses.add(JobStatus.FAILED.value)
|
||||
return statuses
|
||||
|
||||
|
||||
def validate_rerender(job) -> Optional[str]:
|
||||
"""Return a reason the job can't be re-rendered, or None if it can."""
|
||||
if not getattr(job, "tenant_id", None):
|
||||
return "Re-rendering with the current theme is only available for portal tracks."
|
||||
if job.status not in _claimable_statuses(job):
|
||||
return f"Only finished tracks can be re-rendered (current status: {job.status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This track's outputs were deleted, so it can't be re-rendered."
|
||||
if not getattr(job, "theme_id", None):
|
||||
return "This track wasn't made from a theme, so there's nothing to re-apply."
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "This track type can't be re-rendered."
|
||||
state_data = job.state_data or {}
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "This track has no instrumental selection to re-render with."
|
||||
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "This track has no reviewed lyrics to re-render with."
|
||||
if state_data.get("youtube_url") or state_data.get("dropbox_link") or state_data.get("gdrive_files"):
|
||||
return "This track was published to YouTube/Dropbox/Drive and can't be re-rendered here."
|
||||
return None
|
||||
|
||||
|
||||
class ThemeRerenderService:
|
||||
def __init__(
|
||||
self,
|
||||
job_manager: Optional[JobManager] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
self.storage = storage or StorageService()
|
||||
|
||||
async def start(self, job, theme_id: str, requested_by: str) -> None:
|
||||
"""Re-snapshot ``theme_id`` onto the job and kick off the re-render.
|
||||
|
||||
Raises RerenderConflictError if the job stopped being COMPLETE (e.g. a
|
||||
double-click already started a re-render).
|
||||
"""
|
||||
job_id = job.job_id
|
||||
reason = validate_rerender(job)
|
||||
if reason:
|
||||
raise RerenderError(reason)
|
||||
|
||||
# Snapshot the current theme onto the job's style folder. Done before the
|
||||
# claim so a failure here leaves the job untouched; overwriting the style
|
||||
# copy of a still-complete job is harmless (its finals are already made).
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
style_params_path, style_assets, _ = _prepare_theme_for_job(
|
||||
job_id, theme_id, getattr(job, "color_overrides", None) or None
|
||||
)
|
||||
if not style_params_path:
|
||||
raise RerenderError(f"Theme '{theme_id}' has no style to apply.", status_code=500)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
update = {
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"progress": 50,
|
||||
"theme_id": theme_id,
|
||||
"style_params_gcs_path": style_params_path,
|
||||
"style_assets": style_assets,
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"state_data.theme_rerender": {
|
||||
"requested_by": requested_by,
|
||||
"requested_at": now.isoformat(),
|
||||
"theme_id": theme_id,
|
||||
},
|
||||
# The old screens are deleted below. Drop their file_urls so nothing
|
||||
# (e.g. a later retry) reuses them.
|
||||
"file_urls.screens": DELETE_FIELD,
|
||||
"file_urls.videos.with_vocals": DELETE_FIELD,
|
||||
"updated_at": now,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": f"Re-render with current theme '{theme_id}' requested by {requested_by}",
|
||||
}]),
|
||||
}
|
||||
self._claim(job_id, update, _claimable_statuses(job))
|
||||
|
||||
self._delete_stale_artifacts(job_id)
|
||||
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Re-render: failed to trigger screens worker, restoring {job.status}")
|
||||
self.job_manager.update_job(job_id, {
|
||||
"status": job.status,
|
||||
"progress": 100 if job.status == JobStatus.COMPLETE.value else job.progress,
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
"state_data.theme_rerender": DELETE_FIELD,
|
||||
})
|
||||
raise RerenderError("Couldn't start the re-render. Please try again.", status_code=503)
|
||||
|
||||
logger.info(f"[job:{job_id}] Re-render with theme '{theme_id}' started by {requested_by}")
|
||||
|
||||
def _delete_stale_artifacts(self, job_id: str) -> None:
|
||||
"""Best-effort removal of everything the re-render regenerates.
|
||||
|
||||
The GCE encoder looks up the title/end MOV with ``**/*Title*.mov`` /
|
||||
``**/*End*.mov`` across everything it downloaded from ``jobs/{id}/``, so
|
||||
once ``screens/title.mov`` is gone it would pick up the OLD
|
||||
``finals/<Artist> - <Title> (Title).mov`` (or ``finals/title_mov.mov``)
|
||||
and splice the old theme's intro/outro around the new lyrics video.
|
||||
finals/ only holds MOVs for those title/end cards, so drop every MOV there.
|
||||
The MP4/MKV/zip finals stay (overwritten by the re-render).
|
||||
"""
|
||||
paths = [f"jobs/{job_id}/{rel}" for rel in _REGENERATED_ARTIFACTS]
|
||||
try:
|
||||
paths += [
|
||||
p for p in self.storage.list_files(f"jobs/{job_id}/finals/")
|
||||
if p.lower().endswith(".mov")
|
||||
]
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Re-render: failed to list finals: {e}")
|
||||
for path in paths:
|
||||
try:
|
||||
self.storage.delete_file(path, ignore_missing=True)
|
||||
except Exception as e: # best-effort, like the visibility flow
|
||||
logger.warning(f"[job:{job_id}] Re-render: failed to delete {path}: {e}")
|
||||
|
||||
def _claim(self, job_id: str, update: dict, allowed_statuses: set) -> None:
|
||||
"""Atomically apply ``update`` iff the job's status is still claimable."""
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
@firestore.transactional
|
||||
def claim(transaction):
|
||||
snapshot = job_ref.get(transaction=transaction)
|
||||
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
|
||||
if status not in allowed_statuses:
|
||||
return False
|
||||
transaction.update(job_ref, update)
|
||||
return True
|
||||
|
||||
if not claim(db.transaction()):
|
||||
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
|
||||
@@ -382,7 +382,7 @@ class WorkerService:
|
||||
# Convenience methods for specific workers
|
||||
# These provide a cleaner API and better IDE autocomplete
|
||||
|
||||
async def trigger_audio_download_worker(self, job_id: str) -> bool:
|
||||
async def trigger_audio_download_worker(self, job_id: str, keep_trying: bool = False) -> bool:
|
||||
"""
|
||||
Trigger audio download worker.
|
||||
|
||||
@@ -392,11 +392,18 @@ class WorkerService:
|
||||
Uses Cloud Run Jobs to avoid instance termination during long-running
|
||||
downloads. This replaces the BackgroundTasks approach that caused
|
||||
jobs to get stuck when Cloud Run scaled down instances.
|
||||
|
||||
The execution timeout is overridden to fit the torrent stall budget
|
||||
(longer for a user's "Keep trying" retry) — see audio_download_limits.
|
||||
"""
|
||||
from backend.services.audio_download_limits import task_timeout_seconds
|
||||
|
||||
return await self._trigger_worker_cloud_run_job(
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="audio-download-job",
|
||||
worker_module="audio_download_worker",
|
||||
location=self.settings.cpu_jobs_region,
|
||||
timeout_seconds=task_timeout_seconds(keep_trying),
|
||||
)
|
||||
|
||||
async def trigger_bulk_search_worker(self, batch_id: str) -> bool:
|
||||
@@ -419,7 +426,7 @@ class WorkerService:
|
||||
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger bulk search job")
|
||||
return False
|
||||
|
||||
location = self.settings.gcp_region
|
||||
location = self.settings.cpu_jobs_region
|
||||
job_name = f"projects/{project}/locations/{location}/jobs/bulk-search-job"
|
||||
client = run_v2.JobsClient()
|
||||
request = run_v2.RunJobRequest(
|
||||
@@ -472,6 +479,7 @@ class WorkerService:
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="lyrics-transcription-job",
|
||||
worker_module="lyrics_worker",
|
||||
location=self.settings.cpu_jobs_region,
|
||||
)
|
||||
|
||||
async def trigger_screens_worker(self, job_id: str) -> bool:
|
||||
@@ -588,6 +596,7 @@ class WorkerService:
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="video-encoding-job",
|
||||
worker_module="video_worker",
|
||||
location=self.settings.cpu_jobs_region,
|
||||
)
|
||||
|
||||
async def _run_job_with_retry(self, client, request, log_prefix: str):
|
||||
@@ -646,6 +655,7 @@ class WorkerService:
|
||||
cloud_run_job_name: str,
|
||||
worker_module: str,
|
||||
location: str | None = None,
|
||||
timeout_seconds: int | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Trigger a worker as a Cloud Run Job.
|
||||
@@ -659,6 +669,8 @@ class WorkerService:
|
||||
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
|
||||
worker_module: Worker module name (e.g., "lyrics_worker")
|
||||
location: GCP region for the job (defaults to settings.gcp_region)
|
||||
timeout_seconds: Per-execution task timeout override (default: the
|
||||
job's configured timeout)
|
||||
|
||||
Returns:
|
||||
True if job was triggered successfully, False otherwise
|
||||
@@ -687,19 +699,20 @@ class WorkerService:
|
||||
client = run_v2.JobsClient()
|
||||
|
||||
# Run the job with overrides for the specific job_id
|
||||
request = run_v2.RunJobRequest(
|
||||
name=job_name,
|
||||
overrides=run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[
|
||||
run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=[
|
||||
"python", "-m", f"backend.workers.{worker_module}",
|
||||
"--job-id", job_id,
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
overrides = run_v2.RunJobRequest.Overrides(
|
||||
container_overrides=[
|
||||
run_v2.RunJobRequest.Overrides.ContainerOverride(
|
||||
args=[
|
||||
"python", "-m", f"backend.workers.{worker_module}",
|
||||
"--job-id", job_id,
|
||||
],
|
||||
)
|
||||
]
|
||||
)
|
||||
if timeout_seconds:
|
||||
from google.protobuf import duration_pb2
|
||||
overrides.timeout = duration_pb2.Duration(seconds=int(timeout_seconds))
|
||||
request = run_v2.RunJobRequest(name=job_name, overrides=overrides)
|
||||
|
||||
# Run the job (async operation), retrying transient control-plane errors.
|
||||
operation = await self._run_job_with_retry(
|
||||
@@ -737,6 +750,7 @@ class WorkerService:
|
||||
job_id=job_id,
|
||||
cloud_run_job_name="video-encoding-job",
|
||||
worker_module="render_video_worker",
|
||||
location=self.settings.cpu_jobs_region,
|
||||
)
|
||||
return await self.trigger_worker("render-video", job_id)
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Guards on POST /api/jobs/{job_id}/uploads-complete (signed-URL upload flow).
|
||||
|
||||
- Only the job's owner (or an admin) may finalize its uploads.
|
||||
- An existing-instrumental duration mismatch cancels (and refunds) the job
|
||||
before returning the 400, so the job can't be stranded PENDING with files.
|
||||
- An existing-instrumental duration mismatch is first lined up with the mix
|
||||
(conformed); only if that fails is the job cancelled (and refunded) before
|
||||
returning the 400, so it can't be stranded PENDING with files.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import AsyncMock, MagicMock, Mock, patch
|
||||
@@ -74,9 +75,11 @@ async def test_email_less_token_auth_still_allowed(mocks):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_duration_mismatch_cancels_job_then_400(mocks):
|
||||
async def test_unalignable_mismatch_cancels_job_then_400(mocks):
|
||||
with patch("backend.api.routes.file_upload._validate_audio_durations",
|
||||
new_callable=AsyncMock, return_value=(False, 200.0, 190.0)):
|
||||
new_callable=AsyncMock, return_value=(False, 200.0, 190.0)), \
|
||||
patch("backend.api.routes.file_upload._conform_mismatched_instrumental",
|
||||
new_callable=AsyncMock, return_value=None):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_auth())
|
||||
|
||||
@@ -100,3 +103,80 @@ async def test_matching_durations_do_not_cancel(mocks):
|
||||
mocks["job_manager"].cancel_job.assert_not_called()
|
||||
update = mocks["job_manager"].update_job.call_args[0][1]
|
||||
assert update["existing_instrumental_gcs_path"] == "uploads/job-1/audio/existing_instrumental.wav"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_alignable_mismatch_uses_conformed_instrumental(mocks):
|
||||
conformed = "uploads/job-1/conformed/existing_instrumental.flac"
|
||||
info = {"start_trimmed_seconds": 2.974, "end_trimmed_seconds": 0.0}
|
||||
with patch("backend.api.routes.file_upload._validate_audio_durations",
|
||||
new_callable=AsyncMock, return_value=(False, 187.18, 190.16)), \
|
||||
patch("backend.api.routes.file_upload._conform_mismatched_instrumental",
|
||||
new_callable=AsyncMock, return_value=(conformed, info)) as conform, \
|
||||
patch("backend.api.routes.file_upload.get_credential_manager"):
|
||||
await _call(_auth(email=None, is_admin=True))
|
||||
|
||||
conform.assert_awaited_once()
|
||||
mocks["job_manager"].cancel_job.assert_not_called()
|
||||
update = mocks["job_manager"].update_job.call_args[0][1]
|
||||
assert update["existing_instrumental_gcs_path"] == conformed
|
||||
mocks["job_manager"].update_state_data.assert_any_call("job-1", "instrumental_conformed", info)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conform_helper_uploads_outside_audio_prefix():
|
||||
"""The conformed copy must not land under uploads/{job}/audio/, where it
|
||||
would be mistaken for the mixed audio."""
|
||||
from backend.api.routes.file_upload import _conform_mismatched_instrumental
|
||||
from backend.services.instrumental_conform import ConformResult
|
||||
|
||||
storage = MagicMock()
|
||||
result = ConformResult(187.18, 190.16, 2.97, 0.0, 0.8)
|
||||
with patch("backend.services.instrumental_conform.conform_instrumental", return_value=result):
|
||||
path, info = await _conform_mismatched_instrumental(
|
||||
storage, "job-1", "uploads/job-1/audio/song.wav", "uploads/job-1/audio/existing_instrumental.wav")
|
||||
assert path == "uploads/job-1/conformed/existing_instrumental.flac"
|
||||
assert storage.upload_file.call_args[0][1] == path
|
||||
assert info["original_gcs_path"] == "uploads/job-1/audio/existing_instrumental.wav"
|
||||
assert info["start_trimmed_seconds"] == 2.97
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conform_helper_returns_none_only_for_a_real_mismatch():
|
||||
from backend.api.routes.file_upload import _conform_mismatched_instrumental
|
||||
from backend.services.instrumental_conform import InstrumentalConformError
|
||||
|
||||
storage = MagicMock()
|
||||
with patch("backend.services.instrumental_conform.conform_instrumental",
|
||||
side_effect=InstrumentalConformError("wrong file", mismatch=True)):
|
||||
assert await _conform_mismatched_instrumental(
|
||||
storage, "job-1", "uploads/job-1/audio/a.wav", "uploads/job-1/audio/existing_instrumental.wav") is None
|
||||
storage.upload_file.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("exc", [OSError("disk full"), None])
|
||||
async def test_conform_helper_infra_failure_is_retryable_503(exc):
|
||||
"""GCS/ffmpeg failures must not cancel the job as a 'wrong file'."""
|
||||
from backend.api.routes.file_upload import _conform_mismatched_instrumental
|
||||
from backend.services.instrumental_conform import InstrumentalConformError
|
||||
|
||||
exc = exc or InstrumentalConformError("ffmpeg timed out") # mismatch=False
|
||||
with patch("backend.services.instrumental_conform.conform_instrumental", side_effect=exc):
|
||||
with pytest.raises(HTTPException) as err:
|
||||
await _conform_mismatched_instrumental(
|
||||
MagicMock(), "job-1", "uploads/job-1/audio/a.wav", "uploads/job-1/audio/existing_instrumental.wav")
|
||||
assert err.value.status_code == 503
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conform_infra_failure_does_not_cancel_job(mocks):
|
||||
with patch("backend.api.routes.file_upload._validate_audio_durations",
|
||||
new_callable=AsyncMock, return_value=(False, 200.0, 190.0)), \
|
||||
patch("backend.api.routes.file_upload._conform_mismatched_instrumental",
|
||||
new_callable=AsyncMock, side_effect=HTTPException(status_code=503, detail="try again")):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_auth())
|
||||
assert exc.value.status_code == 503
|
||||
mocks["job_manager"].cancel_job.assert_not_called()
|
||||
mocks["job_manager"].update_job.assert_not_called()
|
||||
@@ -619,6 +619,28 @@ class TestVerifyGrantsCredits:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_tenant_login_skips_consumer_credits(self, mock_user_svc):
|
||||
"""Tenant portal sign-ins never get the consumer welcome-credit flow: no
|
||||
eval/grant, no credits-denied screen or email, no consumer welcome email."""
|
||||
user = User(email="randyvild@gmail.com", credits=0, email_verified=True)
|
||||
client = self._make_verify_client(mock_user_svc, user, credits_eligible=False)
|
||||
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
|
||||
mock_ml_doc.to_dict.return_value = {"email": user.email, "tenant_id": "randy-vild"}
|
||||
mock_user_svc.grant_welcome_credits_if_eligible.return_value = (False, "denied")
|
||||
|
||||
try:
|
||||
with patch("backend.services.tenant_service.get_tenant_service") as gts:
|
||||
gts.return_value.get_tenant_config.return_value = None
|
||||
response = client.get("/api/users/auth/verify?token=valid-token")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["credit_status"] == "not_applicable"
|
||||
assert data["credits_granted"] == 0
|
||||
mock_user_svc.grant_welcome_credits_if_eligible.assert_not_called()
|
||||
finally:
|
||||
from backend.main import app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
def test_verify_passes_precomputed_eval(self, mock_user_svc):
|
||||
"""Verify endpoint passes pre-computed eval from magic link doc."""
|
||||
user = User(email="new@example.com", credits=2, email_verified=True)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Budget invariants for the audio-download torrent stall handling."""
|
||||
import pytest
|
||||
|
||||
from backend.services import audio_download_limits as limits
|
||||
from backend.workers.audio_download_worker import DOWNLOAD_WAIT_TIMEOUT_SECONDS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keep_trying", [False, True])
|
||||
def test_task_timeout_exceeds_wait_exceeds_stall(keep_trying):
|
||||
"""Cloud Run must not SIGKILL the worker before its wait (which must outlast
|
||||
flacfetch's stall ceiling) expires, so each budget nests inside the next."""
|
||||
stall = limits.stall_seconds(keep_trying)
|
||||
wait = limits.torrent_wait_timeout_seconds(keep_trying)
|
||||
task = limits.task_timeout_seconds(keep_trying)
|
||||
assert task > wait > stall > 0
|
||||
|
||||
|
||||
def test_stall_budgets():
|
||||
assert limits.stall_seconds(False) == 1200
|
||||
# flacfetch caps max_stall_seconds at 3600 per request.
|
||||
assert limits.stall_seconds(True) == 3600
|
||||
|
||||
|
||||
def test_keep_trying_budgets_are_longer():
|
||||
assert limits.task_timeout_seconds(True) > limits.task_timeout_seconds(False)
|
||||
assert limits.torrent_wait_timeout_seconds(True) > limits.torrent_wait_timeout_seconds(False)
|
||||
|
||||
|
||||
def test_non_torrent_wait_below_default_task_timeout():
|
||||
"""Non-torrent downloads still use DOWNLOAD_WAIT_TIMEOUT_SECONDS under the
|
||||
(default) per-run timeout override."""
|
||||
assert DOWNLOAD_WAIT_TIMEOUT_SECONDS < limits.task_timeout_seconds(False)
|
||||
|
||||
|
||||
def test_cloud_run_max_timeout_not_exceeded():
|
||||
"""Cloud Run Jobs cap a task timeout at 24h (168h preview); stay well under."""
|
||||
assert limits.task_timeout_seconds(True) <= 24 * 3600
|
||||
|
||||
|
||||
def test_heartbeat_well_under_stuck_download_threshold():
|
||||
"""Heartbeats bump updated_at; recover-stuck-jobs parks a downloading_audio
|
||||
job after 10 min without an update (job_health_service downloading_audio_stuck).
|
||||
Leave room for several missed/failed heartbeats."""
|
||||
stuck_threshold_seconds = 10 * 60
|
||||
assert 0 < limits.HEARTBEAT_INTERVAL_SECONDS * 3 <= stuck_threshold_seconds
|
||||
|
||||
|
||||
def test_stuck_threshold_is_still_ten_minutes():
|
||||
"""Guard the assumption above: if the stuck threshold changes, revisit the heartbeat."""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
src = (pathlib.Path(__file__).resolve().parents[1] / "services" / "job_health_service.py").read_text()
|
||||
block = src[src.index("status == JobStatus.DOWNLOADING_AUDIO and job.updated_at"):]
|
||||
m = re.search(r"download_age > timedelta\(minutes=(\d+)\)", block)
|
||||
assert m and int(m.group(1)) == 10
|
||||
@@ -884,3 +884,262 @@ class TestDownloadAudio:
|
||||
target_file=None, download_url=None, remote_search_id=None,
|
||||
selection_index=None, selected={}, storage_service=mock_storage,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Torrent stall -> "Keep trying?" prompt (no silent auto-retry)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
from backend.services import audio_download_limits # noqa: E402
|
||||
from backend.services.flacfetch_client import ( # noqa: E402
|
||||
FlacfetchDownloadStalledError,
|
||||
FlacfetchServiceError,
|
||||
)
|
||||
|
||||
|
||||
def _red_job(**state) -> Job:
|
||||
return _make_job(source_name="RED", source_id="987654", state_data=dict(state))
|
||||
|
||||
|
||||
def _mock_flacfetch(wait_side_effect=None):
|
||||
client = MagicMock()
|
||||
client.download_by_id = AsyncMock(return_value="dl_1")
|
||||
client.download = AsyncMock(return_value="dl_1")
|
||||
if wait_side_effect is not None:
|
||||
client.wait_for_download = AsyncMock(side_effect=wait_side_effect)
|
||||
else:
|
||||
client.wait_for_download = AsyncMock(return_value={
|
||||
"status": "complete",
|
||||
"gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/uploads/test-job-123/audio/song.flac",
|
||||
})
|
||||
return client
|
||||
|
||||
|
||||
class TestTorrentStallAwaitsUser:
|
||||
"""A stalled torrent fails the job with a user prompt instead of auto-retrying."""
|
||||
|
||||
async def _run(self, job, flacfetch, attempt="0"):
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker.get_flacfetch_client", return_value=flacfetch), \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory, \
|
||||
patch("backend.workers.audio_download_worker.reconcile_and_maybe_pause",
|
||||
new_callable=AsyncMock, return_value=False), \
|
||||
patch.dict(os.environ, {"CLOUD_RUN_TASK_ATTEMPT": attempt}, clear=False):
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = job
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
mock_ws_factory.return_value = AsyncMock()
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
return result, mock_jm
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stall_fails_job_with_stalled_details_and_no_retry_pending(self):
|
||||
flacfetch = _mock_flacfetch(FlacfetchDownloadStalledError("Download failed: stalled"))
|
||||
|
||||
result, mock_jm = await self._run(_red_job(), flacfetch, attempt="0")
|
||||
|
||||
assert result is False
|
||||
mock_jm.fail_job.assert_called_once()
|
||||
assert mock_jm.fail_job.call_args.kwargs["error_details"] == {
|
||||
'stage': 'audio_download',
|
||||
'code': 'audio_download_stalled',
|
||||
'stall_minutes': 20,
|
||||
'keep_trying': False,
|
||||
}
|
||||
pending_updates = [c for c in mock_jm.update_state_data.call_args_list
|
||||
if c.args[1] == 'cloud_run_retry_pending']
|
||||
assert pending_updates, "stall must explicitly clear any retry-pending marker"
|
||||
assert all(c.args[2] is None for c in pending_updates), (
|
||||
f"stall must not mark an auto-retry pending; got {pending_updates}"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_job_uses_default_stall_budget(self):
|
||||
flacfetch = _mock_flacfetch()
|
||||
|
||||
result, _ = await self._run(_red_job(), flacfetch)
|
||||
|
||||
assert result is True
|
||||
assert flacfetch.download_by_id.await_args.kwargs["max_stall_seconds"] == 1200
|
||||
assert flacfetch.wait_for_download.await_args.kwargs["timeout"] == (
|
||||
audio_download_limits.torrent_wait_timeout_seconds(False)
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_trying_uses_extended_stall_budget(self):
|
||||
flacfetch = _mock_flacfetch()
|
||||
|
||||
result, _ = await self._run(_red_job(audio_download_keep_trying=True), flacfetch)
|
||||
|
||||
assert result is True
|
||||
assert flacfetch.download_by_id.await_args.kwargs["max_stall_seconds"] == 3600
|
||||
assert flacfetch.wait_for_download.await_args.kwargs["timeout"] == (
|
||||
audio_download_limits.torrent_wait_timeout_seconds(True)
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_trying_stall_reports_60_minutes(self):
|
||||
flacfetch = _mock_flacfetch(FlacfetchDownloadStalledError("Download failed: stalled"))
|
||||
|
||||
result, mock_jm = await self._run(_red_job(audio_download_keep_trying=True), flacfetch)
|
||||
|
||||
assert result is False
|
||||
details = mock_jm.fail_job.call_args.kwargs["error_details"]
|
||||
assert details["code"] == "audio_download_stalled"
|
||||
assert details["stall_minutes"] == 60
|
||||
assert details["keep_trying"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_stall_failure_still_marks_retry_pending(self):
|
||||
flacfetch = _mock_flacfetch(FlacfetchServiceError("Download failed: tracker 500"))
|
||||
|
||||
result, mock_jm = await self._run(_red_job(), flacfetch, attempt="0")
|
||||
|
||||
assert result is False
|
||||
pending = [c.args[2] for c in mock_jm.update_state_data.call_args_list
|
||||
if c.args[1] == 'cloud_run_retry_pending']
|
||||
assert len(pending) == 1 and pending[0]['expected_attempt'] == 1
|
||||
assert mock_jm.fail_job.call_args.kwargs["error_details"] == {'stage': 'audio_download'}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_success_clears_keep_trying_flag(self):
|
||||
flacfetch = _mock_flacfetch()
|
||||
|
||||
result, mock_jm = await self._run(_red_job(audio_download_keep_trying=True), flacfetch)
|
||||
|
||||
assert result is True
|
||||
mock_jm.update_state_data.assert_any_call(
|
||||
"test-job-123", audio_download_limits.KEEP_TRYING_STATE_KEY, None
|
||||
)
|
||||
|
||||
|
||||
class TestMainExitCodes:
|
||||
"""main() exits 0 for a stalled download (no Cloud Run retry), 1 otherwise."""
|
||||
|
||||
def _run_main(self, error_details):
|
||||
from backend.workers import audio_download_worker as worker
|
||||
|
||||
failed_job = _make_job(status=JobStatus.FAILED, error_details=error_details)
|
||||
with patch.object(worker, "process_audio_download", new=AsyncMock(return_value=False)), \
|
||||
patch.object(worker, "JobManager") as mock_jm_cls, \
|
||||
patch("sys.argv", ["audio_download_worker", "--job-id", "test-job-123"]):
|
||||
mock_jm_cls.return_value.get_job.return_value = failed_job
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
worker.main()
|
||||
return exc_info.value.code
|
||||
|
||||
def test_exits_zero_when_stalled_awaiting_user(self):
|
||||
assert self._run_main({'stage': 'audio_download', 'code': 'audio_download_stalled'}) == 0
|
||||
|
||||
def test_exits_one_for_other_failures(self):
|
||||
assert self._run_main({'stage': 'audio_download'}) == 1
|
||||
|
||||
def test_exits_one_when_job_lookup_fails(self):
|
||||
from backend.workers import audio_download_worker as worker
|
||||
|
||||
with patch.object(worker, "process_audio_download", new=AsyncMock(return_value=False)), \
|
||||
patch.object(worker, "JobManager", side_effect=RuntimeError("firestore down")), \
|
||||
patch("sys.argv", ["audio_download_worker", "--job-id", "test-job-123"]):
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
worker.main()
|
||||
assert exc_info.value.code == 1
|
||||
|
||||
|
||||
class TestDownloadHeartbeat:
|
||||
"""_download_heartbeat keeps updated_at fresh during a long torrent wait so
|
||||
the recover-stuck-jobs cron (>10 min without update) doesn't park the job."""
|
||||
|
||||
@staticmethod
|
||||
def _progress_writes(mock_jm):
|
||||
return [c.args[2] for c in mock_jm.update_state_data.call_args_list
|
||||
if c.args[1] == 'audio_download_progress']
|
||||
|
||||
def test_first_call_writes_progress(self):
|
||||
from backend.workers.audio_download_worker import _download_heartbeat
|
||||
|
||||
mock_jm = MagicMock()
|
||||
callback = _download_heartbeat("test-job-123", job_manager=mock_jm)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.time.monotonic", return_value=5000.0):
|
||||
callback({"status": "downloading", "progress": 12.5, "peers": 1, "download_speed_kbps": 800})
|
||||
|
||||
writes = self._progress_writes(mock_jm)
|
||||
assert len(writes) == 1
|
||||
assert writes[0]["progress"] == 12.5
|
||||
assert writes[0]["peers"] == 1
|
||||
assert writes[0]["download_speed_kbps"] == 800
|
||||
assert "at" in writes[0]
|
||||
assert mock_jm.update_state_data.call_args.args[0] == "test-job-123"
|
||||
|
||||
def test_missing_fields_default_to_zero(self):
|
||||
from backend.workers.audio_download_worker import _download_heartbeat
|
||||
|
||||
mock_jm = MagicMock()
|
||||
callback = _download_heartbeat("test-job-123", job_manager=mock_jm)
|
||||
with patch("backend.workers.audio_download_worker.time.monotonic", return_value=5000.0):
|
||||
callback({"status": "queued"})
|
||||
|
||||
write = self._progress_writes(mock_jm)[0]
|
||||
assert write["progress"] == 0 and write["peers"] == 0 and write["download_speed_kbps"] == 0
|
||||
|
||||
def test_throttles_writes_to_heartbeat_interval(self):
|
||||
from backend.workers.audio_download_worker import _download_heartbeat
|
||||
|
||||
interval = audio_download_limits.HEARTBEAT_INTERVAL_SECONDS
|
||||
mock_jm = MagicMock()
|
||||
callback = _download_heartbeat("test-job-123", job_manager=mock_jm)
|
||||
# Poll every few seconds; only calls >= interval apart should write.
|
||||
times = [1000.0, 1005.0, 1000.0 + interval - 1, 1000.0 + interval,
|
||||
1000.0 + interval + 10, 1000.0 + 2 * interval]
|
||||
|
||||
with patch("backend.workers.audio_download_worker.time.monotonic", side_effect=times):
|
||||
for _ in times:
|
||||
callback({"status": "downloading", "progress": 0, "peers": 0})
|
||||
|
||||
assert len(self._progress_writes(mock_jm)) == 3
|
||||
|
||||
def test_write_error_is_swallowed_and_retried_next_interval(self):
|
||||
from backend.workers.audio_download_worker import _download_heartbeat
|
||||
|
||||
interval = audio_download_limits.HEARTBEAT_INTERVAL_SECONDS
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.update_state_data.side_effect = [RuntimeError("firestore unavailable"), None]
|
||||
callback = _download_heartbeat("test-job-123", job_manager=mock_jm)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.time.monotonic",
|
||||
side_effect=[1000.0, 1000.0 + interval]):
|
||||
callback({"status": "downloading"}) # must not raise
|
||||
callback({"status": "downloading"})
|
||||
|
||||
assert mock_jm.update_state_data.call_count == 2
|
||||
|
||||
def test_defaults_to_new_job_manager(self):
|
||||
from backend.workers.audio_download_worker import _download_heartbeat
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.time.monotonic", return_value=5000.0):
|
||||
_download_heartbeat("test-job-123")({"status": "downloading"})
|
||||
|
||||
mock_jm_cls.return_value.update_state_data.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_torrent_passes_heartbeat_progress_callback(self):
|
||||
from backend.workers.audio_download_worker import _download_torrent
|
||||
|
||||
flacfetch = _mock_flacfetch()
|
||||
with patch("backend.workers.audio_download_worker.get_flacfetch_client", return_value=flacfetch), \
|
||||
patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.time.monotonic", return_value=5000.0):
|
||||
await _download_torrent(
|
||||
"test-job-123", "RED", "987654", None, None, None, None,
|
||||
)
|
||||
callback = flacfetch.wait_for_download.await_args.kwargs["progress_callback"]
|
||||
assert callable(callback)
|
||||
callback({"status": "downloading", "progress": 50})
|
||||
|
||||
writes = [c.args for c in mock_jm_cls.return_value.update_state_data.call_args_list
|
||||
if c.args[1] == 'audio_download_progress']
|
||||
assert len(writes) == 1 and writes[0][0] == "test-job-123"
|
||||
@@ -1881,5 +1881,38 @@ class TestUploadEndpointThemeSupport:
|
||||
)
|
||||
|
||||
|
||||
class TestPrepareThemeYoutubeDescriptionPrecedence:
|
||||
"""The canonical Settings.default_youtube_description must win over a theme's
|
||||
legacy youtube_description.txt (which previously overrode it on every themed
|
||||
job, publishing stale Fiverr text that the backfill worker then had to fix)."""
|
||||
|
||||
def _run(self, default_description):
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
|
||||
theme_service = MagicMock()
|
||||
theme_service.theme_exists.return_value = True
|
||||
theme_service.prepare_job_style.return_value = ("jobs/j1/style_params.json", {"bg": "x"})
|
||||
theme_service.get_youtube_description.return_value = "OLD THEME DESCRIPTION"
|
||||
settings = MagicMock(default_youtube_description=default_description)
|
||||
|
||||
with patch("backend.api.routes.file_upload.get_theme_service", return_value=theme_service), \
|
||||
patch("backend.api.routes.file_upload.get_settings", return_value=settings):
|
||||
return _prepare_theme_for_job("j1", "nomad"), theme_service
|
||||
|
||||
def test_canonical_template_suppresses_theme_description(self):
|
||||
(style_path, assets, youtube_desc), theme_service = self._run("🎤 Sing along to {title}")
|
||||
|
||||
assert style_path == "jobs/j1/style_params.json"
|
||||
assert assets == {"bg": "x"}
|
||||
assert youtube_desc is None
|
||||
theme_service.get_youtube_description.assert_not_called()
|
||||
|
||||
def test_theme_description_used_when_no_canonical_template(self):
|
||||
(_, _, youtube_desc), theme_service = self._run("")
|
||||
|
||||
assert youtube_desc == "OLD THEME DESCRIPTION"
|
||||
theme_service.get_youtube_description.assert_called_once_with("nomad")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -19,6 +19,7 @@ import httpx
|
||||
from backend.services.flacfetch_client import (
|
||||
FlacfetchClient,
|
||||
FlacfetchServiceError,
|
||||
FlacfetchDownloadStalledError,
|
||||
_format_httpx_error,
|
||||
get_flacfetch_client,
|
||||
reset_flacfetch_client,
|
||||
@@ -1290,3 +1291,109 @@ class TestCheckYoutube:
|
||||
with pytest.raises(FlacfetchServiceError, match="YouTube availability check failed"):
|
||||
await client.check_youtube("some-id")
|
||||
|
||||
|
||||
|
||||
class TestWaitForDownloadStalled:
|
||||
"""wait_for_download() distinguishes torrent stalls (user-recoverable) from other failures."""
|
||||
|
||||
@staticmethod
|
||||
def _client_with_status(status: dict) -> FlacfetchClient:
|
||||
client = FlacfetchClient(base_url="http://localhost:8080", api_key="test-key")
|
||||
|
||||
async def mock_get_status(download_id):
|
||||
return {"download_id": download_id, **status}
|
||||
|
||||
client.get_download_status = mock_get_status
|
||||
return client
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_error_code_torrent_stalled_raises_stalled_error(self):
|
||||
client = self._client_with_status({
|
||||
"status": "failed",
|
||||
"error": "No progress for 1200s",
|
||||
"error_code": "torrent_stalled",
|
||||
})
|
||||
|
||||
with pytest.raises(FlacfetchDownloadStalledError) as exc_info:
|
||||
await client.wait_for_download("dl_1", timeout=10)
|
||||
|
||||
assert "No progress for 1200s" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_stall_message_raises_stalled_error(self):
|
||||
"""Older flacfetch (no error_code) is still detected from the message."""
|
||||
client = self._client_with_status({
|
||||
"status": "failed",
|
||||
"error": "Torrent download stalled for 600s with no progress",
|
||||
})
|
||||
|
||||
with pytest.raises(FlacfetchDownloadStalledError):
|
||||
await client.wait_for_download("dl_1", timeout=10)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_other_failure_raises_plain_service_error(self):
|
||||
client = self._client_with_status({
|
||||
"status": "failed",
|
||||
"error": "Tracker returned 403",
|
||||
"error_code": "tracker_error",
|
||||
})
|
||||
|
||||
with pytest.raises(FlacfetchServiceError) as exc_info:
|
||||
await client.wait_for_download("dl_1", timeout=10)
|
||||
|
||||
assert not isinstance(exc_info.value, FlacfetchDownloadStalledError)
|
||||
|
||||
def test_stalled_error_is_service_error_subclass(self):
|
||||
"""Existing `except FlacfetchServiceError` handlers still catch stalls."""
|
||||
assert issubclass(FlacfetchDownloadStalledError, FlacfetchServiceError)
|
||||
|
||||
|
||||
class TestDownloadMaxStallSeconds:
|
||||
"""download()/download_by_id() forward max_stall_seconds only when given."""
|
||||
|
||||
@staticmethod
|
||||
def _patched_post():
|
||||
mock_response = Mock()
|
||||
mock_response.json.return_value = {"download_id": "dl_xyz789"}
|
||||
mock_response.raise_for_status = Mock()
|
||||
mock_client = AsyncMock()
|
||||
mock_client.post = AsyncMock(return_value=mock_response)
|
||||
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
||||
mock_client.__aexit__ = AsyncMock(return_value=None)
|
||||
return mock_client
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("max_stall, expected", [(3600, 3600), (None, None)])
|
||||
async def test_download_by_id_payload(self, max_stall, expected):
|
||||
client = FlacfetchClient(base_url="http://localhost:8080", api_key="test-key")
|
||||
mock_client = self._patched_post()
|
||||
|
||||
with patch("httpx.AsyncClient", return_value=mock_client):
|
||||
await client.download_by_id(
|
||||
source_name="RED", source_id="123", max_stall_seconds=max_stall,
|
||||
)
|
||||
|
||||
payload = mock_client.post.call_args.kwargs["json"]
|
||||
assert mock_client.post.call_args.args[0].endswith("/download-by-id")
|
||||
if expected is None:
|
||||
assert "max_stall_seconds" not in payload
|
||||
else:
|
||||
assert payload["max_stall_seconds"] == expected
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("max_stall, expected", [(1200, 1200), (None, None)])
|
||||
async def test_download_payload(self, max_stall, expected):
|
||||
client = FlacfetchClient(base_url="http://localhost:8080", api_key="test-key")
|
||||
mock_client = self._patched_post()
|
||||
|
||||
with patch("httpx.AsyncClient", return_value=mock_client):
|
||||
await client.download(
|
||||
search_id="search_abc", result_index=0, max_stall_seconds=max_stall,
|
||||
)
|
||||
|
||||
payload = mock_client.post.call_args.kwargs["json"]
|
||||
assert mock_client.post.call_args.args[0].endswith("/download")
|
||||
if expected is None:
|
||||
assert "max_stall_seconds" not in payload
|
||||
else:
|
||||
assert payload["max_stall_seconds"] == expected
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Lining a user instrumental up with its mix when their lengths differ."""
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from backend.services.instrumental_conform import (
|
||||
InstrumentalConformError,
|
||||
_probe_duration,
|
||||
build_filter,
|
||||
conform_instrumental,
|
||||
)
|
||||
from backend.services.derived_vocals import SAMPLE_RATE, _decode_mono, find_offset
|
||||
|
||||
requires_ffmpeg = pytest.mark.skipif(
|
||||
shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None, reason="ffmpeg not installed"
|
||||
)
|
||||
|
||||
SR = 44100
|
||||
|
||||
|
||||
def _write_wav(path, samples):
|
||||
subprocess.run(
|
||||
["ffmpeg", "-nostdin", "-v", "error", "-y", "-f", "f32le", "-ar", str(SR), "-ac", "1", "-i", "-",
|
||||
"-c:a", "pcm_s24le", str(path)],
|
||||
input=samples.astype(np.float32).tobytes(), check=True,
|
||||
)
|
||||
|
||||
|
||||
def _song(seconds, seed=1):
|
||||
"""Band-limited noise 'instrumental' + tone-burst 'vocals'."""
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(seconds * SR)
|
||||
inst = np.convolve(rng.normal(0, 0.2, n), np.ones(8) / 8, mode="same")
|
||||
t = np.arange(n) / SR
|
||||
vocals = 0.2 * np.sin(2 * np.pi * 440 * t) * ((t.astype(int) % 2) == 0)
|
||||
return inst, vocals
|
||||
|
||||
|
||||
@requires_ffmpeg
|
||||
@pytest.mark.parametrize(
|
||||
"lead_in, tail, expect_start, expect_end",
|
||||
[
|
||||
(3.0, 0.0, 3.0, 0.0), # extra count-in on the instrumental (Keep Smiling)
|
||||
(0.0, 6.5, 0.0, 6.5), # longer outro on the instrumental (Simulation)
|
||||
(0.0, -4.5, 0.0, -4.5), # instrumental stops early (Faithful and True)
|
||||
(-1.5, 0.0, -1.5, 0.0), # instrumental starts late
|
||||
],
|
||||
)
|
||||
def test_conform_aligns_and_fits_mix_length(tmp_path, lead_in, tail, expect_start, expect_end):
|
||||
inst, vocals = _song(40)
|
||||
mix = inst + vocals
|
||||
body = inst
|
||||
if lead_in > 0:
|
||||
body = np.concatenate([np.random.default_rng(9).normal(0, 0.1, int(lead_in * SR)), body])
|
||||
elif lead_in < 0:
|
||||
body = body[int(-lead_in * SR):]
|
||||
if tail > 0:
|
||||
body = np.concatenate([body, np.random.default_rng(7).normal(0, 0.2, int(tail * SR))])
|
||||
elif tail < 0:
|
||||
body = body[: int(tail * SR)]
|
||||
_write_wav(tmp_path / "mix.wav", mix)
|
||||
_write_wav(tmp_path / "inst.wav", body)
|
||||
|
||||
out = tmp_path / "out.flac"
|
||||
result = conform_instrumental(str(tmp_path / "mix.wav"), str(tmp_path / "inst.wav"), str(out))
|
||||
|
||||
assert result.start_trimmed_seconds == pytest.approx(expect_start, abs=0.01)
|
||||
assert result.end_trimmed_seconds == pytest.approx(expect_end, abs=0.01)
|
||||
assert _probe_duration(str(out)) == pytest.approx(40.0, abs=0.05)
|
||||
# The conformed file now lines up with the mix at zero offset.
|
||||
lag = find_offset(_decode_mono(str(tmp_path / "mix.wav")), _decode_mono(str(out)), 2 * SAMPLE_RATE)
|
||||
assert abs(lag) <= 1
|
||||
|
||||
|
||||
@requires_ffmpeg
|
||||
def test_conform_rejects_unrelated_instrumental(tmp_path):
|
||||
inst, vocals = _song(30, seed=1)
|
||||
other, _ = _song(33, seed=2)
|
||||
_write_wav(tmp_path / "mix.wav", inst + vocals)
|
||||
_write_wav(tmp_path / "inst.wav", other)
|
||||
with pytest.raises(InstrumentalConformError, match="doesn't match") as err:
|
||||
conform_instrumental(str(tmp_path / "mix.wav"), str(tmp_path / "inst.wav"), str(tmp_path / "o.flac"))
|
||||
assert err.value.mismatch
|
||||
|
||||
|
||||
def test_build_filter_trims_lead_in_and_fades_long_outro():
|
||||
af = build_filter(lag_seconds=-3.0, original_duration=210.0, mix_duration=200.0)
|
||||
assert af.startswith("atrim=start=3.000000,asetpts=PTS-STARTPTS")
|
||||
assert "afade=t=out:st=198.000000:d=2.000000" in af
|
||||
assert af.endswith("atrim=end=200.000000")
|
||||
|
||||
|
||||
def test_build_filter_delays_late_start_and_pads_short_outro():
|
||||
af = build_filter(lag_seconds=1.5, original_duration=190.0, mix_duration=200.0)
|
||||
assert af.startswith("adelay=delays=1500.000:all=1")
|
||||
assert "apad=whole_dur=200.000000" in af
|
||||
assert "afade" not in af
|
||||
|
||||
|
||||
@requires_ffmpeg
|
||||
def test_conform_rejects_mid_song_edit(tmp_path):
|
||||
"""A bar removed in the middle: the start lines up but the second half is
|
||||
early. A start/end fix would hide that, so it must be rejected."""
|
||||
inst, vocals = _song(180)
|
||||
mix = inst + vocals
|
||||
cut = int(90 * SR) # between the early (45s) and late (135s) alignment windows
|
||||
edited = np.concatenate([inst[:cut], inst[cut + int(1.5 * SR):]])
|
||||
_write_wav(tmp_path / "mix.wav", mix)
|
||||
_write_wav(tmp_path / "inst.wav", edited)
|
||||
with pytest.raises(InstrumentalConformError, match="mid-song") as err:
|
||||
conform_instrumental(str(tmp_path / "mix.wav"), str(tmp_path / "inst.wav"), str(tmp_path / "o.flac"))
|
||||
assert err.value.mismatch
|
||||
|
||||
|
||||
def test_undecodable_input_is_a_rejecting_mismatch(tmp_path):
|
||||
"""Too-long/empty input fails identically on every retry, so it must be a
|
||||
mismatch (reject), not a retryable processing error."""
|
||||
from unittest.mock import patch
|
||||
from backend.services.derived_vocals import DerivedVocalsError
|
||||
|
||||
with patch("backend.services.instrumental_conform._decode_mono", side_effect=DerivedVocalsError("too long")):
|
||||
with pytest.raises(InstrumentalConformError) as err:
|
||||
conform_instrumental("mix.wav", "inst.wav", str(tmp_path / "o.flac"))
|
||||
assert err.value.mismatch
|
||||
@@ -188,3 +188,74 @@ def test_failed_delivery_does_not_suppress_next(enabled, monkeypatch):
|
||||
# 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
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auto-retry pending / stalled download
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _job_with_retry_pending(expires_at, **kwargs):
|
||||
doc = _job(**kwargs)
|
||||
doc["state_data"]["cloud_run_retry_pending"] = {"expires_at": expires_at, "expected_attempt": 1}
|
||||
return doc
|
||||
|
||||
|
||||
def _iso(delta_minutes):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
return (datetime.now(timezone.utc) + timedelta(minutes=delta_minutes)).isoformat()
|
||||
|
||||
|
||||
def test_unexpired_retry_pending_skips_alert(enabled, captured):
|
||||
db = FakeFirestore(jobs={"job-1": _job_with_retry_pending(_iso(10))})
|
||||
sent = ops_alerts.notify_job_failed(db, "jobs", "job-1", message="transient flacfetch 500")
|
||||
assert sent is False
|
||||
assert captured == []
|
||||
|
||||
|
||||
def test_retry_pending_z_suffix_and_naive_timestamps_honoured(enabled, captured):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
future = datetime.now(timezone.utc) + timedelta(minutes=10)
|
||||
db = FakeFirestore(jobs={
|
||||
"z": _job_with_retry_pending(future.strftime("%Y-%m-%dT%H:%M:%SZ")),
|
||||
"naive": _job_with_retry_pending(future.replace(tzinfo=None).isoformat()),
|
||||
})
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "z", message="err z") is False
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "naive", message="err naive") is False
|
||||
assert captured == []
|
||||
|
||||
|
||||
def test_skipped_retry_pending_does_not_consume_throttle(enabled, captured):
|
||||
"""The final attempt (marker cleared) must still alert for the same signature."""
|
||||
db = FakeFirestore(jobs={
|
||||
"job-1": _job_with_retry_pending(_iso(10)),
|
||||
"job-1-final": _job(),
|
||||
})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "job-1", message="same failure")
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1-final", message="same failure") is True
|
||||
assert len(captured) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("expires_at", [_iso(-1), "not-a-date", None])
|
||||
def test_expired_or_invalid_retry_pending_still_alerts(enabled, captured, expires_at):
|
||||
db = FakeFirestore(jobs={"job-1": _job_with_retry_pending(expires_at)})
|
||||
sent = ops_alerts.notify_job_failed(db, "jobs", "job-1", message=f"err {expires_at}")
|
||||
assert sent is True
|
||||
assert len(captured) == 1
|
||||
|
||||
|
||||
def test_stalled_download_headline(enabled, captured):
|
||||
doc = _job()
|
||||
doc["error_details"] = {"stage": "audio_download", "code": "audio_download_stalled"}
|
||||
db = FakeFirestore(jobs={"job-1": doc})
|
||||
assert ops_alerts.notify_job_failed(db, "jobs", "job-1", message="stalled 20 min") is True
|
||||
headline = captured[0].splitlines()[0]
|
||||
assert "Audio download stalled" in headline
|
||||
assert "Job failed" not in headline
|
||||
|
||||
|
||||
def test_other_failures_keep_job_failed_headline(enabled, captured):
|
||||
doc = _job()
|
||||
doc["error_details"] = {"stage": "audio_download"}
|
||||
db = FakeFirestore(jobs={"job-1": doc})
|
||||
ops_alerts.notify_job_failed(db, "jobs", "job-1", message="tracker 500")
|
||||
assert "Job failed" in captured[0].splitlines()[0]
|
||||
@@ -193,6 +193,26 @@ class TestJobStatusTransitions:
|
||||
# FAILED should allow restart from beginning
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "FAILED should allow restart to DOWNLOADING"
|
||||
|
||||
def test_failed_can_reopen_audio_selection(self):
|
||||
"""FAILED -> AWAITING_AUDIO_SELECTION backs /choose-different-audio after a
|
||||
stalled download; the re-pick then proceeds to DOWNLOADING_AUDIO."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in STATE_TRANSITIONS[JobStatus.FAILED]
|
||||
assert JobStatus.DOWNLOADING_AUDIO in STATE_TRANSITIONS[JobStatus.AWAITING_AUDIO_SELECTION]
|
||||
|
||||
def test_job_manager_accepts_failed_to_awaiting_audio_selection(self):
|
||||
"""The JobManager transition validator honours the new edge."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job = Job(
|
||||
job_id="t1", status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC), updated_at=datetime.now(UTC),
|
||||
)
|
||||
jm = JobManager.__new__(JobManager)
|
||||
with patch.object(JobManager, "get_job", return_value=job):
|
||||
assert jm.validate_state_transition("t1", JobStatus.AWAITING_AUDIO_SELECTION) is True
|
||||
assert jm.validate_state_transition("t1", JobStatus.AWAITING_AUDIO_SELECTION, raise_on_invalid=True) is True
|
||||
|
||||
|
||||
class TestJobModelSerialization:
|
||||
"""Tests for Job model serialization to/from API."""
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
"""HTTP tests for the stalled-download recovery endpoints.
|
||||
|
||||
- POST /api/jobs/{id}/retry accepts an optional {"keep_trying": true} body that
|
||||
retries an audio-search download with the extended (1 hour) stall budget.
|
||||
- POST /api/jobs/{id}/choose-different-audio reopens audio selection for a job
|
||||
whose audio download failed.
|
||||
"""
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.audio_download_limits import KEEP_TRYING_STATE_KEY
|
||||
|
||||
JOB_ID = "stalljob1"
|
||||
|
||||
|
||||
def _stalled_job(**overrides) -> Job:
|
||||
fields = dict(
|
||||
job_id=JOB_ID,
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
user_email="owner@example.com",
|
||||
audio_source_type="audio_search",
|
||||
source_name="RED",
|
||||
source_id="987654",
|
||||
input_media_gcs_path=None,
|
||||
file_urls={},
|
||||
error_message="Audio download didn't start within 20 minutes",
|
||||
error_details={
|
||||
"stage": "audio_download",
|
||||
"code": "audio_download_stalled",
|
||||
"stall_minutes": 20,
|
||||
"keep_trying": False,
|
||||
},
|
||||
state_data={
|
||||
"audio_search_results": [
|
||||
{"provider": "RED", "source_id": "987654", "title": "Test Song"},
|
||||
{"provider": "Spotify", "source_id": "sp1", "title": "Test Song"},
|
||||
],
|
||||
"selected_audio_index": 0,
|
||||
},
|
||||
)
|
||||
fields.update(overrides)
|
||||
return Job(**fields)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_jm():
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _stalled_job()
|
||||
jm.transition_to_state.return_value = True
|
||||
return jm
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_ws():
|
||||
ws = MagicMock()
|
||||
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
return ws
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_jm, mock_ws):
|
||||
mock_creds = MagicMock()
|
||||
mock_creds.universe_domain = "googleapis.com"
|
||||
with patch("backend.api.routes.jobs.job_manager", mock_jm), \
|
||||
patch("backend.api.routes.jobs.worker_service", mock_ws), \
|
||||
patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"), \
|
||||
patch("backend.services.firestore_service.firestore"), \
|
||||
patch("backend.services.storage_service.storage"), \
|
||||
patch("google.auth.default", return_value=(mock_creds, "test-project")):
|
||||
from backend.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
yield TestClient(app)
|
||||
|
||||
|
||||
def _keep_trying_updates(mock_jm):
|
||||
return [c.args[2] for c in mock_jm.update_state_data.call_args_list
|
||||
if c.args[0] == JOB_ID and c.args[1] == KEEP_TRYING_STATE_KEY]
|
||||
|
||||
|
||||
class TestRetryKeepTrying:
|
||||
|
||||
def test_keep_trying_body_sets_flag_and_extended_trigger(self, client, mock_jm, mock_ws, auth_headers):
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/retry", headers=auth_headers, json={"keep_trying": True})
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
data = resp.json()
|
||||
assert data["retry_stage"] == "audio_download"
|
||||
assert data["keep_trying"] is True
|
||||
assert _keep_trying_updates(mock_jm) == [True]
|
||||
mock_ws.trigger_audio_download_worker.assert_awaited_once_with(JOB_ID, keep_trying=True)
|
||||
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.DOWNLOADING_AUDIO
|
||||
|
||||
def test_no_body_defaults_to_normal_budget(self, client, mock_jm, mock_ws):
|
||||
"""Existing callers POST with no body at all — must keep working."""
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/retry", headers={"Authorization": "Bearer test-admin-token"})
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["keep_trying"] is False
|
||||
assert _keep_trying_updates(mock_jm) == [None]
|
||||
mock_ws.trigger_audio_download_worker.assert_awaited_once_with(JOB_ID, keep_trying=False)
|
||||
|
||||
def test_empty_body_with_json_content_type(self, client, mock_jm, mock_ws, auth_headers):
|
||||
"""Callers that send Content-Type: application/json but no body still work."""
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/retry", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
mock_ws.trigger_audio_download_worker.assert_awaited_once_with(JOB_ID, keep_trying=False)
|
||||
|
||||
def test_explicit_false_body(self, client, mock_jm, mock_ws, auth_headers):
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/retry", headers=auth_headers, json={"keep_trying": False})
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert _keep_trying_updates(mock_jm) == [None]
|
||||
mock_ws.trigger_audio_download_worker.assert_awaited_once_with(JOB_ID, keep_trying=False)
|
||||
|
||||
def test_retry_pending_blocks_keep_trying(self, client, mock_jm, mock_ws, auth_headers):
|
||||
expires = (datetime.now(UTC) + timedelta(minutes=10)).isoformat()
|
||||
mock_jm.get_job.return_value = _stalled_job(
|
||||
state_data={"cloud_run_retry_pending": {"expires_at": expires, "expected_attempt": 1}},
|
||||
)
|
||||
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/retry", headers=auth_headers, json={"keep_trying": True})
|
||||
|
||||
assert resp.status_code == 409
|
||||
mock_ws.trigger_audio_download_worker.assert_not_awaited()
|
||||
|
||||
|
||||
class TestChooseDifferentAudio:
|
||||
|
||||
def test_reopens_audio_selection(self, client, mock_jm, auth_headers):
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/choose-different-audio", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["job_status"] == "awaiting_audio_selection"
|
||||
mock_jm.transition_to_state.assert_called_once()
|
||||
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_AUDIO_SELECTION
|
||||
mock_jm.update_job.assert_any_call(JOB_ID, {"error_message": None, "error_details": None})
|
||||
assert _keep_trying_updates(mock_jm) == [None]
|
||||
|
||||
@pytest.mark.parametrize("job_overrides", [
|
||||
pytest.param({"status": JobStatus.DOWNLOADING_AUDIO}, id="not-failed"),
|
||||
pytest.param({"error_details": {"stage": "audio_separation"}}, id="other-stage"),
|
||||
pytest.param({"error_details": None}, id="no-error-details"),
|
||||
pytest.param({"state_data": {}}, id="no-search-results"),
|
||||
pytest.param({"state_data": {"audio_search_results": []}}, id="empty-search-results"),
|
||||
])
|
||||
def test_rejects_ineligible_jobs_with_400(self, client, mock_jm, auth_headers, job_overrides):
|
||||
mock_jm.get_job.return_value = _stalled_job(**job_overrides)
|
||||
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/choose-different-audio", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 400, resp.text
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
def test_forbidden_for_non_owner(self, client, mock_jm, auth_headers):
|
||||
with patch("backend.api.routes.jobs._check_job_ownership", return_value=False):
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/choose-different-audio", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 403
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
def test_conflict_when_auto_retry_pending(self, client, mock_jm, auth_headers):
|
||||
expires = (datetime.now(UTC) + timedelta(minutes=10)).isoformat()
|
||||
job = _stalled_job()
|
||||
job.state_data["cloud_run_retry_pending"] = {"expires_at": expires, "expected_attempt": 1}
|
||||
mock_jm.get_job.return_value = job
|
||||
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/choose-different-audio", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 409
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
def test_not_found(self, client, mock_jm, auth_headers):
|
||||
mock_jm.get_job.return_value = None
|
||||
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/choose-different-audio", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 404
|
||||
|
||||
def test_transition_failure_returns_500(self, client, mock_jm, auth_headers):
|
||||
mock_jm.transition_to_state.return_value = False
|
||||
|
||||
resp = client.post(f"/api/jobs/{JOB_ID}/choose-different-audio", headers=auth_headers)
|
||||
|
||||
assert resp.status_code == 500
|
||||
@@ -515,7 +515,9 @@ def test_update_access_lists_normalized_and_enforced(fake_storage):
|
||||
storage=fake_storage,
|
||||
)
|
||||
assert reopened.auth.require_email_domain is False
|
||||
assert reopened.is_email_allowed("random@gmail.com")
|
||||
# Empty allowlist = admins only (never an open portal)
|
||||
assert not reopened.is_email_allowed("random@gmail.com")
|
||||
assert reopened.is_email_allowed("andrew@nomadkaraoke.com")
|
||||
|
||||
|
||||
def test_update_rejects_invalid_domain(fake_storage):
|
||||
|
||||
@@ -258,11 +258,12 @@ class TestTenantConfig:
|
||||
assert full_config.is_email_allowed("User@VOCAL-STAR.COM") is True
|
||||
assert full_config.is_email_allowed("User@VocalStarMusic.com") is True
|
||||
|
||||
def test_is_email_allowed_no_domain_restrictions(self, basic_config):
|
||||
"""Test any email allowed when no domain restrictions."""
|
||||
# basic_config has empty allowed_email_domains
|
||||
assert basic_config.is_email_allowed("anyone@gmail.com") is True
|
||||
assert basic_config.is_email_allowed("user@anything.com") is True
|
||||
def test_is_email_allowed_no_allowlist_means_admins_only(self, basic_config):
|
||||
"""No allowlist = admins only. Tenant jobs don't use consumer credits, so
|
||||
a tenant portal must never be open to arbitrary sign-ups."""
|
||||
assert basic_config.is_email_allowed("anyone@gmail.com") is False
|
||||
assert basic_config.is_email_allowed("user@anything.com") is False
|
||||
assert basic_config.is_email_allowed("andrew@nomadkaraoke.com") is True
|
||||
|
||||
def test_is_email_allowed_require_domain_false_still_enforced(self):
|
||||
"""A non-empty allowlist is always enforced — the legacy
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Tenant portal users never touch consumer credits.
|
||||
|
||||
Tenants (companies / bulk clients) are billed under a separate commercial
|
||||
agreement, so:
|
||||
- tenant jobs are never credit-checked or charged, and are marked
|
||||
payment_bypassed (so duration reconciliation never pauses them for credits
|
||||
and refunds never mint credits they didn't pay),
|
||||
- consumer jobs are still charged exactly as before.
|
||||
"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import JobCreate
|
||||
from backend.models.tenant import TenantAuth, TenantConfig
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_service():
|
||||
us = MagicMock()
|
||||
us.check_credits.return_value = 0 # a tenant user with no consumer credits
|
||||
us.deduct_credits.return_value = (True, 0, "ok")
|
||||
return us
|
||||
|
||||
|
||||
TENANTS = {
|
||||
"randy-vild": TenantConfig(
|
||||
id="randy-vild",
|
||||
name="Randy Vild",
|
||||
subdomain="randy-vild.nomadkaraoke.com",
|
||||
auth=TenantAuth(allowed_emails=["randyvild@gmail.com"], require_email_domain=True),
|
||||
),
|
||||
"dormant": TenantConfig(
|
||||
id="dormant",
|
||||
name="Dormant",
|
||||
subdomain="dormant.nomadkaraoke.com",
|
||||
is_active=False,
|
||||
auth=TenantAuth(allowed_emails=["randyvild@gmail.com"], require_email_domain=True),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(user_service):
|
||||
tenant_service = MagicMock()
|
||||
tenant_service.get_tenant_config.side_effect = lambda tid: TENANTS.get(tid)
|
||||
with patch("backend.services.job_manager.FirestoreService"), \
|
||||
patch("backend.services.job_manager.StorageService"), \
|
||||
patch("backend.services.user_service.get_user_service", return_value=user_service), \
|
||||
patch("backend.services.tenant_service.get_tenant_service", return_value=tenant_service):
|
||||
jm = JobManager()
|
||||
yield jm
|
||||
|
||||
|
||||
def _create(tenant_id="", email="randyvild@gmail.com"):
|
||||
return JobCreate(
|
||||
artist="Randy Vild",
|
||||
title="Simulation",
|
||||
theme_id="randy-vild",
|
||||
user_email=email,
|
||||
tenant_id=tenant_id,
|
||||
)
|
||||
|
||||
|
||||
def test_tenant_job_not_charged_even_with_zero_credits(manager, user_service):
|
||||
job = manager.create_job(_create(tenant_id="randy-vild"))
|
||||
user_service.check_credits.assert_not_called()
|
||||
user_service.deduct_credits.assert_not_called()
|
||||
assert job.state_data["credits_charged"] == 0
|
||||
assert job.state_data["payment_bypassed"] is True
|
||||
|
||||
|
||||
def test_consumer_job_still_charged(manager, user_service):
|
||||
user_service.check_credits.return_value = 5
|
||||
job = manager.create_job(_create())
|
||||
user_service.check_credits.assert_called_once_with("randyvild@gmail.com")
|
||||
user_service.deduct_credits.assert_called_once()
|
||||
assert job.state_data["credits_charged"] == 1
|
||||
assert "payment_bypassed" not in job.state_data
|
||||
|
||||
|
||||
def test_consumer_job_without_credits_rejected(manager, user_service):
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
|
||||
with pytest.raises(InsufficientCreditsError):
|
||||
manager.create_job(_create())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tenant_id,email",
|
||||
[
|
||||
("randy-vild", "attacker@gmail.com"), # spoofed X-Tenant-ID, not on the allowlist
|
||||
("no-such-tenant", "randyvild@gmail.com"), # unknown tenant
|
||||
("dormant", "randyvild@gmail.com"), # inactive tenant
|
||||
],
|
||||
)
|
||||
def test_tenant_context_without_membership_is_charged(manager, user_service, tenant_id, email):
|
||||
"""Tenant context comes from a client-controlled header, so it only waives
|
||||
consumer credits for users actually allowed on that tenant's portal."""
|
||||
user_service.check_credits.return_value = 5
|
||||
job = manager.create_job(_create(tenant_id=tenant_id, email=email))
|
||||
user_service.deduct_credits.assert_called_once()
|
||||
assert job.state_data["credits_charged"] == 1
|
||||
@@ -0,0 +1,183 @@
|
||||
"""
|
||||
/api/tenant/theme — membership guard + endpoint wiring.
|
||||
|
||||
Tenant context can come from the client-controlled X-Tenant-ID header, so every
|
||||
endpoint must re-check that the signed-in user is allowed on that tenant.
|
||||
"""
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.api.routes import tenant_theme
|
||||
from backend.models.tenant import TenantAuth, TenantConfig, TenantDefaults
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.tenant_admin_service import TenantValidationError
|
||||
from backend.services.theme_preview_service import PreviewImages, ThemePreviewError
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(tenant_theme.router)
|
||||
|
||||
RANDY = TenantConfig(
|
||||
id="randy-vild",
|
||||
name="Randy Vild",
|
||||
subdomain="randy-vild.nomadkaraoke.com",
|
||||
defaults=TenantDefaults(theme_id="randy-vild", locked_theme="randy-vild"),
|
||||
auth=TenantAuth(allowed_emails=["randyvild@gmail.com"], require_email_domain=True),
|
||||
)
|
||||
INACTIVE = RANDY.model_copy(update={"is_active": False})
|
||||
|
||||
THEME = {"theme_id": "randy-vild", "style_params": {"intro": {}}, "images": ["bg.jpg"], "fonts": ["A.ttf"]}
|
||||
|
||||
|
||||
def _auth(email, tenant_id=None):
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.LIMITED, remaining_uses=0, message="ok",
|
||||
user_email=email, is_admin=email.endswith("@nomadkaraoke.com"), tenant_id=tenant_id,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client_for():
|
||||
def make(email="randyvild@gmail.com", tenant=RANDY, token_tenant=None):
|
||||
app.dependency_overrides[require_auth] = lambda: _auth(email, token_tenant)
|
||||
patcher = patch.object(tenant_theme, "get_tenant_config_from_request", return_value=tenant)
|
||||
patcher.start()
|
||||
make.patchers.append(patcher)
|
||||
return TestClient(app)
|
||||
|
||||
make.patchers = []
|
||||
yield make
|
||||
for p in make.patchers:
|
||||
p.stop()
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_member_can_get_theme(client_for):
|
||||
with patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME):
|
||||
resp = client_for().get("/api/tenant/theme")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["images"] == ["bg.jpg"]
|
||||
|
||||
|
||||
def test_admin_can_edit_any_tenant(client_for):
|
||||
with patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME):
|
||||
assert client_for(email="andrew@nomadkaraoke.com").get("/api/tenant/theme").status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs,status",
|
||||
[
|
||||
({"email": "attacker@gmail.com"}, 403), # spoofed X-Tenant-ID: not on allowlist
|
||||
({"tenant": None}, 404), # not a tenant portal
|
||||
({"tenant": INACTIVE}, 404), # deactivated tenant
|
||||
({"token_tenant": "vocalstar"}, 403), # token scoped to another tenant
|
||||
],
|
||||
)
|
||||
def test_non_members_are_rejected_on_every_endpoint(client_for, kwargs, status):
|
||||
client = client_for(**kwargs)
|
||||
with patch.object(tenant_theme, "get_theme_for_editor") as get_theme, \
|
||||
patch.object(tenant_theme, "save_tenant_theme") as save, \
|
||||
patch.object(tenant_theme, "store_uploaded_asset") as upload, \
|
||||
patch.object(tenant_theme, "render_theme_preview") as render:
|
||||
assert client.get("/api/tenant/theme").status_code == status
|
||||
assert client.put("/api/tenant/theme", json={"style_params": {}}).status_code == status
|
||||
assert client.post("/api/tenant/theme/preview", json={"style_params": {}}).status_code == status
|
||||
assert client.post("/api/tenant/theme/assets", files={"file": ("a.png", b"x")}).status_code == status
|
||||
get_theme.assert_not_called(); save.assert_not_called(); upload.assert_not_called(); render.assert_not_called()
|
||||
|
||||
|
||||
def test_preview_returns_data_urls(client_for):
|
||||
with patch.object(tenant_theme, "prepare_preview_styles", return_value={"intro": {}}), \
|
||||
patch.object(tenant_theme, "render_theme_preview", return_value=PreviewImages(b"t", b"k")) as render:
|
||||
resp = client_for().post(
|
||||
"/api/tenant/theme/preview",
|
||||
json={"style_params": {"intro": {}}, "sample": {"artist": "Randy Vild", "title": "What Goes Up"}},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["title_card"].startswith("data:image/jpeg;base64,")
|
||||
assert render.call_args.kwargs["artist"] == "Randy Vild"
|
||||
|
||||
|
||||
def test_preview_validation_and_render_errors(client_for):
|
||||
client = client_for()
|
||||
with patch.object(tenant_theme, "prepare_preview_styles", side_effect=TenantValidationError("bad path")):
|
||||
resp = client.post("/api/tenant/theme/preview", json={"style_params": {}})
|
||||
assert resp.status_code == 400 and "bad path" in resp.json()["detail"]
|
||||
with patch.object(tenant_theme, "prepare_preview_styles", return_value={}), \
|
||||
patch.object(tenant_theme, "render_theme_preview", side_effect=ThemePreviewError("font missing")):
|
||||
resp = client.post("/api/tenant/theme/preview", json={"style_params": {}})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_save_and_upload(client_for):
|
||||
client = client_for()
|
||||
with patch.object(tenant_theme, "save_tenant_theme") as save, \
|
||||
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME):
|
||||
resp = client.put("/api/tenant/theme", json={"style_params": {"intro": {"title_color": "#ffffff"}}})
|
||||
assert resp.status_code == 200
|
||||
assert save.call_args.args[0].id == "randy-vild"
|
||||
with patch.object(tenant_theme, "save_tenant_theme", side_effect=TenantValidationError("nope")):
|
||||
assert client.put("/api/tenant/theme", json={"style_params": {}}).status_code == 400
|
||||
|
||||
with patch.object(tenant_theme, "store_uploaded_asset", return_value="bg-1234abcd.png") as store:
|
||||
resp = client.post("/api/tenant/theme/assets", files={"file": ("bg.png", b"png-bytes")})
|
||||
assert resp.status_code == 200 and resp.json()["name"] == "bg-1234abcd.png"
|
||||
assert store.call_args.args[1] == "bg.png"
|
||||
assert client.post("/api/tenant/theme/assets", files={"file": ("e.png", b"")}).status_code == 400
|
||||
|
||||
|
||||
def test_error_mapping_and_sample_limits(client_for):
|
||||
from backend.services.tenant_theme_service import ThemeNotEditableError, ThemeNotFoundError
|
||||
|
||||
client = client_for()
|
||||
with patch.object(tenant_theme, "get_theme_for_editor", side_effect=ThemeNotFoundError("gone")):
|
||||
assert client.get("/api/tenant/theme").status_code == 404
|
||||
with patch.object(tenant_theme, "get_theme_for_editor", side_effect=ThemeNotEditableError("shared")):
|
||||
assert client.get("/api/tenant/theme").status_code == 403
|
||||
resp = client.post(
|
||||
"/api/tenant/theme/preview",
|
||||
json={"style_params": {}, "sample": {"lyrics": ["x" * 121]}},
|
||||
)
|
||||
assert resp.status_code == 422 # per-line length capped
|
||||
|
||||
|
||||
def test_oversized_upload_rejected_without_calling_store(client_for, monkeypatch):
|
||||
monkeypatch.setattr(tenant_theme, "MAX_UPLOAD_BYTES", 10)
|
||||
with patch.object(tenant_theme, "store_uploaded_asset") as store:
|
||||
resp = client_for().post("/api/tenant/theme/assets", files={"file": ("big.png", b"x" * 11)})
|
||||
assert resp.status_code == 400 and "too large" in resp.json()["detail"]
|
||||
store.assert_not_called()
|
||||
|
||||
|
||||
def test_timed_out_render_keeps_its_slot_until_it_finishes(client_for, monkeypatch):
|
||||
"""A 504'd render still occupies a worker thread, so its semaphore slot must
|
||||
only be released once it really completes."""
|
||||
import threading
|
||||
import time
|
||||
|
||||
monkeypatch.setattr(tenant_theme, "PREVIEW_TIMEOUT_S", 0.05)
|
||||
finished = threading.Event()
|
||||
|
||||
def slow_render(*a, **k):
|
||||
time.sleep(0.4)
|
||||
finished.set()
|
||||
return PreviewImages(b"t", b"k")
|
||||
|
||||
free_before = tenant_theme._PREVIEW_SEMAPHORE._value
|
||||
# `with` keeps TestClient's event loop alive across the request, like uvicorn's.
|
||||
with patch.object(tenant_theme, "prepare_preview_styles", return_value={}), \
|
||||
patch.object(tenant_theme, "render_theme_preview", side_effect=slow_render), \
|
||||
client_for() as client:
|
||||
resp = client.post("/api/tenant/theme/preview", json={"style_params": {}})
|
||||
assert resp.status_code == 504
|
||||
assert tenant_theme._PREVIEW_SEMAPHORE._value == free_before - 1 # still held
|
||||
assert finished.wait(2)
|
||||
for _ in range(50):
|
||||
if tenant_theme._PREVIEW_SEMAPHORE._value == free_before:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
assert tenant_theme._PREVIEW_SEMAPHORE._value == free_before
|
||||
@@ -0,0 +1,266 @@
|
||||
"""
|
||||
Tenant self-service theme editing: sanitisation of untrusted style_params,
|
||||
content-addressed uploads, and save (font consistency + bundled font copy).
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from backend.models.tenant import TenantAuth, TenantConfig, TenantDefaults
|
||||
from backend.services import tenant_theme_service as tts
|
||||
from backend.services.tenant_admin_service import TenantValidationError
|
||||
|
||||
|
||||
def _config():
|
||||
return TenantConfig(
|
||||
id="randy-vild",
|
||||
name="Randy Vild",
|
||||
subdomain="randy-vild.nomadkaraoke.com",
|
||||
defaults=TenantDefaults(theme_id="randy-vild", locked_theme="randy-vild"),
|
||||
auth=TenantAuth(allowed_emails=["randyvild@gmail.com"], require_email_domain=True),
|
||||
)
|
||||
|
||||
|
||||
def _style(**karaoke):
|
||||
return {
|
||||
"intro": {"font": "AvenirNext-Bold.ttf", "background_image": "bg.jpg", "title_color": "#ffffff"},
|
||||
"karaoke": {"background_image": "bg.jpg", "primary_color": "61, 149, 197, 255", **karaoke},
|
||||
"end": {},
|
||||
"cdg": {},
|
||||
}
|
||||
|
||||
|
||||
ASSETS = ["bg.jpg", "Custom-abc12345.ttf"]
|
||||
|
||||
|
||||
# --- sanitize_style_params ----------------------------------------------------
|
||||
|
||||
|
||||
def test_sanitize_applies_one_font_everywhere_and_fills_ass_keys():
|
||||
styles, font = tts.sanitize_style_params(_style(), available_assets=ASSETS)
|
||||
assert font == "AvenirNext-Bold.ttf"
|
||||
assert styles["karaoke"]["font_path"] == "AvenirNext-Bold.ttf"
|
||||
assert styles["end"]["font"] == "AvenirNext-Bold.ttf"
|
||||
assert styles["cdg"]["font_path"] == "AvenirNext-Bold.ttf"
|
||||
for key in ("underline", "strike_out", "angle", "encoding", "ass_name"):
|
||||
assert key in styles["karaoke"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad",
|
||||
["/etc/passwd", "gs://other-bucket/x.jpg", "../x.jpg", "themes/other/assets/bg.jpg", "C:\\x.jpg"],
|
||||
)
|
||||
def test_sanitize_rejects_paths(bad):
|
||||
style = _style()
|
||||
style["karaoke"]["background_image"] = bad
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
|
||||
|
||||
def test_sanitize_rejects_unuploaded_asset_and_unknown_font():
|
||||
style = _style()
|
||||
style["intro"]["background_image"] = "not-uploaded.jpg"
|
||||
with pytest.raises(TenantValidationError, match="hasn't been uploaded"):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
style = _style()
|
||||
style["intro"]["font"] = "Comic.ttf"
|
||||
with pytest.raises(TenantValidationError, match="isn't available"):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
|
||||
|
||||
def test_sanitize_accepts_uploaded_font():
|
||||
style = _style()
|
||||
style["intro"]["font"] = "Custom-abc12345.ttf"
|
||||
styles, font = tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
assert font == styles["karaoke"]["font_path"] == "Custom-abc12345.ttf"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"section,field,value",
|
||||
[
|
||||
("karaoke", "font_size", 5000),
|
||||
("karaoke", "max_line_length", 2),
|
||||
("karaoke", "top_padding", "lots"),
|
||||
("karaoke", "primary_color", "#ff0000"),
|
||||
("karaoke", "secondary_color", "300, 0, 0, 255"),
|
||||
("intro", "title_color", "red"),
|
||||
("intro", "title_region", "0,0,5000,100"),
|
||||
("intro", "artist_region", "nope"),
|
||||
],
|
||||
)
|
||||
def test_sanitize_rejects_out_of_range_values(section, field, value):
|
||||
style = _style()
|
||||
style[section][field] = value
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
|
||||
|
||||
def test_sanitize_rejects_unknown_sections():
|
||||
style = _style()
|
||||
style["evil"] = {}
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
|
||||
|
||||
# --- uploads + save -------------------------------------------------------------
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self):
|
||||
self.blobs = {
|
||||
"themes/randy-vild/style_params.json": json.dumps(_style()).encode(),
|
||||
"themes/randy-vild/assets/bg.jpg": b"jpg",
|
||||
}
|
||||
|
||||
def list_files(self, prefix):
|
||||
return [p for p in self.blobs if p.startswith(prefix)]
|
||||
|
||||
def file_exists(self, path):
|
||||
return path in self.blobs
|
||||
|
||||
def download_json(self, path):
|
||||
return json.loads(self.blobs[path])
|
||||
|
||||
def download_file(self, path, local):
|
||||
with open(local, "wb") as fh:
|
||||
fh.write(self.blobs[path])
|
||||
|
||||
def upload_fileobj(self, fileobj, path, content_type=None, cache_control=None):
|
||||
self.blobs[path] = fileobj.read()
|
||||
self.last_cache_control = cache_control
|
||||
|
||||
|
||||
def _png_bytes():
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (8, 8), "red").save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_upload_is_content_addressed_and_no_store():
|
||||
storage = FakeStorage()
|
||||
data = _png_bytes()
|
||||
name = tts.store_uploaded_asset(_config(), "My Background.png", data, storage=storage)
|
||||
assert name.startswith("My_Background-") and name.endswith(".png")
|
||||
assert storage.blobs[f"themes/randy-vild/assets/{name}"] == data
|
||||
assert storage.last_cache_control == "no-store"
|
||||
# Same content -> same name (idempotent); different content never overwrites it
|
||||
assert tts.store_uploaded_asset(_config(), "My Background.png", data, storage=storage) == name
|
||||
|
||||
|
||||
def test_upload_rejects_non_images_and_bad_fonts():
|
||||
storage = FakeStorage()
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.store_uploaded_asset(_config(), "evil.png", b"not an image", storage=storage)
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.store_uploaded_asset(_config(), "font.ttf", b"not a font", storage=storage)
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.store_uploaded_asset(_config(), "script.svg", b"<svg/>", storage=storage)
|
||||
|
||||
|
||||
def test_save_copies_bundled_font_sets_family_and_never_touches_config(monkeypatch):
|
||||
storage = FakeStorage()
|
||||
calls = {}
|
||||
|
||||
def fake_update_tenant(tenant_id, **kwargs):
|
||||
calls["tenant_id"] = tenant_id
|
||||
calls.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(tts, "update_tenant", fake_update_tenant)
|
||||
styles = tts.save_tenant_theme(_config(), _style(), storage=storage)
|
||||
|
||||
assert calls["tenant_id"] == "randy-vild"
|
||||
assert "config_updates" not in calls and "logo" not in calls # tenants can't edit their config
|
||||
assert styles["karaoke"]["font"].startswith("Avenir Next") # libass family name
|
||||
assert "AvenirNext-Bold.ttf" in calls["assets"] # bundled font copied into the theme
|
||||
assert calls["style_params"]["karaoke"]["font_path"] == "AvenirNext-Bold.ttf"
|
||||
|
||||
|
||||
def test_get_theme_for_editor_lists_images_and_fonts():
|
||||
storage = FakeStorage()
|
||||
storage.blobs["themes/randy-vild/assets/Custom-abc12345.ttf"] = b"font"
|
||||
data = tts.get_theme_for_editor(_config(), storage=storage)
|
||||
assert data["images"] == ["bg.jpg"]
|
||||
assert "Custom-abc12345.ttf" in data["fonts"] and "AvenirNext-Bold.ttf" in data["fonts"]
|
||||
|
||||
|
||||
# --- review hardening -----------------------------------------------------------
|
||||
|
||||
|
||||
def test_missing_intro_font_cannot_leave_a_path_in_other_sections():
|
||||
"""Regression: with intro.font unset, karaoke.font_path used to survive
|
||||
unsanitised and reach ffmpeg's fontsdir / libass."""
|
||||
style = _style()
|
||||
style["intro"]["font"] = None
|
||||
style["karaoke"]["font_path"] = "/proc/self/environ"
|
||||
style["end"]["font"] = "/etc/passwd"
|
||||
styles, font = tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
assert font == tts.DEFAULT_FONT
|
||||
for section, field in tts.FONT_FIELDS:
|
||||
assert styles[section][field] == tts.DEFAULT_FONT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field,value", [("ass_name", "Nomad\nDialogue: 0"), ("font", "Evil, Font"), ("font", "x" * 81)])
|
||||
def test_ass_text_fields_cannot_inject(field, value):
|
||||
style = _style()
|
||||
style["karaoke"][field] = value
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
|
||||
|
||||
def test_all_renderer_required_karaoke_keys_are_filled():
|
||||
from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE
|
||||
|
||||
styles, _ = tts.sanitize_style_params(_style(), available_assets=ASSETS)
|
||||
for key in tts.REQUIRED_KARAOKE_KEYS:
|
||||
assert styles["karaoke"][key] is not None
|
||||
assert styles["karaoke"]["bold"] == DEFAULT_KARAOKE_STYLE["bold"]
|
||||
|
||||
|
||||
def test_existing_image_is_forced_off():
|
||||
style = _style()
|
||||
style["intro"]["existing_image"] = "bg.jpg"
|
||||
styles, _ = tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
assert styles["intro"]["existing_image"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutate",
|
||||
[
|
||||
lambda s: s["karaoke"].update(singers={"1": {"primary_color": "999, 0, 0, 255"}}),
|
||||
lambda s: s["karaoke"].update(singers=["nope"]),
|
||||
lambda s: s["karaoke"].update(scale_x=5000),
|
||||
lambda s: s["intro"].update(title_region="inf,0,100,100"),
|
||||
],
|
||||
)
|
||||
def test_more_invalid_values_rejected(mutate):
|
||||
style = _style()
|
||||
mutate(style)
|
||||
with pytest.raises(TenantValidationError):
|
||||
tts.sanitize_style_params(style, available_assets=ASSETS)
|
||||
|
||||
|
||||
def test_huge_image_upload_rejected():
|
||||
buf = io.BytesIO()
|
||||
Image.new("1", (9000, 10)).save(buf, "PNG") # tiny file, oversized dimensions
|
||||
with pytest.raises(TenantValidationError, match="too large"):
|
||||
tts.store_uploaded_asset(_config(), "wide.png", buf.getvalue(), storage=FakeStorage())
|
||||
|
||||
|
||||
def test_shared_theme_is_not_editable():
|
||||
shared = _config().model_copy(update={"defaults": TenantDefaults(theme_id="nomad", locked_theme="nomad")})
|
||||
with pytest.raises(tts.ThemeNotEditableError):
|
||||
tts.get_theme_for_editor(shared, storage=FakeStorage())
|
||||
with pytest.raises(tts.ThemeNotEditableError):
|
||||
tts.save_tenant_theme(shared, _style(), storage=FakeStorage())
|
||||
with pytest.raises(tts.ThemeNotEditableError):
|
||||
tts.store_uploaded_asset(shared, "a.png", _png_bytes(), storage=FakeStorage())
|
||||
|
||||
|
||||
def test_missing_theme_file_is_not_found():
|
||||
storage = FakeStorage()
|
||||
del storage.blobs["themes/randy-vild/style_params.json"]
|
||||
storage.download_json = lambda path: (_ for _ in ()).throw(FileNotFoundError(path))
|
||||
with pytest.raises(tts.ThemeNotFoundError):
|
||||
tts.get_theme_for_editor(_config(), storage=storage)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
Real renders of the tenant theme preview (title card + karaoke frame).
|
||||
|
||||
Uses the production renderers end-to-end with a colour-background theme and a
|
||||
bundled font; storage is faked in-memory. Skipped without ffmpeg (CI installs it).
|
||||
"""
|
||||
import io
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from backend.services import theme_preview_service as tps
|
||||
|
||||
pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed")
|
||||
|
||||
|
||||
def _theme(sung="255, 0, 0, 255", bg="#102030"):
|
||||
return {
|
||||
"intro": {
|
||||
"background_color": bg,
|
||||
"background_image": None,
|
||||
"font": "AvenirNext-Bold.ttf",
|
||||
"title_color": "#ffffff",
|
||||
"artist_color": "#ffdf6b",
|
||||
"title_region": "370,980,3100,350",
|
||||
"artist_region": "370,1400,3100,450",
|
||||
},
|
||||
"karaoke": {
|
||||
"background_color": bg,
|
||||
"background_image": None,
|
||||
"font_path": "AvenirNext-Bold.ttf",
|
||||
"font": "Avenir Next Bold",
|
||||
"ass_name": "Nomad",
|
||||
"primary_color": sung,
|
||||
"secondary_color": "255, 255, 255, 255",
|
||||
"outline_color": "0, 0, 0, 255",
|
||||
"back_color": "0, 0, 0, 0",
|
||||
"bold": False, "italic": False, "scale_x": 100, "scale_y": 100, "spacing": 0,
|
||||
"border_style": 1, "outline": 1, "shadow": 0, "margin_l": 0, "margin_r": 0, "margin_v": 0,
|
||||
},
|
||||
"end": {},
|
||||
"cdg": {},
|
||||
}
|
||||
|
||||
|
||||
class _NoGcsAssets:
|
||||
"""Storage whose theme has no uploaded assets (font resolves to bundled)."""
|
||||
|
||||
class _Bucket:
|
||||
def get_blob(self, path):
|
||||
return None
|
||||
|
||||
bucket = _Bucket()
|
||||
|
||||
|
||||
def _img(data: bytes) -> Image.Image:
|
||||
return Image.open(io.BytesIO(data)).convert("RGB")
|
||||
|
||||
|
||||
def test_renders_title_card_and_karaoke_frame():
|
||||
tps._CACHE.clear()
|
||||
result = tps.render_theme_preview("t1", _theme(), artist="Randy Vild", title="What Goes Up", storage=_NoGcsAssets())
|
||||
title, karaoke = _img(result.title_card), _img(result.karaoke_frame)
|
||||
assert title.size == (1280, 720)
|
||||
assert karaoke.size == (1280, 720)
|
||||
# The theme's solid #102030 background is what's in the corners of both frames
|
||||
for frame in (title, karaoke):
|
||||
r, g, b = frame.getpixel((8, 8))
|
||||
assert abs(r - 0x10) <= 6 and abs(g - 0x20) <= 6 and abs(b - 0x30) <= 6
|
||||
urls = result.as_data_urls()
|
||||
assert urls["title_card"].startswith("data:image/jpeg;base64,")
|
||||
|
||||
|
||||
def test_sung_colour_is_what_changes_in_the_karaoke_frame():
|
||||
"""The frame shows a part-sung line, so changing only the sung colour must
|
||||
change the karaoke frame (and not the title card)."""
|
||||
tps._CACHE.clear()
|
||||
red = tps.render_theme_preview("t1", _theme(sung="255, 0, 0, 255"), storage=_NoGcsAssets())
|
||||
green = tps.render_theme_preview("t1", _theme(sung="0, 255, 0, 255"), storage=_NoGcsAssets())
|
||||
assert red.title_card == green.title_card
|
||||
assert red.karaoke_frame != green.karaoke_frame
|
||||
reds = sum(1 for r, g, b in _img(red.karaoke_frame).getdata() if r > 200 and g < 60 and b < 60)
|
||||
greens = sum(1 for r, g, b in _img(green.karaoke_frame).getdata() if g > 200 and r < 60 and b < 60)
|
||||
assert reds > 200 and greens > 200
|
||||
|
||||
|
||||
def test_identical_drafts_are_cached():
|
||||
tps._CACHE.clear()
|
||||
a = tps.render_theme_preview("t1", _theme(), storage=_NoGcsAssets())
|
||||
b = tps.render_theme_preview("t1", _theme(), storage=_NoGcsAssets())
|
||||
assert a is b
|
||||
|
||||
|
||||
def test_missing_background_asset_is_a_preview_error():
|
||||
theme = _theme()
|
||||
theme["karaoke"]["background_image"] = "missing.jpg"
|
||||
with pytest.raises(tps.ThemePreviewError, match="missing.jpg"):
|
||||
tps.resolve_assets(theme, "t1", storage=_NoGcsAssets())
|
||||
|
||||
|
||||
def test_font_family_name_from_bundled_font():
|
||||
import os
|
||||
|
||||
name = tps.font_family_name(os.path.join(tps.BUNDLED_FONTS_DIR, "AvenirNext-Bold.ttf"))
|
||||
assert name.startswith("Avenir Next")
|
||||
|
||||
|
||||
def test_evict_keeps_cache_under_limit(tmp_path):
|
||||
import os
|
||||
import time
|
||||
|
||||
for i in range(5):
|
||||
p = tmp_path / f"f{i}"
|
||||
p.write_bytes(b"x" * 100)
|
||||
os.utime(p, (time.time() - 100 + i, time.time()))
|
||||
tps._evict(str(tmp_path), 250, keep=str(tmp_path / "f0"))
|
||||
remaining = sorted(p.name for p in tmp_path.iterdir())
|
||||
assert sum((tmp_path / n).stat().st_size for n in remaining) <= 250
|
||||
assert "f0" in remaining # the file just written is never evicted
|
||||
|
||||
|
||||
def test_failed_download_leaves_no_partial_cache_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(tps, "ASSET_CACHE_ROOT", str(tmp_path))
|
||||
|
||||
class Blob:
|
||||
generation = 7
|
||||
|
||||
def download_to_filename(self, path):
|
||||
open(path, "wb").write(b"partial")
|
||||
raise IOError("network died")
|
||||
|
||||
class Storage:
|
||||
class bucket:
|
||||
@staticmethod
|
||||
def get_blob(path):
|
||||
return Blob()
|
||||
|
||||
with pytest.raises(IOError):
|
||||
tps._local_theme_asset(Storage, "t1", "bg.jpg")
|
||||
assert not any(f.is_file() for f in tmp_path.rglob("*"))
|
||||
@@ -0,0 +1,343 @@
|
||||
"""
|
||||
Tests for re-rendering a finished tenant track with the tenant's current theme.
|
||||
|
||||
Covers validation, the service (theme re-snapshot, atomic claim, artifact
|
||||
cleanup, screens-worker trigger + rollback), the POST /api/jobs/{id}/rerender
|
||||
route (ownership, tenant allowlist), and the encoding-worker id keying that
|
||||
stops a re-run from getting the previous run's cached render/encode back.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderConflictError,
|
||||
RerenderError,
|
||||
ThemeRerenderService,
|
||||
validate_rerender,
|
||||
)
|
||||
from backend.workers.supersede import encoding_worker_job_id
|
||||
|
||||
|
||||
def _job(**overrides):
|
||||
fields = dict(
|
||||
job_id="job123",
|
||||
status="complete",
|
||||
tenant_id="randy-vild",
|
||||
user_email="randy@example.com",
|
||||
theme_id="randy-vild",
|
||||
color_overrides={},
|
||||
outputs_deleted_at=None,
|
||||
prep_only=False,
|
||||
finalise_only=False,
|
||||
state_data={"instrumental_selection": "custom"},
|
||||
file_urls={"lyrics": {"corrections": "jobs/job123/lyrics/corrections.json"}},
|
||||
)
|
||||
fields.update(overrides)
|
||||
return SimpleNamespace(**fields)
|
||||
|
||||
|
||||
class TestValidateRerender:
|
||||
def test_valid_tenant_job(self):
|
||||
assert validate_rerender(_job()) is None
|
||||
|
||||
@pytest.mark.parametrize("overrides, fragment", [
|
||||
({"tenant_id": None}, "portal tracks"),
|
||||
({"status": "rendering_video"}, "Only finished tracks"),
|
||||
({"outputs_deleted_at": "2026-09-29T18:47:13Z"}, "outputs were deleted"),
|
||||
({"theme_id": None}, "wasn't made from a theme"),
|
||||
({"prep_only": True}, "can't be re-rendered"),
|
||||
({"state_data": {}}, "instrumental selection"),
|
||||
({"file_urls": {}}, "reviewed lyrics"),
|
||||
({"state_data": {"instrumental_selection": "clean", "dropbox_link": "https://db"}}, "published"),
|
||||
({"state_data": {"instrumental_selection": "clean", "youtube_url": "https://yt"}}, "published"),
|
||||
])
|
||||
def test_rejections(self, overrides, fragment):
|
||||
assert fragment in validate_rerender(_job(**overrides))
|
||||
|
||||
|
||||
def _service(claim_status="complete", trigger_ok=True):
|
||||
"""ThemeRerenderService wired to a fake Firestore transaction + storage."""
|
||||
job_manager = MagicMock()
|
||||
doc_ref = MagicMock()
|
||||
snapshot = MagicMock(exists=True)
|
||||
snapshot.to_dict.return_value = {"status": claim_status}
|
||||
doc_ref.get.return_value = snapshot
|
||||
job_manager.firestore.db.collection.return_value.document.return_value = doc_ref
|
||||
storage = MagicMock()
|
||||
worker_service = MagicMock()
|
||||
worker_service.trigger_screens_worker = AsyncMock(return_value=trigger_ok)
|
||||
return ThemeRerenderService(job_manager=job_manager, storage=storage), doc_ref, storage, worker_service
|
||||
|
||||
|
||||
def _passthrough_transactional(fn):
|
||||
return fn
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patched_deps():
|
||||
prepare = MagicMock(return_value=(
|
||||
"jobs/job123/style/style_params.json",
|
||||
{"karaoke_background": "themes/randy-vild/assets/bg-new.jpg"},
|
||||
None,
|
||||
))
|
||||
with patch("backend.api.routes.file_upload._prepare_theme_for_job", prepare), \
|
||||
patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional):
|
||||
yield prepare
|
||||
|
||||
|
||||
class TestThemeRerenderService:
|
||||
@pytest.mark.asyncio
|
||||
async def test_resnapshots_theme_claims_and_triggers_screens(self, patched_deps):
|
||||
service, doc_ref, storage, worker_service = _service()
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="randy@example.com")
|
||||
|
||||
patched_deps.assert_called_once_with("job123", "randy-vild", None)
|
||||
transaction.update.assert_called_once()
|
||||
update = transaction.update.call_args.args[1]
|
||||
assert update["status"] == "lyrics_complete"
|
||||
assert update["state_data.regen_restore_status"] == "review_complete"
|
||||
assert update["style_params_gcs_path"] == "jobs/job123/style/style_params.json"
|
||||
assert update["style_assets"] == {"karaoke_background": "themes/randy-vild/assets/bg-new.jpg"}
|
||||
assert update["theme_id"] == "randy-vild"
|
||||
for key in ("screens_progress", "render_progress", "video_progress", "encoding_progress"):
|
||||
assert update[f"state_data.{key}"] is DELETE_FIELD
|
||||
assert update["file_urls.screens"] is DELETE_FIELD
|
||||
assert update["file_urls.videos.with_vocals"] is DELETE_FIELD
|
||||
|
||||
deleted = {c.args[0] for c in storage.delete_file.call_args_list}
|
||||
assert "jobs/job123/screens/title.mov" in deleted
|
||||
assert "jobs/job123/screens/end.png" in deleted
|
||||
assert "jobs/job123/videos/with_vocals.mkv" in deleted
|
||||
assert all(c.kwargs.get("ignore_missing") for c in storage.delete_file.call_args_list)
|
||||
|
||||
worker_service.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_passes_color_overrides(self, patched_deps):
|
||||
service, _, _, worker_service = _service()
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(_job(color_overrides={"sung": "#fff"}), theme_id="t", requested_by="x")
|
||||
patched_deps.assert_called_once_with("job123", "t", {"sung": "#fff"})
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conflict_when_job_no_longer_complete(self, patched_deps):
|
||||
"""A double-click: the second claim sees the job already re-rendering."""
|
||||
service, _, storage, worker_service = _service(claim_status="lyrics_complete")
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
with pytest.raises(RerenderConflictError):
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="x")
|
||||
|
||||
transaction.update.assert_not_called()
|
||||
storage.delete_file.assert_not_called()
|
||||
worker_service.trigger_screens_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restores_complete_when_trigger_fails(self, patched_deps):
|
||||
service, _, _, worker_service = _service(trigger_ok=False)
|
||||
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
with pytest.raises(RerenderError) as exc:
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="x")
|
||||
|
||||
assert exc.value.status_code == 503
|
||||
restore = service.job_manager.update_job.call_args.args[1]
|
||||
assert restore["status"] == "complete"
|
||||
assert restore["state_data.regen_restore_status"] is DELETE_FIELD
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_job_rejected_before_any_work(self, patched_deps):
|
||||
service, _, storage, _ = _service()
|
||||
with pytest.raises(RerenderError):
|
||||
await service.start(_job(tenant_id=None), theme_id="t", requested_by="x")
|
||||
patched_deps.assert_not_called()
|
||||
storage.delete_file.assert_not_called()
|
||||
|
||||
|
||||
class TestRerenderReviewFixes:
|
||||
@pytest.mark.asyncio
|
||||
async def test_deletes_old_title_end_movs_from_finals(self, patched_deps):
|
||||
"""The encoder globs **/*Title*.mov — an old finals MOV would be spliced in."""
|
||||
service, _, storage, worker_service = _service()
|
||||
storage.list_files.return_value = [
|
||||
"jobs/job123/finals/Randy Vild - What Goes Up (Title).mov",
|
||||
"jobs/job123/finals/Randy Vild - What Goes Up (End).mov",
|
||||
"jobs/job123/finals/title_mov.mov",
|
||||
"jobs/job123/finals/end_mov.mov",
|
||||
"jobs/job123/finals/lossy_4k_mp4.mp4",
|
||||
"jobs/job123/finals/lossless_4k_mkv.mkv",
|
||||
]
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(_job(), theme_id="randy-vild", requested_by="x")
|
||||
|
||||
storage.list_files.assert_called_once_with("jobs/job123/finals/")
|
||||
deleted = {c.args[0] for c in storage.delete_file.call_args_list}
|
||||
assert "jobs/job123/finals/Randy Vild - What Goes Up (Title).mov" in deleted
|
||||
assert "jobs/job123/finals/Randy Vild - What Goes Up (End).mov" in deleted
|
||||
assert "jobs/job123/finals/title_mov.mov" in deleted
|
||||
assert "jobs/job123/finals/end_mov.mov" in deleted
|
||||
assert "jobs/job123/finals/lossy_4k_mp4.mp4" not in deleted
|
||||
assert "jobs/job123/finals/lossless_4k_mkv.mkv" not in deleted
|
||||
|
||||
def test_failed_rerender_is_rerenderable(self):
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "custom",
|
||||
"theme_rerender": {"theme_id": "randy-vild"}})
|
||||
assert validate_rerender(job) is None
|
||||
|
||||
def test_failed_ordinary_job_is_not_rerenderable(self):
|
||||
assert "Only finished tracks" in validate_rerender(_job(status="failed"))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_claims_failed_rerender(self, patched_deps):
|
||||
service, _, _, worker_service = _service(claim_status="failed")
|
||||
transaction = service.job_manager.firestore.db.transaction.return_value
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "custom",
|
||||
"theme_rerender": {"theme_id": "randy-vild"}})
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
|
||||
await service.start(job, theme_id="randy-vild", requested_by="x")
|
||||
transaction.update.assert_called_once()
|
||||
assert transaction.update.call_args.args[1]["error_message"] is None
|
||||
worker_service.trigger_screens_worker.assert_awaited_once_with("job123")
|
||||
|
||||
|
||||
class TestEncodingWorkerJobId:
|
||||
def test_generation_zero_keeps_plain_job_id(self):
|
||||
assert encoding_worker_job_id("job123", 0) == "job123"
|
||||
|
||||
def test_generation_suffixes_job_id(self):
|
||||
assert encoding_worker_job_id("job123", 3) == "job123_g3"
|
||||
|
||||
def test_orchestrator_config_captures_generation(self):
|
||||
from backend.workers.video_worker_orchestrator import create_orchestrator_config_from_job
|
||||
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist = "A"
|
||||
job.title = "T"
|
||||
job.state_data = {"worker_generation": 4, "instrumental_selection": "clean"}
|
||||
job.file_urls = {}
|
||||
config = create_orchestrator_config_from_job(job, temp_dir="/tmp/x")
|
||||
assert config.worker_generation == 4
|
||||
|
||||
|
||||
# --- Route ---------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
from backend.main import app
|
||||
yield TestClient(app), app
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def _auth(email="randy@example.com", is_admin=False):
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN if is_admin else UserType.UNLIMITED,
|
||||
remaining_uses=-1,
|
||||
message="Valid",
|
||||
user_email=email,
|
||||
is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def _call(client, auth, job, tenant, start=None):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
async def override():
|
||||
return auth
|
||||
|
||||
app.dependency_overrides[require_auth] = override
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
tenant_service = MagicMock()
|
||||
tenant_service.get_tenant_config.return_value = tenant
|
||||
start = start or AsyncMock()
|
||||
with patch("backend.api.routes.jobs.JobManager", return_value=job_manager), \
|
||||
patch("backend.services.tenant_service.get_tenant_service", return_value=tenant_service), \
|
||||
patch.object(ThemeRerenderService, "start", start):
|
||||
return test_client.post(f"/api/jobs/{job.job_id}/rerender"), start
|
||||
|
||||
|
||||
def _tenant(allowed=True, active=True):
|
||||
tenant = MagicMock()
|
||||
tenant.is_active = active
|
||||
tenant.is_email_allowed.return_value = allowed
|
||||
tenant.defaults.locked_theme = "randy-vild"
|
||||
tenant.defaults.theme_id = None
|
||||
tenant.id = "randy-vild"
|
||||
return tenant
|
||||
|
||||
|
||||
class TestRerenderRoute:
|
||||
def test_owner_starts_rerender_with_tenant_theme(self, client):
|
||||
job = _job()
|
||||
resp, start = _call(client, _auth(), job, _tenant())
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["theme_id"] == "randy-vild"
|
||||
start.assert_awaited_once()
|
||||
assert start.await_args.kwargs["theme_id"] == "randy-vild"
|
||||
assert start.await_args.kwargs["requested_by"] == "randy@example.com"
|
||||
|
||||
def test_non_owner_forbidden(self, client):
|
||||
resp, start = _call(client, _auth(email="someone@else.com"), _job(), _tenant())
|
||||
assert resp.status_code == 403
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_owner_removed_from_allowlist_forbidden(self, client):
|
||||
resp, start = _call(client, _auth(), _job(), _tenant(allowed=False))
|
||||
assert resp.status_code == 403
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_admin_allowed_on_any_job(self, client):
|
||||
resp, start = _call(client, _auth(email="admin@nomadkaraoke.com", is_admin=True), _job(), _tenant(allowed=False))
|
||||
assert resp.status_code == 200
|
||||
start.assert_awaited_once()
|
||||
|
||||
def test_consumer_job_rejected(self, client):
|
||||
resp, start = _call(client, _auth(), _job(tenant_id=None), _tenant())
|
||||
assert resp.status_code == 400
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_inactive_tenant_rejected(self, client):
|
||||
resp, start = _call(client, _auth(), _job(), _tenant(active=False))
|
||||
assert resp.status_code == 400
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_conflict_maps_to_409(self, client):
|
||||
start = AsyncMock(side_effect=RerenderConflictError("already"))
|
||||
resp, _ = _call(client, _auth(), _job(), _tenant(), start=start)
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
class TestRetryAfterFailedRerender:
|
||||
def test_retry_reruns_rerender_when_screens_missing(self, client):
|
||||
test_client, app = client
|
||||
from backend.api.dependencies import require_auth
|
||||
|
||||
async def override():
|
||||
return _auth()
|
||||
|
||||
app.dependency_overrides[require_auth] = override
|
||||
job = _job(status="failed", state_data={"instrumental_selection": "custom",
|
||||
"theme_rerender": {"theme_id": "randy-vild"}})
|
||||
job.error_details = {"stage": "screens"}
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
start = AsyncMock()
|
||||
with patch("backend.api.routes.jobs.job_manager", job_manager), \
|
||||
patch("backend.api.routes.jobs.JobManager", return_value=job_manager), \
|
||||
patch.object(ThemeRerenderService, "start", start):
|
||||
resp = test_client.post("/api/jobs/job123/retry")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["retry_stage"] == "theme_rerender"
|
||||
assert start.await_args.kwargs["theme_id"] == "randy-vild"
|
||||
@@ -767,6 +767,40 @@ class TestVideoWorkerOrchestratorEncoding:
|
||||
assert orchestrator.result.final_video_720p == "/output/720p.mp4"
|
||||
assert orchestrator.result.encoding_time_seconds == 120.5
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("recorded, expected_src, expected_dest", [
|
||||
# Conformed (lined-up) copy recorded on the job wins over the raw upload.
|
||||
("uploads/test-job/conformed/existing_instrumental.flac",
|
||||
"uploads/test-job/conformed/existing_instrumental.flac", "jobs/test-job/custom_instrumental.flac"),
|
||||
# Legacy jobs without a recorded path still find the upload by prefix.
|
||||
(None, "uploads/test-job/audio/existing_instrumental.wav", "jobs/test-job/custom_instrumental.wav"),
|
||||
])
|
||||
async def test_gce_stages_recorded_instrumental(self, recorded, expected_src, expected_dest):
|
||||
from backend.services.encoding_interface import EncodingOutput
|
||||
|
||||
config = OrchestratorConfig(
|
||||
job_id="test-job", artist="A", title="T",
|
||||
title_video_path="/t.mov", karaoke_video_path="/k.mov",
|
||||
instrumental_audio_path="/a.flac", output_dir="/out",
|
||||
existing_instrumental_gcs_path=recorded,
|
||||
)
|
||||
storage = MagicMock()
|
||||
storage.list_files.return_value = ["uploads/test-job/audio/existing_instrumental.wav"]
|
||||
orchestrator = VideoWorkerOrchestrator(config, storage=storage)
|
||||
backend = MagicMock()
|
||||
backend.name = "gce"
|
||||
backend.encode = AsyncMock(return_value=EncodingOutput(
|
||||
success=True, lossless_4k_mp4_path="/out/l.mp4", lossy_4k_mp4_path="/out/y.mp4",
|
||||
lossy_720p_mp4_path="/out/7.mp4", lossless_mkv_path="/out/l.mkv",
|
||||
encoding_time_seconds=1.0, encoding_backend="gce",
|
||||
))
|
||||
with patch.object(orchestrator, "_get_encoding_backend", return_value=backend):
|
||||
try:
|
||||
await orchestrator._run_encoding()
|
||||
except Exception:
|
||||
pass # later GCS result handling isn't under test here
|
||||
storage.copy_blob.assert_any_call(expected_src, expected_dest)
|
||||
|
||||
def test_encoding_input_gcs_paths_pattern(self):
|
||||
"""Test that EncodingInput.options contains proper GCS paths structure.
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
Regression: a successful render must clear ``outputs_deleted_at``.
|
||||
|
||||
The edit flow (and admin "delete outputs") sets ``outputs_deleted_at``; the
|
||||
frontend hides every download while it is set. The flag used to be cleared only
|
||||
when the orchestrator uploaded to YouTube/Dropbox/GDrive, so an edited tenant job
|
||||
(which never distributes anywhere) re-rendered fresh finals but kept showing no
|
||||
download buttons forever (job 2579a1ea, randy-vild, 2026-09-29).
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.workers import video_worker
|
||||
|
||||
|
||||
def _orchestrator_result(**overrides):
|
||||
fields = dict(
|
||||
success=True,
|
||||
error_message=None,
|
||||
brand_code=None,
|
||||
youtube_url=None,
|
||||
youtube_upload_queued=False,
|
||||
dropbox_link=None,
|
||||
gdrive_files={},
|
||||
distribution_warnings=[],
|
||||
final_video=None,
|
||||
final_video_mkv=None,
|
||||
final_video_lossy=None,
|
||||
final_video_720p=None,
|
||||
final_with_vocals_mp4=None,
|
||||
final_karaoke_cdg_zip=None,
|
||||
final_karaoke_txt_zip=None,
|
||||
title_mov=None,
|
||||
end_mov=None,
|
||||
portrait_video=None,
|
||||
)
|
||||
fields.update(overrides)
|
||||
return SimpleNamespace(**fields)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_render_clears_outputs_deleted_without_distribution():
|
||||
job = MagicMock()
|
||||
job.job_id = "job123"
|
||||
job.artist = "Randy Vild"
|
||||
job.title = "What Goes Up"
|
||||
job.tenant_id = "randy-vild"
|
||||
job.enable_youtube_upload = False
|
||||
job.is_private = False
|
||||
job.organised_dir_rclone_root = None
|
||||
job.edit_count = 1
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
orchestrator = MagicMock()
|
||||
orchestrator.run = AsyncMock(return_value=_orchestrator_result())
|
||||
|
||||
style_config = MagicMock()
|
||||
style_config.get_cdg_styles.return_value = None
|
||||
|
||||
with patch.object(video_worker, "JobManager", return_value=job_manager), \
|
||||
patch.object(video_worker, "StorageService", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "create_job_logger", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "setup_job_logging", return_value=MagicMock()), \
|
||||
patch.object(video_worker, "_validate_prerequisites", return_value=True), \
|
||||
patch("backend.services.job_health_service.validate_worker_can_run", return_value=None), \
|
||||
patch.object(video_worker, "_setup_working_directory", new=AsyncMock()), \
|
||||
patch.object(video_worker, "load_style_config", new=AsyncMock(return_value=style_config)), \
|
||||
patch("backend.workers.video_worker_orchestrator.create_orchestrator_config_from_job", return_value=MagicMock()), \
|
||||
patch("backend.workers.video_worker_orchestrator.VideoWorkerOrchestrator", return_value=orchestrator), \
|
||||
patch.object(video_worker, "_handle_native_distribution", new=AsyncMock()), \
|
||||
patch.object(video_worker, "_upload_results", new=AsyncMock()), \
|
||||
patch.object(video_worker, "_store_video_processing_metadata"):
|
||||
ok = await video_worker.generate_video_orchestrated("job123")
|
||||
|
||||
assert ok is True
|
||||
payloads = [c.args[1] for c in job_manager.update_job.call_args_list]
|
||||
cleared = [p for p in payloads if "outputs_deleted_at" in p]
|
||||
assert cleared, f"no update cleared outputs_deleted_at; updates were {payloads}"
|
||||
assert cleared[0]["outputs_deleted_at"] is None
|
||||
assert cleared[0]["outputs_deleted_by"] is None
|
||||
@@ -0,0 +1,89 @@
|
||||
"""audio-download-job gets a per-execution timeout sized to the torrent stall budget.
|
||||
|
||||
The worker waits up to ``torrent_wait_timeout_seconds(keep_trying)`` for flacfetch;
|
||||
the Cloud Run execution timeout override (``task_timeout_seconds``) must exceed it
|
||||
so the worker fails gracefully instead of being SIGKILLed. A user's "Keep trying"
|
||||
retry needs the longer (1 hour stall) budget.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import audio_download_limits
|
||||
|
||||
|
||||
def _settings(monkeypatch):
|
||||
monkeypatch.setenv("ENABLE_CLOUD_TASKS", "true")
|
||||
monkeypatch.setenv("GCP_REGION", "us-central1")
|
||||
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "test-project")
|
||||
monkeypatch.delenv("CPU_JOBS_REGION", raising=False)
|
||||
from backend.config import Settings
|
||||
return Settings()
|
||||
|
||||
|
||||
async def _trigger(monkeypatch, **kwargs) -> MagicMock:
|
||||
"""Trigger the audio download worker against a mocked run_v2; return the mock."""
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
mock_run_v2 = MagicMock()
|
||||
mock_run_v2.JobsClient.return_value.run_job.return_value = MagicMock(metadata="m")
|
||||
|
||||
import google.cloud
|
||||
with patch("backend.services.worker_service.get_settings", return_value=_settings(monkeypatch)), \
|
||||
patch.dict("sys.modules", {"google.cloud.run_v2": mock_run_v2}), \
|
||||
patch.object(google.cloud, "run_v2", mock_run_v2, create=True):
|
||||
assert await WorkerService().trigger_audio_download_worker("job1", **kwargs) is True
|
||||
return mock_run_v2
|
||||
|
||||
|
||||
def _timeout_seconds(mock_run_v2: MagicMock) -> int:
|
||||
overrides = mock_run_v2.RunJobRequest.call_args.kwargs["overrides"]
|
||||
return overrides.timeout.seconds
|
||||
|
||||
|
||||
def _container_args(mock_run_v2: MagicMock) -> list[str]:
|
||||
return mock_run_v2.RunJobRequest.Overrides.ContainerOverride.call_args.kwargs["args"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_timeout_override(monkeypatch) -> None:
|
||||
mock_run_v2 = await _trigger(monkeypatch)
|
||||
assert _timeout_seconds(mock_run_v2) == audio_download_limits.task_timeout_seconds(False)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_keep_trying_timeout_override(monkeypatch) -> None:
|
||||
mock_run_v2 = await _trigger(monkeypatch, keep_trying=True)
|
||||
assert _timeout_seconds(mock_run_v2) == audio_download_limits.task_timeout_seconds(True)
|
||||
assert _timeout_seconds(mock_run_v2) > audio_download_limits.task_timeout_seconds(False)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("keep_trying", [False, True])
|
||||
async def test_container_args_still_set(monkeypatch, keep_trying) -> None:
|
||||
mock_run_v2 = await _trigger(monkeypatch, keep_trying=keep_trying)
|
||||
assert _container_args(mock_run_v2) == [
|
||||
"python", "-m", "backend.workers.audio_download_worker", "--job-id", "job1",
|
||||
]
|
||||
assert mock_run_v2.RunJobRequest.call_args.kwargs["name"].endswith("/jobs/audio-download-job")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_other_jobs_get_no_timeout_override(monkeypatch) -> None:
|
||||
"""Only audio-download-job overrides the timeout; other jobs keep their configured one."""
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
mock_run_v2 = MagicMock()
|
||||
mock_run_v2.JobsClient.return_value.run_job.return_value = MagicMock(metadata="m")
|
||||
overrides = MagicMock(spec=["container_overrides"])
|
||||
mock_run_v2.RunJobRequest.Overrides.return_value = overrides
|
||||
|
||||
import google.cloud
|
||||
with patch("backend.services.worker_service.get_settings", return_value=_settings(monkeypatch)), \
|
||||
patch.dict("sys.modules", {"google.cloud.run_v2": mock_run_v2}), \
|
||||
patch.object(google.cloud, "run_v2", mock_run_v2, create=True):
|
||||
assert await WorkerService().trigger_lyrics_worker("job1") is True
|
||||
|
||||
assert "timeout" not in vars(overrides)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Latency-critical CPU Cloud Run Jobs are triggered in cpu_jobs_region (us-east4).
|
||||
|
||||
Cloud Run Jobs in us-central1 queue 2-5 min before the container starts, even for
|
||||
a tiny sample image (measured 2026-09-28: us-central1 4-5 min, us-east4 8-19s).
|
||||
audio-download-job, lyrics-transcription-job, bulk-search-job and
|
||||
video-encoding-job (video + post-review render workers) therefore run in us-east4,
|
||||
while the jobs and workers keep GCP_REGION=us-central1 for everything else.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _settings(monkeypatch, cpu_jobs_region: str | None = None):
|
||||
monkeypatch.setenv("ENABLE_CLOUD_TASKS", "true")
|
||||
monkeypatch.setenv("GCP_REGION", "us-central1")
|
||||
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "test-project")
|
||||
if cpu_jobs_region is None:
|
||||
monkeypatch.delenv("CPU_JOBS_REGION", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("CPU_JOBS_REGION", cpu_jobs_region)
|
||||
from backend.config import Settings
|
||||
return Settings()
|
||||
|
||||
|
||||
async def _triggered_job_name(settings, trigger) -> str:
|
||||
"""Run ``trigger(service)`` against a mocked run_v2 and return the job path."""
|
||||
from backend.services.worker_service import WorkerService
|
||||
|
||||
mock_run_v2 = MagicMock()
|
||||
mock_run_v2.JobsClient.return_value.run_job.return_value = MagicMock(metadata="m")
|
||||
|
||||
import google.cloud
|
||||
with patch("backend.services.worker_service.get_settings", return_value=settings), \
|
||||
patch.dict("sys.modules", {"google.cloud.run_v2": mock_run_v2}), \
|
||||
patch.object(google.cloud, "run_v2", mock_run_v2, create=True):
|
||||
assert await trigger(WorkerService()) is True
|
||||
|
||||
return mock_run_v2.RunJobRequest.call_args.kwargs["name"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"trigger, job",
|
||||
[
|
||||
(lambda s: s.trigger_audio_download_worker("job1"), "audio-download-job"),
|
||||
(lambda s: s.trigger_lyrics_worker("job1"), "lyrics-transcription-job"),
|
||||
(lambda s: s.trigger_bulk_search_worker("batch1"), "bulk-search-job"),
|
||||
],
|
||||
)
|
||||
async def test_cpu_jobs_triggered_in_us_east4(monkeypatch, trigger, job) -> None:
|
||||
name = await _triggered_job_name(_settings(monkeypatch), trigger)
|
||||
assert name == f"projects/test-project/locations/us-east4/jobs/{job}"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cpu_jobs_region_env_override_for_rollback(monkeypatch) -> None:
|
||||
settings = _settings(monkeypatch, cpu_jobs_region="us-central1")
|
||||
name = await _triggered_job_name(settings, lambda s: s.trigger_audio_download_worker("job1"))
|
||||
assert name == "projects/test-project/locations/us-central1/jobs/audio-download-job"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_encoding_job_triggered_in_us_east4(monkeypatch) -> None:
|
||||
name = await _triggered_job_name(_settings(monkeypatch), lambda s: s._trigger_cloud_run_job("job1"))
|
||||
assert name == "projects/test-project/locations/us-east4/jobs/video-encoding-job"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_render_video_job_triggered_in_us_east4(monkeypatch) -> None:
|
||||
monkeypatch.setenv("USE_CLOUD_RUN_JOBS_FOR_RENDER", "true")
|
||||
settings = _settings(monkeypatch)
|
||||
|
||||
async def trigger(service):
|
||||
with patch.object(service, "_bump_worker_generation"), \
|
||||
patch.object(service, "_start_encoding_worker_warmup"):
|
||||
return await service.trigger_render_video_worker("job1")
|
||||
|
||||
name = await _triggered_job_name(settings, trigger)
|
||||
assert name == "projects/test-project/locations/us-east4/jobs/video-encoding-job"
|
||||
|
||||
|
||||
def test_gcp_region_unaffected_by_cpu_jobs_region(monkeypatch) -> None:
|
||||
settings = _settings(monkeypatch)
|
||||
assert settings.cpu_jobs_region == "us-east4"
|
||||
assert settings.gcp_region == "us-central1"
|
||||
|
||||
|
||||
def test_backend_default_matches_pulumi_cpu_jobs_region(monkeypatch) -> None:
|
||||
"""The backend triggers jobs where Pulumi creates them; the two must agree."""
|
||||
src = (REPO_ROOT / "infrastructure" / "modules" / "cloud_run.py").read_text()
|
||||
m = re.search(r'^CPU_JOBS_REGION = "([a-z0-9-]+)"', src, re.MULTILINE)
|
||||
assert m, "could not locate CPU_JOBS_REGION in infrastructure/modules/cloud_run.py"
|
||||
assert _settings(monkeypatch).cpu_jobs_region == m.group(1)
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadType": "Unsupported audio file type. Please upload one of: {allowed}.",
|
||||
"instrumentalUploadBadPath": "Invalid instrumental upload reference. Please try uploading again.",
|
||||
"instrumentalUploadMissing": "We couldn't find your uploaded instrumental. The upload may not have finished. Please try again.",
|
||||
"uploadDurationMismatchCancelled": "Duration mismatch: the instrumental is {instrumental_duration}s but the song audio is {audio_duration}s (they must match within 0.5s). This job has been cancelled and your credit refunded. Please submit again with matching files.",
|
||||
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead."
|
||||
"uploadDurationMismatchCancelled": "The instrumental ({instrumental_duration}s) doesn't line up with the song audio ({audio_duration}s), so it may be the wrong file for this song. This job has been cancelled and your credit refunded. Please check the files and submit again.",
|
||||
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead.",
|
||||
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "مرجع رفع الموسيقى الآلية غير صالح. يُرجى محاولة الرفع مرة أخرى.",
|
||||
"instrumentalUploadBadType": "نوع ملف الصوت غير مدعوم. يُرجى رفع أحد الأنواع التالية: {allowed}.",
|
||||
"instrumentalUploadMissing": "تعذر العثور على ملف الموسيقى الآلية الذي قمت برفعه. قد لا يكون الرفع قد اكتمل بعد. يُرجى المحاولة مرة أخرى.",
|
||||
"uploadDurationMismatchCancelled": "عدم تطابق في المدة: مدة الموسيقى الآلية هي {instrumental_duration} ثانية ولكن مدة صوت الأغنية هي {audio_duration} ثانية (يجب أن يتطابقا في غضون 0.5 ثانية). تم إلغاء هذه المهمة وإعادة رصيدك. يُرجى إعادة الإرسال باستخدام ملفات متطابقة.",
|
||||
"instrumentalUploadTooLarge": "حجم هذا الملف الموسيقي هو {size_mb} ميجابايت، وهو ما يتجاوز الحد المسموح به البالغ {max_mb} ميجابايت. يُرجى رفع نسخة بصيغة FLAC أو MP3 بدلاً من ذلك."
|
||||
"uploadDurationMismatchCancelled": "لا تتطابق مدة المسار الموسيقي ({instrumental_duration} ثانية) مع مدة صوت الأغنية ({audio_duration} ثانية)، لذا قد يكون الملف غير صحيح لهذه الأغنية. تم إلغاء هذه المهمة واسترداد رصيدك. يُرجى التحقق من الملفات وإعادة المحاولة.",
|
||||
"instrumentalUploadTooLarge": "حجم هذا الملف الموسيقي هو {size_mb} ميجابايت، وهو ما يتجاوز الحد المسموح به البالغ {max_mb} ميجابايت. يُرجى رفع نسخة بصيغة FLAC أو MP3 بدلاً من ذلك.",
|
||||
"instrumentalConformUnavailable": "لم نتمكن من معالجة المقطع الموسيقي الخاص بك الآن. يُرجى محاولة الإرسال مجدداً بعد لحظات."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "المهمة غير موجودة",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Referència de pujada de l'instrumental no vàlida. Si us plau, torna a intentar pujar-lo.",
|
||||
"instrumentalUploadBadType": "Tipus de fitxer d'àudio no admès. Si us plau, puja'n un d'aquests: {allowed}.",
|
||||
"instrumentalUploadMissing": "No hem pogut trobar l'instrumental que has pujat. És possible que la pujada no s'hagi completat. Si us plau, torna-ho a intentar.",
|
||||
"uploadDurationMismatchCancelled": "Diferència de durada: l'instrumental dura {instrumental_duration}s però l'àudio de la cançó dura {audio_duration}s (han de coincidir amb un marge de 0.5s). Aquesta tasca s'ha cancel·lat i se t'ha reemborsat el crèdit. Si us plau, torna-ho a enviar amb fitxers que coincideixin.",
|
||||
"instrumentalUploadTooLarge": "Aquest fitxer instrumental fa {size_mb} MB, que supera el límit de {max_mb} MB. Si us plau, penja una versió en FLAC o MP3 en comptes d'això."
|
||||
"uploadDurationMismatchCancelled": "L'instrumental ({instrumental_duration}s) no coincideix amb l'àudio de la cançó ({audio_duration}s), per la qual cosa podria ser el fitxer equivocat per a aquesta cançó. Aquesta tasca s'ha cancel·lat i se t'ha reemborsat el crèdit. Comprova els fitxers i torna-ho a enviar.",
|
||||
"instrumentalUploadTooLarge": "Aquest fitxer instrumental fa {size_mb} MB, que supera el límit de {max_mb} MB. Si us plau, penja una versió en FLAC o MP3 en comptes d'això.",
|
||||
"instrumentalConformUnavailable": "No hem pogut processar el teu instrumental ara mateix. Si us plau, torna-ho a enviar d'aquí a un moment."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tasca no trobada",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Neplatný odkaz na nahraný instrumentál. Zkus to prosím nahrát znovu.",
|
||||
"instrumentalUploadBadType": "Nepodporovaný typ zvukového souboru. Nahraj prosím jeden z: {allowed}.",
|
||||
"instrumentalUploadMissing": "Nepodařilo se najít tvůj nahraný instrumentál. Nahrávání možná nebylo dokončeno. Zkus to prosím znovu.",
|
||||
"uploadDurationMismatchCancelled": "Nesoulad délky: instrumentál má {instrumental_duration} s, ale audio skladby má {audio_duration} s (musí se shodovat do 0,5 s). Tato úloha byla zrušena a tvůj kredit byl vrácen. Odešli to prosím znovu s odpovídajícími soubory.",
|
||||
"instrumentalUploadTooLarge": "Tento instrumentální soubor má {size_mb} MB, což překračuje limit {max_mb} MB. Nahraj prosím místo toho verzi ve formátu FLAC nebo MP3."
|
||||
"uploadDurationMismatchCancelled": "Instrumentální stopa ({instrumental_duration}s) časově nesedí se zvukem skladby ({audio_duration}s), takže může jít o nesprávný soubor pro tuto skladbu. Tato úloha byla zrušena a tvůj kredit byl vrácen. Zkontroluj prosím soubory a odešli je znovu.",
|
||||
"instrumentalUploadTooLarge": "Tento instrumentální soubor má {size_mb} MB, což překračuje limit {max_mb} MB. Nahraj prosím místo toho verzi ve formátu FLAC nebo MP3.",
|
||||
"instrumentalConformUnavailable": "Právě se nám nepodařilo zpracovat tvůj instrumentál. Zkus to prosím za chvíli odeslat znovu."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha nebyla nalezena",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Ugyldig reference til instrumental-upload. Prøv venligst at uploade igen.",
|
||||
"instrumentalUploadBadType": "Ikke-understøttet lydfiltype. Upload venligst en af følgende: {allowed}.",
|
||||
"instrumentalUploadMissing": "Vi kunne ikke finde din uploadede instrumental. Uploaden blev muligvis ikke fuldført. Prøv venligst igen.",
|
||||
"uploadDurationMismatchCancelled": "Uoverensstemmelse i varighed: instrumentalen er {instrumental_duration}s, men sangens lyd er {audio_duration}s (de skal matche inden for 0,5s). Dette job er blevet annulleret, og din kredit er refunderet. Indsend venligst igen med matchende filer.",
|
||||
"instrumentalUploadTooLarge": "Denne instrumentalfil er på {size_mb} MB, hvilket overskrider grænsen på {max_mb} MB. Upload venligst en FLAC- eller MP3-version i stedet."
|
||||
"uploadDurationMismatchCancelled": "Instrumentalsporet ({instrumental_duration}s) stemmer ikke overens med sangens lydspor ({audio_duration}s), så det er muligvis den forkerte fil til denne sang. Denne opgave er blevet annulleret, og din kredit er blevet refunderet. Tjek venligst filerne, og indsend igen.",
|
||||
"instrumentalUploadTooLarge": "Denne instrumentalfil er på {size_mb} MB, hvilket overskrider grænsen på {max_mb} MB. Upload venligst en FLAC- eller MP3-version i stedet.",
|
||||
"instrumentalConformUnavailable": "Vi kunne ikke behandle dit instrumentalspor lige nu. Prøv venligst at indsende igen om et øjeblik."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet blev ikke fundet",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Ungültige Referenz für das hochgeladene Instrumental. Bitte versuche den Upload erneut.",
|
||||
"instrumentalUploadBadType": "Nicht unterstützter Audiodateityp. Bitte lade eines der folgenden Formate hoch: {allowed}.",
|
||||
"instrumentalUploadMissing": "Wir konnten dein hochgeladenes Instrumental nicht finden. Der Upload wurde möglicherweise nicht abgeschlossen. Bitte versuche es erneut.",
|
||||
"uploadDurationMismatchCancelled": "Dauer stimmt nicht überein: Das Instrumental ist {instrumental_duration}s lang, das Song-Audio jedoch {audio_duration}s (sie müssen bis auf 0.5s übereinstimmen). Dieser Auftrag wurde abgebrochen und dein Guthaben erstattet. Bitte reiche es mit übereinstimmenden Dateien erneut ein.",
|
||||
"instrumentalUploadTooLarge": "Diese Instrumental-Datei ist {size_mb} MB groß, was über dem Limit von {max_mb} MB liegt. Bitte lade stattdessen eine FLAC- oder MP3-Version hoch."
|
||||
"uploadDurationMismatchCancelled": "Das Instrumental ({instrumental_duration}s) stimmt zeitlich nicht mit dem Song-Audio ({audio_duration}s) überein, daher handelt es sich möglicherweise um die falsche Datei für diesen Song. Dieser Auftrag wurde abgebrochen und dein Guthaben erstattet. Bitte überprüfe die Dateien und reiche den Auftrag erneut ein.",
|
||||
"instrumentalUploadTooLarge": "Diese Instrumental-Datei ist {size_mb} MB groß, was über dem Limit von {max_mb} MB liegt. Bitte lade stattdessen eine FLAC- oder MP3-Version hoch.",
|
||||
"instrumentalConformUnavailable": "Wir konnten dein Instrumental gerade nicht verarbeiten. Bitte versuche es in einem Moment noch einmal einzureichen."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Μη έγκυρη αναφορά μεταφόρτωσης ορχηστρικού. Δοκίμασε να κάνεις μεταφόρτωση ξανά.",
|
||||
"instrumentalUploadBadType": "Μη υποστηριζόμενος τύπος αρχείου ήχου. Μεταφόρτωσε ένα από τα εξής: {allowed}.",
|
||||
"instrumentalUploadMissing": "Δεν μπορέσαμε να βρούμε το ορχηστρικό που μεταφόρτωσες. Η μεταφόρτωση ενδέχεται να μην έχει ολοκληρωθεί. Δοκίμασε ξανά.",
|
||||
"uploadDurationMismatchCancelled": "Ασυμφωνία διάρκειας: το ορχηστρικό είναι {instrumental_duration} δευτ. αλλά ο ήχος του τραγουδιού είναι {audio_duration} δευτ. (πρέπει να ταιριάζουν με απόκλιση έως 0,5 δευτ.). Αυτή η εργασία έχει ακυρωθεί και η πίστωσή σου επιστράφηκε. Υπόβαλε ξανά με αρχεία που ταιριάζουν.",
|
||||
"instrumentalUploadTooLarge": "Αυτό το ορχηστρικό αρχείο είναι {size_mb} MB, το οποίο υπερβαίνει το όριο των {max_mb} MB. Παρακαλώ ανέβασε μια έκδοση FLAC ή MP3 αντ' αυτού."
|
||||
"uploadDurationMismatchCancelled": "Το ορχηστρικό ({instrumental_duration}s) δεν ταιριάζει σε διάρκεια με τον ήχο του τραγουδιού ({audio_duration}s), οπότε μπορεί να είναι λάθος αρχείο για αυτό το τραγούδι. Αυτή η εργασία ακυρώθηκε και η πίστωσή σου επιστράφηκε. Παρακαλούμε έλεγξε τα αρχεία και υπόβαλε ξανά.",
|
||||
"instrumentalUploadTooLarge": "Αυτό το ορχηστρικό αρχείο είναι {size_mb} MB, το οποίο υπερβαίνει το όριο των {max_mb} MB. Παρακαλώ ανέβασε μια έκδοση FLAC ή MP3 αντ' αυτού.",
|
||||
"instrumentalConformUnavailable": "Δεν μπορέσαμε να επεξεργαστούμε το ορχηστρικό σου αυτή τη στιγμή. Δοκίμασε να υποβάλεις ξανά σε λίγο."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Η εργασία δεν βρέθηκε",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadType": "Unsupported audio file type. Please upload one of: {allowed}.",
|
||||
"instrumentalUploadBadPath": "Invalid instrumental upload reference. Please try uploading again.",
|
||||
"instrumentalUploadMissing": "We couldn't find your uploaded instrumental. The upload may not have finished. Please try again.",
|
||||
"uploadDurationMismatchCancelled": "Duration mismatch: the instrumental is {instrumental_duration}s but the song audio is {audio_duration}s (they must match within 0.5s). This job has been cancelled and your credit refunded. Please submit again with matching files.",
|
||||
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead."
|
||||
"uploadDurationMismatchCancelled": "The instrumental ({instrumental_duration}s) doesn't line up with the song audio ({audio_duration}s), so it may be the wrong file for this song. This job has been cancelled and your credit refunded. Please check the files and submit again.",
|
||||
"instrumentalUploadTooLarge": "This instrumental file is {size_mb} MB, which is over the {max_mb} MB limit. Please upload a FLAC or MP3 version instead.",
|
||||
"instrumentalConformUnavailable": "We couldn't process your instrumental just now. Please try submitting again in a moment."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job not found",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Referencia de subida de instrumental inválida. Por favor, intenta subirlo de nuevo.",
|
||||
"instrumentalUploadBadType": "Tipo de archivo de audio no compatible. Por favor, sube uno de los siguientes: {allowed}.",
|
||||
"instrumentalUploadMissing": "No pudimos encontrar el instrumental que subiste. Es posible que la subida no haya finalizado. Por favor, inténtalo de nuevo.",
|
||||
"uploadDurationMismatchCancelled": "Discrepancia en la duración: el instrumental dura {instrumental_duration}s pero el audio de la canción dura {audio_duration}s (deben coincidir con una diferencia máxima de 0.5s). Este trabajo ha sido cancelado y se ha reembolsado tu crédito. Por favor, vuelve a enviarlo con archivos que coincidan.",
|
||||
"instrumentalUploadTooLarge": "Este archivo instrumental tiene {size_mb} MB, lo que supera el límite de {max_mb} MB. Por favor, sube una versión en FLAC o MP3 en su lugar."
|
||||
"uploadDurationMismatchCancelled": "El instrumental ({instrumental_duration}s) no coincide con el audio de la canción ({audio_duration}s), por lo que podría ser el archivo incorrecto para esta canción. Este trabajo ha sido cancelado y tu crédito ha sido reembolsado. Por favor, revisa los archivos y vuelve a enviarlos.",
|
||||
"instrumentalUploadTooLarge": "Este archivo instrumental tiene {size_mb} MB, lo que supera el límite de {max_mb} MB. Por favor, sube una versión en FLAC o MP3 en su lugar.",
|
||||
"instrumentalConformUnavailable": "No pudimos procesar tu instrumental en este momento. Por favor, intenta enviarlo de nuevo en un momento."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Virheellinen instrumentaaliraidan latausviite. Yritä ladata uudelleen.",
|
||||
"instrumentalUploadBadType": "Äänitiedostomuotoa ei tueta. Lataa jokin seuraavista: {allowed}.",
|
||||
"instrumentalUploadMissing": "Emme löytäneet lataamaasi instrumentaaliraitaa. Lataus ei ehkä ole valmistunut. Yritä uudelleen.",
|
||||
"uploadDurationMismatchCancelled": "Kestot eivät täsmää: instrumentaaliraita on {instrumental_duration} s, mutta kappaleen ääni on {audio_duration} s (niiden on täsmättävä 0,5 sekunnin tarkkuudella). Tämä työ on peruutettu ja krediittisi on palautettu. Lähetä uudelleen toisiinsa täsmäävillä tiedostoilla.",
|
||||
"instrumentalUploadTooLarge": "Tämä instrumentaalitiedosto on {size_mb} MB, mikä ylittää {max_mb} MB:n rajan. Lataa sen sijaan FLAC- tai MP3-versio."
|
||||
"uploadDurationMismatchCancelled": "Taustaraita ({instrumental_duration}s) ei täsmää kappaleen ääniraidan ({audio_duration}s) kanssa, joten se saattaa olla väärä tiedosto tälle kappaleelle. Tämä työ on peruutettu ja krediittisi on palautettu. Tarkista tiedostot ja lähetä uudelleen.",
|
||||
"instrumentalUploadTooLarge": "Tämä instrumentaalitiedosto on {size_mb} MB, mikä ylittää {max_mb} MB:n rajan. Lataa sen sijaan FLAC- tai MP3-versio.",
|
||||
"instrumentalConformUnavailable": "Emme voineet käsitellä taustaraitaasi juuri nyt. Yritä lähettää uudelleen hetken kuluttua."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Työtä ei löytynyt",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Référence de téléversement de l'instrumentale non valide. Réessaie de téléverser le fichier.",
|
||||
"instrumentalUploadBadType": "Type de fichier audio non pris en charge. Téléverse l'un des formats suivants : {allowed}.",
|
||||
"instrumentalUploadMissing": "Nous n'avons pas trouvé ton instrumentale téléversée. Le téléversement n'est peut-être pas terminé. Réessaie.",
|
||||
"uploadDurationMismatchCancelled": "Différence de durée : l'instrumentale fait {instrumental_duration}s alors que l'audio de la chanson fait {audio_duration}s (ils doivent correspondre à 0,5s près). Cette tâche a été annulée et ton crédit a été remboursé. Réessaie avec des fichiers correspondants.",
|
||||
"instrumentalUploadTooLarge": "Ce fichier instrumental fait {size_mb} Mo, ce qui dépasse la limite de {max_mb} Mo. Téléverse plutôt une version FLAC ou MP3."
|
||||
"uploadDurationMismatchCancelled": "L'instrumental ({instrumental_duration}s) ne correspond pas à l'audio du morceau ({audio_duration}s), il s'agit donc peut-être du mauvais fichier pour cette chanson. Cette tâche a été annulée et ton crédit a été remboursé. Vérifie les fichiers et réessaie.",
|
||||
"instrumentalUploadTooLarge": "Ce fichier instrumental fait {size_mb} Mo, ce qui dépasse la limite de {max_mb} Mo. Téléverse plutôt une version FLAC ou MP3.",
|
||||
"instrumentalConformUnavailable": "Nous n'avons pas pu traiter ton instrumental à l'instant. Réessaie de le soumettre dans un instant."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tâche introuvable",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "הפניה לא תקינה להעלאת הפלייבק. אנא נסו להעלות שוב.",
|
||||
"instrumentalUploadBadType": "סוג קובץ השמע אינו נתמך. אנא העלו קובץ מאחד הסוגים הבאים: {allowed}.",
|
||||
"instrumentalUploadMissing": "לא הצלחנו למצוא את הפלייבק שהעליתם. ייתכן שההעלאה לא הושלמה. אנא נסו שוב.",
|
||||
"uploadDurationMismatchCancelled": "אי-התאמה במשך הזמן: אורך הפלייבק הוא {instrumental_duration} שניות, אך אורך השמע של השיר הוא {audio_duration} שניות (הם חייבים להתאים בהפרש של עד 0.5 שניות). משימה זו בוטלה והקרדיט שלכם הוחזר. אנא שלחו שוב עם קבצים תואמים.",
|
||||
"instrumentalUploadTooLarge": "קובץ הפלייבק הזה הוא בגודל {size_mb} MB, שחורג מהמגבלה של {max_mb} MB. נא להעלות גרסת FLAC או MP3 במקום זאת."
|
||||
"uploadDurationMismatchCancelled": "הפלייבק ({instrumental_duration} שניות) אינו תואם לקובץ השמע של השיר ({audio_duration} שניות), ולכן ייתכן שמדובר בקובץ שגוי עבור שיר זה. משימה זו בוטלה והקרדיט שלך הוחזר. נא לבדוק את הקבצים ולשלוח שוב.",
|
||||
"instrumentalUploadTooLarge": "קובץ הפלייבק הזה הוא בגודל {size_mb} MB, שחורג מהמגבלה של {max_mb} MB. נא להעלות גרסת FLAC או MP3 במקום זאת.",
|
||||
"instrumentalConformUnavailable": "לא הצלחנו לעבד את הפלייבק שלך כרגע. אנא נסה לשלוח שוב בעוד רגע."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "המשימה לא נמצאה",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "अमान्य इंस्ट्रूमेंटल अपलोड संदर्भ। कृपया फिर से अपलोड करने की कोशिश करो।",
|
||||
"instrumentalUploadBadType": "असमर्थित ऑडियो फ़ाइल प्रकार। कृपया इनमें से कोई एक अपलोड करो: {allowed}।",
|
||||
"instrumentalUploadMissing": "हमें तुम्हारा अपलोड किया गया इंस्ट्रूमेंटल नहीं मिला। हो सकता है कि अपलोड पूरा न हुआ हो। कृपया फिर से कोशिश करो।",
|
||||
"uploadDurationMismatchCancelled": "अवधि का बेमेल: इंस्ट्रूमेंटल {instrumental_duration}s का है लेकिन गाने का ऑडियो {audio_duration}s का है (वे 0.5s के भीतर मेल खाने चाहिए)। यह जॉब रद्द कर दी गई है और तुम्हारा क्रेडिट रीफ़ंड कर दिया गया है। कृपया मेल खाने वाली फ़ाइलों के साथ फिर से सबमिट करो।",
|
||||
"instrumentalUploadTooLarge": "यह इंस्ट्रुमेंटल फ़ाइल {size_mb} MB की है, जो {max_mb} MB की सीमा से ज़्यादा है। कृपया इसके बजाय FLAC या MP3 वर्शन अपलोड करो।"
|
||||
"uploadDurationMismatchCancelled": "इंस्ट्रुमेंटल ({instrumental_duration}s) गाने के ऑडियो ({audio_duration}s) से मेल नहीं खा रहा है, इसलिए हो सकता है कि यह इस गाने के लिए गलत फ़ाइल हो। यह जॉब रद्द कर दिया गया है और तुम्हारा क्रेडिट रिफ़ंड कर दिया गया है। कृपया फ़ाइलों की जाँच करो और फिर से सबमिट करो।",
|
||||
"instrumentalUploadTooLarge": "यह इंस्ट्रुमेंटल फ़ाइल {size_mb} MB की है, जो {max_mb} MB की सीमा से ज़्यादा है। कृपया इसके बजाय FLAC या MP3 वर्शन अपलोड करो।",
|
||||
"instrumentalConformUnavailable": "हम अभी तुम्हारा इंस्ट्रुमेंटल प्रोसेस नहीं कर पाए। कृपया थोड़ी देर बाद फिर से सबमिट करने की कोशिश करो।"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "जॉब नहीं मिली",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Nevažeća referenca za prijenos instrumentala. Pokušaj ponovno prenijeti.",
|
||||
"instrumentalUploadBadType": "Nepodržana vrsta audio datoteke. Prenesi jednu od: {allowed}.",
|
||||
"instrumentalUploadMissing": "Nismo uspjeli pronaći tvoj preneseni instrumental. Prijenos možda nije dovršen. Pokušaj ponovno.",
|
||||
"uploadDurationMismatchCancelled": "Nepodudaranje trajanja: instrumental traje {instrumental_duration}s, a audio pjesme traje {audio_duration}s (moraju se podudarati unutar 0.5s). Ovaj je zadatak otkazan, a tvoj kredit vraćen. Pošalji ponovno s datotekama koje se podudaraju.",
|
||||
"instrumentalUploadTooLarge": "Ova instrumentalna datoteka ima {size_mb} MB, što premašuje ograničenje od {max_mb} MB. Umjesto toga učitaj FLAC ili MP3 verziju."
|
||||
"uploadDurationMismatchCancelled": "Instrumental ({instrumental_duration}s) se ne podudara s audiozapisom pjesme ({audio_duration}s), pa je možda riječ o pogrešnoj datoteci za ovu pjesmu. Ovaj je zadatak otkazan, a tvoj je kredit vraćen. Provjeri datoteke i pošalji ponovno.",
|
||||
"instrumentalUploadTooLarge": "Ova instrumentalna datoteka ima {size_mb} MB, što premašuje ograničenje od {max_mb} MB. Umjesto toga učitaj FLAC ili MP3 verziju.",
|
||||
"instrumentalConformUnavailable": "Trenutačno nismo uspjeli obraditi tvoj instrumental. Pokušaj ponovno poslati za koji trenutak."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Zadatak nije pronađen",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Érvénytelen hangszeres feltöltési hivatkozás. Kérlek, próbáld meg újra feltölteni.",
|
||||
"instrumentalUploadBadType": "Nem támogatott hangfájltípus. Kérlek, a következők egyikét töltsd fel: {allowed}.",
|
||||
"instrumentalUploadMissing": "Nem találtuk a feltöltött hangszeres sávot. Lehet, hogy a feltöltés nem fejeződött be. Kérlek, próbáld újra.",
|
||||
"uploadDurationMismatchCancelled": "Időtartam-eltérés: a hangszeres sáv hossza {instrumental_duration} mp, de a dal hanganyaga {audio_duration} mp (legfeljebb 0,5 mp lehet az eltérés). Ezt a feladatot töröltük, a kreditedet pedig visszatérítettük. Kérlek, küldd be újra egyező fájlokkal.",
|
||||
"instrumentalUploadTooLarge": "Ez az instrumentális fájl {size_mb} MB méretű, ami meghaladja a {max_mb} MB-os limitet. Kérlek, tölts fel helyette egy FLAC vagy MP3 verziót."
|
||||
"uploadDurationMismatchCancelled": "Az instrumentális sáv ({instrumental_duration} mp) nem vág egybe a dal hanganyagával ({audio_duration} mp), ezért előfordulhat, hogy nem a megfelelő fájl tartozik ehhez a dalhoz. A feladat törölve lett, és a kreditedet visszatérítettük. Kérjük, ellenőrizd a fájlokat, és küldd be újra.",
|
||||
"instrumentalUploadTooLarge": "Ez az instrumentális fájl {size_mb} MB méretű, ami meghaladja a {max_mb} MB-os limitet. Kérlek, tölts fel helyette egy FLAC vagy MP3 verziót.",
|
||||
"instrumentalConformUnavailable": "Nem sikerült most feldolgozni a zenei alapodat. Kérlek, próbáld meg újra beküldeni egy pillanat múlva."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "A feladat nem található",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Referensi unggahan instrumental tidak valid. Silakan coba unggah lagi.",
|
||||
"instrumentalUploadBadType": "Tipe file audio tidak didukung. Silakan unggah salah satu dari: {allowed}.",
|
||||
"instrumentalUploadMissing": "Kami tidak dapat menemukan instrumental yang Anda unggah. Pengunggahan mungkin belum selesai. Silakan coba lagi.",
|
||||
"uploadDurationMismatchCancelled": "Durasi tidak cocok: instrumental berdurasi {instrumental_duration} detik tetapi audio lagu berdurasi {audio_duration} detik (keduanya harus cocok dalam rentang 0,5 detik). Proses ini telah dibatalkan dan kredit Anda telah dikembalikan. Silakan kirimkan kembali dengan file yang cocok.",
|
||||
"instrumentalUploadTooLarge": "File instrumental ini berukuran {size_mb} MB, yang melebihi batas {max_mb} MB. Silakan unggah versi FLAC atau MP3 sebagai gantinya."
|
||||
"uploadDurationMismatchCancelled": "Audio instrumental ({instrumental_duration} detik) tidak selaras dengan audio lagu ({audio_duration} detik), sehingga mungkin ini bukan file yang tepat untuk lagu ini. Proses ini telah dibatalkan dan kredit Anda telah dikembalikan. Silakan periksa file Anda dan kirimkan kembali.",
|
||||
"instrumentalUploadTooLarge": "File instrumental ini berukuran {size_mb} MB, yang melebihi batas {max_mb} MB. Silakan unggah versi FLAC atau MP3 sebagai gantinya.",
|
||||
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental Anda barusan. Silakan coba kirimkan lagi beberapa saat lagi."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugas tidak ditemukan",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Riferimento al caricamento della base strumentale non valido. Prova a caricarla di nuovo.",
|
||||
"instrumentalUploadBadType": "Tipo di file audio non supportato. Carica uno dei seguenti formati: {allowed}.",
|
||||
"instrumentalUploadMissing": "Non siamo riusciti a trovare la base strumentale caricata. Il caricamento potrebbe non essere stato completato. Riprova.",
|
||||
"uploadDurationMismatchCancelled": "Discrepanza di durata: la base strumentale dura {instrumental_duration}s ma l'audio del brano dura {audio_duration}s (devono corrispondere entro 0.5s). Questa operazione è stata annullata e il tuo credito è stato rimborsato. Invia di nuovo la richiesta con file corrispondenti.",
|
||||
"instrumentalUploadTooLarge": "Questo file strumentale è di {size_mb} MB, che supera il limite di {max_mb} MB. Carica invece una versione in FLAC o MP3."
|
||||
"uploadDurationMismatchCancelled": "La base strumentale ({instrumental_duration}s) non coincide con l'audio del brano ({audio_duration}s), quindi potrebbe trattarsi del file sbagliato per questo brano. Questo lavoro è stato annullato e il tuo credito è stato rimborsato. Controlla i file e invia di nuovo.",
|
||||
"instrumentalUploadTooLarge": "Questo file strumentale è di {size_mb} MB, che supera il limite di {max_mb} MB. Carica invece una versione in FLAC o MP3.",
|
||||
"instrumentalConformUnavailable": "Non siamo riusciti a elaborare la tua base strumentale in questo momento. Riprova a inviarla tra qualche istante."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Lavoro non trovato",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "インスト音源のアップロード情報が無効です。もう一度アップロードをお試しください。",
|
||||
"instrumentalUploadBadType": "サポートされていない音声ファイル形式です。次のいずれかをアップロードしてください:{allowed}",
|
||||
"instrumentalUploadMissing": "アップロードされたインスト音源が見つかりませんでした。アップロードが完了していない可能性があります。もう一度お試しください。",
|
||||
"uploadDurationMismatchCancelled": "再生時間が一致しません:インスト音源は{instrumental_duration}秒ですが、元の楽曲音源は{audio_duration}秒です(差を0.5秒以内に収める必要があります)。この処理はキャンセルされ、クレジットが返還されました。長さが一致するファイルで再度お試しください。",
|
||||
"instrumentalUploadTooLarge": "このインスト音源ファイルは{size_mb} MBで、上限の{max_mb} MBを超えています。代わりにFLACまたはMP3形式のファイルをアップロードしてください。"
|
||||
"uploadDurationMismatchCancelled": "インスト音源({instrumental_duration}秒)の長さが楽曲音源({audio_duration}秒)と一致しないため、この曲とは異なるファイルの可能性があります。このジョブはキャンセルされ、クレジットは返却されました。ファイルをご確認のうえ、再度送信してください。",
|
||||
"instrumentalUploadTooLarge": "このインスト音源ファイルは{size_mb} MBで、上限の{max_mb} MBを超えています。代わりにFLACまたはMP3形式のファイルをアップロードしてください。",
|
||||
"instrumentalConformUnavailable": "インスト音源を処理できませんでした。少し時間をおいてから、もう一度送信してください。"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ジョブが見つかりません",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "반주 업로드 정보가 올바르지 않습니다. 다시 업로드해 주세요.",
|
||||
"instrumentalUploadBadType": "지원하지 않는 오디오 파일 형식입니다. 다음 형식 중 하나를 업로드해 주세요: {allowed}.",
|
||||
"instrumentalUploadMissing": "업로드한 반주 파일을 찾을 수 없습니다. 업로드가 완료되지 않았을 수 있습니다. 다시 시도해 주세요.",
|
||||
"uploadDurationMismatchCancelled": "재생 시간 불일치: 반주는 {instrumental_duration}초이지만 노래 오디오는 {audio_duration}초입니다(0.5초 이내로 일치해야 합니다). 해당 작업이 취소되었으며 크레딧이 환불되었습니다. 길이가 일치하는 파일로 다시 제출해 주세요.",
|
||||
"instrumentalUploadTooLarge": "이 반주 파일의 용량은 {size_mb} MB로 제한 용량인 {max_mb} MB를 초과했습니다. 대신 FLAC 또는 MP3 버전으로 업로드해 주세요."
|
||||
"uploadDurationMismatchCancelled": "반주({instrumental_duration}초)의 길이가 원곡 오디오({audio_duration}초)와 일치하지 않아 이 곡에 맞는 파일이 아닐 수 있습니다. 해당 작업은 취소되었으며 크레딧이 환불되었습니다. 파일을 확인하신 후 다시 제출해 주세요.",
|
||||
"instrumentalUploadTooLarge": "이 반주 파일의 용량은 {size_mb} MB로 제한 용량인 {max_mb} MB를 초과했습니다. 대신 FLAC 또는 MP3 버전으로 업로드해 주세요.",
|
||||
"instrumentalConformUnavailable": "방금 반주 음원을 처리하지 못했습니다. 잠시 후 다시 제출해 주세요."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "작업을 찾을 수 없습니다",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Rujukan muat naik instrumental tidak sah. Sila cuba muat naik semula.",
|
||||
"instrumentalUploadBadType": "Jenis fail audio tidak disokong. Sila muat naik salah satu daripada: {allowed}.",
|
||||
"instrumentalUploadMissing": "Kami tidak dapat mencari instrumental yang anda muat naik. Proses muat naik mungkin belum selesai. Sila cuba lagi.",
|
||||
"uploadDurationMismatchCancelled": "Durasi tidak sepadan: instrumental adalah {instrumental_duration}s tetapi audio lagu adalah {audio_duration}s (kedua-duanya mesti sepadan dalam lingkungan 0.5s). Tugasan ini telah dibatalkan dan kredit anda telah dikembalikan. Sila hantar semula dengan fail yang sepadan.",
|
||||
"instrumentalUploadTooLarge": "Fail instrumental ini bersaiz {size_mb} MB, iaitu melebihi had {max_mb} MB. Sila muat naik versi FLAC atau MP3 sebagai ganti."
|
||||
"uploadDurationMismatchCancelled": "Instrumental ({instrumental_duration}s) tidak sepadan dengan audio lagu ({audio_duration}s), jadi ia mungkin fail yang salah untuk lagu ini. Tugasan ini telah dibatalkan dan kredit anda telah dikembalikan. Sila semak fail tersebut dan hantar semula.",
|
||||
"instrumentalUploadTooLarge": "Fail instrumental ini bersaiz {size_mb} MB, iaitu melebihi had {max_mb} MB. Sila muat naik versi FLAC atau MP3 sebagai ganti.",
|
||||
"instrumentalConformUnavailable": "Kami tidak dapat memproses instrumental anda sebentar tadi. Sila cuba hantar semula sebentar lagi."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugasan tidak dijumpai",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Ugyldig referanse for opplasting av instrumental. Prøv å laste opp på nytt.",
|
||||
"instrumentalUploadBadType": "Lydfiltypen støttes ikke. Vennligst last opp en av følgende: {allowed}.",
|
||||
"instrumentalUploadMissing": "Vi fant ikke den opplastede instrumentalen din. Det kan hende opplastingen ikke ble fullført. Prøv igjen.",
|
||||
"uploadDurationMismatchCancelled": "Ulik varighet: instrumentalen er {instrumental_duration}s, men sanglyden er {audio_duration}s (de må stemme overens innen 0,5 s). Denne jobben har blitt kansellert og kreditten din er refundert. Vennligst send inn på nytt med filer som stemmer overens.",
|
||||
"instrumentalUploadTooLarge": "Denne instrumentalfilen er på {size_mb} MB, noe som er over grensen på {max_mb} MB. Vennligst last opp en FLAC- eller MP3-versjon i stedet."
|
||||
"uploadDurationMismatchCancelled": "Instrumentalsporet ({instrumental_duration}s) stemmer ikke overens med sanglyden ({audio_duration}s), så det kan være feil fil for denne sangen. Denne jobben har blitt kansellert og kreditten din er refundert. Vennligst sjekk filene og send inn på nytt.",
|
||||
"instrumentalUploadTooLarge": "Denne instrumentalfilen er på {size_mb} MB, noe som er over grensen på {max_mb} MB. Vennligst last opp en FLAC- eller MP3-versjon i stedet.",
|
||||
"instrumentalConformUnavailable": "Vi kunne ikke behandle instrumentalen din akkurat nå. Prøv å sende inn på nytt om et øyeblikk."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobben ble ikke funnet",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Ongeldige referentie voor de instrumentale upload. Probeer opnieuw te uploaden.",
|
||||
"instrumentalUploadBadType": "Niet-ondersteund audiobestandstype. Upload een van de volgende: {allowed}.",
|
||||
"instrumentalUploadMissing": "We konden je geüploade instrumentale track niet vinden. De upload is mogelijk niet voltooid. Probeer het opnieuw.",
|
||||
"uploadDurationMismatchCancelled": "Verschil in tijdsduur: de instrumentale track duurt {instrumental_duration}s, maar de songaudio duurt {audio_duration}s (ze moeten binnen 0.5s overeenkomen). Deze taak is geannuleerd en je tegoed is teruggestort. Dien opnieuw in met overeenkomende bestanden.",
|
||||
"instrumentalUploadTooLarge": "Dit instrumentale bestand is {size_mb} MB, wat de limiet van {max_mb} MB overschrijdt. Upload in plaats daarvan een FLAC- of MP3-versie."
|
||||
"uploadDurationMismatchCancelled": "De instrumentale track ({instrumental_duration}s) komt niet overeen met de audio van het nummer ({audio_duration}s), dus het is mogelijk het verkeerde bestand voor dit nummer. Deze opdracht is geannuleerd en je tegoed is teruggestort. Controleer de bestanden en dien de aanvraag opnieuw in.",
|
||||
"instrumentalUploadTooLarge": "Dit instrumentale bestand is {size_mb} MB, wat de limiet van {max_mb} MB overschrijdt. Upload in plaats daarvan een FLAC- of MP3-versie.",
|
||||
"instrumentalConformUnavailable": "We konden je instrumental zojuist niet verwerken. Probeer het over een ogenblik opnieuw in te dienen."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Taak niet gevonden",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Nieprawidłowe odwołanie do przesłanego podkładu instrumentalnego. Spróbuj przesłać go ponownie.",
|
||||
"instrumentalUploadBadType": "Nieobsługiwany typ pliku audio. Prześlij jeden z następujących: {allowed}.",
|
||||
"instrumentalUploadMissing": "Nie udało się znaleźć Twojego przesłanego podkładu instrumentalnego. Przesyłanie mogło się nie zakończyć. Spróbuj ponownie.",
|
||||
"uploadDurationMismatchCancelled": "Niezgodność czasu trwania: podkład instrumentalny trwa {instrumental_duration}s, a ścieżka audio utworu trwa {audio_duration}s (muszą być zgodne z dokładnością do 0,5 s). To zadanie zostało anulowane, a Twój kredyt zwrócony. Prześlij zgłoszenie ponownie z pasującymi plikami.",
|
||||
"instrumentalUploadTooLarge": "Ten plik instrumentalny ma {size_mb} MB, co przekracza limit {max_mb} MB. Prześlij zamiast tego wersję FLAC lub MP3."
|
||||
"uploadDurationMismatchCancelled": "Wersja instrumentalna ({instrumental_duration}s) nie zgadza się z plikiem audio utworu ({audio_duration}s), więc może to być niewłaściwy plik dla tej piosenki. To zadanie zostało anulowane, a Twój kredyt zwrócony. Sprawdź pliki i prześlij je ponownie.",
|
||||
"instrumentalUploadTooLarge": "Ten plik instrumentalny ma {size_mb} MB, co przekracza limit {max_mb} MB. Prześlij zamiast tego wersję FLAC lub MP3.",
|
||||
"instrumentalConformUnavailable": "Nie udało nam się teraz przetworzyć Twojego podkładu instrumentalnego. Spróbuj przesłać go ponownie za chwilę."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Nie znaleziono zadania",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Referência de upload do instrumental inválida. Tente fazer o upload novamente.",
|
||||
"instrumentalUploadBadType": "Tipo de arquivo de áudio não suportado. Faça o upload de um dos seguintes: {allowed}.",
|
||||
"instrumentalUploadMissing": "Não conseguimos encontrar o instrumental enviado. O upload pode não ter sido concluído. Tente novamente.",
|
||||
"uploadDurationMismatchCancelled": "Diferença de duração: o instrumental tem {instrumental_duration}s, mas o áudio da música tem {audio_duration}s (a diferença deve ser de no máximo 0.5s). Esta tarefa foi cancelada e seu crédito foi reembolsado. Envie novamente com arquivos correspondentes.",
|
||||
"instrumentalUploadTooLarge": "Este arquivo instrumental tem {size_mb} MB, o que ultrapassa o limite de {max_mb} MB. Por favor, envie uma versão em FLAC ou MP3 em vez disso."
|
||||
"uploadDurationMismatchCancelled": "O instrumental ({instrumental_duration}s) não coincide com o áudio da música ({audio_duration}s), portanto pode ser o arquivo errado para esta música. Esta tarefa foi cancelada e seu crédito foi reembolsado. Por favor, verifique os arquivos e envie novamente.",
|
||||
"instrumentalUploadTooLarge": "Este arquivo instrumental tem {size_mb} MB, o que ultrapassa o limite de {max_mb} MB. Por favor, envie uma versão em FLAC ou MP3 em vez disso.",
|
||||
"instrumentalConformUnavailable": "Não conseguimos processar seu instrumental agora. Por favor, tente enviar novamente em alguns instantes."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job não encontrado",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Referință nevalidă pentru încărcarea instrumentalului. Te rugăm să încerci să încarci din nou.",
|
||||
"instrumentalUploadBadType": "Tip de fișier audio neacceptat. Te rugăm să încarci unul dintre: {allowed}.",
|
||||
"instrumentalUploadMissing": "Nu am putut găsi instrumentalul încărcat. Este posibil ca încărcarea să nu se fi finalizat. Te rugăm să încerci din nou.",
|
||||
"uploadDurationMismatchCancelled": "Nepotrivire de durată: instrumentalul are {instrumental_duration}s, dar fișierul audio al piesei are {audio_duration}s (trebuie să coincidă în limita a 0.5s). Această sarcină a fost anulată, iar creditul ți-a fost rambursat. Te rugăm să trimiți din nou cu fișiere care se potrivesc.",
|
||||
"instrumentalUploadTooLarge": "Acest fișier instrumental are {size_mb} MB, ceea ce depășește limita de {max_mb} MB. Te rugăm să încarci în schimb o versiune FLAC sau MP3."
|
||||
"uploadDurationMismatchCancelled": "Instrumentalul ({instrumental_duration}s) nu se potrivește cu fișierul audio al melodiei ({audio_duration}s), așa că este posibil să fie fișierul greșit pentru această melodie. Această sarcină a fost anulată, iar creditul tău a fost rambursat. Te rugăm să verifici fișierele și să trimiți din nou.",
|
||||
"instrumentalUploadTooLarge": "Acest fișier instrumental are {size_mb} MB, ceea ce depășește limita de {max_mb} MB. Te rugăm să încarci în schimb o versiune FLAC sau MP3.",
|
||||
"instrumentalConformUnavailable": "Nu am putut procesa instrumentalul tău chiar acum. Te rugăm să încerci să trimiți din nou peste câteva momente."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobul nu a fost găsit",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Неверная ссылка на загрузку инструментала. Попробуй загрузить файл ещё раз.",
|
||||
"instrumentalUploadBadType": "Неподдерживаемый тип аудиофайла. Пожалуйста, загрузи один из следующих: {allowed}.",
|
||||
"instrumentalUploadMissing": "Мы не смогли найти твой загруженный инструментал. Возможно, загрузка не завершилась. Попробуй ещё раз.",
|
||||
"uploadDurationMismatchCancelled": "Несовпадение длительности: инструментал длится {instrumental_duration} с, а аудио песни — {audio_duration} с (они должны совпадать с точностью до 0.5 с). Эта задача отменена, а твой кредит возвращён. Пожалуйста, отправь запрос ещё раз с совпадающими файлами.",
|
||||
"instrumentalUploadTooLarge": "Этот файл инструментала весит {size_mb} МБ, что превышает лимит в {max_mb} МБ. Пожалуйста, загрузи вместо него версию в формате FLAC или MP3."
|
||||
"uploadDurationMismatchCancelled": "Длительность инструментала ({instrumental_duration} с) не совпадает с длительностью аудио песни ({audio_duration} с), поэтому, возможно, для этой песни выбран не тот файл. Задача отменена, а твой кредит возвращен. Пожалуйста, проверь файлы и отправь снова.",
|
||||
"instrumentalUploadTooLarge": "Этот файл инструментала весит {size_mb} МБ, что превышает лимит в {max_mb} МБ. Пожалуйста, загрузи вместо него версию в формате FLAC или MP3.",
|
||||
"instrumentalConformUnavailable": "Нам не удалось обработать твой инструментал прямо сейчас. Пожалуйста, попробуй отправить снова чуть позже."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Задача не найдена",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Neplatný odkaz na nahraný inštrumentál. Skús to, prosím, nahrať znova.",
|
||||
"instrumentalUploadBadType": "Nepodporovaný typ zvukového súboru. Nahraj, prosím, jeden z: {allowed}.",
|
||||
"instrumentalUploadMissing": "Nenašli sme tvoj nahraný inštrumentál. Nahrávanie sa pravdepodobne nedokončilo. Skús to, prosím, znova.",
|
||||
"uploadDurationMismatchCancelled": "Nezhoda dĺžky: inštrumentál má {instrumental_duration}s, ale zvuk skladby má {audio_duration}s (musia sa zhodovať s presnosťou do 0.5s). Táto úloha bola zrušená a tvoj kredit ti bol vrátený. Odošli to, prosím, znova so zhodujúcimi sa súbormi.",
|
||||
"instrumentalUploadTooLarge": "Tento inštrumentálny súbor má {size_mb} MB, čo prekračuje limit {max_mb} MB. Namiesto toho prosím nahraj verziu vo formáte FLAC alebo MP3."
|
||||
"uploadDurationMismatchCancelled": "Inštrumentálna stopa ({instrumental_duration}s) sa nezhoduje so zvukom skladby ({audio_duration}s), takže môže ísť o nesprávny súbor pre túto skladbu. Táto úloha bola zrušená a tvoj kredit bol vrátený. Prosím, skontroluj súbory a odošli ich znova.",
|
||||
"instrumentalUploadTooLarge": "Tento inštrumentálny súbor má {size_mb} MB, čo prekračuje limit {max_mb} MB. Namiesto toho prosím nahraj verziu vo formáte FLAC alebo MP3.",
|
||||
"instrumentalConformUnavailable": "Nepodarilo sa nám práve spracovať tvoj inštrumentál. Skús to, prosím, o chvíľu odoslať znova."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha sa nenašla",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Ogiltig referens för den instrumentala uppladdningen. Försök att ladda upp igen.",
|
||||
"instrumentalUploadBadType": "Ljudfilstypen stöds inte. Ladda upp någon av följande: {allowed}.",
|
||||
"instrumentalUploadMissing": "Vi kunde inte hitta ditt uppladdade instrumentala spår. Uppladdningen slutfördes eventuellt inte. Försök igen.",
|
||||
"uploadDurationMismatchCancelled": "Tidslängden matchar inte: det instrumentala spåret är {instrumental_duration}s men låtljudet är {audio_duration}s (de måste matcha inom 0,5s). Det här jobbet har avbrutits och din kredit har återbetalats. Skicka in igen med matchande filer.",
|
||||
"instrumentalUploadTooLarge": "Den här instrumentalfilen är på {size_mb} MB, vilket överskrider gränsen på {max_mb} MB. Ladda upp en FLAC- eller MP3-version istället."
|
||||
"uploadDurationMismatchCancelled": "Instrumentalspåret ({instrumental_duration}s) stämmer inte överens med låtens ljud ({audio_duration}s), så det kan vara fel fil för den här låten. Det här jobbet har avbrutits och din kredit har återbetalats. Kontrollera filerna och skicka in igen.",
|
||||
"instrumentalUploadTooLarge": "Den här instrumentalfilen är på {size_mb} MB, vilket överskrider gränsen på {max_mb} MB. Ladda upp en FLAC- eller MP3-version istället.",
|
||||
"instrumentalConformUnavailable": "Vi kunde inte bearbeta ditt instrumentalspår just nu. Försök att skicka in igen om en stund."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet hittades inte",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "ข้อมูลอ้างอิงไฟล์เสียงดนตรีที่อัปโหลดไม่ถูกต้อง โปรดลองอัปโหลดใหม่อีกครั้ง",
|
||||
"instrumentalUploadBadType": "ไม่รองรับไฟล์เสียงประเภทนี้ โปรดอัปโหลดไฟล์ประเภทใดประเภทหนึ่งต่อไปนี้: {allowed}",
|
||||
"instrumentalUploadMissing": "เราไม่พบไฟล์เสียงดนตรีที่คุณอัปโหลด การอัปโหลดอาจยังไม่เสร็จสมบูรณ์ โปรดลองอีกครั้ง",
|
||||
"uploadDurationMismatchCancelled": "ความยาวไม่ตรงกัน: ไฟล์เสียงดนตรีมีความยาว {instrumental_duration} วินาที แต่ไฟล์เสียงเพลงมีความยาว {audio_duration} วินาที (ความยาวต้องต่างกันไม่เกิน 0.5 วินาที) รายการนี้ถูกยกเลิกแล้วและได้คืนเครดิตให้คุณเรียบร้อยแล้ว โปรดส่งใหม่อีกครั้งด้วยไฟล์ที่มีความยาวตรงกัน",
|
||||
"instrumentalUploadTooLarge": "ไฟล์เสียงดนตรีนี้มีขนาด {size_mb} MB ซึ่งเกินขีดจำกัด {max_mb} MB โปรดอัปโหลดเป็นเวอร์ชัน FLAC หรือ MP3 แทน"
|
||||
"uploadDurationMismatchCancelled": "ไฟล์ดนตรี ({instrumental_duration} วินาที) มีความยาวไม่ตรงกับไฟล์เสียงเพลง ({audio_duration} วินาที) จึงอาจเป็นไฟล์ที่ไม่ถูกต้องสำหรับเพลงนี้ รายการนี้ถูกยกเลิกแล้วและระบบได้คืนเครดิตของคุณเรียบร้อยแล้ว โปรดตรวจสอบไฟล์และส่งใหม่อีกครั้ง",
|
||||
"instrumentalUploadTooLarge": "ไฟล์เสียงดนตรีนี้มีขนาด {size_mb} MB ซึ่งเกินขีดจำกัด {max_mb} MB โปรดอัปโหลดเป็นเวอร์ชัน FLAC หรือ MP3 แทน",
|
||||
"instrumentalConformUnavailable": "เราไม่สามารถประมวลผลไฟล์ดนตรีของคุณได้ในขณะนี้ โปรดลองส่งใหม่อีกครั้งในอีกสักครู่"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ไม่พบงาน",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Hindi wasto ang reference sa pag-upload ng instrumental. Pakisubukang mag-upload muli.",
|
||||
"instrumentalUploadBadType": "Hindi suportado ang uri ng audio file. Mangyaring mag-upload ng isa sa: {allowed}.",
|
||||
"instrumentalUploadMissing": "Hindi namin mahanap ang na-upload mong instrumental. Maaaring hindi natapos ang pag-upload. Pakisubukan muli.",
|
||||
"uploadDurationMismatchCancelled": "Hindi tugma ang haba: ang instrumental ay {instrumental_duration}s ngunit ang audio ng kanta ay {audio_duration}s (dapat magkatugma ang mga ito sa loob ng 0.5s). Kinansela ang job na ito at naibalik na ang iyong credit. Mangyaring magsumite muli na may magkatugmang mga file.",
|
||||
"instrumentalUploadTooLarge": "Ang instrumental file na ito ay {size_mb} MB, na lampas sa {max_mb} MB na limitasyon. Mangyaring mag-upload na lang ng bersyong FLAC o MP3."
|
||||
"uploadDurationMismatchCancelled": "Hindi tumutugma ang instrumental ({instrumental_duration}s) sa audio ng kanta ({audio_duration}s), kaya maaaring maling file ito para sa kantang ito. Kinansela ang job na ito at na-refund ang iyong credit. Pakisuri ang mga file at i-submit muli.",
|
||||
"instrumentalUploadTooLarge": "Ang instrumental file na ito ay {size_mb} MB, na lampas sa {max_mb} MB na limitasyon. Mangyaring mag-upload na lang ng bersyong FLAC o MP3.",
|
||||
"instrumentalConformUnavailable": "Hindi namin naproseso ang iyong instrumental sa ngayon. Pakisubukang isumite muli sa ilang sandali."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Hindi nahanap ang job",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Geçersiz enstrümantal yükleme referansı. Lütfen tekrar yüklemeyi dene.",
|
||||
"instrumentalUploadBadType": "Desteklenmeyen ses dosyası türü. Lütfen şunlardan birini yükle: {allowed}.",
|
||||
"instrumentalUploadMissing": "Yüklediğin enstrümantali bulamadık. Yükleme tamamlanmamış olabilir. Lütfen tekrar dene.",
|
||||
"uploadDurationMismatchCancelled": "Süre uyuşmazlığı: Enstrümantal {instrumental_duration} sn ancak şarkı sesi {audio_duration} sn (aralarındaki fark en fazla 0,5 sn olmalıdır). Bu işlem iptal edildi ve kredin iade edildi. Lütfen eşleşen dosyalarla tekrar gönder.",
|
||||
"instrumentalUploadTooLarge": "Bu enstrümantal dosya {size_mb} MB ve {max_mb} MB sınırını aşıyor. Lütfen bunun yerine bir FLAC veya MP3 sürümü yükle."
|
||||
"uploadDurationMismatchCancelled": "Enstrümantal ({instrumental_duration} sn.) şarkı sesiyle ({audio_duration} sn.) uyuşmuyor, bu yüzden bu şarkı için yanlış dosya olabilir. Bu işlem iptal edildi ve kredin iade edildi. Lütfen dosyaları kontrol edip tekrar gönder.",
|
||||
"instrumentalUploadTooLarge": "Bu enstrümantal dosya {size_mb} MB ve {max_mb} MB sınırını aşıyor. Lütfen bunun yerine bir FLAC veya MP3 sürümü yükle.",
|
||||
"instrumentalConformUnavailable": "Enstrümantal parçanı şu anda işleyemedik. Lütfen birazdan tekrar göndermeyi dene."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "İş bulunamadı",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Недійсне посилання на завантажений інструментал. Будь ласка, спробуй завантажити ще раз.",
|
||||
"instrumentalUploadBadType": "Непідтримуваний тип аудіофайлу. Будь ласка, завантаж один із таких: {allowed}.",
|
||||
"instrumentalUploadMissing": "Нам не вдалося знайти твій завантажений інструментал. Можливо, завантаження не завершилося. Будь ласка, спробуй ще раз.",
|
||||
"uploadDurationMismatchCancelled": "Невідповідність тривалості: інструментал триває {instrumental_duration} с, а аудіо пісні — {audio_duration} с (вони мають збігатися з точністю до 0,5 с). Це завдання скасовано, а твій кредит повернено. Будь ласка, надішли ще раз із файлами однакової тривалості.",
|
||||
"instrumentalUploadTooLarge": "Цей інструментальний файл має розмір {size_mb} МБ, що перевищує ліміт у {max_mb} МБ. Будь ласка, завантаж натомість версію у форматі FLAC або MP3."
|
||||
"uploadDurationMismatchCancelled": "Інструментал ({instrumental_duration} с) не збігається з аудіо пісні ({audio_duration} с), тому, можливо, це неправильний файл для цієї пісні. Це завдання скасовано, а твій кредит повернено. Будь ласка, перевір файли та надішли знову.",
|
||||
"instrumentalUploadTooLarge": "Цей інструментальний файл має розмір {size_mb} МБ, що перевищує ліміт у {max_mb} МБ. Будь ласка, завантаж натомість версію у форматі FLAC або MP3.",
|
||||
"instrumentalConformUnavailable": "Нам щойно не вдалося обробити твій інструментал. Будь ласка, спробуй надіслати ще раз за мить."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Завдання не знайдено",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "Tham chiếu tệp nhạc nền tải lên không hợp lệ. Vui lòng thử tải lên lại.",
|
||||
"instrumentalUploadBadType": "Định dạng tệp âm thanh không được hỗ trợ. Vui lòng tải lên một trong các định dạng: {allowed}.",
|
||||
"instrumentalUploadMissing": "Chúng tôi không tìm thấy bản nhạc nền bạn đã tải lên. Quá trình tải lên có thể chưa hoàn tất. Vui lòng thử lại.",
|
||||
"uploadDurationMismatchCancelled": "Thời lượng không khớp: bản nhạc nền dài {instrumental_duration}s nhưng âm thanh bài hát dài {audio_duration}s (chúng phải khớp nhau trong vòng 0.5s). Tác vụ này đã bị hủy và credit của bạn đã được hoàn lại. Vui lòng gửi lại với các tệp có thời lượng khớp nhau.",
|
||||
"instrumentalUploadTooLarge": "Tệp nhạc nền này có dung lượng {size_mb} MB, vượt quá giới hạn {max_mb} MB. Vui lòng tải lên phiên bản FLAC hoặc MP3 thay thế."
|
||||
"uploadDurationMismatchCancelled": "Bản nhạc không lời ({instrumental_duration}s) không khớp với âm thanh bài hát ({audio_duration}s), do đó có thể đây không phải là tệp chính xác cho bài hát này. Tác vụ này đã bị hủy và credit của bạn đã được hoàn lại. Vui lòng kiểm tra lại các tệp và gửi lại.",
|
||||
"instrumentalUploadTooLarge": "Tệp nhạc nền này có dung lượng {size_mb} MB, vượt quá giới hạn {max_mb} MB. Vui lòng tải lên phiên bản FLAC hoặc MP3 thay thế.",
|
||||
"instrumentalConformUnavailable": "Hiện tại chúng tôi không thể xử lý bản nhạc nền của bạn. Vui lòng thử gửi lại sau giây lát."
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Không tìm thấy công việc",
|
||||
|
||||
@@ -53,8 +53,9 @@
|
||||
"instrumentalUploadBadPath": "伴奏上传引用无效。请尝试重新上传。",
|
||||
"instrumentalUploadBadType": "不支持的音频文件类型。请上传以下格式之一:{allowed}。",
|
||||
"instrumentalUploadMissing": "未找到您上传的伴奏。上传可能尚未完成,请重试。",
|
||||
"uploadDurationMismatchCancelled": "时长不匹配:伴奏时长为 {instrumental_duration} 秒,但歌曲音频时长为 {audio_duration} 秒(两者相差须在 0.5 秒以内)。该任务已取消,您的点数已退还。请使用时长匹配的文件重新提交。",
|
||||
"instrumentalUploadTooLarge": "此伴奏文件大小为 {size_mb} MB,已超出 {max_mb} MB 的限制。请改为上传 FLAC 或 MP3 版本。"
|
||||
"uploadDurationMismatchCancelled": "伴奏时长({instrumental_duration} 秒)与歌曲音频时长({audio_duration} 秒)不匹配,可能不是该歌曲对应的正确文件。该任务已取消,您的点数已退还。请检查文件后重新提交。",
|
||||
"instrumentalUploadTooLarge": "此伴奏文件大小为 {size_mb} MB,已超出 {max_mb} MB 的限制。请改为上传 FLAC 或 MP3 版本。",
|
||||
"instrumentalConformUnavailable": "我们刚才无法处理您的伴奏。请稍后重新尝试提交。"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "未找到任务",
|
||||
|
||||
@@ -22,13 +22,19 @@ import mimetypes
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.flacfetch_client import (
|
||||
get_flacfetch_client,
|
||||
FlacfetchDownloadStalledError,
|
||||
FlacfetchServiceError,
|
||||
)
|
||||
from backend.services import audio_download_limits
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
|
||||
@@ -80,14 +86,14 @@ DOWNLOAD_ALREADY_DONE_STATUSES = frozenset({
|
||||
JobStatus.CANCELLED,
|
||||
})
|
||||
|
||||
# How long to wait for a flacfetch download before giving up. This MUST stay
|
||||
# strictly below the Cloud Run task `timeout` for audio-download-job (see
|
||||
# infrastructure/modules/cloud_run.py::create_audio_download_job). If they are
|
||||
# equal, Cloud Run SIGKILLs the task before this timeout can fire, so the
|
||||
# How long to wait for a (non-torrent) flacfetch download before giving up. This
|
||||
# MUST stay strictly below the Cloud Run task timeout for audio-download-job. If
|
||||
# they are equal, Cloud Run SIGKILLs the task before this timeout can fire, so the
|
||||
# worker never records retry-pending or fails gracefully — leaving an in-flight
|
||||
# auto-retry that races manual retries (job 1cd29294). The headroom below the
|
||||
# task timeout covers the final GCS upload + state transition.
|
||||
DOWNLOAD_WAIT_TIMEOUT_SECONDS = 1080 # task timeout is 1200s
|
||||
# auto-retry that races manual retries (job 1cd29294). The execution timeout is
|
||||
# overridden per run (audio_download_limits.task_timeout_seconds, >= 2700s);
|
||||
# torrents use the longer audio_download_limits.torrent_wait_timeout_seconds.
|
||||
DOWNLOAD_WAIT_TIMEOUT_SECONDS = 1080
|
||||
|
||||
|
||||
def _current_task_attempt() -> int:
|
||||
@@ -132,12 +138,36 @@ def _clear_retry_pending_and_error(job_manager: JobManager, job_id: str) -> None
|
||||
no longer wrongly suggests action is required.
|
||||
"""
|
||||
job_manager.update_state_data(job_id, 'cloud_run_retry_pending', None)
|
||||
job_manager.update_state_data(job_id, audio_download_limits.KEEP_TRYING_STATE_KEY, None)
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': {},
|
||||
})
|
||||
|
||||
|
||||
def _fail_stalled_download(job_manager: JobManager, job_id: str, keep_trying: bool, error: Exception) -> None:
|
||||
"""Fail a job whose torrent never started transferring, for the user to decide.
|
||||
|
||||
No Cloud Run auto-retry: re-adding the same torrent seconds later rarely helps
|
||||
when its only seeder is offline. The job card shows a "Keep trying (up to 1
|
||||
hour)" / "Choose different audio" prompt keyed on error_details.code, and
|
||||
main() exits 0 so Cloud Run doesn't retry the task.
|
||||
"""
|
||||
minutes = audio_download_limits.stall_seconds(keep_trying) // 60
|
||||
job_manager.update_state_data(job_id, 'cloud_run_retry_pending', None)
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Audio download didn't start within {minutes} minutes (source offline, "
|
||||
f"no peers reachable): {error}",
|
||||
error_details={
|
||||
'stage': 'audio_download',
|
||||
'code': audio_download_limits.STALLED_ERROR_CODE,
|
||||
'stall_minutes': minutes,
|
||||
'keep_trying': keep_trying,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _extract_gcs_path(filepath: str) -> str:
|
||||
"""Extract relative GCS path from a full gs:// URL or path."""
|
||||
bucket_prefix = "gs://karaoke-gen-storage-nomadkaraoke/"
|
||||
@@ -213,6 +243,8 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
logger.error(f"[job:{job_id}] No download params available, aborting")
|
||||
return False
|
||||
|
||||
keep_trying = bool(job.state_data.get(audio_download_limits.KEEP_TRYING_STATE_KEY))
|
||||
|
||||
# Get download params from job
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
selection_index = job.state_data.get('selected_audio_index')
|
||||
@@ -250,6 +282,7 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
selection_index=selection_index,
|
||||
selected=selected,
|
||||
storage_service=storage_service,
|
||||
keep_trying=keep_trying,
|
||||
)
|
||||
|
||||
# Concurrency guard: a second download run may have completed while we
|
||||
@@ -332,15 +365,21 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
logger.info(f"[job:{job_id}] Audio download complete, workers triggered")
|
||||
return True
|
||||
|
||||
except FlacfetchDownloadStalledError as e:
|
||||
logger.warning(f"[job:{job_id}] Torrent stalled; asking the user to keep trying or re-pick: {e}")
|
||||
_fail_stalled_download(job_manager, job_id, keep_trying, e)
|
||||
return False
|
||||
except (DownloadError, FlacfetchServiceError) as e:
|
||||
logger.error(f"[job:{job_id}] Download failed: {e}")
|
||||
_mark_retry_pending_if_attempts_remain(job_manager, job_id)
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}",
|
||||
error_details={'stage': 'audio_download'})
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Download failed: {e}", exc_info=True)
|
||||
_mark_retry_pending_if_attempts_remain(job_manager, job_id)
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}",
|
||||
error_details={'stage': 'audio_download'})
|
||||
return False
|
||||
|
||||
|
||||
@@ -406,6 +445,7 @@ async def _download_audio(
|
||||
selection_index: int | None,
|
||||
selected: dict,
|
||||
storage_service: StorageService,
|
||||
keep_trying: bool = False,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
Download audio from the selected source and return (gcs_path, filename).
|
||||
@@ -418,7 +458,8 @@ async def _download_audio(
|
||||
elif source_name in ('RED', 'OPS'):
|
||||
return await _download_torrent(
|
||||
job_id, source_name, source_id, target_file,
|
||||
download_url, remote_search_id, selection_index
|
||||
download_url, remote_search_id, selection_index,
|
||||
keep_trying=keep_trying,
|
||||
)
|
||||
|
||||
elif source_name == 'Spotify':
|
||||
@@ -465,6 +506,38 @@ async def _download_youtube(
|
||||
raise DownloadError(f"YouTube download failed: {e}")
|
||||
|
||||
|
||||
def _download_heartbeat(job_id: str, job_manager: JobManager | None = None):
|
||||
"""Progress callback that periodically records download progress on the job.
|
||||
|
||||
Besides giving admins visibility (progress / peers), each write bumps the
|
||||
job's updated_at so the recover-stuck-jobs cron — which treats a job sitting
|
||||
in downloading_audio for >10 min *without an update* as a dead worker — does
|
||||
not park a torrent we're still legitimately waiting on (stall budgets are
|
||||
20-60 min). Best-effort: a failed write never interrupts the download.
|
||||
"""
|
||||
last_write = [0.0]
|
||||
manager = [job_manager] # created lazily once, reused for every write
|
||||
|
||||
def _callback(status: dict) -> None:
|
||||
now = time.monotonic()
|
||||
if last_write[0] and now - last_write[0] < audio_download_limits.HEARTBEAT_INTERVAL_SECONDS:
|
||||
return
|
||||
last_write[0] = now
|
||||
try:
|
||||
if manager[0] is None:
|
||||
manager[0] = JobManager()
|
||||
manager[0].update_state_data(job_id, 'audio_download_progress', {
|
||||
'progress': status.get('progress', 0),
|
||||
'peers': status.get('peers', 0),
|
||||
'download_speed_kbps': status.get('download_speed_kbps', 0),
|
||||
'at': datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] Download heartbeat write failed: {e}")
|
||||
|
||||
return _callback
|
||||
|
||||
|
||||
async def _download_torrent(
|
||||
job_id: str,
|
||||
source_name: str,
|
||||
@@ -473,8 +546,13 @@ async def _download_torrent(
|
||||
download_url: str | None,
|
||||
remote_search_id: str | None,
|
||||
selection_index: int | None,
|
||||
keep_trying: bool = False,
|
||||
) -> tuple[str, str]:
|
||||
"""Download from torrent source (RED/OPS) via flacfetch."""
|
||||
"""Download from torrent source (RED/OPS) via flacfetch.
|
||||
|
||||
flacfetch aborts after `stall_seconds(keep_trying)` with no progress, which
|
||||
surfaces here as FlacfetchDownloadStalledError.
|
||||
"""
|
||||
flacfetch_client = get_flacfetch_client()
|
||||
if not flacfetch_client:
|
||||
raise DownloadError(
|
||||
@@ -483,15 +561,20 @@ async def _download_torrent(
|
||||
)
|
||||
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
max_stall_seconds = audio_download_limits.stall_seconds(keep_trying)
|
||||
|
||||
if source_id:
|
||||
logger.info(f"[job:{job_id}] Torrent download: {source_name} ID={source_id}")
|
||||
logger.info(
|
||||
f"[job:{job_id}] Torrent download: {source_name} ID={source_id} "
|
||||
f"(max stall {max_stall_seconds}s)"
|
||||
)
|
||||
download_id = await flacfetch_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
max_stall_seconds=max_stall_seconds,
|
||||
)
|
||||
else:
|
||||
if not remote_search_id:
|
||||
@@ -503,11 +586,13 @@ async def _download_torrent(
|
||||
search_id=remote_search_id,
|
||||
result_index=selection_index,
|
||||
gcs_path=gcs_destination,
|
||||
max_stall_seconds=max_stall_seconds,
|
||||
)
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
timeout=audio_download_limits.torrent_wait_timeout_seconds(keep_trying),
|
||||
progress_callback=_download_heartbeat(job_id),
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
@@ -558,6 +643,16 @@ async def _download_spotify(
|
||||
return audio_gcs_path, filename
|
||||
|
||||
|
||||
def _failed_awaiting_user(job_id: str) -> bool:
|
||||
"""True if the job failed with a user-recoverable stall (see _fail_stalled_download)."""
|
||||
try:
|
||||
job = JobManager().get_job(job_id)
|
||||
except Exception:
|
||||
return False
|
||||
details = (job.error_details or {}) if job else {}
|
||||
return details.get('code') == audio_download_limits.STALLED_ERROR_CODE
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
CLI entry point for running audio download worker as a Cloud Run Job.
|
||||
@@ -592,6 +687,11 @@ def main():
|
||||
if success:
|
||||
logger.info(f"Audio download completed successfully for job {job_id}")
|
||||
sys.exit(0)
|
||||
elif _failed_awaiting_user(job_id):
|
||||
# Stalled torrent: the job is failed with a "Keep trying?" prompt for
|
||||
# the user. Exit 0 so Cloud Run doesn't auto-retry the same torrent.
|
||||
logger.warning(f"Audio download stalled for job {job_id}; awaiting user decision")
|
||||
sys.exit(0)
|
||||
else:
|
||||
logger.error(f"Audio download failed for job {job_id}")
|
||||
sys.exit(1)
|
||||
|
||||
@@ -40,7 +40,7 @@ from backend.utils.audio_filenames import local_audio_filename
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
from backend.workers.supersede import capture_generation, check_superseded
|
||||
from backend.workers.supersede import capture_generation, check_superseded, encoding_worker_job_id
|
||||
from backend.config import get_settings
|
||||
from backend.workers.registry import worker_registry
|
||||
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
|
||||
@@ -278,7 +278,9 @@ async def process_render_video(job_id: str) -> bool:
|
||||
)
|
||||
|
||||
result = await run_with_lost_job_resubmit(
|
||||
_submit_render, job_id, log=job_log
|
||||
_submit_render,
|
||||
encoding_worker_job_id(job_id, captured_generation),
|
||||
log=job_log,
|
||||
)
|
||||
render_duration = time.time() - render_start
|
||||
render_span.set_attribute("duration_seconds", render_duration)
|
||||
|
||||
@@ -37,6 +37,19 @@ def capture_generation(job) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def encoding_worker_job_id(job_id: str, generation: int) -> str:
|
||||
"""Id to submit to the encoding worker for this run of a job.
|
||||
|
||||
The encoding worker caches finished jobs in memory by id and answers a
|
||||
resubmission with the OLD result ("cached"). A re-run of the same job (theme
|
||||
re-render, edit, admin reset) bumps ``worker_generation``, so keying the
|
||||
worker id by generation makes each run a fresh worker job, while a duplicate
|
||||
delivery of the same trigger (same generation) still dedups. Output GCS paths
|
||||
are explicit in the request, so the id doesn't move any files.
|
||||
"""
|
||||
return f"{job_id}_g{generation}" if generation else job_id
|
||||
|
||||
|
||||
def _normalize_status(status) -> Optional[JobStatus]:
|
||||
"""Job.status is deserialised with use_enum_values=True (a plain str)."""
|
||||
if isinstance(status, JobStatus):
|
||||
|
||||
@@ -393,6 +393,14 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
'state_data.gdrive_files': result.gdrive_files,
|
||||
# Clear the visibility-change guard flag (previously popped from the map).
|
||||
'state_data.visibility_change_in_progress': DELETE_FIELD,
|
||||
# Fresh finals were just uploaded, so any earlier "outputs deleted"
|
||||
# marker (edit flow, admin delete) is stale — regardless of whether
|
||||
# this job distributes anywhere (tenant jobs never do).
|
||||
'outputs_deleted_at': None,
|
||||
'outputs_deleted_by': None,
|
||||
# A theme re-render (if any) finished; only a FAILED re-render
|
||||
# keeps this marker (it lets the retry re-run the re-render).
|
||||
'state_data.theme_rerender': DELETE_FIELD,
|
||||
}
|
||||
if result.distribution_warnings:
|
||||
state_updates['state_data.distribution_warnings'] = result.distribution_warnings
|
||||
@@ -1014,7 +1022,9 @@ async def generate_video_legacy(job_id: str) -> bool:
|
||||
'youtube_url': result.get('youtube_url'),
|
||||
'dropbox_link': result.get('dropbox_link'),
|
||||
'gdrive_files': result.get('gdrive_files'),
|
||||
}
|
||||
},
|
||||
'outputs_deleted_at': None,
|
||||
'outputs_deleted_by': None,
|
||||
})
|
||||
|
||||
# Mark job as complete (triggers completion email with youtube_url now available)
|
||||
|
||||
@@ -28,6 +28,7 @@ from backend.models.job import JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.tracing import job_span, add_span_event
|
||||
from backend.workers.supersede import capture_generation, encoding_worker_job_id
|
||||
from backend.services.original_audio import (
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
@@ -106,6 +107,10 @@ class OrchestratorConfig:
|
||||
# Encoding backend preference
|
||||
encoding_backend: str = "auto" # "auto", "local", "gce"
|
||||
|
||||
# state_data.worker_generation at config time; keys the encoding-worker job
|
||||
# id so a re-run never gets the previous run's cached encode back.
|
||||
worker_generation: int = 0
|
||||
|
||||
# Additional options
|
||||
dry_run: bool = False
|
||||
non_interactive: bool = True
|
||||
@@ -509,9 +514,13 @@ class VideoWorkerOrchestrator:
|
||||
# existing-instrumental jobs fail at the encoder with "No instrumental audio found".
|
||||
if encoding_backend.name == "gce" and self.storage:
|
||||
try:
|
||||
srcs = self.storage.list_files(f"uploads/{self.config.job_id}/audio/existing_instrumental")
|
||||
if srcs:
|
||||
src = srcs[0]
|
||||
# Prefer the job's recorded path: it points at the conformed copy
|
||||
# (uploads/{job_id}/conformed/) when the upload was lined up with the mix.
|
||||
src = self.config.existing_instrumental_gcs_path
|
||||
if not src:
|
||||
srcs = self.storage.list_files(f"uploads/{self.config.job_id}/audio/existing_instrumental")
|
||||
src = srcs[0] if srcs else None
|
||||
if src:
|
||||
ext = os.path.splitext(src)[1].lower() or ".mp3"
|
||||
dest = f"jobs/{self.config.job_id}/custom_instrumental{ext}"
|
||||
self.storage.copy_blob(src, dest)
|
||||
@@ -534,7 +543,9 @@ class VideoWorkerOrchestrator:
|
||||
add_span_event("encoding_started", {"backend": encoding_backend.name})
|
||||
|
||||
output = await run_with_lost_job_resubmit(
|
||||
_submit_encode, self.config.job_id, log=self.job_log
|
||||
_submit_encode,
|
||||
encoding_worker_job_id(self.config.job_id, self.config.worker_generation),
|
||||
log=self.job_log,
|
||||
)
|
||||
|
||||
add_span_event("encoding_completed", {
|
||||
@@ -710,22 +721,6 @@ class VideoWorkerOrchestrator:
|
||||
if self.config.gdrive_folder_id:
|
||||
await self._upload_to_gdrive()
|
||||
|
||||
# Clear outputs_deleted_at if set (job was re-processed after output deletion)
|
||||
# Only clear if we actually uploaded something
|
||||
uploads_happened = (
|
||||
self.result.youtube_url or
|
||||
self.result.dropbox_link or
|
||||
self.result.gdrive_files
|
||||
)
|
||||
if uploads_happened and self.job_manager:
|
||||
job = self.job_manager.get_job(self.config.job_id)
|
||||
if job and job.outputs_deleted_at:
|
||||
self.job_manager.update_job(self.config.job_id, {
|
||||
"outputs_deleted_at": None,
|
||||
"outputs_deleted_by": None,
|
||||
})
|
||||
self.job_log.info("Cleared outputs_deleted_at flag (job was re-processed)")
|
||||
|
||||
# Incident-hardening G1 (SHADOW): before a public release is considered
|
||||
# done, assert the outputs it *should* have shipped (lossy 4K + 720p, plus
|
||||
# CDG when enabled) actually landed on the public GDrive share. This closes
|
||||
@@ -1211,6 +1206,7 @@ def create_orchestrator_config_from_job(
|
||||
break
|
||||
|
||||
return OrchestratorConfig(
|
||||
worker_generation=capture_generation(job),
|
||||
job_id=job.job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
|
||||
+94
-3
@@ -221,8 +221,18 @@ jobs still awaiting upload 6h after creation (signed URLs expire at 60 min, but
|
||||
PUT can outlast that), or 24h if some files already landed under `uploads/{job_id}/`. Tenant
|
||||
bulk (`batch_id`) jobs are exempt.
|
||||
|
||||
A signed-in user can't finalize another user's job (admins and email-less API tokens can). With an `existing_instrumental` file, a >0.5s
|
||||
duration mismatch cancels the job (credit refunded) and returns 400
|
||||
A signed-in user can't finalize another user's job (admins and email-less API tokens can).
|
||||
|
||||
With an `existing_instrumental` file whose length differs from the mix by >0.5s, the backend
|
||||
lines the instrumental up with the mix (`backend/services/instrumental_conform.py`): it finds the
|
||||
start offset by FFT cross-correlation at 25% and 75% of the song (±15s), trims/pads the start,
|
||||
then trims the end with a 2s fade or pads it with silence to the mix length. The conformed FLAC
|
||||
is stored at `uploads/{job_id}/conformed/existing_instrumental.flac` (becomes
|
||||
`existing_instrumental_gcs_path`; the original upload is kept) and the adjustment is recorded in
|
||||
`state_data.instrumental_conformed` (`start_trimmed_seconds`, `end_trimmed_seconds`,
|
||||
`correlation`, `original_gcs_path`, …). Only when that fails — correlation < 0.3 (wrong file) or
|
||||
the two offsets differ by >20 ms (edited differently mid-song) — is the job cancelled (credit
|
||||
refunded) with 400
|
||||
`{detail: {error: "duration_mismatch", message, audio_duration, instrumental_duration, difference}}`.
|
||||
|
||||
**Optional fields:**
|
||||
@@ -268,6 +278,33 @@ Query parameters:
|
||||
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
|
||||
- `search` (string, optional) - Text search filter (summary mode only). Case-insensitive substring match against artist, title, audio_search_artist, audio_search_title, and job_id. When active, fetches up to 1000 results internally and filters in Python.
|
||||
|
||||
#### Retry Job
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/retry
|
||||
Content-Type: application/json
|
||||
|
||||
{"keep_trying": false} # body optional
|
||||
```
|
||||
|
||||
Resumes a `failed`/`cancelled` job from its last checkpoint. `409` while a Cloud
|
||||
Run auto-retry is pending. For an audio-download failure it re-runs the download.
|
||||
`keep_trying: true` retries a **stalled torrent** (`error_details.code ==
|
||||
"audio_download_stalled"`) with the extended stall budget (1 hour instead of 20
|
||||
minutes; see `backend/services/audio_download_limits.py`).
|
||||
|
||||
#### Choose Different Audio
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/choose-different-audio
|
||||
```
|
||||
|
||||
For a `failed` job whose `error_details.stage == "audio_download"`: moves it back
|
||||
to `awaiting_audio_selection` using its saved search results, so the owner can
|
||||
pick another source via the Select Audio dialog. `400` if the job isn't an
|
||||
audio-download failure or has no saved results, `403` for non-owners, `409` while
|
||||
an auto-retry is pending.
|
||||
|
||||
#### Delete Job
|
||||
|
||||
```http
|
||||
@@ -305,6 +342,22 @@ Response:
|
||||
|
||||
**Validation:** Job must be `complete`, not a tenant job, not already at target visibility, and no concurrent visibility change in progress.
|
||||
|
||||
### Re-render With Current Theme (tenant jobs)
|
||||
|
||||
Re-render a finished tenant track with the tenant's **current** theme, e.g. after editing it in "Theme & style". Jobs snapshot the theme at creation, so theme edits otherwise apply only to new jobs.
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/rerender
|
||||
```
|
||||
|
||||
Response: `{"status": "processing", "job_id": "abc123", "theme_id": "randy-vild"}`
|
||||
|
||||
Re-snapshots the tenant theme onto the job (`style_params_gcs_path`, `style_assets`), deletes the old screens and `videos/with_vocals`, then goes `LYRICS_COMPLETE` (with `state_data.regen_restore_status = "review_complete"`) → screens → render → encode → `complete`. It reuses the reviewed `corrections_updated.json` and `instrumental_selection`, so there's no review step. Free (tenant jobs are never charged). About 10-15 minutes.
|
||||
|
||||
**Access:** the job owner, if still on the tenant allowlist, or an admin.
|
||||
|
||||
**Validation (400):** tenant job; `complete`; outputs not deleted; has a theme, reviewed lyrics and an instrumental selection; never distributed to YouTube/Dropbox/GDrive. **409** if the job left `complete` in the meantime (e.g. a double-click already started a re-render).
|
||||
|
||||
### Review
|
||||
|
||||
The combined review flow allows users to review lyrics AND select instrumental track in a single session.
|
||||
@@ -1284,6 +1337,38 @@ The tenant portal's Bulk mode (`TenantBulkFlow.tsx`) renders these rows as an ed
|
||||
table, then submits each confirmed row through the standard signed-URL upload flow
|
||||
(`upload_mode: "resumable"`, `batch_id` grouping).
|
||||
|
||||
#### Tenant Theme Editor (tenant users)
|
||||
|
||||
```
|
||||
GET /api/tenant/theme → {theme_id, style_params, images[], fonts[]}
|
||||
POST /api/tenant/theme/assets (multipart `file`) → {name}
|
||||
POST /api/tenant/theme/preview {style_params, sample?: {artist, title, lyrics[]}} → {title_card, karaoke_frame}
|
||||
PUT /api/tenant/theme {style_params} → same as GET
|
||||
Authorization: Bearer <session/token> (on the tenant portal: subdomain or X-Tenant-ID)
|
||||
```
|
||||
|
||||
Self-service theme editing for **any user allowed on the tenant** (its email/domain allowlist; admins
|
||||
always). Tenant context may come from the client-controlled `X-Tenant-ID` header, so every endpoint
|
||||
re-checks membership (`require_tenant_member`): non-members/spoofed headers → 403, no/inactive tenant →
|
||||
404, a token scoped to another tenant → 403.
|
||||
|
||||
- **Uploads** (PNG/JPG/GIF/WEBP ≤15 MB, TTF/OTF) are verified with PIL and stored content-addressed as
|
||||
`<stem>-<sha8>.<ext>` under `themes/<id>/assets/` (`no-store`), so they never overwrite an asset
|
||||
existing jobs use.
|
||||
- **Preview** renders the draft with the production renderers (`services/theme_preview_service.py`):
|
||||
title card via `VideoGenerator.create_title_video(duration=0)`, karaoke frame via
|
||||
`SegmentResizer` → `SubtitlesGenerator.generate_ass` → one ffmpeg frame (same `ass` filter/background
|
||||
as the real render) with the first line half-sung. Returns 1280×720 JPEG data URLs (~2 s; ≤2
|
||||
concurrent; identical drafts cached). 400 invalid draft, 422 render failure, 504 timeout.
|
||||
- **Save** (applies to jobs created afterwards). Stricter than the admin console: asset fields must
|
||||
be basenames already in the theme's assets (no paths / `gs://`), numeric/colour/region bounds are
|
||||
checked, and the font is made consistent with the render pipeline — `intro.font` is applied to
|
||||
`karaoke.font_path`/`end.font`/`cdg.font_path`, `karaoke.font` is set to the TTF family name libass
|
||||
matches, and a chosen bundled font is copied into the theme's assets. Tenants can't change their
|
||||
config/allowlist through this API.
|
||||
|
||||
UI: user menu → **Theme & style** on tenant portals (`components/tenant-theme/`).
|
||||
|
||||
#### Tenant Provisioning (Admin Only)
|
||||
|
||||
```
|
||||
@@ -1312,7 +1397,13 @@ kept. `502` if Cloudflare removal fails (nothing in GCS is deleted, so it can be
|
||||
**Portal access:** `allowed_emails` (individual addresses, e.g. a client's gmail) and
|
||||
`allowed_email_domains` (form fields on create; `config.auth.*` on `PUT`). Either non-empty → only
|
||||
listed emails/domains receive magic links (always — the legacy `require_email_domain` flag no
|
||||
longer loosens a non-empty allowlist); both empty → open portal. `@nomadkaraoke.com` admins can
|
||||
longer loosens a non-empty allowlist); both empty → **admins only** (never an open portal).
|
||||
|
||||
**Tenant users never touch consumer credits** (v0.247.0): tenant-portal sign-ins skip the welcome
|
||||
credit (no AI credit eval, no credits-denied/welcome emails, `credit_status: not_applicable`) and
|
||||
referral attribution; tenant jobs (`tenant_id` set) are never credit-checked or charged and are created
|
||||
with `payment_bypassed` (no duration-credit pauses, no refunds). Tenants are billed under a separate
|
||||
agreement. The frontend hides credits, Buy Credits and Referrals on tenant portals. `@nomadkaraoke.com` admins can
|
||||
always sign in.
|
||||
|
||||
Admin-only endpoints (`require_admin`) that mint and manage white-label tenants from the admin panel
|
||||
|
||||
+11
-4
@@ -272,7 +272,7 @@ Three Cloud Functions manage the community karaoke data pipeline, running daily
|
||||
| Function | Schedule | Purpose |
|
||||
|----------|----------|---------|
|
||||
| `divebar-mirror` | Daily 2:00 AM ET | Indexes 48K+ files from [diveBar Karaoke Google Drive](https://drive.google.com/drive/folders/1zxnSZcE03gzy0YVGOdnTrEIi8It_3Wu8) into BigQuery `divebar_catalog` |
|
||||
| `kn-data-sync` | Daily 3:05 AM + 4:30 AM ET | Fetches KaraokeNerds catalog (281K songs) and community tracks (58K with YouTube URLs) to BigQuery + GCS. `full` mode then exports the **kjbox song-identification index** (≈2M songs: Spotify popularity ≥ 30 + all KN; `EXPORT DATA` → `gs://nomadkaraoke-kn-data/song-id/<run>/songs-*.tsv.gz`, manifest `song-id/latest.json`, last 3 runs kept), which the NomadPC downloads. Design: kjbox `docs/SONG-IDENTIFICATION.md` |
|
||||
| `kn-data-sync` | Daily 3:05 AM + 4:30 AM ET | Fetches KaraokeNerds catalog (281K songs) and community tracks (58K with YouTube URLs) to BigQuery + GCS. `full` mode then exports the **kjbox song-identification index** (≈6.6M rows: MusicBrainz songs scored/kept by Spotify track popularity and **ListenBrainz** listeners (`lb_*` tables from karaoke-decide's `lb-refresh`), the Spotify snapshot ≥ 30, and all KN; ~8 GB scanned, ~25 s; `EXPORT DATA` → `gs://nomadkaraoke-kn-data/song-id/<run>/songs-*.tsv.gz`, manifest `song-id/latest.json`, last 3 runs kept), which the NomadPC downloads. Design: kjbox `docs/SONG-IDENTIFICATION.md` |
|
||||
| `divebar-lookup` | Daily 6:00 AM ET + on-demand API | Public search/lookup API for KJ Controller; rebuilds KN↔Divebar cross-reference index |
|
||||
|
||||
**Infrastructure** (Pulumi-managed in `infrastructure/`):
|
||||
@@ -535,16 +535,23 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Cloud Run Jobs (via WorkerService) │
|
||||
│ │
|
||||
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
|
||||
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
|
||||
│ audio-download-job - 30s-5 min typical; torrent waits ≤20/60 min │
|
||||
│ lyrics-transcription-job - 5-15 min (AudioShake + correction, us-east4)│
|
||||
│ bulk-search-job - batch audio search (us-east4) │
|
||||
│ audio-separation-job - 10-20 min (L4 GPU, us-east4, direct) │
|
||||
│ video-encoding-job - up to 60 min (optional) │
|
||||
│ video-encoding-job - up to 60 min (us-east4) │
|
||||
│ │
|
||||
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
|
||||
│ Job ID passed as: --job-id argument │
|
||||
│ (bulk-search-job takes --batch-id instead) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Job regions**: the CPU jobs a customer waits on (download, lyrics, bulk search, video/render) run in
|
||||
`us-east4` (`CPU_JOBS_REGION`), because Cloud Run Jobs in `us-central1` wait 2-5 min before the
|
||||
container starts. The bucket and GCE encoding VMs stay in `us-central1`. See TROUBLESHOOTING.md, "Cloud Run Jobs
|
||||
take 2-5 minutes to start".
|
||||
|
||||
**Why Cloud Run Jobs**: When using FastAPI BackgroundTasks, Cloud Run would terminate instances when HTTP requests completed, even if background work was still running. Cloud Run Jobs solve this by running workers as standalone processes that complete naturally. This applies to audio downloads (jobs 51b8231d, 89e497b1 were killed mid-download), lyrics transcription (job c94cc9d6 killed mid-processing), and audio separation.
|
||||
|
||||
**CLI Entry Points**: Each worker has a `main()` function for Cloud Run Job execution:
|
||||
|
||||
@@ -6,6 +6,38 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## Re-running the render pipeline: three ways the OLD output sneaks back in (Sep 2026, v0.253.0)
|
||||
|
||||
Building "re-render with the current theme" turned up three traps. Any path that re-runs screens/render/encode on a finished job (edit, visibility change, admin reset, theme re-render) has to handle all three.
|
||||
|
||||
1. **The encoding worker caches finished jobs by id** (in memory, `jobs[job_id]`). Resubmitting the same id while the VM is still up returns `"cached"` with the *previous* outputs. Render and encode now submit as `encoding_worker_job_id(job_id, worker_generation)` → `{job_id}_g{n}`. Every trigger bumps the generation, so re-runs are fresh, while a duplicate delivery of the same trigger still dedups.
|
||||
2. **The encoder finds title/end cards with `**/*Title*.mov` across everything under `jobs/{id}/`.** Deleting `screens/title.mov` isn't enough: it then picks up the old `finals/<Artist> - <Title> (Title).mov` and splices the old intro/outro around the new video. Delete the MOVs in `finals/` too (the visibility flow deletes all of `finals/`).
|
||||
3. **`outputs_deleted_at` (set by Edit) was only cleared when the re-render distributed to YouTube/Dropbox/GDrive.** Tenant and undistributed private jobs re-rendered fine but hid every download indefinitely (jobs 2579a1ea and 6452888e; the second was a customer's track, hidden for a month). Every successful render now clears it. Clear UI-hiding flags on the success path itself, never inside an optional side effect.
|
||||
|
||||
## Cloud Run Job start latency was the region, not our image (Sep 2026, v0.247.1)
|
||||
|
||||
Every us-central1 CPU Cloud Run Job (download, lyrics, encoding, error monitor, even decide's 203 MB
|
||||
image on 4 CPU) waited 2-5 min between "execution created" and the container starting. The obvious
|
||||
suspects were image size, lazy imports and CPU, and all three were wrong. The execution's `Started`
|
||||
condition fired about 10s before the first Python log, so Python wasn't the problem. The decisive
|
||||
test was a throwaway job running Google's tiny sample image in three regions:
|
||||
**us-central1 4-5 min, us-east4 8-19s, us-east1 8-25s.** All four us-central1 probes started in the
|
||||
same second, so executions are queued and released in batches on Google's side. Quotas were far from
|
||||
their limits.
|
||||
|
||||
- **Separate your own startup time from the platform's first.** Compare `status.startTime`, the
|
||||
`Started` condition's `lastTransitionTime`, and the first app log line. Only the last gap is ours.
|
||||
- **An A/B with a trivial image across regions** isolates platform behaviour in minutes and costs
|
||||
pennies. Do it before optimizing image size or imports.
|
||||
- **Measure cross-region transfer before assuming it's expensive.** Cloud Monitoring's
|
||||
`run.googleapis.com/container/network/received_bytes_count` (kind=google) gives bytes per job, and
|
||||
the Billing Catalog API gives exact SKU prices. `video-encoding-job` turned out to read only
|
||||
~156 GB/month, about $1.60/month after GCS's 100 GB free inter-region tier, so it moved too
|
||||
(v0.249.1). Writes to GCS from Cloud Run are free. Also push the image to a same-region registry so
|
||||
the multi-GB image never crosses regions (Artifact Registry egress).
|
||||
- **Keep region-for-jobs separate from `GCP_REGION`.** The workers still use `GCP_REGION` for other
|
||||
resources. Same lesson as `cloud_tasks_region` (job b8bda9c2).
|
||||
|
||||
## "Eager" prep keyed to the wrong pipeline stage silently became lazy (Sep 2026, v0.238.0)
|
||||
|
||||
**Symptom:** clicking the backing-vocals waveform in the preview modal played nothing for 7-15 s.
|
||||
@@ -1922,6 +1954,19 @@ carries the flag; the email now deep-links to
|
||||
- Any field a frontend filter branches on must be in `SUMMARY_FIELD_PATHS`, or
|
||||
it arrives `undefined` and the branch silently takes the wrong path.
|
||||
|
||||
**Recurrence (Sep 2026):** fiverrbot parks orders with no recommended audio at
|
||||
`awaiting_audio_selection` via `POST /api/audio-search/search` (owner
|
||||
`fiverr@nomadkaraoke.com`, not `made_for_you`), expecting the admin to click
|
||||
Select Audio in `/app` — and they were hidden by the same filter (job
|
||||
`bdf35771`). Worse, the viewer's **own** jobs were hidden too, so gen's
|
||||
"Choose different audio" (stalled-torrent recovery, v0.250.0) moved a job to
|
||||
this status and its card, with the picker it had just opened, vanished. The
|
||||
wizard reason for hiding no longer holds (the guided flow searches via
|
||||
`searchStandalone` and never creates a job at this status). Fix (v0.251.0): show
|
||||
every `awaiting_audio_selection` job. Admins get a "Show Jobs Awaiting Audio"
|
||||
switch in the account menu (`showAwaitingAudioJobs` in `lib/admin-settings.ts`,
|
||||
default on) that hides only **other accounts'** non-made-for-you jobs there.
|
||||
|
||||
---
|
||||
|
||||
## Spike-based alerting is blind to novel low-volume failures (NOMAD-1632 follow-up, v0.223.0)
|
||||
|
||||
@@ -27,10 +27,12 @@ human step.
|
||||
|
||||
## Retention policy
|
||||
|
||||
Keep every release from the **last 60 days**, plus the **newest release of each
|
||||
Keep every release from the **last 30 days**, plus the **newest release of each
|
||||
older calendar month**, plus the **latest release overall**. Delete the rest.
|
||||
Run recurringly, this holds steady-state around 6–7 GB — permanently under the
|
||||
cap. Deletion is irreversible and a deleted version/filename can never be
|
||||
cap. (The window was 60 days until 2026-09-29; at the current release rate a
|
||||
60-day window alone is ~9.6 GB, so a prune freed only ~1 GB and the cap refilled
|
||||
within a week.) Deletion is irreversible and a deleted version/filename can never be
|
||||
re-uploaded; that's acceptable here (nothing builds from source; PyPI is only the
|
||||
public `pip install` channel, whose users want recent versions).
|
||||
|
||||
@@ -72,8 +74,8 @@ python scripts/prune_pypi_releases.py --format console-js
|
||||
python scripts/prune_pypi_releases.py --format json
|
||||
python scripts/prune_pypi_releases.py --format markdown
|
||||
|
||||
# Tune the window (default 60 days) or target another project
|
||||
python scripts/prune_pypi_releases.py --keep-days 90 --project karaoke-gen
|
||||
# Tune the window (default 30 days) or target another project
|
||||
python scripts/prune_pypi_releases.py --keep-days 60 --project karaoke-gen
|
||||
```
|
||||
|
||||
Stdlib only — no dependencies to install.
|
||||
|
||||
@@ -57,6 +57,9 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Tenant "Re-render" with the current theme + edited tenant tracks no longer lose their downloads** (2026-09-30, v0.253.0): Finished portal tracks have a **Re-render** button (`POST /api/jobs/{id}/rerender`). It re-applies the tenant's current theme and rebuilds the screens, lyrics video, encodes and CDG/TXT from the already-reviewed lyrics, with no review step (`backend/services/theme_rerender_service.py`, same mechanism as the private→public visibility change). The encoding worker caches finished jobs by id in memory, so a re-run submitted while the VM was still up could get the previous render back. Render and encode now submit as `{job_id}_g{worker_generation}` (`encoding_worker_job_id`). Separately, `outputs_deleted_at` (set by Edit) was only cleared when the re-render uploaded to YouTube/Dropbox/GDrive, so edited tenant jobs re-rendered but hid every download (job 2579a1ea). Every successful render now clears it.
|
||||
- **Hold a word's resize handle at the row edge to keep extending it** (2026-09-30, v0.252.0): in the lyrics review Waveforms rows (and the Edit Segment timeline) the view is the segment ±1s and was fixed during a drag, so a word ending 5s+ too early took several drag-release cycles. Holding a resize handle within 24px of the edge it's heading toward (or past it) now keeps growing the word at 1–4 s/s (faster nearer the edge), zooming the view out so the handle stays under the cursor. It stops when the pointer leaves the zone, on release, or at the neighbouring word, including the next/previous line's first/last word (`computeNeighbourBoundsBySegment`), else the audio bounds. Drags are tracked on `window`, so leaving the row no longer abandons them, and resizes clamp to the neighbour instead of freezing short of it (`TimelineEditor.tsx`).
|
||||
- **Mismatched user instrumentals are lined up, not rejected + tenant bulk upload modal** (2026-09-29, v0.251.0): A Randy Vild bulk upload lost 3 of 10 tracks to the 0.5s duration check, and all three were valid edits of the same song: an extra 2.97s count-in on the instrumental, a 6.5s longer outro, and an outro 4.45s short. `uploads-complete` now conforms the instrumental to the mix instead of cancelling (`backend/services/instrumental_conform.py`, reusing `derived_vocals.find_offset`). It measures the offset at 25% and 75% of the song, trims/pads the start, and fades-and-cuts or pads the end. It still rejects files that don't correlate (wrong pairing, ~0.01 vs 0.78–0.90 for real pairs) or whose offset changes mid-song. The single-track tenant form and own-instrumental field now only check the size cap in the browser. Tenant bulk: shows `UploadProgressModal` for the whole batch (aggregate bytes, speed/ETA, tracks submitted/failed, offline notice); a job the server rejected is dropped so a retry creates a fresh job (previously a retry's 400 on the cancelled job was read as "already processing" and shown as Submitted).
|
||||
- **Vocal waveforms for own-instrumental jobs** (2026-09-26, v0.244.1): jobs with a user-supplied instrumental skip GPU separation, so the lyrics review Waveforms mode had no vocals stem (`/vocals-peaks` 404). The lyrics worker now derives approximate vocals on CPU, alongside transcription: it aligns the instrumental to the mix by FFT cross-correlation (±2s), fits a gain by least squares, and subtracts (`backend/services/derived_vocals.py`, numpy + ffmpeg, a few seconds). The result is stored as `stems.vocals_derived` (mono 22.05 kHz FLAC), which `vocals_stem_path` uses only as a last resort, so screens pre-computes the peaks as usual. It's waveform-only: never shipped as a deliverable stem, never downloaded by the remote CLI, and never used for the original-vocals guide. Safeguards: alignment correlates a fixed 60s excerpt (memory doesn't scale with track length); inputs over 20 min are skipped; ffmpeg calls time out; the handoff waits at most 3 min; nothing is registered when the instrumental didn't cancel (residual > 85% of the mix), since a full-mix envelope would mislead timing edits. Best-effort: any failure logs and the job proceeds.
|
||||
- **User-instrumental renders: WAV/M4A/OGG/AAC no longer fail** (2026-09-26, v0.243.1): the orchestrator render path sent only `instrumental_selection="custom"` to the GCE encoder, whose custom lookup accepted just `*custom_instrumental*.{flac,mp3}`. Tenant MP3s worked, but a `.wav` user instrumental failed with "No instrumental audio found" (job 3ea34552). The orchestrator now passes `existing_instrumental` (the encoder downloads it and matches any extension), and the custom lookup (`resolve_instrumental` in `gce_encoding/main.py`) accepts any audio extension.
|
||||
- **Crash reports carry diagnostics + breadcrumbs** (2026-09-26, v0.243.1): A Firefox "Uncaught out of memory" froze a tab mid-upload, and the alert was useless. The browser gave no Error object, so the reporter's own stack became the pattern, and that stack pushed URL/UA/build out of Discord's view (`extra` was never kept). Now `lib/diagnostics.ts` keeps a 30-entry breadcrumb trail (navigation, clicks, upload phases, errors) and snapshots page age, DOM/canvas/audio counts, live blob URLs and the JS heap (Chromium) into every report. Errors without an Error object are flagged `synthetic` (stack dropped, location kept) and group by message. One page load can send at most 20 reports. The alert sample now lists message → location → URL/UA/build → Diag → Trail → trimmed stack, and the full `extra` is logged as `client_extra` on `frontend_crash_reported`.
|
||||
|
||||
+91
-17
@@ -72,7 +72,10 @@ state *now* rather than wait for a forward fix to build and deploy.
|
||||
revision — instant, no rebuild), and
|
||||
- the three Cloud Run **jobs** that share the backend image
|
||||
(`video-encoding-job`, `lyrics-transcription-job`, `audio-separation-job`) by
|
||||
re-pinning them to a previous image tag. Cloud Run Jobs can't traffic-split, so
|
||||
re-pinning them to a previous image tag. `lyrics-transcription-job` runs in us-east4 from the
|
||||
`karaoke-backend-cpu` image copy. That copy only has tags from releases after the region move, so
|
||||
`rollback.sh` skips (with a warning) any job whose target tag is missing and re-pins the rest. `audio-download-job` and `bulk-search-job`
|
||||
track `:latest` and aren't re-pinned. Cloud Run Jobs can't traffic-split, so
|
||||
they are re-pinned; the old image takes effect on each job's **next** invocation
|
||||
(in-flight runs are unaffected).
|
||||
|
||||
@@ -133,6 +136,11 @@ runbook: **[docs/PYPI-STORAGE-PRUNE.md](PYPI-STORAGE-PRUNE.md)**.
|
||||
- **Torrent sources (RED/OPS)** → parks the job in `download_pending_retry` and keeps re-attempting the download for up to **24 hours** (handles rare tracks with few/intermittent seeders and transient tracker outages), then fails permanently with a clear message. No manual action needed. See `download_pending_retry` below.
|
||||
- **Other sources (YouTube/Spotify/URL)** → fails the job (deterministic); use the admin retry button to re-attempt.
|
||||
|
||||
**The stuck check needs a heartbeat.** A torrent wait can legitimately last 20-60 min
|
||||
(see "Audio download stalled" below), so while waiting the worker writes
|
||||
`state_data.audio_download_progress` (`progress`, `peers`, `at`) every 2 min. That bumps
|
||||
`updated_at`, so only a genuinely dead worker (no update for 10 min) gets parked.
|
||||
|
||||
**Manual recovery:**
|
||||
|
||||
```bash
|
||||
@@ -152,6 +160,33 @@ curl -X POST "https://api.nomadkaraoke.com/api/jobs/YOUR_JOB_ID/retry" \
|
||||
|
||||
---
|
||||
|
||||
## Audio download stalled ("Your audio hasn't started downloading after N minutes")
|
||||
|
||||
**Symptoms:** A `failed` job with `error_details.code == "audio_download_stalled"`. The job
|
||||
card shows an amber prompt with **Keep trying (up to 1 hour)** and **Choose different
|
||||
audio** instead of the raw error. Discord gets a 🟠 "Audio download stalled" alert.
|
||||
|
||||
**Cause:** A torrent (RED/OPS) made **no progress** for the whole stall budget, almost
|
||||
always because its only seeder is offline (flacfetch logs `peers: 0` on every re-announce).
|
||||
Seeders often come back soon; job 64be8a87 (2026-09-29) sat at 0 peers for 10 min, then
|
||||
finished in 17s on the next attempt. flacfetch ≥ 0.31 reports `error_code:
|
||||
"torrent_stalled"` for this case.
|
||||
|
||||
**Behaviour (v0.250.0+):**
|
||||
- First attempt waits **20 min** with no progress (`max_stall_seconds` sent per request to
|
||||
flacfetch; the Cloud Run execution timeout is overridden to fit, see
|
||||
`backend/services/audio_download_limits.py`).
|
||||
- On a stall the worker fails the job with the code above and exits 0, so there is **no
|
||||
Cloud Run auto-retry** of the same torrent. Other download failures still auto-retry.
|
||||
- **Keep trying** → `POST /api/jobs/{id}/retry {"keep_trying": true}`, which waits up to
|
||||
**60 min** (flacfetch's cap).
|
||||
- **Choose different audio** → `POST /api/jobs/{id}/choose-different-audio`, which sets the job
|
||||
back to `awaiting_audio_selection` with its saved results.
|
||||
|
||||
**Admin:** use the same buttons on the job card, or reset to "Audio" in admin.
|
||||
|
||||
---
|
||||
|
||||
## Job stuck at `downloading` or `audio_edit_complete` (no error)
|
||||
|
||||
Two known signatures (both fixed in v0.238.5, job 2c1b922e):
|
||||
@@ -741,31 +776,70 @@ client.run_job(request=run_v2.RunJobRequest(
|
||||
| Job Name | Region | Module | GPU |
|
||||
|----------|--------|--------|-----|
|
||||
| `audio-separation-job` | `us-east4` | `audio_worker` | L4 |
|
||||
| `lyrics-transcription-job` | `us-central1` | `lyrics_worker` | No |
|
||||
| `video-encoding-job` | `us-central1` | `video_worker` | No |
|
||||
| `audio-download-job` | `us-east4` | `audio_download_worker` | No |
|
||||
| `lyrics-transcription-job` | `us-east4` | `lyrics_worker` | No |
|
||||
| `bulk-search-job` | `us-east4` | `bulk_search_worker` | No |
|
||||
| `video-encoding-job` | `us-east4` | `video_worker` / `render_video_worker` | No |
|
||||
|
||||
The CPU jobs above run in `us-east4` (`CPU_JOBS_REGION`) even though everything else lives in
|
||||
`us-central1`. See "Cloud Run Jobs take 2-5 minutes to start" below.
|
||||
|
||||
---
|
||||
|
||||
## CI does not update `lyrics-transcription-job` image
|
||||
## Cloud Run Jobs take 2-5 minutes to start
|
||||
|
||||
**Symptoms:** Deployed code fixes don't take effect for lyrics processing. The backend service shows the new version, but lyrics jobs still crash with the old bug.
|
||||
**Symptoms:** A job execution sits between "created" and its first Python log line for 2-5 minutes.
|
||||
`gcloud run jobs executions describe <exec>` shows `Started deployed execution in 3m...`. Concurrent
|
||||
executions often start in the same second, as if a queue drained.
|
||||
|
||||
**Cause:** The CI workflow (`.github/workflows/ci.yml`) updates `audio-separation-job` and `video-encoding-job` after deploy, but does NOT update `lyrics-transcription-job`. The job uses the `:latest` tag, but Cloud Run Jobs resolve the tag to a digest at update time — pushing a new `:latest` image doesn't automatically update running jobs.
|
||||
**Cause:** Google-side scheduling of Cloud Run **Jobs** in `us-central1`. It doesn't depend on our
|
||||
image, CPU or code. Measured 2026-09-28 with Google's tiny sample job image
|
||||
(`us-docker.pkg.dev/cloudrun/container/job`) on 1 CPU: `us-central1` took 4-5 min, while `us-east4`
|
||||
and `us-east1` took 8-25s. decide's 203 MB image on 4 CPU was just as slow in `us-central1`, so
|
||||
slimming our image or adding CPU doesn't help. Quotas were nowhere near their limits.
|
||||
|
||||
**Manual fix after deploy:**
|
||||
**Fix in place:** the latency-critical CPU jobs (`audio-download-job`, `lyrics-transcription-job`,
|
||||
`bulk-search-job`, `video-encoding-job`) run in `us-east4`. The backend setting is `CPU_JOBS_REGION` (default `us-east4`),
|
||||
and the Pulumi constant `CPU_JOBS_REGION` must match it (a unit test checks this). CI pushes a copy of
|
||||
the CPU image to `us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-cpu` so the
|
||||
jobs pull from their own region. Inside the jobs, `GCP_REGION` stays `us-central1`. A new image digest takes a
|
||||
one-time ~2.5 min "Container image import" on its first execution in a region, so after each
|
||||
deploy CI starts one no-op `audio-download-job` execution (`python -c pass`) to do that import.
|
||||
`video-encoding-job` (video + post-review render) moved in v0.249.1. It reads about 0.3 GB per run
|
||||
from the us-central1 bucket, which is roughly 156 GB/month cross-region: about $1.60/month after
|
||||
GCS's 100 GB/month free inter-region tier, or $3/month worst case. Its writes to GCS and its
|
||||
internet uploads cost the same from either region. The GCE encoding VMs stay in `us-central1`; they
|
||||
have public IPs (port 8080, API key), so the job reaches them from us-east4.
|
||||
|
||||
**Measure:**
|
||||
```bash
|
||||
# Pin to the specific version tag (preferred)
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:vX.Y.Z \
|
||||
--region us-central1 --project nomadkaraoke
|
||||
|
||||
# Or force re-resolve :latest
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:latest \
|
||||
--region us-central1 --project nomadkaraoke
|
||||
for e in $(gcloud run jobs executions list --job audio-download-job --region us-east4 \
|
||||
--project nomadkaraoke --limit 8 --format='value(name)'); do
|
||||
gcloud run jobs executions describe $e --region us-east4 --project nomadkaraoke --format=json \
|
||||
| jq -r '[.metadata.creationTimestamp, (.status.conditions[]|select(.type=="Started")|.message)]|@tsv'
|
||||
done
|
||||
```
|
||||
|
||||
**Permanent fix:** Add `lyrics-transcription-job` update to CI deploy step in `.github/workflows/ci.yml` alongside the existing `video-encoding-job` and `audio-separation-job` updates (~line 1568).
|
||||
**Rollback to us-central1.** The legacy us-central1 copies were removed on 2026-09-30, after the
|
||||
us-east4 jobs were verified in prod. To move back:
|
||||
1. **Add** the us-central1 jobs in Pulumi alongside the us-east4 ones: in `infrastructure/__main__.py`,
|
||||
add `create_*_job(bucket, backend_service_account)` calls with no `region=` argument, so they use
|
||||
the default region and the `karaoke-repo` image. Run `pulumi up`. Don't change the
|
||||
`CPU_JOBS_REGION` constant yet, because that would replace the us-east4 jobs the live backend is
|
||||
still using.
|
||||
2. **Switch** the backend with the env var, not the constants. Add `CPU_JOBS_REGION=us-central1` to
|
||||
the service's `--set-env-vars` in `ci.yml`, and point the CI "Update Cloud Run Jobs" step at
|
||||
us-central1 and `karaoke-repo`. Changing the Pulumi constant now would re-point the us-east4
|
||||
declarations onto the same logical names as the step-1 jobs. Deploy, and confirm new executions
|
||||
land in us-central1. The download/bulk-search/video jobs trigger other jobs, so add the same env
|
||||
var to the us-central1 job definitions from step 1.
|
||||
3. **Remove** the us-east4 job declarations in Pulumi, then set both `CPU_JOBS_REGION` defaults
|
||||
(`backend/config.py` and `infrastructure/modules/cloud_run.py`; a unit test enforces that they
|
||||
match) to `us-central1`. Run `pulumi up`. Update `scripts/rollback.sh` to use us-central1 and the
|
||||
`karaoke-repo` image.
|
||||
|
||||
A rollback of the backend service to before v0.247.1 also needs step 1 first, because older revisions
|
||||
trigger the jobs in us-central1.
|
||||
|
||||
## Frontend error alert ("New Error Pattern Detected", service `frontend`)
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# Tenant self-service theme editor — plan (2026-09-29)
|
||||
|
||||
## Goal
|
||||
Tenant portal users (every allowed user of the tenant) can edit their tenant's theme from their own
|
||||
portal — a **"Theme & style"** item in the user menu opens an editor modal with a guided form, an
|
||||
Advanced JSON tab, and **exact server-rendered previews** (title card + a karaoke frame with a
|
||||
partly-sung line) that refresh as they edit. **Save applies to new jobs only** (jobs copy the theme at
|
||||
creation, unchanged).
|
||||
|
||||
Decisions (Andrew, 2026-09-29): editors = every allowed tenant user; previews = server-rendered exact;
|
||||
scope = guided form + advanced JSON; apply = new jobs only.
|
||||
|
||||
## Backend
|
||||
|
||||
### Membership guard (security-critical)
|
||||
`X-Tenant-ID` is client-controlled and magic-link sessions carry no tenant id, so a new dependency
|
||||
`require_tenant_member` (in `backend/api/routes/tenant_theme.py`):
|
||||
- tenant config must resolve from the request (`request.state.tenant_config`) and be `is_active`;
|
||||
- `auth_result.tenant_id` must be None or equal to that tenant id;
|
||||
- `config.is_email_allowed(auth_result.user_email)` (allowlist; admins always pass).
|
||||
Otherwise 403. (Same rule as `JobManager._is_tenant_billed`; do NOT copy `tenant_bulk.py`, which only
|
||||
checks the tenant exists.)
|
||||
|
||||
### Endpoints — `/api/tenant/theme` (new router, registered in `main.py`)
|
||||
- `GET` → `{theme_id, style_params, assets[], fonts[]}` (fonts = bundled `karaoke_gen.resources`
|
||||
fonts + uploaded .ttf/.otf assets).
|
||||
- `POST /assets` (multipart, one file) → stores under `themes/<id>/assets/<stem>-<sha8>.<ext>`
|
||||
(content-addressed ⇒ never overwrites an asset a live job/theme uses; `no-store`), returns the
|
||||
basename. Images ≤15 MB, fonts ttf/otf. Reuses `_read_asset` validation.
|
||||
- `POST /preview` (JSON `{style_params, sample?: {artist,title}}`) → `{title_card, karaoke_frame}`
|
||||
as `data:image/jpeg;base64` (1280×720). Draft is NOT saved.
|
||||
- `PUT` (JSON `{style_params}`) → sanitize + validate, then `update_tenant(style_params=...)` with
|
||||
`config_updates=None, logo=None` (tenants can't touch their own config/allowlist).
|
||||
|
||||
### Sanitization (tenant saves + previews)
|
||||
`_validate_style_params` is shallow; tenant input additionally:
|
||||
- asset fields (`intro/end.background_image`, `intro/end.font`, `karaoke.background_image`,
|
||||
`karaoke.font_path`, cdg asset fields) must be **bare basenames** that exist in the theme's assets
|
||||
or bundled fonts (reject `/…`, `gs://…`, `..`);
|
||||
- **font consistency**: render pipeline only downloads one `font` asset (from `intro.font`) and uses
|
||||
it for every section → the guided font picker sets `intro.font`, `end.font`, `karaoke.font_path`,
|
||||
`cdg.font_path` together and derives `karaoke.font` (the ASS family name libass matches) from the
|
||||
TTF via PIL `ImageFont.getname()`. Save rejects a karaoke `font_path` ≠ `intro.font`.
|
||||
- numeric bounds (font_size 40–600, top_padding 0–2000, max_line_length 10–80, regions inside 3840×2160).
|
||||
|
||||
### Preview renderer — `backend/services/theme_preview_service.py`
|
||||
- Resolve assets: download referenced theme assets (by basename) from GCS to a per-tenant temp cache
|
||||
keyed by generation; bundled fonts from `karaoke_gen.resources`.
|
||||
- **Title card**: `VideoGenerator(...).create_title_video(artist, title, format, noext, video_path,
|
||||
intro_video_duration=0)` → PNG, format = `{**DEFAULT_INTRO_STYLE, **intro}` with local paths
|
||||
(same call production `screens_worker` makes). Downscale → JPEG.
|
||||
- **Karaoke frame**: `k = {**DEFAULT_KARAOKE_STYLE, **karaoke}` (build_karaoke_styles needs
|
||||
underline/strike_out/angle/encoding/ass_name); fake `LyricsSegment`s (first start <10 s, gaps <10 s
|
||||
to avoid SectionDetector intro/instrumental screens) through `SegmentResizer(max_line_length)`;
|
||||
`SubtitlesGenerator(..., video_resolution=(3840,2160), font_size, line_height=font_size,
|
||||
styles={"karaoke": k}).generate_ass(...)`; ffmpeg single frame at a timestamp mid-way through
|
||||
line 2 (`-ss T -frames:v 1`, same bg input as `output/video.py`, `ass=…:fontsdir=…,scale=1280:-2`).
|
||||
- Concurrency: module semaphore (1–2) + dedicated executor, 20 s timeout, like
|
||||
`review._render_preview_locally`. Cache identical drafts (hash of style_params+sample) briefly.
|
||||
|
||||
## Frontend
|
||||
- `AuthStatus` menu: **"Theme & style"** item when `!useTenant().isDefault` → `TenantThemeEditorDialog`.
|
||||
- `components/tenant-theme/`: dialog (wide), two tabs:
|
||||
- **Guided**: Title card (background image upload / colour, title colour, artist colour, text case,
|
||||
vertical position + size of title/artist), Karaoke (background image / colour, sung, unsung,
|
||||
outline colours, font size, lyrics top position, max line length), End screen (closing text +
|
||||
colour), Font (bundled list + upload).
|
||||
- **Advanced**: validated full-theme JSON editor.
|
||||
- Right/top: title-card + karaoke previews, debounced ~700 ms after edits, stale requests aborted,
|
||||
spinner overlay, error state. Save / Discard; unsaved-changes guard on close.
|
||||
- `lib/api.ts`: `tenantThemeApi.{get, uploadAsset, preview, save}` via `getAuthHeaders()`.
|
||||
- i18n: all strings in `messages/en.json` (`tenantTheme.*`), translate all 33 locales.
|
||||
|
||||
## Tests
|
||||
- **pytest**: membership guard (non-member 403, spoofed `X-Tenant-ID` 403, inactive tenant 403,
|
||||
member/admin 200); sanitization (absolute/gs:// paths rejected, font consistency, bounds);
|
||||
asset upload naming (content-addressed, no overwrite); save uses `update_tenant` without
|
||||
config/logo; preview service renders real PNGs from a fixture theme (colour background + bundled
|
||||
font) — title card + karaoke frame non-empty and differ when sung colour changes (skip if ffmpeg
|
||||
absent locally; CI has it).
|
||||
- **Jest**: dialog loads theme, editing a colour triggers a debounced preview call, Advanced JSON
|
||||
validation blocks save, save sends sanitized style_params, menu item only on tenant portals.
|
||||
- **Playwright production E2E** (`e2e/production/tenant-theme-editor.spec.ts`): on the randy-vild
|
||||
portal as admin, open editor, change sung colour, previews refresh, Discard (no persistent change).
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Tests for the persisted admin settings store.
|
||||
*/
|
||||
import { useAdminSettings } from '../lib/admin-settings';
|
||||
|
||||
describe('useAdminSettings', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useAdminSettings.setState({ showTestData: false, showAwaitingAudioJobs: true });
|
||||
});
|
||||
|
||||
it('defaults to hiding test data and showing jobs awaiting audio', () => {
|
||||
const state = useAdminSettings.getState();
|
||||
expect(state.showTestData).toBe(false);
|
||||
expect(state.showAwaitingAudioJobs).toBe(true);
|
||||
});
|
||||
|
||||
it('toggles showAwaitingAudioJobs and persists it to localStorage', () => {
|
||||
useAdminSettings.getState().setShowAwaitingAudioJobs(false);
|
||||
expect(useAdminSettings.getState().showAwaitingAudioJobs).toBe(false);
|
||||
const persisted = JSON.parse(localStorage.getItem('admin-settings') || '{}');
|
||||
expect(persisted.state.showAwaitingAudioJobs).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -152,13 +152,13 @@ describe('Admin Tenants page', () => {
|
||||
expect(config.auth.allowed_emails).toEqual(['randy@gmail.com', 'andrew@example.com'])
|
||||
})
|
||||
|
||||
it('warns when the portal is open to anyone', async () => {
|
||||
it('warns when no client can sign in yet', async () => {
|
||||
render(<AdminTenantsPage />)
|
||||
await screen.findByText('Vocal Star')
|
||||
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
|
||||
fireEvent.change(await screen.findByLabelText(/allowed emails/i), { target: { value: '' } })
|
||||
fireEvent.change(screen.getByLabelText(/allowed email domains/i), { target: { value: '' } })
|
||||
expect(screen.getByText(/anyone can sign in/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/only nomad karaoke admins can sign in/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows domain status and can set up a missing domain', async () => {
|
||||
@@ -202,12 +202,12 @@ describe('Admin Tenants page', () => {
|
||||
|
||||
|
||||
describe('Admin Tenants page — access warning edge cases', () => {
|
||||
it('treats separator-only input as an open portal (matches what Save sends)', async () => {
|
||||
it('treats separator-only input as no client access (matches what Save sends)', async () => {
|
||||
render(<AdminTenantsPage />)
|
||||
await screen.findByText('Vocal Star')
|
||||
fireEvent.click(screen.getByRole('button', { name: /manage/i }))
|
||||
fireEvent.change(await screen.findByLabelText(/allowed emails/i), { target: { value: ' , ' } })
|
||||
fireEvent.change(screen.getByLabelText(/allowed email domains/i), { target: { value: ',' } })
|
||||
expect(screen.getByText(/anyone can sign in/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/only nomad karaoke admins can sign in/i)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -788,17 +788,46 @@ describe('isVisibilityChangeInProgress', () => {
|
||||
});
|
||||
|
||||
describe('shouldShowJobOnDashboard', () => {
|
||||
const viewer = { viewerEmail: 'andrew@nomadkaraoke.com' };
|
||||
const fiverrJob = { status: 'awaiting_audio_selection', user_email: 'fiverr@nomadkaraoke.com' };
|
||||
const ownJob = { status: 'awaiting_audio_selection', user_email: 'Andrew@NomadKaraoke.com' };
|
||||
|
||||
it('shows normal (non-audio-selection) jobs', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'complete' })).toBe(true);
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_review' })).toBe(true);
|
||||
});
|
||||
|
||||
it('hides self-service jobs still in the guided-flow at awaiting_audio_selection', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection' })).toBe(false);
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection', made_for_you: false })).toBe(false);
|
||||
it('shows awaiting_audio_selection jobs by default', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection' })).toBe(true);
|
||||
expect(shouldShowJobOnDashboard(fiverrJob, viewer)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps made-for-you orders visible even at awaiting_audio_selection', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection', made_for_you: true })).toBe(true);
|
||||
it("shows the viewer's own job after 'Choose different audio'", () => {
|
||||
expect(shouldShowJobOnDashboard(ownJob, viewer)).toBe(true);
|
||||
});
|
||||
|
||||
describe('with the admin toggle off', () => {
|
||||
const off = { ...viewer, showOthersAwaitingAudio: false };
|
||||
|
||||
it("hides other accounts' jobs (e.g. fiverrbot)", () => {
|
||||
expect(shouldShowJobOnDashboard(fiverrJob, off)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the viewer's own jobs (case-insensitive)", () => {
|
||||
expect(shouldShowJobOnDashboard(ownJob, off)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps made-for-you orders visible', () => {
|
||||
expect(shouldShowJobOnDashboard({ ...fiverrJob, made_for_you: true }, off)).toBe(true);
|
||||
});
|
||||
|
||||
it('hides jobs whose owner or viewer is unknown', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection' }, off)).toBe(false);
|
||||
expect(shouldShowJobOnDashboard(fiverrJob, { showOthersAwaitingAudio: false })).toBe(false);
|
||||
});
|
||||
|
||||
it('does not affect jobs at other statuses', () => {
|
||||
expect(shouldShowJobOnDashboard({ ...fiverrJob, status: 'complete' }, off)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,7 @@ jest.mock('@/lib/api', () => ({
|
||||
createJobWithUploadUrls: jest.fn(),
|
||||
uploadToSignedUrl: jest.fn(),
|
||||
completeJobUpload: jest.fn(),
|
||||
getJob: jest.fn(),
|
||||
},
|
||||
ApiError: class ApiError extends Error {
|
||||
status: number
|
||||
@@ -119,6 +120,7 @@ beforeEach(() => {
|
||||
}))
|
||||
mockApi.uploadToSignedUrl.mockResolvedValue(undefined)
|
||||
mockApi.completeJobUpload.mockResolvedValue({ status: 'success', message: 'started' })
|
||||
;(mockApi.getJob as jest.Mock).mockResolvedValue({ status: 'pending' })
|
||||
})
|
||||
|
||||
it('analyze populates one editable row per proposed pair and lists warnings', async () => {
|
||||
@@ -319,6 +321,230 @@ it('offers to resume an unfinished batch and resumes without re-creating jobs',
|
||||
expect(mockUploadResumable.mock.calls.map(c => c[0])).toEqual(['https://session/audio', 'https://session/inst'])
|
||||
})
|
||||
|
||||
it('shows a batch-wide upload modal with byte progress, track counts and connection state', async () => {
|
||||
// Two 1 MB rows (mixed + instrumental each 512 KB) so aggregate bytes are exact.
|
||||
const half = 'x'.repeat(512 * 1024)
|
||||
const bigFiles = [MIXED_1, INST_1, MIXED_2, INST_2].map(name => new File([half], name, { type: 'audio/mpeg' }))
|
||||
mockApi.createJobWithUploadUrls.mockImplementation(async () => ({
|
||||
status: 'success',
|
||||
job_id: `job-${Math.random().toString(36).slice(2, 8)}`,
|
||||
message: 'ok',
|
||||
upload_urls: [
|
||||
{ file_type: 'audio', gcs_path: 'p1', upload_url: 'https://session/audio', content_type: 'audio/mpeg', resumable: true },
|
||||
{ file_type: 'existing_instrumental', gcs_path: 'p2', upload_url: 'https://session/inst', content_type: 'audio/mpeg', resumable: true },
|
||||
],
|
||||
server_version: '1',
|
||||
}))
|
||||
// Hold every upload open so the test can drive progress by hand.
|
||||
const pending: { onProgress: (p: any) => void; resolve: () => void }[] = []
|
||||
mockUploadResumable.mockImplementation((_url, _file, opts: any) =>
|
||||
new Promise<void>(resolve => { pending.push({ onProgress: opts.onProgress, resolve }) }))
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
fireEvent.change(screen.getByTestId('bulk-files-input'), { target: { files: bigFiles } })
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 2 tracks/i }))
|
||||
|
||||
const modal = await screen.findByTestId('upload-progress-modal')
|
||||
expect(within(modal).getByText('Uploading 2 tracks')).toBeInTheDocument()
|
||||
await waitFor(() => expect(pending).toHaveLength(2)) // both rows' mixed files in flight
|
||||
|
||||
// Row 1 has sent 512 KB of its 1 MB → 25% of the 2 MB batch.
|
||||
const { act } = await import('react')
|
||||
act(() => pending[0].onProgress({ loaded: 512 * 1024, bytesPerSecond: 1024, state: 'uploading' }))
|
||||
expect(within(modal).getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25')
|
||||
expect(within(modal).getByText(/0\.5 MB of 2\.0 MB/)).toBeInTheDocument()
|
||||
expect(within(modal).getByTestId('upload-progress-detail')).toHaveTextContent('0 of 2 tracks submitted')
|
||||
|
||||
// The resumable engine waiting for the network surfaces as a notice.
|
||||
act(() => pending[1].onProgress({ loaded: 0, bytesPerSecond: null, state: 'waiting-online' }))
|
||||
expect(within(modal).getByText(/Waiting for connection/)).toBeInTheDocument()
|
||||
|
||||
// Finish row 1 (mixed then instrumental) → 1 of 2 submitted.
|
||||
act(() => pending[0].resolve())
|
||||
await waitFor(() => expect(pending).toHaveLength(3))
|
||||
act(() => pending[2].resolve())
|
||||
await waitFor(() => expect(screen.getByTestId('upload-progress-detail')).toHaveTextContent('1 of 2 tracks submitted'))
|
||||
|
||||
// Finish row 2 → modal closes and the done summary shows.
|
||||
act(() => pending[1].resolve())
|
||||
await waitFor(() => expect(pending).toHaveLength(4))
|
||||
act(() => pending[3].resolve())
|
||||
await waitFor(() => expect(screen.queryByTestId('upload-progress-modal')).not.toBeInTheDocument())
|
||||
expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('drops a failed row out of the modal totals and reports it', async () => {
|
||||
mockApi.uploadToSignedUrl.mockRejectedValueOnce(new Error('network blip'))
|
||||
let releaseSecond: () => void = () => {}
|
||||
mockApi.uploadToSignedUrl.mockImplementation(() => new Promise<void>(r => { releaseSecond = r }))
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 2 tracks/i }))
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('upload-progress-detail')).toHaveTextContent('1 failed'))
|
||||
const { act } = await import('react')
|
||||
// Let the surviving row finish; the modal closes and the failed row stays retryable.
|
||||
for (let i = 0; i < 2; i++) {
|
||||
act(() => releaseSecond())
|
||||
await new Promise(r => setTimeout(r, 0))
|
||||
}
|
||||
await waitFor(() => expect(screen.queryByTestId('upload-progress-modal')).not.toBeInTheDocument())
|
||||
expect(screen.getByText(/will retry on submit/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('a job the server rejected is retried as a fresh job, not re-finalized', async () => {
|
||||
// Regression: a duration-mismatch 400 cancels the job server-side. The row
|
||||
// used to keep the cancelled jobId, and the retry's 400 ("not pending") was
|
||||
// then mistaken for "already processing" — showing Submitted for a dead job.
|
||||
const { ApiError } = jest.requireMock('@/lib/api')
|
||||
mockApi.analyzeBulk.mockResolvedValue({
|
||||
rows: [{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'high', warning: null }],
|
||||
unpaired: [],
|
||||
ignored: [],
|
||||
})
|
||||
mockApi.completeJobUpload
|
||||
.mockRejectedValueOnce(new ApiError('Duration mismatch: cancelled', 400))
|
||||
.mockResolvedValueOnce({ status: 'success', message: 'started' })
|
||||
;(mockApi.getJob as jest.Mock).mockResolvedValueOnce({ status: 'cancelled' })
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(screen.getByText(/Duration mismatch: cancelled/)).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(2))
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(2)
|
||||
const [first, second] = mockApi.completeJobUpload.mock.calls.map(c => c[0])
|
||||
expect(second).not.toBe(first)
|
||||
expect(markRowDone).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('a recovered row whose job was cancelled is not reported as submitted', async () => {
|
||||
const { ApiError } = jest.requireMock('@/lib/api')
|
||||
const mixedFile = new File(['x'], MIXED_1, { type: 'audio/mpeg', lastModified: 111 })
|
||||
const instFile = new File(['x'], INST_1, { type: 'audio/mpeg', lastModified: 222 })
|
||||
mockLoadPendingBatch.mockResolvedValue({
|
||||
batchId: 'b', rows: [{
|
||||
key: 'b:row-1', batchId: 'b', rowId: 'row-1', jobId: 'job-dead', artist: 'Eddy Grant', title: 'I Dont Wanna Dance', createdAt: Date.now(),
|
||||
files: [
|
||||
{ fileType: 'audio', identity: MIXED_1, name: MIXED_1, size: 1, lastModified: 111, sessionUri: 'https://session/audio' },
|
||||
{ fileType: 'existing_instrumental', identity: INST_1, name: INST_1, size: 1, lastModified: 222, sessionUri: 'https://session/inst' },
|
||||
],
|
||||
}],
|
||||
})
|
||||
mockApi.completeJobUpload.mockRejectedValueOnce(new ApiError('Job is not pending', 400))
|
||||
;(mockApi.getJob as jest.Mock).mockResolvedValue({ job_id: 'job-dead', status: 'cancelled' })
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
await screen.findByTestId('resume-banner')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Choose folder to resume/i }))
|
||||
fireEvent.change(screen.getByTestId('bulk-folder-input'), { target: { files: [mixedFile, instFile] } })
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/Job is not pending/)).toBeInTheDocument())
|
||||
expect(mockApi.getJob).toHaveBeenCalledWith('job-dead')
|
||||
expect(screen.queryByText(/Submitted/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('a recovered row whose job is already processing counts as submitted', async () => {
|
||||
const { ApiError } = jest.requireMock('@/lib/api')
|
||||
const mixedFile = new File(['x'], MIXED_1, { type: 'audio/mpeg', lastModified: 111 })
|
||||
const instFile = new File(['x'], INST_1, { type: 'audio/mpeg', lastModified: 222 })
|
||||
mockLoadPendingBatch.mockResolvedValue({
|
||||
batchId: 'b', rows: [{
|
||||
key: 'b:row-1', batchId: 'b', rowId: 'row-1', jobId: 'job-live', artist: 'Eddy Grant', title: 'I Dont Wanna Dance', createdAt: Date.now(),
|
||||
files: [
|
||||
{ fileType: 'audio', identity: MIXED_1, name: MIXED_1, size: 1, lastModified: 111, sessionUri: 'https://session/audio' },
|
||||
{ fileType: 'existing_instrumental', identity: INST_1, name: INST_1, size: 1, lastModified: 222, sessionUri: 'https://session/inst' },
|
||||
],
|
||||
}],
|
||||
})
|
||||
mockApi.completeJobUpload.mockRejectedValueOnce(new ApiError('Job is not pending', 400))
|
||||
;(mockApi.getJob as jest.Mock).mockResolvedValue({ job_id: 'job-live', status: 'transcribing' })
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
await screen.findByTestId('resume-banner')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Choose folder to resume/i }))
|
||||
fireEvent.change(screen.getByTestId('bulk-folder-input'), { target: { files: [mixedFile, instFile] } })
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/All tracks submitted/i)).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('a first-time row whose finalize response was lost but job started is not duplicated', async () => {
|
||||
// The server accepted uploads-complete but the response was lost; the
|
||||
// client's retry of the call then gets a 400 "not pending". The job is
|
||||
// processing, so the row is done — no second job.
|
||||
const { ApiError } = jest.requireMock('@/lib/api')
|
||||
mockApi.analyzeBulk.mockResolvedValue({
|
||||
rows: [{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'high', warning: null }],
|
||||
unpaired: [],
|
||||
ignored: [],
|
||||
})
|
||||
mockApi.completeJobUpload.mockRejectedValueOnce(new ApiError('Job is not pending', 400))
|
||||
;(mockApi.getJob as jest.Mock).mockResolvedValue({ status: 'transcribing' })
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/All tracks submitted/i)).toBeInTheDocument())
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('a 400 on a still-pending job keeps the job for retry (no duplicate)', async () => {
|
||||
const { ApiError } = jest.requireMock('@/lib/api')
|
||||
mockApi.analyzeBulk.mockResolvedValue({
|
||||
rows: [{ artist: 'Eddy Grant', title: 'I Dont Wanna Dance', mixed_filename: MIXED_1, instrumental_filename: INST_1, confidence: 'high', warning: null }],
|
||||
unpaired: [],
|
||||
ignored: [],
|
||||
})
|
||||
mockApi.completeJobUpload
|
||||
.mockRejectedValueOnce(new ApiError('File not uploaded', 400))
|
||||
.mockResolvedValueOnce({ status: 'success', message: 'started' })
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
selectFiles()
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(screen.getByText(/File not uploaded/)).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 1 tracks/i }))
|
||||
await waitFor(() => expect(mockApi.completeJobUpload).toHaveBeenCalledTimes(2))
|
||||
expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledTimes(1)
|
||||
const [first, second] = mockApi.completeJobUpload.mock.calls.map(c => c[0])
|
||||
expect(second).toBe(first)
|
||||
})
|
||||
|
||||
it('rows queued for retry are not counted as failed in the modal', async () => {
|
||||
// Four rows fail, then are retried: only 3 start at once, the 4th waits.
|
||||
const rows4 = [1, 2, 3, 4].map(i => ({ artist: 'A', title: `S${i}`, mixed_filename: `m${i}.mp3`, instrumental_filename: `i${i}.mp3`, confidence: 'high', warning: null }))
|
||||
mockApi.analyzeBulk.mockResolvedValue({ rows: rows4, unpaired: [], ignored: [] })
|
||||
const files = rows4.flatMap(r => [new File(['x'], r.mixed_filename, { type: 'audio/mpeg' }), new File(['x'], r.instrumental_filename, { type: 'audio/mpeg' })])
|
||||
mockApi.createJobWithUploadUrls.mockRejectedValue(new Error('backend down'))
|
||||
|
||||
render(<TenantBulkFlow onJobsChanged={jest.fn()} />)
|
||||
fireEvent.change(screen.getByTestId('bulk-files-input'), { target: { files } })
|
||||
await screen.findAllByLabelText('Artist')
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 4 tracks/i }))
|
||||
await waitFor(() => expect(screen.getAllByText(/will retry on submit/i)).toHaveLength(4))
|
||||
|
||||
// Retry with creation hanging, so rows stay queued / in flight.
|
||||
mockApi.createJobWithUploadUrls.mockImplementation(() => new Promise(() => {}))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Submit 4 tracks/i }))
|
||||
const detail = await screen.findByTestId('upload-progress-detail')
|
||||
expect(detail).toHaveTextContent('0 of 4 tracks submitted')
|
||||
expect(detail).not.toHaveTextContent('failed')
|
||||
})
|
||||
|
||||
it('matchRepickedFile requires an exact size and disambiguates by mtime', () => {
|
||||
const { matchRepickedFile } = jest.requireActual('@/lib/upload-recovery')
|
||||
const persisted = { fileType: 'audio', identity: 'a.mp3', name: 'a.mp3', size: 1, lastModified: 111, sessionUri: 's' }
|
||||
|
||||
@@ -65,7 +65,7 @@ function AppPageContent() {
|
||||
// Bulk mode is available on the default portal (search-based) and on tenant
|
||||
// portals with the bulk_upload feature (folder upload + auto-pair).
|
||||
const showBulkToggle = isDefaultTenant || tenantFeatures.bulk_upload
|
||||
const { showTestData } = useAdminSettings()
|
||||
const { showTestData, showAwaitingAudioJobs } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
const saved = localStorage.getItem("nomad-karaoke-job-limit")
|
||||
@@ -102,11 +102,16 @@ function AppPageContent() {
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
|
||||
|
||||
// Hide self-service jobs still in the guided-flow wizard, but keep made-for-you orders
|
||||
// visible even at awaiting_audio_selection (see shouldShowJobOnDashboard).
|
||||
// Admins can hide other accounts' jobs parked at awaiting_audio_selection
|
||||
// (see shouldShowJobOnDashboard); everyone else sees all of their jobs.
|
||||
const viewerEmail = user?.email
|
||||
const showOthersAwaitingAudio = isAdmin ? showAwaitingAudioJobs : true
|
||||
const jobs = useMemo(
|
||||
() => sortJobs(allJobs.filter(shouldShowJobOnDashboard), sortField, sortDirection, locale),
|
||||
[allJobs, sortField, sortDirection, locale]
|
||||
() => sortJobs(
|
||||
allJobs.filter((job) => shouldShowJobOnDashboard(job, { viewerEmail, showOthersAwaitingAudio })),
|
||||
sortField, sortDirection, locale,
|
||||
),
|
||||
[allJobs, sortField, sortDirection, locale, viewerEmail, showOthersAwaitingAudio]
|
||||
)
|
||||
|
||||
// Debounce search input — only update the query (which triggers API calls) after 300ms
|
||||
|
||||
@@ -114,12 +114,15 @@ function VerifyMagicLinkContent() {
|
||||
}
|
||||
}
|
||||
|
||||
// Show appropriate interstitial based on credit status
|
||||
if (status === "granted" && credits > 0) {
|
||||
// Show appropriate interstitial based on credit status. Never on a tenant
|
||||
// portal — tenants don't use consumer credits (backend sends not_applicable;
|
||||
// this is defence in depth).
|
||||
const isTenantLogin = !!lastVerifyResponse?.tenant_subdomain
|
||||
if (!isTenantLogin && status === "granted" && credits > 0) {
|
||||
setState("credits_granted")
|
||||
} else if (status === "denied") {
|
||||
} else if (!isTenantLogin && status === "denied") {
|
||||
setState("credits_denied")
|
||||
} else if (status === "pending_review") {
|
||||
} else if (!isTenantLogin && status === "pending_review") {
|
||||
setState("credits_pending")
|
||||
} else {
|
||||
// Returning user or not applicable — go to the intended destination.
|
||||
|
||||
@@ -554,7 +554,7 @@ export default function AdminTenantsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-2">
|
||||
Comma-separated. Who can sign in to the portal. Both blank = anyone. Nomad Karaoke admins can always sign in.
|
||||
Comma-separated. Who can sign in to the portal. Both blank = only Nomad Karaoke admins (who can always sign in).
|
||||
</p>
|
||||
|
||||
<div>
|
||||
@@ -691,7 +691,7 @@ export default function AdminTenantsPage() {
|
||||
</div>
|
||||
{accessOpen ? (
|
||||
<p className="flex items-center gap-1.5 text-xs text-amber-500">
|
||||
<AlertTriangle className="h-3.5 w-3.5" /> Open portal: anyone can sign in. Add emails or domains to restrict it.
|
||||
<AlertTriangle className="h-3.5 w-3.5" /> No client access yet: only Nomad Karaoke admins can sign in. Add the client's emails or domains.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">Only these can sign in (plus Nomad Karaoke admins).</p>
|
||||
|
||||
@@ -20,6 +20,12 @@ jest.mock('@/lib/auth', () => ({
|
||||
|
||||
const mockUseAuth = useAuth as unknown as jest.Mock
|
||||
|
||||
// Tenant context: default Nomad (consumer) unless a test flips it
|
||||
let mockIsDefaultTenant = true
|
||||
jest.mock('@/lib/tenant', () => ({
|
||||
useTenant: () => ({ isDefault: mockIsDefaultTenant }),
|
||||
}))
|
||||
|
||||
// Mock window.location.reload
|
||||
const mockReload = jest.fn()
|
||||
Object.defineProperty(window, 'location', {
|
||||
@@ -30,6 +36,19 @@ Object.defineProperty(window, 'location', {
|
||||
describe('AuthStatus', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockIsDefaultTenant = true
|
||||
})
|
||||
|
||||
it('hides consumer credits on tenant portals', () => {
|
||||
mockIsDefaultTenant = false
|
||||
mockUseAuth.mockReturnValue({
|
||||
user: { email: 'randyvild@gmail.com', credits: 0, display_name: null },
|
||||
logout: jest.fn(),
|
||||
})
|
||||
render(<AuthStatus />)
|
||||
|
||||
expect(screen.getByText('randyvild@gmail.com')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/credits available/i)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Login button when not authenticated', () => {
|
||||
|
||||
@@ -52,6 +52,16 @@ describe('JobActions', () => {
|
||||
expect(screen.getByText('Retry')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the generic retry button for a stalled download (it has its own prompt)', () => {
|
||||
const stalled = {
|
||||
...baseJob,
|
||||
status: 'failed',
|
||||
error_details: { stage: 'audio_download', code: 'audio_download_stalled' },
|
||||
} as Job
|
||||
render(<JobActions job={stalled} onRefresh={mockOnRefresh} />)
|
||||
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show retry button for cancelled jobs (legacy status)', () => {
|
||||
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
||||
render(
|
||||
|
||||
@@ -77,6 +77,19 @@ describe('JobCard', () => {
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the stalled-download prompt instead of the raw error', () => {
|
||||
const stalledJob = {
|
||||
...mockJob,
|
||||
status: 'failed',
|
||||
error_message: 'Audio download failed: Torrent download stalled for 1200s',
|
||||
error_details: { stage: 'audio_download', code: 'audio_download_stalled', stall_minutes: 20 },
|
||||
}
|
||||
render(<JobCard job={stalledJob} onRefresh={mockOnRefresh} />)
|
||||
expect(screen.getByTestId('stalled-download-notice')).toBeInTheDocument()
|
||||
expect(screen.getByText('Keep trying (up to 1 hour)')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/Torrent download stalled/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides stale error message on completed jobs', () => {
|
||||
// Regression: a transient failure (e.g. Cloud Run auto-retried download)
|
||||
// leaves error_message populated even after the job completes. We must
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* including hiding links when outputs have been deleted.
|
||||
*/
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { OutputLinks } from '../job/OutputLinks'
|
||||
import { Job } from '@/lib/api'
|
||||
|
||||
@@ -27,6 +27,7 @@ jest.mock('@/lib/tenant', () => ({
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
getDownloadUrl: jest.fn((jobId, category, key) => `https://example.com/${jobId}/${category}/${key}`),
|
||||
rerenderWithCurrentTheme: jest.fn(() => Promise.resolve({ status: 'processing' })),
|
||||
},
|
||||
adminApi: {
|
||||
getCompletionMessage: jest.fn(),
|
||||
@@ -385,4 +386,54 @@ describe('OutputLinks', () => {
|
||||
expect(screen.queryByText('YouTube')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('re-render with current theme (tenant portals)', () => {
|
||||
const tenantJob: Job = { ...baseJob, state_data: {} }
|
||||
|
||||
const asTenant = (tenantId: string | null) => {
|
||||
const { useTenant } = require('@/lib/tenant')
|
||||
useTenant.mockReturnValue({ tenantId, features: { youtube_upload: false, dropbox_upload: false } })
|
||||
}
|
||||
|
||||
it('shows Re-render for a finished portal track', () => {
|
||||
asTenant('randy-vild')
|
||||
render(<OutputLinks job={tenantJob} />)
|
||||
expect(screen.getByText('Re-render')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is hidden outside tenant portals', () => {
|
||||
asTenant(null)
|
||||
render(<OutputLinks job={tenantJob} />)
|
||||
expect(screen.queryByText('Re-render')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is hidden while the track is not finished', () => {
|
||||
asTenant('randy-vild')
|
||||
render(<OutputLinks job={{ ...tenantJob, status: 'rendering_video' }} />)
|
||||
expect(screen.queryByText('Re-render')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is hidden when outputs were deleted', () => {
|
||||
asTenant('randy-vild')
|
||||
render(<OutputLinks job={{ ...tenantJob, outputs_deleted_at: '2026-09-29T18:47:13Z' }} />)
|
||||
expect(screen.queryByText('Re-render')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('confirms, then starts the re-render and refreshes the job', async () => {
|
||||
asTenant('randy-vild')
|
||||
const { api } = require('@/lib/api')
|
||||
const onJobUpdated = jest.fn()
|
||||
render(<OutputLinks job={tenantJob} onJobUpdated={onJobUpdated} />)
|
||||
|
||||
fireEvent.click(screen.getByText('Re-render'))
|
||||
expect(screen.getByText('Re-render with your current theme?')).toBeInTheDocument()
|
||||
expect(api.rerenderWithCurrentTheme).not.toHaveBeenCalled()
|
||||
|
||||
const buttons = screen.getAllByRole('button', { name: 'Re-render' })
|
||||
fireEvent.click(buttons[buttons.length - 1])
|
||||
|
||||
await waitFor(() => expect(api.rerenderWithCurrentTheme).toHaveBeenCalledWith('test-123'))
|
||||
await waitFor(() => expect(onJobUpdated).toHaveBeenCalled())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Tests for StalledDownloadNotice — the "Keep trying?" prompt shown on a job
|
||||
* whose torrent audio download stalled (source offline).
|
||||
*/
|
||||
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { StalledDownloadNotice, isStalledDownload } from '../job/StalledDownloadNotice'
|
||||
import { Job, api } from '@/lib/api'
|
||||
|
||||
jest.mock('@/lib/api', () => ({
|
||||
api: {
|
||||
retryJob: jest.fn(),
|
||||
chooseDifferentAudio: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockToast = jest.fn()
|
||||
jest.mock('@/hooks/use-toast', () => ({
|
||||
useToast: () => ({ toast: mockToast }),
|
||||
}))
|
||||
|
||||
const stalledJob = (details: Record<string, any> = {}): Job => ({
|
||||
job_id: 'job-1',
|
||||
status: 'failed',
|
||||
progress: 12,
|
||||
created_at: '2026-09-29T00:00:00Z',
|
||||
updated_at: '2026-09-29T00:00:00Z',
|
||||
artist: 'Burn The Ballroom',
|
||||
title: 'Goodbye Cruel World',
|
||||
error_message: 'Audio download failed: Torrent download stalled for 1200s',
|
||||
error_details: { stage: 'audio_download', code: 'audio_download_stalled', stall_minutes: 20, keep_trying: false, ...details },
|
||||
})
|
||||
|
||||
describe('isStalledDownload', () => {
|
||||
it('is true only for failed jobs with the stalled code', () => {
|
||||
expect(isStalledDownload(stalledJob())).toBe(true)
|
||||
expect(isStalledDownload({ ...stalledJob(), status: 'downloading_audio' })).toBe(false)
|
||||
expect(isStalledDownload({ ...stalledJob(), error_details: { stage: 'audio_download' } })).toBe(false)
|
||||
expect(isStalledDownload({ status: 'failed' } as Job)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('StalledDownloadNotice', () => {
|
||||
const onRefresh = jest.fn()
|
||||
const onChooseAudio = jest.fn()
|
||||
|
||||
beforeEach(() => jest.clearAllMocks())
|
||||
|
||||
it('explains the stall with the waited minutes instead of the raw error', () => {
|
||||
render(<StalledDownloadNotice job={stalledJob()} onRefresh={onRefresh} onChooseAudio={onChooseAudio} />)
|
||||
expect(screen.getByText("Your audio hasn't started downloading after 20 minutes")).toBeInTheDocument()
|
||||
expect(screen.getByText(/low availability/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/Torrent download stalled/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the extended explanation after a keep-trying attempt', () => {
|
||||
render(<StalledDownloadNotice job={stalledJob({ stall_minutes: 60, keep_trying: true })}
|
||||
onRefresh={onRefresh} onChooseAudio={onChooseAudio} />)
|
||||
expect(screen.getByText("Your audio hasn't started downloading after 60 minutes")).toBeInTheDocument()
|
||||
expect(screen.getByText(/still offline/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('Keep trying retries with keepTrying and refreshes', async () => {
|
||||
;(api.retryJob as jest.Mock).mockResolvedValue({ status: 'success' })
|
||||
render(<StalledDownloadNotice job={stalledJob()} onRefresh={onRefresh} onChooseAudio={onChooseAudio} />)
|
||||
fireEvent.click(screen.getByText('Keep trying (up to 1 hour)'))
|
||||
await waitFor(() => expect(onRefresh).toHaveBeenCalled())
|
||||
expect(api.retryJob).toHaveBeenCalledWith('job-1', { keepTrying: true })
|
||||
expect(onChooseAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('Choose different audio reopens selection and opens the picker', async () => {
|
||||
;(api.chooseDifferentAudio as jest.Mock).mockResolvedValue({ status: 'success' })
|
||||
render(<StalledDownloadNotice job={stalledJob()} onRefresh={onRefresh} onChooseAudio={onChooseAudio} />)
|
||||
fireEvent.click(screen.getByText('Choose different audio'))
|
||||
await waitFor(() => expect(onChooseAudio).toHaveBeenCalled())
|
||||
expect(api.chooseDifferentAudio).toHaveBeenCalledWith('job-1')
|
||||
expect(onRefresh).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows an error toast and does not open the picker when the call fails', async () => {
|
||||
;(api.chooseDifferentAudio as jest.Mock).mockRejectedValue(new Error('boom'))
|
||||
render(<StalledDownloadNotice job={stalledJob()} onRefresh={onRefresh} onChooseAudio={onChooseAudio} />)
|
||||
fireEvent.click(screen.getByText('Choose different audio'))
|
||||
await waitFor(() => expect(mockToast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'destructive' })))
|
||||
expect(onChooseAudio).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user