Compare commits

...
9 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 0bba4ff041 fix(made-for-you): isolate order emails from audio-acquisition failures (#924)
## Problem

Job `17dc6f48` (a Made-For-You order) failed on a YouTube "confirm
you're not a bot" download error, and the admin **never received the
"New Made-For-You Order Received!" email** — leaving no signal that a
paid order needed attention, and no certainty the customer got their
confirmation. The Discord error monitor also fired `'EmailService'
object has no attribute 'send_email'`.

Two root causes in `_handle_made_for_you_order`
(`backend/api/routes/users.py`):

1. **Emails were sent *after* audio acquisition.** Both the customer
confirmation and the admin notification ran only after the fallible
YouTube download / audio search. When acquisition raised, execution
jumped to the error handler, **skipping both emails.**
2. **The error fallback itself crashed.** It called
`email_service.send_email(...)`, but that method existed only on the
*provider* (`self.provider.send_email`), never on `EmailService` — so
even the failure alert was lost.

## Changes

- **Send the customer order-confirmation email up-front**, right after
job creation and *before* audio acquisition. The order is paid/confirmed
regardless of the download/search outcome. Resilient: a delivery failure
is logged, not fatal.
- **Wrap the admin notification** so an email hiccup on a successful
order can't fake a `[FAILED]` alert.
- **Route the outer failure handler through
`_send_mfy_failure_alert()`** — never raises, HTML-escapes user input,
tolerates `job_id=None`. Success → normal admin notification;
audio-acquisition failure → `[FAILED]` admin alert while the customer
stays confirmed.
- **Add a thin `EmailService.send_email()` passthrough** to the provider
(fixes the `AttributeError`).
- **Handle `False` provider results** (providers signal rejection by
returning `False`, not raising): log accurately instead of always
"Sent"; a rejected *customer* confirmation is escalated to the admin so
it can be resent manually.
- **Retry dropped paid orders:** if job creation fails (no `job_id`,
session never marked processed), re-raise after alerting so the Stripe
webhook returns non-2xx and Stripe retries. Post-creation failures keep
`job_id` set and return 200 to avoid duplicate jobs on retry.
- Idempotency preserved: the Stripe session is marked processed before
the confirmation send, so a webhook retry can't double-send.

## Out of scope

The YouTube "confirm you're not a bot" download error itself is a
separate flacfetch/yt-dlp cookies issue (credential keeper) — this PR
only makes the order emails resilient to it.

## Testing

- `make`-level backend suites for made-for-you, tenant/email,
admin-feedback, internal-webhook all green (138 passed locally).
- New/updated regression tests:
  - customer confirmation survives a YouTube download failure
- confirmation-email failure doesn't abort order processing (and is
escalated)
  - provider-returns-`False` confirmation is escalated
  - job-creation failure re-raises (Stripe retry) after alerting
  - `EmailService.send_email` passthrough delegates to the provider
- Local CodeRabbit review: 2 findings addressed, re-run clean (no new
findings).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 19:23:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c76d58394d fix(fallbacks): T7 — prod fail-fast on missing config + tenant gate safe-by-default (#808)
## Summary
Theme 7 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A single
unset/rotated env var used to silently produce wrong behaviour in prod
with only a warning. Now production fails fast / is safe-by-default.
Verified against Pulumi infra: prod sets `ENVIRONMENT=production`,
`CLOUD_RUN_SERVICE_URL`, `GCS_BUCKET_NAME`, `GOOGLE_CLOUD_PROJECT`, and
Postmark (secret); Cloud Run also auto-sets `K_SERVICE`.

## Changes
- **`config.is_production()` + `validate_production_config()`** (called
from `main.py` lifespan): production refuses to boot if
`GOOGLE_CLOUD_PROJECT`, `GCS_BUCKET_NAME`, or `CLOUD_RUN_SERVICE_URL`
are unset — instead of silently using a dev default (wrong project for
secret lookups / wrong bucket / localhost worker URL). This **subsumes
7.3** (worker_service localhost fallback). `is_production()` treats
Cloud Run's auto-set `K_SERVICE` as production, so it's robust even if
`ENVIRONMENT` were unset.
- **Tenant middleware (7.4, security)**: the `?tenant=` override (a
spoofing vector) is now disabled whenever `K_SERVICE` is present, not
only when `ENVIRONMENT=production` — production-safe by default.
- **dropbox_service (7.1)**: `GOOGLE_CLOUD_PROJECT` default was the
**wrong literal** `"karaoke-gen"` (real project is `nomadkaraoke`);
replaced with an empty default (prod requires it via the startup gate).
- **email_service (7.5)**: a missing `POSTMARK_SERVER_TOKEN` in
production used to silently use the console provider (sends "succeed"
while emails vanish). Now raises in production; console fallback remains
for dev/test.

## Deferred (flagged)
**7.2** `GCS_TEMP_BUCKET` / `GCS_OUTPUT_BUCKET` — these are **not** set
via env in infra, so their config defaults are load-bearing. Requiring
or changing them risks prod, so deferred pending confirmation of whether
those buckets are actually used.

## Testing
- [x] New `backend/tests/test_fallback_prod_config.py` (is_production,
validate gate raise/pass/no-op, email prod-raise vs dev-console, tenant
K_SERVICE)
- [x] 111 related tests pass (email, tenant, config) — no regressions,
no cross-test pollution from the tenant module reload

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 19:01:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 51d9233cb8 fix(fallbacks): T4 — fail loud on missing configured render asset (font dir, background) (#807)
## Summary
Theme 4 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A
*configured* branded render asset that is missing must not silently
substitute a different font/background on a paid deliverable. Mirrors
the existing background-image check in
`output/video.VideoGenerator.__init__` (which already raises).

## Changes
- **`output/video._build_ass_filter`** (4.1): when the theme's karaoke
`font_path` is set but the file is missing, the final MP4 used to
silently drop `:fontsdir` → libass resolves a system fallback font for
the whole song. Now raises `FileNotFoundError`. *(Unset `font_path` is
still fine — no fontsdir, no raise.)*
- **`video_generator._create_background`** (4.3): a set-but-missing
title/end-screen `background_image` used to silently fall back to a flat
color. Now raises `FileNotFoundError`. *(No background configured is
still fine — flat color.)*

## Scope (per your decision)
Only these two clean "configured-but-missing → raise" cases are changed.
The font **substitution** items (4.2 title/end font, 4.4 CDG→arial, 4.8
measurement font) and duet/colour items (4.5–4.7) are **left as-is** —
font substitution overlaps with legitimate CJK font fallback
(`test_video_generator_cjk_font.py`) and warrants per-item treatment.

## Testing
- [x] New `tests/unit/test_fallback_render_assets.py` (raise +
legitimate-unset cases)
- [x] 105 render/video tests pass

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:50:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6c374842f9 infra: Firestore composite index for jobs by request_metadata.client_id (#923)
## Problem

`karaoke-backend` started logging `400 The query requires an index` for
`GET /api/jobs?client_id=` (both "Error listing jobs" and "Error listing
jobs summary" patterns — one prod error alert). The query filters
`request_metadata.client_id` + `tenant_id` and orders by `created_at`,
with no composite index.

This surfaced because the **fiverr-agent** now tags the jobs it creates
with `client_id="fiverr:{order_id}"` and calls that endpoint for
idempotency (finding an existing job before creating one).

## Fix

Adds `firestore-index-jobs-client-id` to the IaC:
- `request_metadata.client_id` ASC
- `tenant_id` ASC
- `created_at` DESC

(matches the index Firestore's error link requested).

## Applied

Already applied to prod via `pulumi up` (`+1 created, 294 unchanged` —
clean preview, no other drift). Verified: `GET
/api/jobs?client_id=fiverr:…` now returns **200** (was 500/400). This PR
codifies the change to prevent IaC drift.

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

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved database query support for filtering jobs by client and
tenant while sorting by newest first.
  * Helps ensure relevant job results load reliably and efficiently.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 18:49:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 5fff6d67b0 fix(fallbacks): T1 — flacfetch sole downloader, no silent YouTube downgrade (#806)
## Summary
Theme 1 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, added in #805).
flacfetch is the sole/lossless downloader — a configured-remote failure
must not silently downgrade to a local YouTube-only rip. This is the
exact class as the 2026-06-08 Facebook-URL incident.

## Changes
- **`audio_search_service._search_remote`**: a `FlacfetchServiceError`
from the remote service was swallowed and silently re-run against the
local YouTube-only fetcher. Now fails loudly (`AudioSearchError`) and
clears cached state. **No silent downgrade.**
- **`create_audio_fetcher`** (local CLI factory): a half-configured
remote (exactly one of `FLACFETCH_API_URL`/`FLACFETCH_API_KEY`) used to
warn and silently use local mode, masking a deploy/secret typo. Now
raises `AudioFetcherError`.

## Scope / deferred (needs your call)
Findings **1.2** (tracker configured-but-unusable → silently
YouTube-only) and **1.4** (`select_best` → first result on ranking
failure) live in the **shared local `FlacFetcher`** and have dedicated
tests asserting graceful local-CLI behaviour
(`test_select_best_handles_exception`). Your "fail loud" directive was
framed around the *cloud* silent-downgrade; hard-failing the local CLI
when a user simply has no usable tracker would change intentional local
behaviour. **Deferred for a per-item decision** rather than steamrolled
— see the audit plan doc.

## Testing
- [x] `backend/tests/test_audio_search.py` +
`tests/unit/test_audio_fetcher.py` pass (209)
- Added: remote-error-does-not-fall-back-to-local; updated the two
half-config factory tests to expect a raise.

## Review
- [x] CodeRabbit CLI review completed locally (1 major finding: clear
cached results on failure — fixed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:35:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 27a5d8fdff fix(fallbacks): T8 — fail loud cleanups (docstrings, download errors, admin-token signal) (#805)
## Summary
First (low-risk) batch of the silent-fallback audit — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the full catalogue
and Andrew's per-theme decisions. This PR is **Theme 8**: fix
lying/stale docstrings, surface specific download-failure reasons, and
make an empty admin-token config a loud signal.

## Changes
- **Fail-open docstring lie → fail-closed**
(`credit_evaluation_service.py`, `config.py`): the AI credit evaluator
is fail-CLOSED (`pending_review`, no auto-grant) but its docstrings
claimed fail-open. Corrected so a future maintainer can't "fix" the code
into a free-credit-abuse hole.
- **Stale yt-dlp docstrings** (`youtube_download_service.py`,
`lyrics_worker.py`): removed text still describing the deleted
local-yt-dlp fallback. flacfetch is the sole downloader; the service
raises when unconfigured.
- **Specific download errors** (`audio_worker.py`, `lyrics_worker.py`):
`download_audio()` now raises a specific `DownloadError` per failure
mode instead of returning `None` → generic "Failed to download audio
file". Workers map it to a clear `Audio download failed: <reason>`
job-failure message.
- **Loud admin-token signal** (`auth_service.py`): empty `ADMIN_TOKENS`
now logs at ERROR (error-monitor → Discord) instead of a quiet warning.
It fails closed (403 everywhere) and looked like an auth bug rather than
a config error.
- Adds the audit plan doc + a `LESSONS-LEARNED` principle ("don't invent
silent fallbacks — ask or fail loud").

## Testing
- [x] Affected backend tests pass locally (85 passed): `test_workers`,
`test_workers_extended`, `test_audio_worker_download`,
`test_auth_admin_tokens`
- [x] Import sanity check (no circular import from new `DownloadError`
imports)
- Updated `test_download_audio_url_without_gcs_path_refuses` to expect
`DownloadError`; added no-source raise tests for both workers +
admin-token tests.

## Review
- [x] CodeRabbit CLI review completed locally (1 minor doc finding,
fixed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:19:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3d56dd4108 fix: connectivity banner only on real read stall (not slowness) (#922)
## Why

Follow-up to #921. In prod the connectivity banner was **too
sensitive**:
1. It fired during a normal lyrics-review load — the 2.5s "slow request"
hint tripped on any request taking >2.5s, even successful ones.
2. The "Preview Video" modal showed **"The server is temporarily
unavailable"** — the long-running preview-generation POST (video encode,
often >45s) hit apiFetch's blanket 45s hard-timeout and failed, even
though the backend was fine.

## What

- **`backend-status.ts` — status now derives purely from a real STALL.**
It tracks how long the *oldest in-flight tracked read* has been
outstanding: `reconnecting` at 10s, `unavailable` at 20s, back to
`online` the instant it settles. A read that completes — even a
normal-slow 3–5s one — surfaces **nothing**.
- **`apiFetch` — GET-only tracking + GET-only hard-timeout.**
- Only GETs feed the banner (a page waits on reads during a recycle;
long POSTs are legitimately slow).
- The 45s hard-timeout backstop applies to **GETs only** —
preview/generate/search POSTs run **untimed** to completion, fixing the
false "unavailable" error.
- New `opts.trackConnectivity: false` lets a known-slow read opt out;
`opts.timeoutMs` still time-boxes any call.

Retry semantics unchanged (GET-only, never replays a mutation).

## Testing
- Rewrote store + apiFetch unit tests for the stall model: POST
untracked, POST not hard-timed-out (signal not aborted after 60s), a
stalled GET → reconnecting→unavailable→clear, fast failures stay
`online`.
- Full suite green: **1132 passing**.
- Banner rendering re-verified locally.
- Local CodeRabbit review: **no findings**.

No infra changes in this PR.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:57:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c65a920a59 feat: graceful backend-outage handling + soften uptime alert noise (#921)
## Why

A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06
UTC on 2026-08-22 and auto-recovered ~1m41s later. Investigation showed
it was a **routine Cloud Run instance recycle** on `--min-instances 1`:
the single warm instance (up ~9.6h) was reaped at 06:01:53, leaving a
~80s gap with no origin, so Cloudflare failed the health check from all
6 checker regions at once. No crash/OOM — a self-healing platform
recycle. (Full write-up:
`docs/archive/2026-08-22-health-check-alert-noise-and-graceful-degradation.md`.)

We're deliberately keeping `--min-instances 1` for cost, so this
addresses the two things we *can* control: alert noise, and how the UI
behaves during such a blip.

## What

**1. Soften the uptime alert** (`infrastructure/modules/monitoring.py`)
- Condition `duration` 60s → **300s**: a sub-5-min self-healing recycle
no longer pages; a sustained hard-down still fires (~5–6 min). Incident
documented in-code.

**2. Graceful frontend degradation**
- `lib/api.ts` — new **`apiFetch`** wrapping every backend call:
non-aborting 2.5s "reconnecting" hint, hard-timeout backstop, **safe
retries (GET only — never replays a mutation)**, transient-status
detection (502/503/504 + Cloudflare 52x), GCS/third-party passthrough.
Throws a typed `BackendUnavailableError`.
- `lib/backend-status.ts` — framework-agnostic connectivity store
(`online | reconnecting | unavailable`); escalates to `unavailable` on a
10s clock, clears to `online` on any success.
- `components/backend-status-banner.tsx` — one reassuring app-wide
banner (mounted under `[locale]`, covers landing + logged-in dashboard +
review screens), **i18n across all 33 locales**. `/admin/*`
intentionally excluded. Copy reassures that in-flight renders are
unaffected.

During a real recycle the dashboard's own polling drives the banner and
it self-heals when the backend returns — no refresh needed.

## Testing
- New unit tests: `__tests__/backend-status.test.ts`,
`__tests__/api-fetch.test.ts` (GET retry→10s escalation, transient 503,
transparent recovery, non-GET never retried, `Request`-input
method/signal, GCS passthrough, caller-abort passthrough). Updated
`completeJobUpload` assertion.
- Full suite green: **1130 passing**.
- Banner verified visually locally (reconnecting + unavailable, en +
es).
- Local CodeRabbit review: 5 findings (1 major, 4 minor) all addressed;
cycle 2 clean.

## Deploy notes
- Infra change: `pulumi up` run locally before merge to avoid IaC drift
(Pulumi CI re-runs as no-op).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:11:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 df93eb9f82 feat(status): opaque System Status modal + live encoding-worker instance type (#920)
## Summary

Two fixes to the **System Status** modal (opened from the version
footer):

### 1. Modal was transparent
The modal set `backgroundColor: var(--card-bg)` — but `--card-bg` is
**defined nowhere** in the codebase (the real vars are `--card` /
`--card-border`). An undefined CSS variable makes the property invalid,
so the modal fell back to `transparent` and the job list showed through
it (see the reported screenshot).

Fixed by using defined opaque surfaces:
- Dialog shell → `var(--bg)` (`#0f0f0f` dark / `#f8fafc` light)
- Service cards → `var(--card)` (`#1a1a1a` dark / `#ffffff` light)

This was the only usage of the phantom `var(--card-bg)` anywhere in the
frontend.

### 2. Show the currently-live encoding worker
Given the recent c4d stockout / multi-instance-family fallback work,
admins couldn't see **which** worker was actually serving or its
instance type. The live worker is the `active_override` VM when a
capacity fallback has routed off the primary, else the c4d blue-green
primary.

- **Backend** (`/health/system-status`): the admin-only encoder
`admin_details` now carries `active_vm`, `active_zone`,
`active_machine_type`, and `on_fallback`. The instance type is derived
via the existing `infer_machine_type` helper (primary →
`c4d-highcpu-32`; fallbacks decoded from the VM-name family token, e.g.
`…-fallback-n2c` → `n2-highcpu-32`).
- **Frontend**: a new `LiveWorkerSection` on the Encoder card shows the
instance type prominently, the serving `VM · zone`, and an amber
**"Fallback"** badge + notice when running off the primary due to a
stockout. The existing Blue-Green expander is unchanged.

## Changes
- `backend/api/routes/health.py` — compute live-worker fields (admin
only)
- `frontend/components/system-status-modal.tsx` — opaque vars +
`LiveWorkerSection`
- `frontend/lib/api.ts` — `ServiceStatus.admin_details` new fields
- `frontend/messages/*` — 3 new `status` keys translated to all 32
locales

## Testing
- `make test` — full suite green (backend 1741+3878+103, frontend 1115
tests / 86 suites)
- Added a capacity-fallback path test to
`test_system_status_endpoint.py`
- Added `frontend/__tests__/system-status-modal.test.tsx` (primary,
fallback badge/notice, non-admin omission)
- CodeRabbit reviewed locally; addressed 3 minor translation-grammar
findings (ja/sk/ro)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 22:47:16 -04:00
76 changed files with 2946 additions and 357 deletions

No files matched your search

+26
View File
@@ -15,6 +15,7 @@ from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
from backend.services.encoding_service import get_encoding_service
from backend.services.encoding_worker_preference import infer_machine_type, PRIMARY_MACHINE_TYPE
from backend.services.spacy_preloader import get_preloaded_model, is_model_preloaded
from backend.services.nltk_preloader import get_preloaded_cmudict, is_cmudict_preloaded
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler, is_langfuse_preloaded, is_langfuse_configured
@@ -443,6 +444,26 @@ async def system_status(
if manager:
try:
config = manager.get_config()
# Which VM is actually serving right now? When a capacity
# fallback is active (e.g. a c4d stockout routed us to an
# alternate family) the override points at the live VM;
# otherwise it's the blue-green primary. The primary pair is
# always c4d — fallbacks carry their family in the VM name
# (…-fallback-n2c, …-fallback-c4a), which infer_machine_type
# decodes when no explicit machine_type is stored on the config.
on_fallback = bool(config.active_override_vm)
active_vm = config.active_override_vm or config.primary_vm
default_zone = getattr(manager, "_zone", "us-central1-c")
active_zone = config.active_override_zone or default_zone
if on_fallback:
active_machine_type = infer_machine_type({"vm": active_vm})
else:
active_machine_type = (
getattr(config, "primary_machine_type", None)
or PRIMARY_MACHINE_TYPE
)
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
@@ -456,6 +477,11 @@ async def system_status(
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
# Currently-serving worker (fallback-aware)
"active_vm": active_vm,
"active_zone": active_zone,
"active_machine_type": active_machine_type,
"on_fallback": on_fallback,
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
+160 -54
View File
@@ -9,6 +9,7 @@ Handles:
- Admin user management
"""
import hashlib
import html
import logging
import threading
from datetime import datetime
@@ -844,6 +845,72 @@ async def create_made_for_you_checkout(
ADMIN_EMAIL = "madeforyou@nomadkaraoke.com"
def _send_mfy_failure_alert(
email_service: EmailService,
*,
customer_email: str,
artist: str,
title: str,
job_id: Optional[str],
error: Exception,
) -> None:
"""Best-effort admin alert when a made-for-you order can't be fully processed.
This never raises: a failure to send the alert must not mask the original
error, nor interfere with the customer-facing order-confirmation email
(which is sent independently, before audio acquisition is attempted).
"""
safe_customer = html.escape(customer_email or "")
safe_artist = html.escape(artist or "")
safe_title = html.escape(title or "")
safe_error = html.escape(str(error))
job_line_html = f"<li><strong>Job ID:</strong> {html.escape(job_id)}</li>" if job_id else ""
job_line_text = f"Job ID: {job_id}\n" if job_id else ""
remediation = (
"The customer's order-confirmation email is sent separately and up-front, so it "
"is unaffected by failures during processing. Please review this order and take "
"any needed manual action — e.g. provide/repair the audio source, or resend the "
"customer confirmation."
)
try:
sent = email_service.send_email(
to_email=ADMIN_EMAIL,
subject=f"[FAILED] Made For You Order: {artist} - {title}",
html_content=f"""
<h2>Made-For-You Order — Action Needed</h2>
<p>A problem occurred while processing this order:</p>
<ul>
<li><strong>Customer:</strong> {safe_customer}</li>
<li><strong>Artist:</strong> {safe_artist}</li>
<li><strong>Title:</strong> {safe_title}</li>
{job_line_html}
<li><strong>Error:</strong> {safe_error}</li>
</ul>
<p>{remediation}</p>
""",
text_content=(
"Made-For-You Order — Action Needed\n\n"
f"Customer: {customer_email}\n"
f"Artist: {artist}\n"
f"Title: {title}\n"
f"{job_line_text}"
f"Error: {error}\n\n"
f"{remediation}"
),
)
if sent:
logger.info(f"Sent made-for-you failure alert to admin for job {job_id}")
else:
logger.error(
f"Made-for-you failure alert to admin was rejected by the email provider (job {job_id})"
)
except Exception as email_error:
logger.error(
f"Failed to send made-for-you failure alert (job {job_id}): {email_error}",
exc_info=True,
)
async def _handle_made_for_you_order(
session_id: str,
metadata: dict,
@@ -892,6 +959,10 @@ async def _handle_made_for_you_order(
f"(session: {session_id}, source_type: {source_type})"
)
# Defined up-front so the outer failure handler can reference it even if job
# creation is what failed (job_id stays None until the job actually exists).
job_id = None
try:
job_manager = JobManager()
storage_service = StorageService()
@@ -977,6 +1048,48 @@ async def _handle_made_for_you_order(
# Initialize search_results for later use in email notification
search_results = None
# Send the customer's order-confirmation email NOW, before attempting audio
# acquisition. The order is paid and confirmed regardless of whether the
# (fallible) YouTube download / audio search succeeds, so a failure there must
# never rob the customer of their confirmation email. Resilient: a delivery
# failure is logged but does not abort order processing.
confirmation_ok = False
try:
# Providers return False (not an exception) when the send is rejected, so
# check the result rather than assuming success.
confirmation_ok = bool(email_service.send_made_for_you_order_confirmation(
to_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
notes=notes,
))
if confirmation_ok:
logger.info(f"Sent made-for-you customer confirmation for job {job_id}")
else:
logger.error(
f"Job {job_id}: customer order-confirmation email was rejected by the email provider"
)
except Exception as confirm_error:
logger.error(
f"Job {job_id}: Failed to send customer order-confirmation email: {confirm_error}",
exc_info=True,
)
if not confirmation_ok:
# A paid customer must never silently miss their confirmation. Escalate to
# the admin so it can be resent manually. Order processing still continues.
_send_mfy_failure_alert(
email_service,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
error=RuntimeError(
"Customer order-confirmation email failed to send — please resend it manually"
),
)
# Handle based on whether we have a YouTube URL or need to search
if youtube_url:
# URL provided - download audio first, then trigger workers
@@ -1099,66 +1212,59 @@ async def _handle_made_for_you_order(
# (search_results may be set from the search flow above, or None for YouTube URL orders)
audio_source_count = len(search_results) if search_results else 0
# Generate admin login token for one-click email access (24hr expiry)
admin_login = user_service.create_admin_login_token(
email=ADMIN_EMAIL,
expiry_hours=24,
)
# Send notification email to admin using professional template.
# Resilient: an email delivery error here must not turn a successfully-created
# order into a "[FAILED]" alert — it's logged and swallowed instead.
try:
# Generate admin login token for one-click email access (24hr expiry)
admin_login = user_service.create_admin_login_token(
email=ADMIN_EMAIL,
expiry_hours=24,
)
admin_notified = bool(email_service.send_made_for_you_admin_notification(
to_email=ADMIN_EMAIL,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
admin_login_token=admin_login.token,
notes=notes,
audio_source_count=audio_source_count,
))
if admin_notified:
logger.info(f"Sent made-for-you admin notification for job {job_id}")
else:
logger.error(
f"Job {job_id}: admin order notification was rejected by the email provider"
)
except Exception as admin_email_error:
logger.error(
f"Job {job_id}: Failed to send admin order notification: {admin_email_error}",
exc_info=True,
)
# Send confirmation email to customer using professional template
email_service.send_made_for_you_order_confirmation(
to_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
notes=notes,
)
# Send notification email to admin using professional template
email_service.send_made_for_you_admin_notification(
to_email=ADMIN_EMAIL,
except Exception as e:
# A hard failure in order processing (e.g. job creation, or audio acquisition
# raising after transitioning the job to FAILED). The customer confirmation is
# sent earlier and independently, so it is unaffected by failures here. Alert
# the admin so they can intervene manually.
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
_send_mfy_failure_alert(
email_service,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
admin_login_token=admin_login.token,
notes=notes,
audio_source_count=audio_source_count,
error=e,
)
logger.info(f"Sent made-for-you order notifications for job {job_id}")
except Exception as e:
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
# Still try to notify Andrew of the failure
try:
email_service.send_email(
to_email=ADMIN_EMAIL,
subject=f"[FAILED] Made For You Order: {artist} - {title}",
html_content=f"""
<h2>Made-For-You Order Failed</h2>
<p>An error occurred processing this order:</p>
<ul>
<li><strong>Customer:</strong> {customer_email}</li>
<li><strong>Artist:</strong> {artist}</li>
<li><strong>Title:</strong> {title}</li>
<li><strong>Error:</strong> {str(e)}</li>
</ul>
<p>Please manually create this job and notify the customer.</p>
""",
text_content=f"""
Made-For-You Order Failed
Customer: {customer_email}
Artist: {artist}
Title: {title}
Error: {str(e)}
Please manually create this job and notify the customer.
""".strip(),
)
except Exception as email_error:
logger.error(f"Failed to send error notification: {email_error}")
# If we failed before the job was even created, no job exists and the Stripe
# session was never marked processed — re-raise so the webhook returns non-2xx
# and Stripe retries the (likely transient) failure rather than silently
# dropping a paid order. Post-creation failures keep job_id set: those return
# normally (job exists, session marked processed, admin already alerted), so a
# retry would be a no-op / risk a duplicate job.
if job_id is None:
raise
@router.post("/webhooks/stripe")
+50 -1
View File
@@ -85,7 +85,8 @@ class Settings(BaseSettings):
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
# before granting. Fail-CLOSED: if evaluation fails, the decision becomes
# "pending_review" (no auto-grant; an admin is notified to decide).
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
@@ -306,3 +307,51 @@ def get_settings() -> Settings:
"""Get the global settings instance."""
return settings
def is_production() -> bool:
"""True when running in a deployed/production environment.
Cloud Run automatically sets ``K_SERVICE``, so we treat its presence as
production even if ``ENVIRONMENT`` were somehow unset — a production-safe
default. Local dev/test have no ``K_SERVICE`` and a non-"production"
``ENVIRONMENT``. (Fallback audit 2026-06-09, Theme 7.)
"""
env = (os.environ.get("ENVIRONMENT") or os.environ.get("ENV") or "").lower()
if env == "production":
return True
return bool(os.environ.get("K_SERVICE"))
# Env vars that MUST be explicitly set in production. A missing one used to
# silently fall back to a dev default and produce wrong behaviour with only a
# warning (wrong GCP project for secret lookups, wrong GCS bucket, localhost
# worker URL). We only require vars that infra confirms are set on every service
# (GCS temp/output buckets are intentionally excluded — their defaults are
# load-bearing and not set via env). (Fallback audit 2026-06-09, Theme 7.)
_REQUIRED_PRODUCTION_ENV_VARS = (
"GOOGLE_CLOUD_PROJECT",
"GCS_BUCKET_NAME",
"CLOUD_RUN_SERVICE_URL",
)
def validate_production_config() -> None:
"""Fail fast at startup if required production env vars are missing.
In production each var in ``_REQUIRED_PRODUCTION_ENV_VARS`` must be explicitly
set; otherwise the service would silently run with a dev default (wrong GCP
project / wrong GCS bucket / localhost worker URL) and appear to work while
doing the wrong thing. Raises RuntimeError listing every missing var. No-op
outside production. (Fallback audit 2026-06-09, Theme 7.)
"""
if not is_production():
return
missing = [v for v in _REQUIRED_PRODUCTION_ENV_VARS if not (os.environ.get(v) or "").strip()]
if missing:
raise RuntimeError(
"Production misconfiguration: required environment variable(s) not set: "
+ ", ".join(missing)
+ ". Refusing to start with silent dev defaults (wrong GCP project / "
"GCS bucket / localhost worker URL)."
)
+6 -1
View File
@@ -9,7 +9,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
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, rate_limits, push, catalog, encoding_worker, client_errors, 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
@@ -77,6 +77,11 @@ async def lifespan(app: FastAPI):
logger.info(f"GCS Bucket: {settings.gcs_bucket_name}")
logger.info(f"Tracing enabled: {tracing_enabled}")
# Fail fast if required production config is missing, rather than silently
# running on dev defaults (wrong GCP project / GCS bucket / localhost worker
# URL). No-op outside production. (Fallback audit 2026-06-09, Theme 7.)
validate_production_config()
# Preload NLP models and resources to avoid cold start delays
# See docs/archive/2026-01-08-performance-investigation.md for background
+7 -2
View File
@@ -26,9 +26,14 @@ from backend.models.tenant import TenantConfig
logger = logging.getLogger(__name__)
# Only allow query param tenant override in non-production environments
# Only allow the `?tenant=` query-param override in non-production environments —
# in production it is a tenant-spoofing vector. Production-safe by default: Cloud
# Run always sets K_SERVICE, so we treat its presence as production even if
# ENVIRONMENT were somehow unset (which would otherwise re-enable the override).
# (Fallback audit 2026-06-09, Theme 7.)
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
os.environ.get("ENVIRONMENT", "").lower() == "production"
os.environ.get("ENVIRONMENT", "").lower() == "production" or \
bool(os.environ.get("K_SERVICE"))
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
+10 -5
View File
@@ -368,12 +368,17 @@ class AudioSearchService:
return results
except FlacfetchServiceError as e:
logger.warning(f"Remote flacfetch search failed, falling back to local: {e}")
# Fallback to local search
# flacfetch is the sole downloader. The remote service was explicitly
# configured, so a failure here must NOT silently downgrade to the
# local YouTube-only fetcher — that hides the outage and ships a worse
# source than the user expected (the 2026-06-08 incident class).
# Fail loudly. (Fallback audit 2026-06-09, Theme 1.)
logger.error(f"Remote flacfetch search failed (not falling back to local): {e}")
# Clear cached state so a later download() can't consume stale results
# from a previous successful search on this (singleton) instance.
self._remote_search_id = None
results = self._fetcher.search(artist, title)
self._cached_results = results
return results
self._cached_results = []
raise AudioSearchError(f"Remote flacfetch search failed: {e}") from e
def select_best(self, results: List[AudioSearchResult]) -> int:
"""
+9 -1
View File
@@ -87,7 +87,15 @@ class AuthService:
if self.admin_tokens:
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
else:
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
# Loud signal: with no admin tokens, every admin/internal-worker
# endpoint fails closed (403). That's safe but looks like an auth bug
# rather than a config error, so log at ERROR (picked up by the error
# monitor → Discord alert) instead of a quiet warning.
logger.error(
"No admin tokens configured! All admin and internal-worker "
"endpoints will reject every request (403). Set the ADMIN_TOKENS "
"secret/env var. This is almost certainly a misconfiguration."
)
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
"""
@@ -2,8 +2,9 @@
AI-powered credit evaluation service.
Evaluates whether to grant free credits (welcome or feedback) by collecting
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
the AI call fails for any reason, credits are granted.
abuse signals and asking Gemini for a grant/deny decision. Fail-CLOSED: if
the AI call fails for any reason, the decision becomes "pending_review" (no
credits auto-granted; an admin is notified to decide manually).
"""
import json
import logging
@@ -25,7 +26,7 @@ class CreditEvaluation:
decision: str # "grant" or "deny"
reasoning: str
confidence: float
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
error: Optional[str] = None # Set if evaluation failed (decision defaults to "pending_review")
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
+7 -2
View File
@@ -30,8 +30,13 @@ class DropboxService:
"""Load OAuth credentials from Secret Manager."""
try:
client = secretmanager.SecretManagerServiceClient()
# Try to get the project ID from environment or use default
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "karaoke-gen")
# Use the configured GCP project. The old default "karaoke-gen" was a
# WRONG literal (the real project is "nomadkaraoke"); an unset var
# would silently target a non-existent project and disable Dropbox.
# Prod always sets GOOGLE_CLOUD_PROJECT (startup validation requires
# it), so use an empty default rather than a misleading wrong one.
# (Fallback audit 2026-06-09, Theme 7.)
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
name = f"projects/{project_id}/secrets/dropbox-oauth-credentials/versions/latest"
response = client.access_secret_version(request={"name": name})
return json.loads(response.payload.data.decode("UTF-8"))
+40 -3
View File
@@ -17,7 +17,7 @@ from zoneinfo import ZoneInfo
import requests
from backend.config import get_settings
from backend.config import get_settings, is_production
from backend.i18n import t, get_locale_prefix
from karaoke_gen.utils import sanitize_filename
@@ -231,7 +231,7 @@ class EmailService:
"""Get the configured email provider.
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
back to console logging (dev/test).
back to console logging (dev/test only).
"""
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
@@ -241,13 +241,50 @@ class EmailService:
logger.info("Using Postmark email provider")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
logger.warning("No email provider configured, using console logging")
# In production a missing Postmark token used to silently fall back to
# console logging — every send "succeeded" while magic-link/completion/
# receipt emails vanished (users can't log in or get downloads). Fail
# loudly instead. (Fallback audit 2026-06-09, Theme 7.)
if is_production():
raise RuntimeError(
"POSTMARK_SERVER_TOKEN is not set in production. Refusing to "
"silently drop emails via the console provider — set the Postmark "
"token secret."
)
logger.warning("No email provider configured, using console logging (dev/test)")
return ConsoleEmailProvider()
def is_configured(self) -> bool:
"""Check if a real email provider is configured (not just console logging)."""
return isinstance(self.provider, PostmarkEmailProvider)
def send_email(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
"""Send a raw email via the configured provider.
Thin passthrough for callers that need to send an ad-hoc/plain email
(e.g. internal failure alerts) without a dedicated template method.
Prefer a dedicated ``send_*`` template method for customer-facing mail.
"""
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email_override=from_email_override,
)
def send_magic_link(
self,
email: str,
+7 -5
View File
@@ -2,13 +2,15 @@
YouTube download service for cloud backend.
This service provides a single entry point for all YouTube downloads in the cloud.
It automatically routes downloads through the remote flacfetch service when configured,
avoiding YouTube bot detection issues on Cloud Run IPs.
flacfetch is the SOLE downloader: downloads are always routed through the remote
flacfetch service, which has YouTube cookies and avoids bot detection on Cloud Run IPs.
The flow is:
1. Check if remote flacfetch is configured (FLACFETCH_API_URL)
2. If yes: Use FlacfetchClient.download_by_id() - downloads on VM, uploads to GCS
3. If no: Use local yt_dlp (with warning about bot detection risk)
3. If no: raise YouTubeDownloadError — there is NO local yt-dlp fallback. We never
run yt-dlp inside the Cloud Run container (it's blocked by bot detection and a
silent fallback previously masked a real download bug — 2026-06-08 incident).
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
@@ -34,8 +36,8 @@ class YouTubeDownloadService:
When remote flacfetch is configured (FLACFETCH_API_URL), downloads happen
on the flacfetch VM which has YouTube cookies and avoids bot detection.
When remote is not configured, falls back to local yt_dlp with a warning
that downloads may be blocked on Cloud Run IPs.
When remote is not configured, this raises YouTubeDownloadError. There is no
local yt-dlp fallback — flacfetch is the sole downloader.
Usage:
service = get_youtube_download_service()
@@ -502,8 +502,12 @@ class TestMadeForYouYouTubeErrorHandling:
youtube_order_metadata
):
"""
Test that exceptions during processing send failure notification to admin.
Test that a job-creation failure sends a failure notification to admin AND
re-raises so the Stripe webhook returns non-2xx and Stripe retries the (likely
transient) failure — a paid order must not be silently dropped when no job was
ever created.
"""
import pytest
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Make job creation fail
@@ -516,15 +520,16 @@ class TestMadeForYouYouTubeErrorHandling:
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)):
# Should not raise - error is handled internally
await _handle_made_for_you_order(
session_id="sess_test_error",
metadata=youtube_order_metadata,
user_service=mock_user_service_for_webhook,
email_service=mock_email_service,
)
# Re-raises (job never created) so the webhook returns non-2xx -> Stripe retries
with pytest.raises(Exception, match="Database error"):
await _handle_made_for_you_order(
session_id="sess_test_error",
metadata=youtube_order_metadata,
user_service=mock_user_service_for_webhook,
email_service=mock_email_service,
)
# Verify failure email was sent to admin
# Verify failure email was sent to admin before re-raising
mock_email_service.send_email.assert_called()
call_args = mock_email_service.send_email.call_args
assert call_args.kwargs['to_email'] == ADMIN_EMAIL
+16
View File
@@ -321,6 +321,22 @@ class TestAudioSearchServiceSearch:
assert "No results found" in str(exc_info.value)
def test_remote_search_failure_does_not_fall_back_to_local(self):
"""A remote flacfetch error must fail loudly, not silently downgrade to local YouTube."""
from backend.services.flacfetch_client import FlacfetchServiceError
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
mock_remote = Mock()
mock_remote.search = AsyncMock(side_effect=FlacfetchServiceError("remote service down"))
service._remote_client = mock_remote
service._fetcher = Mock() # local fetcher — must NOT be used as a silent fallback
with pytest.raises(AudioSearchError, match="Remote flacfetch search failed"):
service.search("ABBA", "Waterloo")
# Critical: we did NOT silently fall back to the local YouTube-only fetcher.
service._fetcher.search.assert_not_called()
def test_search_multiple_results(self):
"""Test search returns multiple results with correct indices."""
mock_results = []
+42
View File
@@ -0,0 +1,42 @@
"""
Tests for admin-token initialization in AuthService.
An empty ADMIN_TOKENS configuration silently breaks every admin/internal-worker
endpoint (they fail closed with 403). That's safe but looks like an auth bug
rather than a config error, so it must be a LOUD signal: an ERROR log (picked up
by the error monitor → Discord alert), not a quiet warning.
"""
from unittest.mock import patch, MagicMock
from backend.services.auth_service import AuthService
def _make_service(admin_tokens_value):
"""Construct AuthService with a controlled settings.admin_tokens value."""
with patch("backend.services.auth_service.FirestoreService"), \
patch("backend.services.auth_service.get_settings") as mock_get_settings, \
patch("backend.services.auth_service.logger") as mock_logger:
mock_settings = MagicMock()
mock_settings.admin_tokens = admin_tokens_value
mock_settings.scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
mock_get_settings.return_value = mock_settings
service = AuthService()
return service, mock_logger
def test_no_admin_tokens_logs_error_not_warning():
"""Empty ADMIN_TOKENS → ERROR-level loud signal, not a quiet warning."""
service, mock_logger = _make_service("")
assert service.admin_tokens == []
mock_logger.error.assert_called_once()
# It used to be a quiet warning — make sure it isn't anymore.
mock_logger.warning.assert_not_called()
def test_admin_tokens_present_no_error():
"""Configured admin tokens → no error, tokens parsed."""
service, mock_logger = _make_service("tok1, tok2 ,tok3")
assert service.admin_tokens == ["tok1", "tok2", "tok3"]
mock_logger.error.assert_not_called()
+102
View File
@@ -0,0 +1,102 @@
"""
Fallback audit (Theme 7): production must fail loudly on missing required config
rather than silently running on dev defaults (wrong GCP project / GCS bucket /
localhost worker URL / console-only email), and the tenant query-param override
must be production-safe by default.
"""
import importlib
import pytest
from backend.config import is_production, validate_production_config
from backend.services.email_service import EmailService
# ---- is_production() ----
def test_is_production_via_environment(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
assert is_production() is True
def test_is_production_via_k_service(monkeypatch):
"""Cloud Run sets K_SERVICE automatically — production-safe even if ENVIRONMENT is unset."""
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.setenv("K_SERVICE", "karaoke-api")
assert is_production() is True
def test_is_production_false_in_dev(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
assert is_production() is False
# ---- validate_production_config() ----
def test_validate_raises_when_required_var_missing_in_prod(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False) # missing!
with pytest.raises(RuntimeError, match="CLOUD_RUN_SERVICE_URL"):
validate_production_config()
def test_validate_passes_when_all_required_set_in_prod(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
monkeypatch.setenv("CLOUD_RUN_SERVICE_URL", "https://api.nomadkaraoke.com")
validate_production_config() # must not raise
def test_validate_noop_in_dev(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False)
validate_production_config() # no-op, must not raise
# ---- email provider (7.5) ----
def test_email_provider_raises_in_prod_without_postmark(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
with pytest.raises(RuntimeError, match="POSTMARK_SERVER_TOKEN"):
EmailService()
def test_email_provider_console_in_dev_without_postmark(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
svc = EmailService() # must not raise — console fallback is fine in dev
assert svc.is_configured() is False
# ---- tenant gate (7.4) ----
def test_tenant_gate_production_safe_with_k_service(monkeypatch):
"""K_SERVICE present (Cloud Run) → IS_PRODUCTION True → query-param override disabled."""
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.setenv("K_SERVICE", "karaoke-api")
import backend.middleware.tenant as tenant_mod
try:
importlib.reload(tenant_mod)
assert tenant_mod.IS_PRODUCTION is True
finally:
# Restore module to a clean (dev) state so other tests aren't affected.
monkeypatch.delenv("K_SERVICE", raising=False)
importlib.reload(tenant_mod)
+204
View File
@@ -266,6 +266,37 @@ class TestMadeForYouOrderConfirmationEmail:
assert call_kwargs.get('cc_emails') is None
class TestEmailServiceSendEmailPassthrough:
"""Tests for the generic EmailService.send_email passthrough.
Regression (2026-08-22): the made-for-you failure handler called
``email_service.send_email(...)`` but EmailService had no such method (only the
provider did), so the failure alert itself crashed with
``'EmailService' object has no attribute 'send_email'`` — masking the original
error and losing the admin alert entirely.
"""
def test_send_email_delegates_to_provider(self):
service = EmailService()
service.provider = Mock()
service.provider.send_email.return_value = True
result = service.send_email(
to_email="admin@example.com",
subject="[FAILED] Test",
html_content="<p>oops</p>",
text_content="oops",
)
assert result is True
service.provider.send_email.assert_called_once()
call_kwargs = service.provider.send_email.call_args.kwargs
assert call_kwargs["to_email"] == "admin@example.com"
assert call_kwargs["subject"] == "[FAILED] Test"
assert call_kwargs["html_content"] == "<p>oops</p>"
assert call_kwargs["text_content"] == "oops"
class TestMadeForYouAdminNotificationEmail:
"""Tests for send_made_for_you_admin_notification method."""
@@ -1757,6 +1788,179 @@ class TestMadeForYouYouTubeDownloadContract:
assert "[FAILED]" in email_call.kwargs.get('subject', ''), \
"Error notification email should have [FAILED] in subject"
@pytest.mark.asyncio
async def test_youtube_download_failure_still_sends_customer_confirmation(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Regression: a YouTube download failure must NOT prevent the paid customer
from receiving their order-confirmation email, nor prevent the admin from
being alerted.
Bug context (2026-08-22): Job 17dc6f48 failed on a YouTube bot-check
download error. Because the confirmation + admin emails were only sent
*after* audio acquisition, the download failure skipped both — Andrew never
received the "New Made-For-You Order Received!" notification and there was no
guarantee the customer got their confirmation. The confirmation email is now
sent up-front, independently of the (fallible) audio acquisition step.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
from backend.services.youtube_download_service import YouTubeDownloadError
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
side_effect=YouTubeDownloadError(
"Sign in to confirm you're not a bot"
)
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
# Must not raise - order intake is resilient to audio-acquisition failures
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# CRITICAL: customer still receives their order confirmation despite the failure
mock_email_service.send_made_for_you_order_confirmation.assert_called_once()
confirm_kwargs = mock_email_service.send_made_for_you_order_confirmation.call_args.kwargs
assert confirm_kwargs['to_email'] == youtube_order_metadata['customer_email']
assert confirm_kwargs['job_id'] == "test-job-123"
# CRITICAL: admin is alerted to the failure so they can intervene manually
mock_email_service.send_email.assert_called_once()
failure_kwargs = mock_email_service.send_email.call_args.kwargs
assert failure_kwargs['to_email'] == ADMIN_EMAIL
assert "[FAILED]" in failure_kwargs['subject']
@pytest.mark.asyncio
async def test_customer_confirmation_email_failure_does_not_abort_order(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Resilience: if the customer confirmation email itself fails to send, order
processing (audio acquisition + admin notification) must still proceed, and the
failed confirmation must be escalated to the admin (never silently lost). An
email-provider hiccup should never block the actual work.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Confirmation email raises, but the order must still be processed
mock_email_service.send_made_for_you_order_confirmation.side_effect = \
RuntimeError("Postmark timeout")
# start_job_processing is async - mock it so the success path completes
mock_job_manager.start_job_processing = AsyncMock()
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
return_value="uploads/test-job-123/audio/test.webm"
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
# Must not raise despite the confirmation email failure
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Download still happened and admin notification still sent
mock_youtube_service.download.assert_called_once()
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
# The failed customer confirmation is escalated to the admin so it can be
# resent manually — a paid confirmation must never be silently lost.
mock_email_service.send_email.assert_called_once()
alert_kwargs = mock_email_service.send_email.call_args.kwargs
assert alert_kwargs['to_email'] == ADMIN_EMAIL
assert "[FAILED]" in alert_kwargs['subject']
@pytest.mark.asyncio
async def test_confirmation_provider_rejection_is_escalated(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Providers return False (not an exception) when a send is rejected. A rejected
customer confirmation must be escalated to the admin, not silently logged as
sent. Regression guard for the "log success even on False" bug.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Provider rejects the confirmation (returns False, does not raise)
mock_email_service.send_made_for_you_order_confirmation.return_value = False
mock_job_manager.start_job_processing = AsyncMock()
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
return_value="uploads/test-job-123/audio/test.webm"
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Rejected confirmation escalated to admin; order still processed
mock_email_service.send_email.assert_called_once()
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
@pytest.mark.asyncio
async def test_job_creation_failure_reraises_for_stripe_retry(
self, mock_email_service, mock_user_service, mock_theme_service,
youtube_order_metadata
):
"""
If job creation fails (no job_id, session never marked processed), the handler
must re-raise so the Stripe webhook returns non-2xx and Stripe retries — a paid
order must not be silently dropped. The admin is still alerted first.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
mock_job_manager = MagicMock()
mock_job_manager.create_job.side_effect = RuntimeError("Firestore unavailable")
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service):
with pytest.raises(RuntimeError, match="Firestore unavailable"):
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Admin alerted before the re-raise; no confirmation (job never created)
mock_email_service.send_email.assert_called_once()
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
mock_email_service.send_made_for_you_order_confirmation.assert_not_called()
class TestMadeForYouYouTubeImports:
"""
@@ -51,6 +51,12 @@ def mock_encoding_worker_config():
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
# No capacity fallback active by default → serving the c4d primary.
config.active_override_vm = None
config.active_override_ip = None
config.active_override_zone = None
config.active_override_set_at = None
config.primary_machine_type = None
return config
@@ -134,6 +140,7 @@ class TestSystemStatusAdmin:
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager._zone = "us-central1-c"
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
@@ -155,3 +162,46 @@ class TestSystemStatusAdmin:
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
# No fallback active → serving the c4d primary VM.
assert admin["on_fallback"] is False
assert admin["active_vm"] == "encoding-worker-b"
assert admin["active_zone"] == "us-central1-c"
assert admin["active_machine_type"] == "c4d-highcpu-32"
@pytest.mark.asyncio
async def test_admin_sees_capacity_fallback_worker(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
"""When a stockout routes off the primary, the live worker reflects the fallback."""
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
# Capacity fallback active: serving an n2-family VM in an alternate zone.
mock_encoding_worker_config.active_override_vm = "encoding-worker-fallback-n2c"
mock_encoding_worker_config.active_override_ip = "34.9.9.9"
mock_encoding_worker_config.active_override_zone = "us-central1-a"
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager._zone = "us-central1-c"
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
admin = result["services"]["encoder"]["admin_details"]
assert admin["on_fallback"] is True
assert admin["active_vm"] == "encoding-worker-fallback-n2c"
assert admin["active_zone"] == "us-central1-a"
# "n2c" family token → n2-highcpu-32 (inferred from the VM name).
assert admin["active_machine_type"] == "n2-highcpu-32"
+36 -10
View File
@@ -816,20 +816,46 @@ class TestDownloadAudioWithUrl:
@pytest.mark.asyncio
async def test_download_audio_url_without_gcs_path_refuses(self, mock_job_with_url, mock_job_manager, mock_storage):
"""A URL job with no GCS file must fail (no local yt-dlp fallback)."""
"""A URL job with no GCS file must fail loudly (no local yt-dlp fallback)."""
from backend.workers.audio_worker import download_audio
from backend.services.audio_search_service import DownloadError
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Fails loudly with a specific DownloadError rather than returning
# None (which used to surface a generic "Failed to download audio file").
with pytest.raises(DownloadError, match="flacfetch service"):
await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Refuses to download locally → returns None, never touches storage
assert result is None
# Refuses to download locally → never touches storage
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_download_audio_no_source_raises(self, mock_job_manager, mock_storage):
"""A job with no GCS path, no file_urls and no URL must fail loudly."""
from backend.workers.audio_worker import download_audio
from backend.services.audio_search_service import DownloadError
no_source_job = Job(
job_id="test123",
status=JobStatus.PROCESSING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
)
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(DownloadError, match="No input audio source"):
await download_audio(
"test123", temp_dir, mock_storage, no_source_job,
job_manager_instance=mock_job_manager,
)
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
+22
View File
@@ -176,3 +176,25 @@ class TestWorkerFileOperations:
result = await download_audio("test123", temp_dir, mock_storage, mock_job, mock_job_manager)
mock_storage.download_file.assert_called()
@pytest.mark.asyncio
async def test_lyrics_download_audio_no_source_raises(self):
"""Lyrics worker download_audio must fail loudly when there's no source."""
from backend.workers.lyrics_worker import download_audio
from backend.services.audio_search_service import DownloadError
mock_storage = MagicMock()
mock_job_manager = MagicMock()
mock_job = Job(
job_id="test123",
status=JobStatus.TRANSCRIBING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
# No input_media_gcs_path and no url → nothing to download
)
mock_job_manager.get_job.return_value = mock_job
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(DownloadError, match="No input audio available"):
await download_audio("test123", temp_dir, mock_storage, mock_job, mock_job_manager)
mock_storage.download_file.assert_not_called()
+33 -9
View File
@@ -24,6 +24,7 @@ from typing import Optional, Dict, Any
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
from backend.config import get_settings
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -213,9 +214,9 @@ async def process_audio_separation(job_id: str) -> bool:
# Download audio file from GCS or URL
with job_span("download-audio", job_id) as download_span:
job_log.info("Downloading audio file...")
# download_audio raises DownloadError with a specific reason
# on failure (no silent None → generic-error fallback).
audio_path = await download_audio(job_id, temp_dir, storage, job, job_manager_instance=job_manager)
if not audio_path:
raise Exception("Failed to download audio file")
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
download_span.set_attribute("source", "url" if job.url else "gcs")
@@ -363,6 +364,16 @@ async def process_audio_separation(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
return True
except DownloadError as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
error_details={"stage": "download_audio", "error": str(e)}
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
@@ -396,7 +407,7 @@ async def download_audio(
storage: StorageService,
job,
job_manager_instance: JobManager = None
) -> Optional[str]:
) -> str:
"""
Fetch the job's audio file from GCS to a local temp directory.
@@ -414,9 +425,14 @@ async def download_audio(
storage: StorageService instance
job: Job object with URL or GCS path
job_manager_instance: Optional JobManager instance for updating job metadata
Returns:
Path to downloaded audio file, or None if failed
Path to the downloaded audio file.
Raises:
DownloadError: with a specific reason if the audio can't be obtained.
We fail loudly with the real cause rather than returning None and
surfacing a generic "Failed to download audio file" to the user.
"""
try:
from karaoke_gen.utils import sanitize_filename
@@ -464,14 +480,22 @@ async def download_audio(
"fetched via the flacfetch service before processing; refusing to "
"download locally."
)
return None
raise DownloadError(
"URL job reached the audio worker without a downloaded input file. "
"URLs must be fetched via the flacfetch service before processing; "
"we never download locally on Cloud Run."
)
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
return None
raise DownloadError(
"No input audio source found for this job (no GCS path and no file_urls)."
)
except DownloadError:
raise
except Exception as e:
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
return None
raise DownloadError(f"Failed to download audio from storage: {e}") from e
async def upload_separation_results(
+45 -17
View File
@@ -31,6 +31,7 @@ from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
from backend.services.lyrics_cache_service import LyricsCacheService
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -302,9 +303,9 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# Download audio file from GCS (waits for audio worker if URL job)
with job_span("download-audio", job_id) as download_span:
job_log.info("Downloading audio file from GCS...")
# download_audio raises DownloadError with a specific reason
# on failure (no silent None → generic-error fallback).
audio_path = await download_audio(job_id, temp_dir, storage, job, job_manager)
if not audio_path:
raise Exception("Failed to download audio file")
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
@@ -552,6 +553,17 @@ async def process_lyrics_transcription(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_END worker=lyrics status=success duration={duration:.1f}s")
return True
except DownloadError as e:
duration = time.time() - start_time
job_log.error(f"Audio download failed: {str(e)}", exc_info=True)
logger.error(f"[job:{job_id}] WORKER_END worker=lyrics status=error duration={duration:.1f}s error={e}")
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
error_details={"stage": "download_audio", "error": str(e)}
)
return False
except Exception as e:
duration = time.time() - start_time
job_log.error(f"Lyrics transcription failed: {str(e)}", exc_info=True)
@@ -587,13 +599,14 @@ async def download_audio(
job,
job_manager: JobManager,
max_wait_seconds: int = 300
) -> Optional[str]:
) -> str:
"""
Download audio file from GCS to local temp directory.
For URL jobs, the audio worker downloads from YouTube first and uploads to GCS.
We wait for the input_media_gcs_path to be set by the audio worker.
For URL jobs, the audio worker fetches the source via the flacfetch service
first and uploads it to GCS. We wait for the input_media_gcs_path to be set
by the audio worker.
Args:
job_id: Job ID
temp_dir: Temporary directory for download
@@ -601,9 +614,14 @@ async def download_audio(
job: Job object
job_manager: JobManager instance
max_wait_seconds: Maximum time to wait for audio worker to download
Returns:
Path to downloaded audio file, or None if failed
Path to the downloaded audio file.
Raises:
DownloadError: with a specific reason if the audio can't be obtained
(fail loudly with the real cause instead of returning None and
surfacing a generic "Failed to download audio file").
"""
import time
@@ -636,20 +654,30 @@ async def download_audio(
# Check if audio worker failed
if updated_job and updated_job.status == JobStatus.FAILED:
logger.error(f"Job {job_id}: Audio worker failed, cannot proceed with lyrics")
return None
raise DownloadError(
"Audio worker failed before lyrics could run; cannot "
"proceed without the downloaded/separated audio."
)
# Wait before next poll - use asyncio.sleep to not block event loop
await asyncio.sleep(poll_interval)
logger.error(f"Job {job_id}: Timed out waiting for audio download (waited {max_wait_seconds}s)")
return None
raise DownloadError(
f"Timed out after {max_wait_seconds}s waiting for the audio worker "
"to download the input audio."
)
logger.error(f"Job {job_id}: No input_media_gcs_path found and no URL")
return None
raise DownloadError(
"No input audio available (no input_media_gcs_path and no URL)."
)
except DownloadError:
raise
except Exception as e:
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
return None
raise DownloadError(f"Failed to download audio for lyrics: {e}") from e
async def upload_lyrics_results(
+80
View File
@@ -6,6 +6,51 @@ Key insights for future AI agents working on this codebase.
---
## Don't Invent Silent Fallbacks — Ask or Fail Loud (Jun 2026)
When the desired behaviour for an edge case is unclear, **do not** invent a quiet
fallback that lets the system keep going while doing the wrong thing. Either ask
the human, or fail loudly with a clear, specific error. Silent fallbacks hide
bugs: the system "works" while producing wrong output, and the real failure
surfaces much later (or never).
**Motivating incident (2026-06-08):** a Facebook-URL job failed with a generic
"Failed to download audio file". A non-YouTube path had silently fallen back to
running yt-dlp *inside the Cloud Run container* (flacfetch was supposed to be the
sole downloader), which then died in a broken `convert_to_wav`. The download had
actually succeeded — the fallback was both unintended and broken. The fix
**deleted** the fallback rather than patching it.
A full audit of the codebase's fallback paths followed — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the catalogue and the
per-item decisions.
**Rules of thumb:**
- A function that can't produce its result should **raise a specific exception**,
not `return None` and let a caller surface a generic message. (See
`download_audio()` in `backend/workers/audio_worker.py` / `lyrics_worker.py`:
each failure mode now raises `DownloadError` with the real reason.)
- "If X isn't configured, silently do Y instead" is the most dangerous shape —
especially around download, payment, job-state, and worker-triggering. Prefer
failing closed and visibly. (See `YouTubeDownloadService.download` — no
flacfetch → raises, no local yt-dlp.)
- Don't trust a comment that *says* a path is a safe fallback — verify what the
user actually observes when it triggers.
- Comments/docstrings must not lie about fail-open vs fail-closed. The credit
evaluation service is **fail-closed** (`pending_review` on error); its
docstrings used to claim fail-open, which would have tempted a future
maintainer to "fix" the code into a free-credit-abuse hole.
- A safe-but-silent fallback (e.g. empty `ADMIN_TOKENS` → everything 403s) should
still log at ERROR so the error monitor alerts — a quiet warning reads as an
auth bug, not a config error.
Good loud-failure models already in the tree to copy:
`lyrics_transcriber/output/video.py` (raises on a missing background image) and
`backend/services/visibility_change_service.py` (checks the trigger result,
restores state, and raises rather than silently dropping a worker trigger).
---
## Multi-instance-type encode pool: one shared speed-rank, availability-aware (Aug 2026, v0.195.0)
"c4d primary + a single n2 fallback family" is not resilient — a stockout is per
@@ -980,6 +1025,41 @@ All status transitions after workers complete fail silently because they're inva
- `test_youtube_url_calls_start_job_processing_after_download` - verifies proper sequence
- `TestInvalidStateTransitionError`, `TestValidateStateTransitionRaisesBehavior`, `TestStartJobProcessing` in `test_job_manager.py`
### Made-For-You Order Emails Must Be Isolated From Audio Acquisition (Aug 2026)
**Problem**: Job 17dc6f48 (made_for_you order) failed on a YouTube "confirm you're
not a bot" download error, and the admin never received the "New Made-For-You Order
Received!" email. The error-fallback then crashed with
`'EmailService' object has no attribute 'send_email'`, so even the failure alert was lost.
**Root cause**: In `_handle_made_for_you_order`, both the customer order-confirmation
and the admin notification were sent *after* the fallible audio-acquisition step
(YouTube download / audio search). When acquisition raised, execution jumped straight
to the outer `except`, skipping BOTH emails. Separately, the fallback called
`email_service.send_email(...)` — a method that only existed on the *provider*
(`self.provider.send_email`), never on `EmailService` itself.
**Fix**:
1. Send the customer order-confirmation email **up-front**, right after job creation and
*before* audio acquisition — the order is paid/confirmed regardless of whether the
download or search succeeds. Wrapped so an email error is logged, not fatal.
2. Wrap the admin notification so an email hiccup on a successful order can't fake a
`[FAILED]` alert.
3. Route the outer failure handler through `_send_mfy_failure_alert()` (never raises,
HTML-escapes user input, tolerates `job_id=None`): success → normal admin
notification; acquisition failure → `[FAILED]` admin alert while the customer is
still confirmed.
4. Add a thin `EmailService.send_email()` passthrough to the provider so ad-hoc/plain
emails (like the failure alert) work.
**Why tests didn't catch it**: `email_service` was a `MagicMock` in the handler tests,
so `mock.send_email(...)` auto-created the attribute and never surfaced the real
`AttributeError`. **Pattern**: for critical fallbacks, add at least one test that
exercises the real `EmailService` (only mocking `.provider`), and assert that a failure
in a *later* step (audio) does not suppress *earlier* side effects (the confirmation
email). Idempotency note: mark the Stripe session processed *before* sending the
confirmation so a webhook retry can't double-send.
### Use data-testid for E2E
Prefer `data-testid` over label/text selectors. They're immune to label changes and won't break when similar fields are added.
@@ -0,0 +1,237 @@
# Fallback Logic Audit — karaoke-gen (2026-06-09)
**Driver prompt:** `docs/archive/2026-06-08-fallback-logic-audit-prompt.md`
**Motivating incident:** 2026-06-08 Facebook-URL job → generic "Failed to download
audio file". A non-YouTube path silently fell back to running yt-dlp *inside the
Cloud Run container*, which died in a broken `convert_to_wav`. flacfetch was
supposed to be the sole downloader. The fix **deleted** the fallback rather than
patching it. See `docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md` and
memory `project_flacfetch_sole_downloader`.
**Goal of this audit:** make every silent fallback an *explicit, intentional*
decision — fail loudly with a clear error, OR keep + log/alert, OR something
else. Do **not** change behaviour without Andrew's answer. Some fallbacks are
load-bearing graceful degradation and should stay.
**Classification:**
- **A** = legitimate graceful degradation (intended, fails safe + visible). Keep.
- **B** = silent fallback masking a bug/misconfig (like the yt-dlp case). Delete or fail-fast.
- **C** = ambiguous — needs Andrew's intent.
**Method:** 5 parallel read-only triage agents over (1) audio/lyrics acquisition,
(2) job-state & worker triggering, (3) payment/credits/referral/auth, (4)
karaoke_gen core render, (5) backend routes/services/config. Findings below are
verified against actual behaviour, not comments.
> **DECISION fields capture Andrew's answers verbatim** (interview held 2026-06-09).
---
## THEME 1 — Source downgrade: flacfetch → YouTube-only (the motivating class)
These reconstruct the exact "silently use a worse source" pattern that caused the
incident. flacfetch is supposed to be the sole/lossless downloader.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 1.1 | `backend/services/audio_search_service.py:224-230` | **B** | Remote flacfetch search error → silently re-runs **local** flacfetch (YouTube-only on Cloud Run). Transient remote outage silently downgrades a RED/OPS lossless job to a YouTube rip; user sees only a `logger.warning`. |
| 1.2 | `karaoke_gen/audio_fetcher.py:405-433` | **B** | If `TorrentDownloader` import fails / Transmission down / tracker `*_API_URL` unset → RED/OPS skipped, only `YoutubeProvider` registered. The concrete mechanism behind 1.1. |
| 1.3 | `karaoke_gen/audio_fetcher.py:1818-1823` | **C** | If exactly one of `FLACFETCH_API_URL` / `FLACFETCH_API_KEY` is set → logs "falling back to local mode". A typo'd secret silently disables the remote service. |
| 1.4 | `karaoke_gen/audio_fetcher.py:558-577` | **C** | `select_best` returns result[0] on any ranking failure → may silently auto-pick a lower-quality source. |
**DECISION (Theme 1):** Andrew — **"Fail loudly, no YouTube fallback."** flacfetch
is the sole/lossless downloader; if it can't serve (remote error, RED/OPS
unavailable, half-configured), fail the job with a clear error rather than
silently ripping YouTube. Applies to 1.1–1.4.
---
## THEME 2 — Silent worker-trigger drops → jobs stall forever
A recurring pattern: a downstream worker is triggered fire-and-forget and the
boolean/return is discarded. If the enqueue fails, the job sits in an intermediate
state with **no error and nothing to recover it**. The user is often told "success".
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 2.1 | `backend/services/job_manager.py:1126-1137` | **B** | `_trigger_screens_worker` catches `RuntimeError` (no event loop) and just logs `# TODO: use message queue`. Called from `mark_lyrics_complete` in the **lyrics_worker Cloud Run Job** (sync). If it no-ops, `lyrics_complete=True` is written but screens worker never fires → job stalls before AWAITING_REVIEW; `recover_stuck_jobs` doesn't cover this. *(Verify: does a loop exist in that Job?)* |
| 2.2 | `backend/api/routes/review.py:504` | **B** | After REVIEW_COMPLETE, `asyncio.create_task(trigger_render_video_worker)` result discarded; endpoint returns `{"status":"success"}`. Failed enqueue → stuck at REVIEW_COMPLETE, no error, no auto-recovery. |
| 2.3 | `backend/workers/render_video_worker.py:281,546` | **B** | `await trigger_video_worker(job_id)` bool ignored. Failed trigger → job stuck at INSTRUMENTAL_SELECTED with render done but final encode never started. |
| 2.4 | `backend/api/routes/internal.py:725-728` | **C** | Retry scheduler resets parked job to REVIEW_COMPLETE then triggers; on raise the comment assumes it'll be re-picked as RENDER_PENDING_CAPACITY, but the next tick queries `status==RENDER_PENDING_CAPACITY` and won't see it. Escapes both retry query and 24h timeout sweep → stuck indefinitely. |
| 2.5 | `backend/services/encoding_service.py:1018-1020` | **B** | `get_encoding_service()` does `try: set_worker_manager(manager) except Exception: pass`. Any client-init failure → service silently runs with **no worker manager**, falls back to static URL, loses multi-zone capacity failover, no signal. |
| 2.6 | `audio_download_worker.py:291-294`, `job_manager.py:1078-1081`, `jobs.py:70-71`, `review.py:2208-2209` | **B** | `asyncio.gather(trigger_audio, trigger_lyrics)` results discarded across these sites. One failed enqueue → that pipeline branch silently never starts while the other proceeds; job hangs. |
**Model to emulate:** `backend/services/visibility_change_service.py:194-205` does it
right — checks `triggered`, logs error, restores state, raises.
**DECISION (Theme 2):** Andrew — **"Fail loud / re-park & retry."** Check every
trigger result; on failure mark the job failed or re-queue (the
`visibility_change_service` pattern) so a job can never silently stall. Applies
to 2.1–2.6. _(Still verify reachability of 2.1's no-event-loop path during impl,
but the directional call is fail-loud/retry.)_
---
## THEME 3 — Lyrics/transcription silently degraded or missing
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 3.1 | `karaoke_gen/lyrics_transcriber/core/controller.py:487-491` | **B** | If every transcriber returns empty (no exception, e.g. AudioShake 200 with no words), code logs a warning and proceeds; `process()` skips output but job is still reported "completed successfully". → karaoke video with **no synced lyrics**, no error. |
| 3.2 | `karaoke_gen/lyrics_processor.py:372-373` + `core/config.py:16` | **B/C** | `enable_local_whisper=True` hardcoded as priority-3 fallback. On a host with `whisper_timestamped` installed, AudioShake failure silently yields much lower-quality Whisper timing with no signal. (No-op on Cloud Run where pkg absent — env-dependent.) |
| 3.3 | `core/controller.py:396-398` | **C** | Failure loading existing corrections JSON is swallowed → silently re-transcribes from scratch, discarding prior **human review** work. |
| 3.4 | `core/controller.py:442-454` | **C** | Per-provider reference-lyric fetch errors (Genius/Spotify/LRCLIB/Musixmatch) swallowed; all-fail → "No lyrics found", correction runs transcription-only (lower accuracy). Masks systemic outages (e.g. expired Spotify cookie). |
**DECISION (Theme 3):** Andrew — **"Fail the job loudly."** No transcription
results = fail with a clear error; lyrics are the core deliverable and a
lyric-less "success" must never ship. Treat 3.1 as a hard fail. _(Apply the same
fail-loud principle to 3.2–3.4 during impl — silent low-quality Whisper and
silently discarding human-review corrections both violate the principle; flag if
any needs a different call.)_
---
## THEME 4 — Wrong font / asset / color on a paid deliverable
Silent substitution of a missing branded asset → a wrong-looking video/CDG the
customer paid for. Note the karaoke-render path at
`lyrics_transcriber/output/video.py:43-44` already **raises** on a missing
background — a good loud-failure model the others diverge from.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 4.1 | `lyrics_transcriber/output/video.py:417-423` | **B** | Final karaoke MP4: if theme font file missing, `:fontsdir` is silently dropped → libass resolves via system fontconfig → whole song in a substitute font, no log above debug. |
| 4.2 | `video_generator.py:120-132,153,174,191` | **B** | Title/end screens: missing font → `ImageFont.load_default()` (~10px bitmap). 4K title/end card renders artist/title in a near-invisible default font. |
| 4.3 | `video_generator.py:368-377` | **B/C** | Title/end screen: missing `background_image` → silently uses flat `background_color` (karaoke path raises instead — inconsistent). |
| 4.4 | `lyrics_transcriber/output/cdg.py:294-306` | **B/C** | CDG: unresolved theme font → bundled `arial.ttf` (warning only). Hardware disc renders all lyrics in Arial. |
| 4.5 | `karaoke_finalise.py:1132-1159` | **B/C** | Duet job: missing/malformed `duet_corrections_json` → renders CDG via LRC path = **solo colors**, loses singer-color distinction (warning only). |
| 4.6 | `lyrics_transcriber/output/cdg.py:551-561` | **B/C** | Duet CDG: lost/length-mismatched line→singer map → defaults every line to singer 1 "to keep the file valid". Silently wrong color attribution. |
| 4.7 | `lyrics_transcriber/output/ass/config.py:115-117,149-151` | **B/C** | Malformed theme color → hardcoded default blue/black. A typo'd theme color renders lyrics in the wrong brand color. |
| 4.8 | `lyrics_transcriber/output/ass/lyrics_line.py:39-45` | **B/C** | Text-measurement font → `load_default()` (different metrics) while libass renders a different font → line-wrap decisions desync from the actual video. Pairs with 4.1. |
**A (keep, verified intended + logged):** GPU→CPU encode fallback
(`karaoke_finalise.py:1803-1881`, visually equivalent libx264, warned);
`style_loader.py:164-192` documented default duet palette;
`subtitles.py:100-107` audio-duration estimate (logged).
**DECISION (Theme 4):** Andrew — **"Fail loudly on missing branded asset."** Match
`video.py:43-44` which already raises. A paid deliverable shouldn't silently
substitute fonts/backgrounds/colors — fail with a clear error so it's caught
before delivery. Applies to 4.1–4.8. _(Keep the confirmed-A items: GPU→CPU
encode, documented duet palette, audio-duration estimate.)_
---
## THEME 5 — Pricing undercharge / ceiling bypass
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 5.1 | `backend/api/routes/jobs.py:128-134` + `services/pricing.py:13-22` | **B** | Client-supplied `duration_seconds`; if `None`, `duration_to_credits(None)=1` and `is_blocked(None)=False`. Omitting duration → any-length job for 1 credit **and** skips the 60-min hard ceiling. `acknowledged_credits` guard only fires if client *sends* a mismatch. |
| 5.2 | `backend/api/routes/jobs.py:2446-2466` (`create_job_from_search`) | **B** | Guided/search flow never passes `credits=` → always `JobCreate.credits=1` regardless of length. Inconsistent with URL path; long-input undercharge. |
| 5.3 | `backend/api/routes/users.py:97` | **B** | Referral discount: `except Exception: discount_percent = 10` on Firestore read failure. A 20% link charged at 10% on a transient error. |
**DECISION (Theme 5):** Andrew — **"Keep defaults but always enforce ceiling +
alert."** Keep the 1-credit default, but the 60-min hard ceiling must always be
enforced (never silently bypassed when duration is omitted), and any
undercharge / discount-guess must raise a Discord alert so it's visible.
_Impl note:_ when duration is unknown we still alert + apply the ceiling rather
than reject; charge-by-duration consistency between URL and search flows to be
handled under this (alert if they diverge). Applies to 5.1–5.3.
---
## THEME 6 — Lost paid orders / "Unknown" customer data
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 6.1 | `backend/api/routes/users.py:1105-1135` (`_handle_made_for_you_order`) | **B** | Broad `except Exception` swallows fulfilment failure *after Stripe charged*; emails admin "[FAILED]" but does **not** re-raise → webhook returns 200 (no Stripe retry). If the email also fails (line 1134 logs only), a paid $50 order silently vanishes. |
| 6.2 | `backend/api/routes/users.py:858-859` | **B** | Made-for-you order: `metadata.get("artist","Unknown Artist")`/`("title","Unknown Title")` → a paid video titled "Unknown Artist - Unknown Title" instead of rejecting the order. |
**DECISION (Theme 6):** Andrew — **"Re-raise + durable failed-order record."** On
made-for-you fulfilment failure, re-raise so Stripe retries AND/OR write a
durable `needs_manual_fulfilment` record (don't rely on an email an admin might
miss); reject orders missing artist/title rather than shipping "Unknown Artist -
Unknown Title". Applies to 6.1–6.2.
---
## THEME 7 — Env-var / config defaults masking prod misconfiguration
A single unset/rotated env var silently produces wrong behaviour with only a
warning. Env vars are set in Cloud Run today, but the defaults are landmines.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 7.1 | `backend/services/dropbox_service.py:34` | **B** | `GOOGLE_CLOUD_PROJECT` default `"karaoke-gen"` (real project is `nomadkaraoke`). If unset → secret lookup targets a non-existent project; bare `except` swallows → Dropbox distribution silently disabled. |
| 7.2 | `backend/config.py:19-21` | **B** | GCS bucket defaults `karaoke-gen-storage[/-temp/-outputs]` ≠ real `karaoke-gen-storage-nomadkaraoke`. If `GCS_BUCKET_NAME` unset → reads/writes a non-existent bucket, runtime 500s deep in processing instead of boot failure. |
| 7.3 | `backend/services/worker_service.py:160-166` | **B** | If `CLOUD_RUN_SERVICE_URL` unset → worker base URL = `http://localhost:{PORT}` with no env guard. Workers invoked against localhost → jobs created but silently never run. |
| 7.4 | `backend/middleware/tenant.py:30-31,102-105` | **B (security)** | `IS_PRODUCTION` from `ENV/ENVIRONMENT=="production"`, but app default is `"development"`. If prod doesn't explicitly set it → `?tenant=<id>` query override active → **tenant spoofing** (impersonate white-label portal). *(Verify prod sets ENVIRONMENT=production.)* |
| 7.5 | `backend/services/email_service.py:230-245` | **B** | No `POSTMARK_SERVER_TOKEN` → silent `ConsoleEmailProvider`; all sends "succeed". In prod with token unset/rotated, magic-link/completion/receipt emails silently vanish → users can't log in or get downloads. |
**DECISION (Theme 7):** Andrew — **"Fail-fast at startup in prod."** When
`ENVIRONMENT=production`, require these vars and refuse to boot (or go
health-check red) if missing; make the tenant-detection gate production-safe by
default (disable `?tenant=` override unless explicitly development). No silent
wrong-resource defaults. Applies to 7.1–7.5. _Impl note:_ first confirm prod
actually sets `ENVIRONMENT=production` (Pulumi `cloud_run.py`) — the security
gate 7.4 depends on it.
---
## THEME 8 — Lower-risk cleanups (docs lie, opaque errors, auth layers)
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 8.1 | `backend/config.py:77-78` & `credit_evaluation_service.py` module/`grant_welcome_credits` docstrings | **C/doc** | Docstrings say "Fail-open: credits granted on error" but code is **fail-CLOSED** (`pending_review`, no grant) — the *safe* behaviour. The lie risks a future maintainer "fixing code to match docs" and re-introducing free-credit abuse. Fix the docs, confirm policy. |
| 8.2 | `youtube_download_service.py:11,37-38`; `lyrics_worker.py:566` | **doc** | Stale docstrings still describe the deleted yt-dlp fallback ("falls back to local yt_dlp"). Misleading post-incident. |
| 8.3 | `backend/workers/audio_worker.py:467-473`, `lyrics_worker.py:611-623` → `audio_worker.py:217-218` | **C** | Distinct download failure causes all collapse to `return None` → generic user-facing "Failed to download audio file" (the opaque message from the incident). Surface specific reasons to the user? |
| 8.4 | `backend/api/routes/users.py:734-762` (`create_checkout`) | **C** | Unauthenticated; email + referral-discount taken from request body. Anyone can compute a discount against an arbitrary email. Direct money risk low (webhook keys off session metadata). Intended pre-login flow? |
| 8.5 | `backend/services/auth_service.py:107-111` | **C** | OIDC verified with `audience=None` (audience check skipped); mitigated by strict `token_email == scheduler SA`. Acceptable or tighten to URL allowlist? |
| 8.6 | `backend/services/auth_service.py:81-90` | **C** | Empty `ADMIN_TOKENS` → warning only; all admin endpoints 403 (fails closed = safe, but looks like an auth bug not a config bug). Louder signal in prod? |
| 8.7 | `backend/services/email_validation_service.py:226` | **C** | Missing Firestore blocklist doc → `DEFAULT_DISPOSABLE_DOMAINS` (the Firestore `.get` itself is unwrapped, so hard failures propagate — good). Acceptable degradation? |
**DECISION (Theme 8):** Andrew — **"Fix docs + specific errors + admin-token
signal."** Correct the lying/stale docstrings (8.1 fail-open→fail-closed, 8.2
yt-dlp), surface specific download-failure reasons to the user instead of the
generic "Failed to download audio file" (8.3), and add a loud prod signal when
`ADMIN_TOKENS` is empty (8.6). Leave 8.4 (unauth checkout), 8.5 (OIDC
audience=None), 8.7 (blocklist default) as acceptable fail-safe.
---
## A — Legitimate graceful degradation confirmed (no change; listed for the record)
- `audio_transcoding_service.py:113-130,171-175` — review-audio transcode fail → serve original FLAC (logged).
- `backend/workers/audio_worker.py:207-211` — audio separation not configured → **raises** (good model).
- `youtube_download_service.py:118-126` — flacfetch unconfigured → **raises** (the post-incident fix).
- `audio_download_worker.py:341-342` — unsupported source → raises `DownloadError` (post-fix state of the incident).
- `video_worker.py:182-185` — `_encode_via_gce` re-raises on GCE failure (no silent local fallback).
- `local_encoding_service.py:241-264` — GPU→CPU encode, warned. Visible perf degradation.
- `stripe_service.py` (multiple) — unconfigured/invalid → fail closed + visible.
- `user_service.py:1003-1017` — `add_credits` idempotent via `PROCESSED_STRIPE_SESSIONS`.
- `job_manager.py:146-164` — credit-deduction failure deletes job + raises `InsufficientCreditsError`.
- `referral_service.py:283-305` — `record_earning` returns None only for invalid/expired referral; wrapped so it never blocks the buyer's credits.
- `catalog_proxy_service.py:71,103` — autocomplete `[]` on karaoke-decide outage (cosmetic).
- `credential_manager` distribution checks — distinct NOT_CONFIGURED/INVALID/ERROR/VALID, blocking 400 on create-from-url.
- `file_upload.py:1827-1833` (create-from-url) — re-raises, calls `fail_job`, 500 with real detail.
---
## Execution roadmap (Phase 4) — one PR per theme, with tests
Ordered safest/clearest → most delicate. Each PR updates `docs/LESSONS-LEARNED.md`
with the principle ("don't invent silent fallbacks — ask or fail loud") + the
notable example(s) it fixes.
| PR | Theme | Decision in one line | Risk |
|----|-------|----------------------|------|
| 1 | **T8** docs/errors | Fix lying fail-open docstrings + stale yt-dlp docstrings; surface specific download-failure reasons; loud prod signal on empty ADMIN_TOKENS | Low |
| 2 | **T1** sourcing | flacfetch sole downloader → fail loud (no silent YouTube downgrade) across 1.1–1.4 | Low/Med |
| 3 | **T4** render assets | Missing branded font/bg/duet-color → raise (match video.py:43-44) across 4.1–4.8 | Med |
| 4 | **T7** env config | Prod fail-fast on missing required vars; tenant gate production-safe by default | Med (verify Pulumi env first) |
| 5 | **T3** lyrics | Empty transcription = fail loud; same principle to whisper/corrections/reference | Med |
| 6 | **T2** worker triggers | Check every trigger result → fail/re-park; never silently stall (2.1–2.6) | High (job state machine) |
| 7 | **T5** pricing | Keep 1-credit default but always enforce 60-min ceiling + alert on undercharge/discount-guess | High (money) |
| 8 | **T6** paid orders | Re-raise + durable needs_manual_fulfilment record; reject missing artist/title | High (money/webhook) |
**Status:** Phases 1–3 complete (discover + triage + interview; all 8 decisions
captured above). Phase 4 (execute) — pending sequencing go-ahead from Andrew.
@@ -0,0 +1,94 @@
# Health-check alert noise + frontend graceful degradation (2026-08-22)
## Trigger
A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06 UTC on
2026-08-22 and auto-recovered ~1m41s later. Investigation of the noise, plus a
follow-on request to make the frontend degrade gracefully during such blips.
## Root cause of the alert
**A routine, platform-initiated Cloud Run instance recycle — not a crash.**
- The backend runs on `--min-instances 1` (a deliberate cost choice).
- At 06:01:53 UTC Cloud Run reaped the single warm instance (which had run ~9.6h
since the previous evening's deploy) and started a replacement
(`Reason: MANUAL_OR_CUSTOMER_MIN_INSTANCE`, then `AUTOSCALING`). The new
container's STARTUP probe passed ~06:03:13.
- During the ~80s gap (06:02:30–06:03:50) there was **no warm origin**, so
Cloudflare failed the health check from **all 6** uptime checker regions
simultaneously. Zero `/api/health` requests reached the origin in that window;
no `SIGTERM`/OOM/error was logged (platform reaps leave no teardown log).
- The uptime alert (reworked 2026-08-19 to page only when >1 checker location
fails) did its job — it caught a genuine, if brief, hard-down.
- A second, related failure mode was also observed (00:11–00:12 UTC): the single
instance's event loop stalled (orchestrating an encoding-worker fallback
cold-start with blocking timeouts), so health probes queued past the 10s
uptime timeout across regions, then flushed at once.
Blast radius of such a blip: ~80s of API unavailability. The **frontend still
loads** (static Cloudflare Pages export), **Cloud Run Jobs** (video renders) and
**GCE encoding-worker** executions already in flight **keep running**; only
backend-side orchestration is briefly paused and self-heals via Cloud
Tasks/Scheduler retries + the recover-stuck-jobs / retry-pending-render crons.
## Change 1 — soften the alert (server-side)
`infrastructure/modules/monitoring.py`: the "Service Unavailable" condition
`duration` 60s → **300s**. A sub-5-min self-healing recycle/stall no longer
pages; a sustained hard-down still fires (~5–6 min). The read-retry budget in the
frontend (`lib/backend-status.ts`) is aligned to the same ~10s escalation.
We deliberately did **not** raise `--min-instances` to 2 (cost choice). If real
outages ever slip through undetected, that is the cheaper-detection lever and it
removes both failure modes at the source.
## Change 2 — graceful degradation (frontend)
Goal: during a blip, retry transparently and show one reassuring app-wide message
instead of every screen throwing a generic error.
- **`lib/backend-status.ts`** — framework-agnostic connectivity store
(`online | reconnecting | unavailable`) + `useBackendStatus()`. **Status is
derived purely from how long the OLDEST in-flight tracked read has been
outstanding** (`beginRequest`/`endRequest`): `reconnecting` at
`STALL_RECONNECTING_MS` (10s), `unavailable` at `STALL_UNAVAILABLE_MS` (20s),
back to `online` the instant the stalled read settles.
- **`lib/api.ts` — `apiFetch`** wraps every backend call (drop-in for `fetch`;
internals use `globalThis.fetch`). Design decisions:
- **The banner keys on a genuine STALL, not slowness.** A read that completes —
even a normal-slow 3–5s one — surfaces nothing; only a read still outstanding
past 10s shows the hint. (The original 2.5s "slow-request" hint was too
trigger-happy — it fired during normal lyrics-review loads.)
- **Only GETs are tracked, and only GETs get a hard-timeout (45s) backstop.**
Long-running POSTs (preview video, generate, search, auto-correct) are
legitimately slow: they must never trip the banner nor be aborted mid-encode.
Callers can opt a slow read out with `opts.trackConnectivity: false`, or
time-box any request with `opts.timeoutMs`.
- **Retries GET only** (idempotent); **never auto-retries non-GET** (a replayed
create/submit/payment could double-charge). GETs retry within a ~2s budget,
then throw `BackendUnavailableError`.
- Transient = 502/503/504 + Cloudflare 520–524. Third-party hosts (GCS
signed-URL uploads) pass straight through untouched.
- **`components/backend-status-banner.tsx`** — the two UX states; mounted in
`app/[locale]/layout.tsx` so it covers all customer-facing surfaces (landing,
logged-in dashboard, review screens) with full i18n. `/admin/*` is intentionally
not covered (internal, English-only).
- **i18n** — `backendStatus` namespace added to `messages/en.json` and translated
to all 32 other locales.
### Copy (en)
> **We're having trouble reaching our servers**
> This is usually temporary — please try again in a couple of minutes.
> Any karaoke videos currently being created are unaffected and will keep processing.
## Tests
- `__tests__/backend-status.test.ts` — store transitions + timer escalation.
- `__tests__/api-fetch.test.ts` — GET retry→unavailable, transient-503 retry,
transparent recovery, non-GET no-retry, GCS passthrough, caller-abort passthrough.
- `lib/__tests__/api.test.ts` — updated `completeJobUpload` assertion (network
failure now maps to `BackendUnavailableError` preserving `.cause`).
- Banner verified visually (reconnecting + unavailable, en + es) via local dev.
- Full suite: 1129 passing.
+223
View File
@@ -0,0 +1,223 @@
/**
* @jest-environment jsdom
*
* Tests for apiFetch — the timeout + safe-retry wrapper that all backend calls go
* through (lib/api.ts). In jsdom the hostname is "localhost", so API_BASE_URL is ""
* and backend calls are addressed with relative "/api/..." URLs.
*/
import { apiFetch, BackendUnavailableError } from '@/lib/api'
import {
getBackendStatus,
STALL_RECONNECTING_MS,
STALL_UNAVAILABLE_MS,
} from '@/lib/backend-status'
function mockResponse(status: number, body: unknown = {}): Response {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
} as unknown as Response
}
/** A fetch mock that returns a promise you resolve/reject by hand, so a request can
* be held "in flight" under fake timers and then settled to clean up. */
function deferredFetch() {
let settle!: (r: Response) => void
let fail!: (e: unknown) => void
const fn = jest.fn(
() =>
new Promise<Response>((res, rej) => {
settle = res
fail = rej
}),
)
return { fn, settle: (r: Response) => settle(r), fail: (e: unknown) => fail(e) }
}
describe('apiFetch', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(globalThis as unknown as { fetch: unknown }).fetch = fetchMock
})
afterEach(() => {
jest.useRealTimers()
})
it('returns the response and stays online on a fast successful GET', async () => {
fetchMock.mockResolvedValue(mockResponse(200, { ok: true }))
const res = await apiFetch('/api/jobs/abc')
expect(res.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('does NOT retry a deterministic 404 and stays online', async () => {
fetchMock.mockResolvedValue(mockResponse(404))
const res = await apiFetch('/api/jobs/missing')
expect(res.status).toBe(404)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('retries a GET on repeated network failure, then throws BackendUnavailableError', async () => {
jest.useFakeTimers()
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const p = apiFetch('/api/jobs/abc')
const assertion = expect(p).rejects.toBeInstanceOf(BackendUnavailableError)
await jest.advanceTimersByTimeAsync(600)
await jest.advanceTimersByTimeAsync(1500)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
// A fast total failure (~2s) is NOT a stall, so the banner never appears.
expect(getBackendStatus()).toBe('online')
})
it('retries a GET that keeps returning a transient 503, then throws', async () => {
jest.useFakeTimers()
fetchMock.mockResolvedValue(mockResponse(503))
const p = apiFetch('/api/jobs/abc')
const assertion = expect(p).rejects.toBeInstanceOf(BackendUnavailableError)
await jest.advanceTimersByTimeAsync(600)
await jest.advanceTimersByTimeAsync(1500)
await assertion
expect(fetchMock).toHaveBeenCalledTimes(3)
expect(getBackendStatus()).toBe('online')
})
it('recovers transparently when a retried GET succeeds on a later attempt', async () => {
jest.useFakeTimers()
fetchMock
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(mockResponse(200, { ok: true }))
const p = apiFetch('/api/jobs/abc')
await jest.advanceTimersByTimeAsync(600)
const res = await p
expect(res.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(getBackendStatus()).toBe('online')
})
it('surfaces the banner only once a GET has STALLED past the thresholds, then clears', async () => {
jest.useFakeTimers()
const d = deferredFetch()
fetchMock.mockImplementation(d.fn)
const p = apiFetch('/api/jobs/abc')
p.catch(() => {}) // avoid unhandled rejection if it ever fails
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('unavailable')
d.settle(mockResponse(200, { ok: true }))
await p
expect(getBackendStatus()).toBe('online')
})
it('never surfaces the banner for a slow POST (mutations are not tracked)', async () => {
jest.useFakeTimers()
const d = deferredFetch()
fetchMock.mockImplementation(d.fn)
const p = apiFetch('/api/jobs/create-from-url', { method: 'POST', body: '{}' })
p.catch(() => {})
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 5000)
expect(getBackendStatus()).toBe('online')
d.settle(mockResponse(200, { ok: true }))
await p
})
it('does NOT impose a hard timeout on a long-running POST (e.g. preview render)', async () => {
jest.useFakeTimers()
let capturedSignal: AbortSignal | undefined
const d = deferredFetch()
fetchMock.mockImplementation((_url: unknown, init: RequestInit) => {
capturedSignal = init.signal ?? undefined
return d.fn()
})
const p = apiFetch('/api/review/abc/preview-video', { method: 'POST', body: '{}' })
p.catch(() => {})
// Well past the GET hard-timeout (45s): a POST must still be running, unaborted.
await jest.advanceTimersByTimeAsync(60_000)
expect(capturedSignal?.aborted).toBe(false)
d.settle(mockResponse(200, { ok: true }))
await expect(p).resolves.toBeDefined()
})
it('never auto-retries a non-GET, even on network failure', async () => {
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
await expect(
apiFetch('/api/jobs/create-from-url', { method: 'POST', body: '{}' }),
).rejects.toBeInstanceOf(BackendUnavailableError)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('reads method + signal from a Request input (a POST Request is not retried)', async () => {
// jsdom has no global Request; provide a minimal stand-in with the fields
// apiFetch reads (url/method/signal) so `input instanceof Request` engages.
class FakeRequest {
url: string
method: string
signal?: AbortSignal
constructor(url: string, init?: { method?: string; signal?: AbortSignal }) {
this.url = url
this.method = init?.method ?? 'GET'
this.signal = init?.signal
}
}
;(globalThis as unknown as { Request: unknown }).Request = FakeRequest
try {
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const req = new FakeRequest('http://localhost/api/jobs/create-from-url', {
method: 'POST',
})
await expect(apiFetch(req as unknown as Request)).rejects.toBeInstanceOf(
BackendUnavailableError,
)
expect(fetchMock).toHaveBeenCalledTimes(1)
} finally {
delete (globalThis as unknown as { Request?: unknown }).Request
}
})
it('passes non-backend URLs (e.g. GCS uploads) straight through with the original error', async () => {
const gcsError = new TypeError('gcs unreachable')
fetchMock.mockRejectedValue(gcsError)
await expect(
apiFetch('https://storage.googleapis.com/bucket/obj', { method: 'PUT', body: 'x' }),
).rejects.toBe(gcsError)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(getBackendStatus()).toBe('online')
})
it('propagates a caller-initiated abort without surfacing the banner', async () => {
const abortErr = new DOMException('Aborted', 'AbortError')
fetchMock.mockRejectedValue(abortErr)
const controller = new AbortController()
controller.abort()
await expect(
apiFetch('/api/jobs/abc', { signal: controller.signal }),
).rejects.toBe(abortErr)
expect(getBackendStatus()).toBe('online')
})
})
+90
View File
@@ -0,0 +1,90 @@
/**
* @jest-environment jsdom
*
* Tests for the backend-connectivity status store (lib/backend-status.ts).
* Status is derived from how long the OLDEST in-flight tracked read has been
* outstanding — a read that completes promptly never surfaces the banner.
*/
import {
getBackendStatus,
beginRequest,
endRequest,
STALL_RECONNECTING_MS,
STALL_UNAVAILABLE_MS,
} from '@/lib/backend-status'
describe('backend-status store (stall-based)', () => {
let open: number[] = []
beforeEach(() => {
jest.useFakeTimers()
open = []
})
afterEach(() => {
// Settle anything still in flight so the module singleton resets to online.
open.forEach((id) => endRequest(id))
jest.clearAllTimers()
jest.useRealTimers()
})
it('starts online', () => {
expect(getBackendStatus()).toBe('online')
})
it('stays online while a read is young, then escalates as it stalls', async () => {
open.push(beginRequest())
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS - 1000)
expect(getBackendStatus()).toBe('online')
await jest.advanceTimersByTimeAsync(1000) // cross the reconnecting threshold
expect(getBackendStatus()).toBe('reconnecting')
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('unavailable')
})
it('returns to online the moment the stalled read settles', async () => {
const id = beginRequest()
open.push(id)
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 100)
expect(getBackendStatus()).toBe('unavailable')
endRequest(id)
open = []
expect(getBackendStatus()).toBe('online')
})
it('a read that completes quickly never surfaces the banner', async () => {
const id = beginRequest()
await jest.advanceTimersByTimeAsync(3000) // 3s — normal-slow, not a stall
endRequest(id)
expect(getBackendStatus()).toBe('online')
// ...and nothing appears later either (nothing is in flight).
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS)
expect(getBackendStatus()).toBe('online')
})
it('tracks the OLDEST outstanding read, not the newest', async () => {
const a = beginRequest()
open.push(a)
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
expect(getBackendStatus()).toBe('reconnecting')
const b = beginRequest() // fresh read starts while `a` is still stalled
open.push(b)
expect(getBackendStatus()).toBe('reconnecting')
endRequest(b) // settling the young one doesn't clear the old stall
open = [a]
expect(getBackendStatus()).toBe('reconnecting')
endRequest(a)
open = []
expect(getBackendStatus()).toBe('online')
})
})
@@ -0,0 +1,93 @@
import { render, screen, waitFor } from '@testing-library/react'
import { SystemStatusModal } from '@/components/system-status-modal'
import type { SystemStatus } from '@/lib/api'
// Mock the API layer so the modal renders against controlled status payloads.
const getSystemStatus = jest.fn()
jest.mock('@/lib/api', () => ({
api: {
getSystemStatus: () => getSystemStatus(),
},
}))
function baseStatus(overrides: Partial<SystemStatus['services']> = {}): SystemStatus {
return {
services: {
frontend: { status: 'ok', version: '0.196.3' },
backend: { status: 'ok', version: '0.196.3' },
encoder: { status: 'ok', version: '0.196.3' },
flacfetch: { status: 'ok', version: '0.21.1' },
separator: { status: 'offline' },
...overrides,
},
}
}
describe('SystemStatusModal', () => {
beforeEach(() => {
getSystemStatus.mockReset()
})
it('shows the live encoding worker instance type on the primary (no fallback)', async () => {
getSystemStatus.mockResolvedValue(
baseStatus({
encoder: {
status: 'ok',
version: '0.196.3',
admin_details: {
primary_vm: 'encoding-worker-a',
active_vm: 'encoding-worker-a',
active_zone: 'us-central1-c',
active_machine_type: 'c4d-highcpu-32',
on_fallback: false,
},
},
}),
)
render(<SystemStatusModal open onClose={() => {}} />)
// Instance type + serving VM are surfaced for the live worker.
expect(await screen.findByText('c4d-highcpu-32')).toBeInTheDocument()
expect(screen.getByText(/encoding-worker-a · us-central1-c/)).toBeInTheDocument()
// No fallback badge/notice when serving the primary.
expect(screen.queryByText('Fallback')).not.toBeInTheDocument()
})
it('flags a capacity fallback with the fallback badge and notice', async () => {
getSystemStatus.mockResolvedValue(
baseStatus({
encoder: {
status: 'ok',
version: '0.196.3',
admin_details: {
primary_vm: 'encoding-worker-a',
active_vm: 'encoding-worker-fallback-n2c',
active_zone: 'us-central1-a',
active_machine_type: 'n2-highcpu-32',
on_fallback: true,
},
},
}),
)
render(<SystemStatusModal open onClose={() => {}} />)
expect(await screen.findByText('n2-highcpu-32')).toBeInTheDocument()
expect(screen.getByText('Fallback')).toBeInTheDocument()
expect(
screen.getByText(/Primary capacity unavailable/i),
).toBeInTheDocument()
})
it('omits the live-worker section for non-admins (no admin_details)', async () => {
getSystemStatus.mockResolvedValue(baseStatus())
render(<SystemStatusModal open onClose={() => {}} />)
// Encoder card still renders, but there is no live-worker detail.
await waitFor(() => expect(getSystemStatus).toHaveBeenCalled())
expect(screen.queryByText('Live worker:')).not.toBeInTheDocument()
expect(screen.queryByText('Fallback')).not.toBeInTheDocument()
})
})
+2
View File
@@ -5,6 +5,7 @@ import { hasLocale } from 'next-intl';
import { notFound } from 'next/navigation';
import { routing } from '@/i18n/routing';
import { ReferralCapture } from '@/components/ReferralCapture';
import { BackendStatusBanner } from '@/components/backend-status-banner';
export function generateStaticParams() {
return routing.locales.map((locale) => ({ locale }));
@@ -37,6 +38,7 @@ export default async function LocaleLayout({
<Suspense fallback={null}>
<ReferralCapture />
</Suspense>
<BackendStatusBanner />
{children}
</NextIntlClientProvider>
);
@@ -0,0 +1,88 @@
"use client"
import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { Loader2, CloudOff, X } from "lucide-react"
import {
useBackendStatus,
__installBackendStatusDevHook,
} from "@/lib/backend-status"
/**
* App-wide, non-blocking banner that reacts to backend connectivity (see
* lib/backend-status.ts). During a brief origin blip — e.g. Cloud Run recycling its
* single min-instance — the API is momentarily unreachable even though nothing is
* broken and any in-flight karaoke renders keep running. Rather than every screen
* showing its own scary error, this shows a single reassuring message:
*
* - "reconnecting": a subtle pill with a spinner while we transparently retry.
* - "unavailable": a gentle card explaining it's temporary and that ongoing jobs
* are unaffected, once trouble persists past the threshold.
*
* It floats over content (no layout shift) and disappears the instant connectivity
* is restored.
*/
export function BackendStatusBanner() {
const status = useBackendStatus()
const t = useTranslations("backendStatus")
const [dismissed, setDismissed] = useState(false)
// Expose the dev/preview trigger (window.__nkBackendStatus) for manual UX review.
useEffect(() => {
__installBackendStatusDevHook()
}, [])
// Re-arm the dismiss so a *later* outage episode shows again.
useEffect(() => {
if (status === "online") setDismissed(false)
}, [status])
if (status === "online") return null
if (status === "reconnecting") {
return (
<div
className="fixed top-3 left-1/2 z-[60] -translate-x-1/2 pointer-events-none"
role="status"
aria-live="polite"
>
<div className="flex items-center gap-2 rounded-full border border-amber-500/30 bg-amber-950/80 px-3.5 py-1.5 text-xs text-amber-200 shadow-lg backdrop-blur">
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
<span>{t("reconnecting")}</span>
</div>
</div>
)
}
// status === "unavailable"
if (dismissed) return null
return (
<div
className="fixed top-3 left-1/2 z-[60] w-[calc(100%-1.5rem)] max-w-md -translate-x-1/2"
role="alert"
aria-live="assertive"
>
<div className="relative rounded-xl border border-amber-500/40 bg-amber-950/90 px-4 py-3 pr-9 text-amber-100 shadow-2xl backdrop-blur">
<button
type="button"
onClick={() => setDismissed(true)}
aria-label={t("dismiss")}
className="absolute right-2 top-2 rounded-md p-1 text-amber-300/70 transition-colors hover:bg-amber-800/50 hover:text-amber-100"
>
<X className="h-4 w-4" />
</button>
<div className="flex items-start gap-3">
<CloudOff className="mt-0.5 h-5 w-5 shrink-0 text-amber-300" />
<div className="space-y-1">
<p className="text-sm font-semibold text-amber-50">{t("unavailable.title")}</p>
<p className="text-xs leading-relaxed text-amber-200/90">{t("unavailable.body")}</p>
<p className="text-xs leading-relaxed text-amber-200/70">
{t("unavailable.reassurance")}
</p>
</div>
</div>
</div>
</div>
)
}
+40 -6
View File
@@ -59,7 +59,7 @@ function ServiceCard({
className="rounded-lg border p-4"
style={{
borderColor: "var(--card-border)",
backgroundColor: "var(--card-bg)",
backgroundColor: "var(--card)",
}}
>
<div className="flex items-center justify-between mb-1">
@@ -106,6 +106,38 @@ function ServiceCard({
);
}
function LiveWorkerSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const t = useTranslations('status');
return (
<div className="mt-2 text-xs">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="opacity-60">{t('liveWorker')}:</span>
<span className="font-mono font-medium">{details.active_machine_type}</span>
{details.on_fallback && (
<span
className="rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-400"
style={{ backgroundColor: "rgba(251,191,36,0.12)" }}
>
{t('fallbackBadge')}
</span>
)}
</div>
{details.active_vm && (
<div className="mt-0.5 font-mono opacity-50">
{details.active_vm}
{details.active_zone ? ` · ${details.active_zone}` : ""}
</div>
)}
{details.on_fallback && (
<div className="mt-1 opacity-50 text-[10px] leading-snug">
{t('fallbackNote')}
</div>
)}
</div>
);
}
function BlueGreenSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const t = useTranslations('status');
const [expanded, setExpanded] = useState(false);
@@ -216,7 +248,7 @@ export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--card-bg)", borderColor: "var(--card-border)" }}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--bg)", borderColor: "var(--card-border)" }}>
<DialogHeader>
<DialogTitle className="text-foreground">{t('systemStatus')}</DialogTitle>
</DialogHeader>
@@ -234,10 +266,12 @@ export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
<ServiceCard name={t('frontend')} service={frontendService} />
<ServiceCard name={t('backend')} service={services.backend} />
<ServiceCard name={t('encoder')} service={services.encoder}>
{services.encoder.admin_details &&
services.encoder.admin_details.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
{services.encoder.admin_details?.active_machine_type && (
<LiveWorkerSection details={services.encoder.admin_details} />
)}
{services.encoder.admin_details?.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
</ServiceCard>
<ServiceCard name={t('flacfetch')} service={services.flacfetch} />
<ServiceCard name={t('separator')} service={services.separator} />
+12 -6
View File
@@ -2,7 +2,7 @@
* Tests for API client
*/
import { api, ApiError, extractErrorMessage } from "../api"
import { api, ApiError, BackendUnavailableError, extractErrorMessage } from "../api"
// Mock fetch globally
global.fetch = jest.fn()
@@ -307,12 +307,18 @@ describe("API Client", () => {
expect(global.fetch).toHaveBeenCalledTimes(2)
})
it("gives up after 3 network failures and rethrows the network error", async () => {
;(global.fetch as jest.Mock).mockRejectedValue(new TypeError("Failed to fetch"))
it("gives up after 3 network failures with BackendUnavailableError (preserving the cause)", async () => {
const networkError = new TypeError("Failed to fetch")
;(global.fetch as jest.Mock).mockRejectedValue(networkError)
await expect(api.completeJobUpload("job-789", ["audio"])).rejects.toThrow(
"Failed to fetch"
)
// apiFetch maps a network-level failure to a typed BackendUnavailableError
// (which drives the app-wide connectivity banner) while keeping the original
// error as `.cause`, so nothing is silently swallowed.
const err = await api
.completeJobUpload("job-789", ["audio"])
.catch((e) => e)
expect(err).toBeInstanceOf(BackendUnavailableError)
expect(err.cause).toBe(networkError)
expect(global.fetch).toHaveBeenCalledTimes(3)
})
+362 -170
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -9,6 +9,7 @@
* flows through the existing corrections/complete paths.
*/
import type { LyricsSegment, ReferenceSource } from '@/lib/lyrics-review/types'
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
@@ -100,7 +101,7 @@ export async function fetchAutoCorrectSuggestions(
}
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(
const response = await apiFetch(
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/auto-correct`,
{
method: 'POST',
+3 -1
View File
@@ -7,6 +7,8 @@
* preview. Persistence still flows through the existing replace-segments
* Save path.
*/
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
@@ -95,7 +97,7 @@ export async function generateCustomLyrics(
const headers: Record<string, string> = {}
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(
const response = await apiFetch(
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/custom-lyrics/generate`,
{ method: 'POST', body: form, headers, signal },
)
+144
View File
@@ -0,0 +1,144 @@
'use client'
/**
* Global backend-connectivity status.
*
* The backend runs on Cloud Run with `--min-instances 1`. When Cloud Run recycles
* that single instance (routine host maintenance / instance max-lifetime), there is
* a brief window where the origin is unreachable and requests HANG (Cloud Run holds
* them during the cold start) even though nothing is actually broken — and any
* karaoke jobs already rendering keep running untouched.
*
* We want ONE reassuring app-wide banner during those blips, but only when there's
* real evidence of a problem — NOT merely because a request was a little slow. So
* status is derived purely from **how long the oldest in-flight backend GET has been
* outstanding**: a read that completes (even a slowish 3–5s one) shows nothing; only
* a read stalled past STALL_RECONNECTING_MS surfaces the hint, escalating past
* STALL_UNAVAILABLE_MS to the full message. This matches "only tell the user once
* something has genuinely been trying to load for >10s / timed out."
*
* Only GETs are tracked: reads are what a page waits on during a recycle, and long
* POSTs (search, generate, auto-correct) are legitimately slow and must never trip
* the banner. See lib/api.ts (apiFetch) for the begin/endRequest wiring.
*/
import { useSyncExternalStore } from 'react'
export type BackendStatus =
/** No stalled reads — everything is completing in a reasonable time. */
| 'online'
/** A read has been outstanding a while; show a subtle "reconnecting" hint. */
| 'reconnecting'
/** A read has been stalled long enough to show the full "temporarily unavailable". */
| 'unavailable'
/** A tracked read must be outstanding at least this long before we show ANYTHING —
* so a normal slow-but-successful load never surfaces the banner. */
export const STALL_RECONNECTING_MS = 10_000
/** ...and this long before we escalate to the full assertive message. */
export const STALL_UNAVAILABLE_MS = 20_000
let nextId = 1
/** id -> startedAt (ms) for every tracked backend GET currently in flight. */
const inFlight = new Map<number, number>()
/** Dev/preview override: when non-null, forces the reported status. */
let devOverride: BackendStatus | null = null
let status: BackendStatus = 'online'
let ticker: ReturnType<typeof setInterval> | null = null
const listeners = new Set<() => void>()
function emit() {
listeners.forEach((l) => l())
}
function setStatus(next: BackendStatus) {
if (status === next) return
status = next
emit()
}
function computeFromStalls(): BackendStatus {
if (inFlight.size === 0) return 'online'
let oldest = Infinity
for (const startedAt of inFlight.values()) {
if (startedAt < oldest) oldest = startedAt
}
const age = Date.now() - oldest
if (age >= STALL_UNAVAILABLE_MS) return 'unavailable'
if (age >= STALL_RECONNECTING_MS) return 'reconnecting'
return 'online'
}
function recompute() {
setStatus(devOverride ?? computeFromStalls())
// Stop the clock once nothing is outstanding (and no dev override needs it).
if (inFlight.size === 0 && devOverride === null && ticker) {
clearInterval(ticker)
ticker = null
}
}
function ensureTicker() {
if (ticker) return
// Re-evaluate every second so a request that keeps hanging escalates over time.
ticker = setInterval(recompute, 1000)
}
/**
* Mark a tracked backend read as started. Returns an id to pass to `endRequest` when
* it settles (success OR failure — either way it's no longer outstanding).
*/
export function beginRequest(): number {
const id = nextId++
inFlight.set(id, Date.now())
ensureTicker()
recompute()
return id
}
/** Mark a tracked read as settled. */
export function endRequest(id: number): void {
if (inFlight.delete(id)) recompute()
}
export function getBackendStatus(): BackendStatus {
return status
}
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
/**
* React hook: subscribe to the current backend connectivity status. Server render
* always yields "online" so the banner never appears in the static HTML.
*/
export function useBackendStatus(): BackendStatus {
return useSyncExternalStore(subscribe, getBackendStatus, () => 'online')
}
/**
* Dev/preview-only escape hatch so the outage UX can be demoed without waiting on a
* real stall. Exposed on `window.__nkBackendStatus` and no-ops on the production
* consumer host. Not referenced by app code paths.
*/
export function __installBackendStatusDevHook() {
if (typeof window === 'undefined') return
if (window.location.hostname === 'gen.nomadkaraoke.com') return
const simulate = (s: BackendStatus | null) => {
devOverride = s
if (s !== null) ensureTicker()
recompute()
}
;(window as unknown as { __nkBackendStatus?: unknown }).__nkBackendStatus = {
reconnecting: () => simulate('reconnecting'),
unavailable: () => simulate('unavailable'),
online: () => simulate(null),
get: () => getBackendStatus(),
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "الخلفية",
"encoder": "المشفر",
"flacfetch": "Flacfetch",
"separator": "الفاصل"
"separator": "الفاصل",
"fallbackBadge": "احتياطي",
"fallbackNote": "السعة الأساسية غير متوفرة — تم التوجيه إلى خادم احتياطي.",
"liveWorker": "عامل نشط"
},
"credits": {
"title": "شراء المزيد من الأرصدة",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} إضافي",
"variantOriginal": "أصلي",
"variantReissue": "إعادة إصدار"
},
"backendStatus": {
"reconnecting": "جارٍ إعادة الاتصال…",
"unavailable": {
"body": "هذا عادةً ما يكون مؤقتاً — يرجى المحاولة مرة أخرى بعد بضع دقائق.",
"reassurance": "أي مقاطع فيديو كاريوكي يتم إنشاؤها حالياً لن تتأثر وستستمر قيد المعالجة.",
"title": "نواجه مشكلة في الوصول إلى خوادمنا"
},
"dismiss": "تجاهل"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Codificador",
"flacfetch": "Flacfetch",
"separator": "Separador"
"separator": "Separador",
"fallbackBadge": "De reserva",
"fallbackNote": "Capacitat principal no disponible — s'ha redirigit a un tipus d'instància de reserva.",
"liveWorker": "Procés actiu"
},
"credits": {
"title": "Compra més crèdits",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reedició"
},
"backendStatus": {
"reconnecting": "Reconnectant…",
"unavailable": {
"body": "Això sol ser temporal — si us plau, torna-ho a provar d'aquí a un parell de minuts.",
"reassurance": "Els vídeos de karaoke que s'estiguin creant ara mateix no es veuran afectats i es continuaran processant.",
"title": "Tenim problemes per connectar amb els nostres servidors"
},
"dismiss": "Descarta"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Enkodér",
"flacfetch": "Flacfetch",
"separator": "Separátor"
"separator": "Separátor",
"fallbackBadge": "Záložní",
"fallbackNote": "Primární kapacita je nedostupná — přesměrováno na záložní typ instance.",
"liveWorker": "Aktivní worker"
},
"credits": {
"title": "Koupit další kredity",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originál",
"variantReissue": "Reedice"
},
"backendStatus": {
"reconnecting": "Obnovování připojení…",
"unavailable": {
"body": "Většinou jde o dočasný problém — zkus to prosím znovu za pár minut.",
"reassurance": "Právě vytvářená karaoke videa nejsou nijak ovlivněna a budou se nadále zpracovávat.",
"title": "Nedaří se nám spojit s našimi servery"
},
"dismiss": "Zavřít"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primær kapacitet utilgængelig — omdirigeret til en fallback-instanstype.",
"liveWorker": "Live worker"
},
"credits": {
"title": "Køb flere credits",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Genudgivelse"
},
"backendStatus": {
"reconnecting": "Genopretter forbindelse…",
"unavailable": {
"body": "Dette er som regel midlertidigt — prøv igen om et par minutter.",
"reassurance": "Eventuelle karaokevideoer, der i øjeblikket bliver lavet, påvirkes ikke og vil fortsat blive behandlet.",
"title": "Vi har problemer med at få forbindelse til vores servere"
},
"dismiss": "Afvis"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primäre Kapazität nicht verfügbar — auf einen Fallback-Instanztyp umgeleitet.",
"liveWorker": "Live-Worker"
},
"credits": {
"title": "Mehr Guthaben kaufen",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} Bonus",
"variantOriginal": "Original",
"variantReissue": "Neuauflage"
},
"backendStatus": {
"reconnecting": "Verbindung wird wiederhergestellt…",
"unavailable": {
"body": "Dies ist meist nur vorübergehend — bitte versuche es in ein paar Minuten noch einmal.",
"reassurance": "Alle Karaoke-Videos, die gerade erstellt werden, sind davon nicht betroffen und werden weiterverarbeitet.",
"title": "Wir haben Probleme, unsere Server zu erreichen"
},
"dismiss": "Ausblenden"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Εφεδρικό",
"fallbackNote": "Η κύρια χωρητικότητα δεν είναι διαθέσιμη — δρομολογήθηκε σε εφεδρικό τύπο instance.",
"liveWorker": "Ενεργός worker"
},
"credits": {
"title": "Αγόρασε Περισσότερες Μονάδες",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} μπόνους",
"variantOriginal": "Πρωτότυπο",
"variantReissue": "Επανέκδοση"
},
"backendStatus": {
"reconnecting": "Επανασύνδεση…",
"unavailable": {
"body": "Αυτό είναι συνήθως προσωρινό — παρακαλούμε δοκίμασε ξανά σε λίγα λεπτά.",
"reassurance": "Τυχόν βίντεο καραόκε που δημιουργούνται αυτήν τη στιγμή δεν επηρεάζονται και η επεξεργασία τους θα συνεχιστεί.",
"title": "Αντιμετωπίζουμε πρόβλημα σύνδεσης με τους διακομιστές μας"
},
"dismiss": "Απόρριψη"
}
}
+12
View File
@@ -357,6 +357,15 @@
"almostThere": "Almost there...",
"firstLoadNote": "First load can take up to 30 seconds"
},
"backendStatus": {
"reconnecting": "Reconnecting…",
"unavailable": {
"title": "We're having trouble reaching our servers",
"body": "This is usually temporary — please try again in a couple of minutes.",
"reassurance": "Any karaoke videos currently being created are unaffected and will keep processing."
},
"dismiss": "Dismiss"
},
"status": {
"queued": "Queued",
"processing": "Processing",
@@ -373,6 +382,9 @@
"secondaryStopped": "Secondary (stopped)",
"lastSwap": "Last swap: {time}",
"activeJobs": "Active jobs: {count}",
"liveWorker": "Live worker",
"fallbackBadge": "Fallback",
"fallbackNote": "Primary capacity unavailable — routed to a fallback instance type.",
"systemStatus": "System Status",
"frontend": "Frontend",
"backend": "Backend",
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Codificador",
"flacfetch": "Flacfetch",
"separator": "Separador"
"separator": "Separador",
"fallbackBadge": "Respaldo",
"fallbackNote": "Capacidad principal no disponible — redirigido a un tipo de instancia de respaldo.",
"liveWorker": "Worker activo"
},
"credits": {
"title": "Comprar más créditos",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reedición"
},
"backendStatus": {
"reconnecting": "Reconectando…",
"unavailable": {
"body": "Esto suele ser temporal — por favor, inténtalo de nuevo en un par de minutos.",
"reassurance": "Los videos de karaoke que se estén creando en este momento no se verán afectados y seguirán procesándose.",
"title": "Tenemos problemas para conectar con nuestros servidores"
},
"dismiss": "Descartar"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Varajärjestelmä",
"fallbackNote": "Ensisijainen kapasiteetti ei ole käytettävissä — ohjattu varainstanssiin.",
"liveWorker": "Live-työprosessi"
},
"credits": {
"title": "Osta lisää krediittejä",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonusta",
"variantOriginal": "Alkuperäinen",
"variantReissue": "Uudelleenjulkaisu"
},
"backendStatus": {
"reconnecting": "Yhdistetään uudelleen…",
"unavailable": {
"body": "Tämä on yleensä väliaikaista — yritä uudelleen parin minuutin kuluttua.",
"reassurance": "Tämä ei vaikuta parhaillaan luotaviin karaokevideoihin, vaan niiden käsittely jatkuu normaalisti.",
"title": "Palvelimiimme yhdistämisessä on ongelmia"
},
"dismiss": "Ohita"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encodeur",
"flacfetch": "Flacfetch",
"separator": "Séparateur"
"separator": "Séparateur",
"fallbackBadge": "Secours",
"fallbackNote": "Capacité principale indisponible — redirection vers un type d'instance de secours.",
"liveWorker": "Worker actif"
},
"credits": {
"title": "Acheter plus de crédits",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originale",
"variantReissue": "Réédition"
},
"backendStatus": {
"reconnecting": "Reconnexion…",
"unavailable": {
"body": "C'est généralement temporaire — réessaie dans quelques minutes.",
"reassurance": "Les vidéos de karaoké en cours de création ne sont pas affectées et continueront d'être traitées.",
"title": "Nous avons des difficultés à joindre nos serveurs"
},
"dismiss": "Ignorer"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "צד שרת",
"encoder": "מקודד",
"flacfetch": "Flacfetch",
"separator": "מפריד"
"separator": "מפריד",
"fallbackBadge": "גיבוי",
"fallbackNote": "הקיבולת הראשית אינה זמינה — נותב לסוג מופע גיבוי.",
"liveWorker": "תהליך פעיל"
},
"credits": {
"title": "קנה עוד קרדיטים",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} בונוס",
"variantOriginal": "מקורי",
"variantReissue": "הוצאה מחודשת"
},
"backendStatus": {
"reconnecting": "מתחבר מחדש…",
"unavailable": {
"body": "זה בדרך כלל זמני — אנא נסו שוב בעוד מספר דקות.",
"reassurance": "סרטוני קריוקי שנוצרים כרגע לא יושפעו וימשיכו בתהליך העיבוד.",
"title": "אנחנו מתקשים להתחבר לשרתים שלנו"
},
"dismiss": "התעלם"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "बैकएंड",
"encoder": "एनकोडर",
"flacfetch": "Flacfetch",
"separator": "सेपरेटर"
"separator": "सेपरेटर",
"fallbackBadge": "फ़ॉलबैक",
"fallbackNote": "प्राथमिक क्षमता उपलब्ध नहीं है — फ़ॉलबैक इंस्टेंस प्रकार पर रूट किया गया।",
"liveWorker": "लाइव वर्कर"
},
"credits": {
"title": "और क्रेडिट्स खरीदो",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} बोनस",
"variantOriginal": "मूल",
"variantReissue": "रीइश्यू"
},
"backendStatus": {
"reconnecting": "फिर से कनेक्ट हो रहा है…",
"unavailable": {
"body": "यह आमतौर पर अस्थायी होता है — कृपया कुछ मिनट बाद फिर से कोशिश करो।",
"reassurance": "अभी बन रहे किसी भी कराओके वीडियो पर कोई असर नहीं पड़ा है और उनकी प्रोसेसिंग जारी रहेगी।",
"title": "हमें अपने सर्वर तक पहुँचने में परेशानी हो रही है"
},
"dismiss": "हटाओ"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Enkoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Pričuva",
"fallbackNote": "Primarni kapacitet nije dostupan — preusmjereno na pričuvnu vrstu instance.",
"liveWorker": "Aktivni radnik"
},
"credits": {
"title": "Kupi još kredita",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reizdanje"
},
"backendStatus": {
"reconnecting": "Ponovno povezivanje…",
"unavailable": {
"body": "Ovo je obično privremeno — molim te pokušaj ponovno za nekoliko minuta.",
"reassurance": "Ovo ne utječe na karaoke videozapise koji se trenutno izrađuju i njihova će se obrada nastaviti.",
"title": "Imamo problema s povezivanjem na naše servere"
},
"dismiss": "Odbaci"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Kódoló",
"flacfetch": "Flacfetch",
"separator": "Szétválasztó"
"separator": "Szétválasztó",
"fallbackBadge": "Tartalék",
"fallbackNote": "Az elsődleges kapacitás nem elérhető — átirányítva egy tartalék példánytípusra.",
"liveWorker": "Élő feldolgozó"
},
"credits": {
"title": "Vásárolj több kreditet",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bónusz",
"variantOriginal": "Eredeti",
"variantReissue": "Újrakiadás"
},
"backendStatus": {
"reconnecting": "Újracsatlakozás…",
"unavailable": {
"body": "Ez általában átmeneti — kérlek, próbáld újra néhány perc múlva.",
"reassurance": "A jelenleg készülő karaoke videókat ez nem érinti, a feldolgozásuk zavartalanul folytatódik.",
"title": "Nem tudjuk elérni a szervereinket"
},
"dismiss": "Elvetés"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Pemisah"
"separator": "Pemisah",
"fallbackBadge": "Cadangan",
"fallbackNote": "Kapasitas utama tidak tersedia — dialihkan ke tipe instans cadangan.",
"liveWorker": "Pekerja aktif"
},
"credits": {
"title": "Beli Lebih Banyak Kredit",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Rilis ulang"
},
"backendStatus": {
"reconnecting": "Menghubungkan kembali…",
"unavailable": {
"body": "Biasanya ini hanya sementara — silakan coba lagi dalam beberapa menit.",
"reassurance": "Video karaoke yang sedang dibuat tidak akan terpengaruh dan akan terus diproses.",
"title": "Kami kesulitan terhubung ke server"
},
"dismiss": "Abaikan"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separatore"
"separator": "Separatore",
"fallbackBadge": "Fallback",
"fallbackNote": "Capacità principale non disponibile — reindirizzato a un tipo di istanza di fallback.",
"liveWorker": "Worker live"
},
"credits": {
"title": "Acquista altri crediti",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originale",
"variantReissue": "Ristampa"
},
"backendStatus": {
"reconnecting": "Riconnessione…",
"unavailable": {
"body": "Di solito è un problema temporaneo — riprova tra un paio di minuti.",
"reassurance": "I video karaoke attualmente in fase di creazione non subiranno interruzioni e continueranno a essere elaborati.",
"title": "Abbiamo problemi a raggiungere i nostri server"
},
"dismiss": "Ignora"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "バックエンド",
"encoder": "エンコーダー",
"flacfetch": "Flacfetch",
"separator": "セパレーター"
"separator": "セパレーター",
"fallbackBadge": "フォールバック",
"fallbackNote": "プライマリ容量が利用できないため、フォールバックのインスタンスタイプにルーティングされました。",
"liveWorker": "稼働中のワーカー"
},
"credits": {
"title": "クレジットを追加購入",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} ボーナス",
"variantOriginal": "オリジナル",
"variantReissue": "リイシュー"
},
"backendStatus": {
"reconnecting": "再接続中…",
"unavailable": {
"body": "通常は一時的な問題ですので、数分後にもう一度お試しください。",
"reassurance": "現在作成中のカラオケ動画に影響はありません。そのまま処理が継続されます。",
"title": "サーバーへの接続に問題が発生しています"
},
"dismiss": "閉じる"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "백엔드",
"encoder": "인코더",
"flacfetch": "Flacfetch",
"separator": "분리기"
"separator": "분리기",
"fallbackBadge": "대체",
"fallbackNote": "기본 용량을 사용할 수 없어 대체 인스턴스 유형으로 연결되었습니다.",
"liveWorker": "라이브 워커"
},
"credits": {
"title": "크레딧 추가 구매",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} 보너스",
"variantOriginal": "오리지널",
"variantReissue": "재발매"
},
"backendStatus": {
"reconnecting": "다시 연결하는 중…",
"unavailable": {
"body": "대부분 일시적인 현상이니 몇 분 후에 다시 시도해 주세요.",
"reassurance": "현재 생성 중인 노래방 영상은 영향을 받지 않고 정상적으로 처리됩니다.",
"title": "서버에 연결하는 데 문제가 발생했습니다"
},
"dismiss": "닫기"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Bahagian Belakang",
"encoder": "Pengekod",
"flacfetch": "Flacfetch",
"separator": "Pemisah"
"separator": "Pemisah",
"fallbackBadge": "Sandaran",
"fallbackNote": "Kapasiti utama tidak tersedia — dihalakan ke jenis sandaran.",
"liveWorker": "Pekerja aktif"
},
"credits": {
"title": "Beli Lebih Banyak Kredit",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Asal",
"variantReissue": "Keluaran semula"
},
"backendStatus": {
"reconnecting": "Menyambung semula…",
"unavailable": {
"body": "Ini biasanya sementara — sila cuba lagi dalam beberapa minit.",
"reassurance": "Sebarang video karaoke yang sedang dihasilkan tidak terjejas dan akan terus diproses.",
"title": "Kami menghadapi masalah menyambung ke pelayan kami"
},
"dismiss": "Tutup"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Koder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Reserve",
"fallbackNote": "Primærkapasitet er utilgjengelig — omdirigert til en reserveinstans.",
"liveWorker": "Aktiv arbeider"
},
"credits": {
"title": "Kjøp flere kreditter",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Nyutgivelse"
},
"backendStatus": {
"reconnecting": "Kobler til på nytt…",
"unavailable": {
"body": "Dette er vanligvis midlertidig — prøv igjen om et par minutter.",
"reassurance": "Eventuelle karaokevideoer som lages akkurat nå påvirkes ikke, og vil fortsette å behandles.",
"title": "Vi har problemer med å nå serverne våre"
},
"dismiss": "Lukk"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primaire capaciteit niet beschikbaar — omgeleid naar een fallback-instancetype.",
"liveWorker": "Live worker"
},
"credits": {
"title": "Koop meer credits",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Origineel",
"variantReissue": "Heruitgave"
},
"backendStatus": {
"reconnecting": "Opnieuw verbinden…",
"unavailable": {
"body": "Dit is meestal tijdelijk — probeer het over een paar minuten opnieuw.",
"reassurance": "Karaokevideo's die momenteel worden gemaakt, ondervinden hier geen hinder van en worden gewoon verder verwerkt.",
"title": "We kunnen onze servers even niet bereiken"
},
"dismiss": "Sluiten"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Koder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Zapasowy",
"fallbackNote": "Główne zasoby niedostępne — przekierowano do zapasowego typu instancji.",
"liveWorker": "Aktywny proces roboczy"
},
"credits": {
"title": "Kup więcej kredytów",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Oryginał",
"variantReissue": "Reedycja"
},
"backendStatus": {
"reconnecting": "Ponowne łączenie…",
"unavailable": {
"body": "To zazwyczaj problem tymczasowy — spróbuj ponownie za kilka minut.",
"reassurance": "Obecnie tworzone filmy karaoke są bezpieczne i będą nadal przetwarzane.",
"title": "Mamy problem z połączeniem z naszymi serwerami"
},
"dismiss": "Zamknij"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Capacidade principal indisponível — redirecionado para um tipo de instância de fallback.",
"liveWorker": "Worker ativo"
},
"credits": {
"title": "Comprar Mais Créditos",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bônus",
"variantOriginal": "Original",
"variantReissue": "Reedição"
},
"backendStatus": {
"reconnecting": "Reconectando…",
"unavailable": {
"body": "Isso geralmente é temporário — por favor, tente novamente em alguns minutos.",
"reassurance": "Os vídeos de karaokê que estão sendo criados no momento não serão afetados e continuarão sendo processados.",
"title": "Estamos com problemas para acessar nossos servidores"
},
"dismiss": "Dispensar"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Rezervă",
"fallbackNote": "Capacitatea principală este indisponibilă — redirecționată către un tip de instanță de rezervă.",
"liveWorker": "Worker activ"
},
"credits": {
"title": "Cumpără mai multe credite",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Reeditare"
},
"backendStatus": {
"reconnecting": "Se reconectează…",
"unavailable": {
"body": "Această situație este de obicei temporară — încearcă din nou în câteva minute.",
"reassurance": "Videoclipurile de karaoke aflate în curs de creare nu sunt afectate și vor continua să fie procesate.",
"title": "Întâmpinăm probleme la conectarea cu serverele noastre"
},
"dismiss": "Închide"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Бэкенд",
"encoder": "Кодировщик",
"flacfetch": "Flacfetch",
"separator": "Разделитель"
"separator": "Разделитель",
"fallbackBadge": "Резерв",
"fallbackNote": "Основные ресурсы недоступны — перенаправлено на резервный тип инстанса.",
"liveWorker": "Активный воркер"
},
"credits": {
"title": "Купить еще кредиты",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} бонус",
"variantOriginal": "Оригинал",
"variantReissue": "Переиздание"
},
"backendStatus": {
"reconnecting": "Переподключение…",
"unavailable": {
"body": "Обычно это временно — пожалуйста, попробуй еще раз через пару минут.",
"reassurance": "Это не повлияет на караоке-видео, которые сейчас создаются — они продолжат обрабатываться.",
"title": "Возникли проблемы с подключением к нашим серверам"
},
"dismiss": "Скрыть"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Enkodér",
"flacfetch": "Flacfetch",
"separator": "Separátor"
"separator": "Separátor",
"fallbackBadge": "Záloha",
"fallbackNote": "Primárna kapacita je nedostupná — presmerovaná na záložný typ inštancie.",
"liveWorker": "Aktívny worker"
},
"credits": {
"title": "Kúpiť viac kreditov",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Originál",
"variantReissue": "Reedícia"
},
"backendStatus": {
"reconnecting": "Obnovuje sa pripojenie…",
"unavailable": {
"body": "Zvyčajne ide len o dočasný problém — skús to znova o pár minút.",
"reassurance": "Karaoke videá, ktoré sa práve vytvárajú, to neovplyvní a ich spracovanie bude pokračovať.",
"title": "Máme problémy s pripojením k našim serverom"
},
"dismiss": "Zavrieť"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Primär kapacitet är otillgänglig — omdirigerad till en fallback-instans.",
"liveWorker": "Live-worker"
},
"credits": {
"title": "Köp fler krediter",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Original",
"variantReissue": "Nyutgåva"
},
"backendStatus": {
"reconnecting": "Återansluter…",
"unavailable": {
"body": "Detta är oftast tillfälligt — försök igen om ett par minuter.",
"reassurance": "Karaokevideor som håller på att skapas påverkas inte, utan fortsätter att bearbetas.",
"title": "Vi har problem med att nå våra servrar"
},
"dismiss": "Avfärda"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "สำรอง",
"fallbackNote": "ทรัพยากรหลักไม่พร้อมใช้งาน — เปลี่ยนเส้นทางไปยังอินสแตนซ์สำรองแล้ว",
"liveWorker": "เวิร์กเกอร์ที่ทำงานอยู่"
},
"credits": {
"title": "ซื้อเครดิตเพิ่ม",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} โบนัส",
"variantOriginal": "ต้นฉบับ",
"variantReissue": "วางจำหน่ายใหม่"
},
"backendStatus": {
"reconnecting": "กำลังเชื่อมต่อใหม่…",
"unavailable": {
"body": "ปัญหานี้มักเกิดขึ้นเพียงชั่วคราว — กรุณาลองใหม่อีกครั้งในอีกสองสามนาที",
"reassurance": "วิดีโอคาราโอเกะที่กำลังสร้างอยู่จะไม่ได้รับผลกระทบ และจะประมวลผลต่อไป",
"title": "เราพบปัญหาในการเชื่อมต่อกับเซิร์ฟเวอร์"
},
"dismiss": "ปิดทิ้ง"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Fallback",
"fallbackNote": "Hindi available ang pangunahing kapasidad — inilipat sa isang fallback instance type.",
"liveWorker": "Live worker"
},
"credits": {
"title": "Bumili ng Higit Pang Credits",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Orihinal",
"variantReissue": "Muling inilabas"
},
"backendStatus": {
"reconnecting": "Kumokonekta muli…",
"unavailable": {
"body": "Kadalasan ay pansamantala lamang ito — pakisubukan muli pagkalipas ng ilang minuto.",
"reassurance": "Ang anumang karaoke video na kasalukuyang ginagawa ay hindi maaapektuhan at patuloy na ipoproseso.",
"title": "Nahihirapan kaming kumonekta sa aming mga server"
},
"dismiss": "I-dismiss"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Arkayüz",
"encoder": "Kodlayıcı",
"flacfetch": "Flacfetch",
"separator": "Ayırıcı"
"separator": "Ayırıcı",
"fallbackBadge": "Yedek",
"fallbackNote": "Ana kapasite kullanılamıyor — yedek bir sunucu tipine yönlendirildi.",
"liveWorker": "Canlı işlemci"
},
"credits": {
"title": "Daha Fazla Kredi Al",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} bonus",
"variantOriginal": "Orijinal",
"variantReissue": "Yeniden basım"
},
"backendStatus": {
"reconnecting": "Yeniden bağlanıyor…",
"unavailable": {
"body": "Bu genellikle geçici bir durum — lütfen birkaç dakika sonra tekrar dene.",
"reassurance": "Şu anda oluşturulmakta olan karaoke videoları bu durumdan etkilenmez ve işlenmeye devam eder.",
"title": "Sunucularımıza ulaşmakta sorun yaşıyoruz"
},
"dismiss": "Kapat"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Бекенд",
"encoder": "Кодувальник",
"flacfetch": "Flacfetch",
"separator": "Розділювач"
"separator": "Розділювач",
"fallbackBadge": "Резерв",
"fallbackNote": "Основні потужності недоступні — перенаправлено на резервний тип інстансу.",
"liveWorker": "Активний воркер"
},
"credits": {
"title": "Купити більше кредитів",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} бонус",
"variantOriginal": "Оригінал",
"variantReissue": "Перевидання"
},
"backendStatus": {
"reconnecting": "Відновлення з'єднання…",
"unavailable": {
"body": "Зазвичай це тимчасово — будь ласка, спробуй ще раз за кілька хвилин.",
"reassurance": "Це не вплине на караоке-відео, які зараз створюються, їхня обробка продовжиться.",
"title": "Виникли проблеми зі зв'язком із нашими серверами"
},
"dismiss": "Закрити"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "Backend",
"encoder": "Encoder",
"flacfetch": "Flacfetch",
"separator": "Separator"
"separator": "Separator",
"fallbackBadge": "Dự phòng",
"fallbackNote": "Tài nguyên chính không khả dụng — đã chuyển hướng sang máy chủ dự phòng.",
"liveWorker": "Worker đang hoạt động"
},
"credits": {
"title": "Mua thêm credit",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} tặng kèm",
"variantOriginal": "Bản gốc",
"variantReissue": "Tái bản"
},
"backendStatus": {
"reconnecting": "Đang kết nối lại…",
"unavailable": {
"body": "Sự cố này thường chỉ là tạm thời — vui lòng thử lại sau vài phút.",
"reassurance": "Các video karaoke đang được tạo sẽ không bị ảnh hưởng và vẫn tiếp tục được xử lý.",
"title": "Chúng tôi đang gặp sự cố khi kết nối với máy chủ"
},
"dismiss": "Bỏ qua"
}
}
+13 -1
View File
@@ -378,7 +378,10 @@
"backend": "后端",
"encoder": "编码器",
"flacfetch": "Flacfetch",
"separator": "分离器"
"separator": "分离器",
"fallbackBadge": "备用",
"fallbackNote": "主容量不可用 — 已切换至备用实例类型。",
"liveWorker": "在线工作节点"
},
"credits": {
"title": "购买更多积分",
@@ -1680,5 +1683,14 @@
"variantBonus": "+{count} 附加曲目",
"variantOriginal": "原版",
"variantReissue": "再版"
},
"backendStatus": {
"reconnecting": "重新连接中…",
"unavailable": {
"body": "这通常是暂时现象,请几分钟后再试。",
"reassurance": "当前正在制作的卡拉OK视频不会受到影响,系统将继续进行处理。",
"title": "我们连接服务器时遇到了一些问题"
},
"dismiss": "忽略"
}
}
+17
View File
@@ -104,6 +104,23 @@ def create_database() -> dict:
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Jobs: query by request_metadata.client_id + tenant_id, order by created_at.
# Powers GET /api/jobs?client_id= — the idempotency lookup for externally
# created jobs (the Fiverr agent tags jobs client_id="fiverr:{order_id}").
# Without it that query 400s ("The query requires an index").
resources["firestore_index_jobs_client_id"] = firestore.Index(
"firestore-index-jobs-client-id",
project=PROJECT_ID,
database=firestore_db.name,
collection="jobs",
fields=[
firestore.IndexFieldArgs(field_path="request_metadata.client_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="tenant_id", order="ASCENDING"),
firestore.IndexFieldArgs(field_path="created_at", order="DESCENDING"),
],
opts=pulumi.ResourceOptions(depends_on=[firestore_db]),
)
# Sessions: query by user_email + is_active, order by created_at
resources["firestore_index_sessions_active"] = firestore.Index(
"firestore-index-sessions-active",
+29 -2
View File
@@ -210,7 +210,8 @@ def create_alert_policies(
# against the public health endpoint (through the Cloudflare edge, exactly
# the path real users take), and page only when it FAILS from more than one
# checker location — so a single flaky checker can't page us, but a genuine
# hard-down (every checker failing) does within ~1-2 min.
# hard-down (every checker failing) does after the retest window (~5-6 min
# with the 300s `duration`; see the HISTORY note on that below).
#
# NOTE on granularity: with selected_regions unset the check runs from all
# of Google's checker locations (several are in the USA alone). The
@@ -218,6 +219,28 @@ def create_alert_policies(
# by host), NOT broad geographic regions — two failed US checkers is enough
# to fire. That is intentional: >1 failing location is a real reachability
# problem worth paging, and requiring >1 filters out single-checker noise.
#
# HISTORY — why `duration` is 300s, not 60s:
# The service runs on `--min-instances 1` (a single warm instance). Two
# self-healing failure modes each briefly take health checks down from ALL
# checker locations at once, tripping the >1-location threshold:
# (a) Instance recycle. Cloud Run periodically replaces the lone instance
# (host maintenance / max-lifetime). On 2026-08-22 06:02:30–06:03:50
# UTC the instance was replaced (log: "Starting new instance …
# MIN_INSTANCE" then AUTOSCALING; STARTUP probe ready ~06:03:13),
# leaving ~80s with no warm origin — every uptime checker failed, then
# it self-healed. The alert fired at 06:06 and auto-cleared in ~1m41s.
# (b) Event-loop stall. The single instance can block on synchronous-ish
# work (e.g. orchestrating an encoding-worker fallback cold-start with
# blocking timeouts, seen 2026-08-22 00:11–00:12 UTC where four queued
# health probes all flushed at the same instant), so probes queue past
# the 10s uptime timeout across regions until it frees up.
# Both clear on their own well under 5 minutes. Rather than pay for a second
# always-on instance, we require the >1-location failure to PERSIST for 300s
# before paging: sub-5-min blips are suppressed, a genuine sustained hard-down
# still pages (at ~5–6 min instead of ~1–2). If real outages ever slip
# through undetected, the cheaper-detection lever is `--min-instances 2`
# (ci.yml) — that removes both failure modes at the source.
uptime_health = gcp.monitoring.UptimeCheckConfig(
"backend-health-uptime-check",
display_name="Karaoke Backend - /api/health",
@@ -273,7 +296,11 @@ def create_alert_policies(
# over the window; fire when more than one location is failing.
comparison="COMPARISON_GT",
threshold_value=1,
duration="60s",
# Require the >1-location failure to persist for 5 minutes
# before paging. Filters out sub-5-min self-healing blips on
# the single min-instance (recycle gap + event-loop stall);
# see the HISTORY note above. A sustained hard-down still fires.
duration="300s",
aggregations=[
gcp.monitoring.AlertPolicyConditionConditionThresholdAggregationArgs(
alignment_period="1200s",
+13 -4
View File
@@ -1816,11 +1816,20 @@ def create_audio_fetcher(
logger=logger,
)
elif api_url and not api_key:
if logger:
logger.warning("FLACFETCH_API_URL is set but FLACFETCH_API_KEY is not - falling back to local mode")
# Half-configured remote flacfetch is almost always a deploy/secret typo.
# Silently using local mode masks the misconfiguration — fail loudly so
# the operator fixes it. (Fallback audit 2026-06-09, Theme 1.)
raise AudioFetcherError(
"FLACFETCH_API_URL is set but FLACFETCH_API_KEY is not. Remote flacfetch "
"is half-configured — set both (or neither, for local mode). Refusing to "
"silently fall back to local mode and mask the misconfiguration."
)
elif api_key and not api_url:
if logger:
logger.warning("FLACFETCH_API_KEY is set but FLACFETCH_API_URL is not - falling back to local mode")
raise AudioFetcherError(
"FLACFETCH_API_KEY is set but FLACFETCH_API_URL is not. Remote flacfetch "
"is half-configured — set both (or neither, for local mode). Refusing to "
"silently fall back to local mode and mask the misconfiguration."
)
# Use local flacfetch library
return FlacFetchAudioFetcher(
+11 -1
View File
@@ -414,7 +414,17 @@ class VideoGenerator:
karaoke_styles = self.styles.get("karaoke", {})
font_path = karaoke_styles.get("font_path")
if font_path and os.path.isfile(font_path):
if font_path:
if not os.path.isfile(font_path):
# The theme specifies a branded karaoke font but the file is
# missing. Refuse to silently render the whole song with a libass
# system-fallback font on a paid deliverable — mirrors the
# background-image check in __init__. (Fallback audit, Theme 4.)
raise FileNotFoundError(
f"Karaoke font not found: {font_path}. The theme specifies a "
"branded font but the file is missing — refusing to silently "
"render with a system fallback font."
)
font_dir = os.path.dirname(font_path)
escaped_font_dir = self._escape_ffmpeg_filter_path(font_dir)
ass_filter += f":fontsdir={escaped_font_dir}"
+14 -3
View File
@@ -367,9 +367,20 @@ class VideoGenerator:
def _create_background(self, format, resolution):
"""Create or load the background image."""
if format["background_image"] and os.path.exists(format["background_image"]):
self.logger.info(f"Using background image file: {format['background_image']}")
background = Image.open(format["background_image"])
background_image = format["background_image"]
if background_image:
if not os.path.exists(background_image):
# A themed background was specified but the file is missing.
# Refuse to silently fall back to a flat color on a paid title/end
# card — mirrors the karaoke video path, which raises on a missing
# background image. (Fallback audit, Theme 4.)
raise FileNotFoundError(
f"Background image not found: {background_image}. The theme "
"specifies a background image but the file is missing — refusing "
"to silently render a flat color instead."
)
self.logger.info(f"Using background image file: {background_image}")
background = Image.open(background_image)
else:
self.logger.info(f"Using background color: {format['background_color']}")
background = Image.new("RGB", resolution, color=self.hex_to_rgb(format["background_color"]))
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.196.2"
version = "0.196.9"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+8 -8
View File
@@ -2342,20 +2342,20 @@ class TestCreateAudioFetcherRemoteSelection:
assert fetcher.api_key == "custom_key"
@patch.dict(os.environ, {"FLACFETCH_API_URL": "http://localhost:8080"}, clear=False)
def test_falls_back_to_local_without_api_key(self):
"""Test factory falls back to local when only URL is set."""
def test_half_configured_url_only_raises(self):
"""Half-configured remote (URL only) must fail loudly, not silently use local."""
# Clear FLACFETCH_API_KEY if it exists
with patch.dict(os.environ, {"FLACFETCH_API_KEY": ""}, clear=False):
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
with pytest.raises(AudioFetcherError, match="FLACFETCH_API_KEY is not"):
create_audio_fetcher()
@patch.dict(os.environ, {"FLACFETCH_API_KEY": "test_key"}, clear=False)
def test_falls_back_to_local_without_api_url(self):
"""Test factory falls back to local when only key is set."""
def test_half_configured_key_only_raises(self):
"""Half-configured remote (key only) must fail loudly, not silently use local."""
# Clear FLACFETCH_API_URL if it exists
with patch.dict(os.environ, {"FLACFETCH_API_URL": ""}, clear=False):
fetcher = create_audio_fetcher()
assert isinstance(fetcher, FlacFetchAudioFetcher)
with pytest.raises(AudioFetcherError, match="FLACFETCH_API_URL is not"):
create_audio_fetcher()
@patch.dict(os.environ, {}, clear=True)
def test_creates_local_fetcher_by_default(self):
+65
View File
@@ -0,0 +1,65 @@
"""
Fallback audit (Theme 4): a *configured* branded render asset that is missing
must fail loudly rather than silently substituting a different font/background on
a paid deliverable. Mirrors the existing background-image check in
lyrics_transcriber/output/video.VideoGenerator.__init__ (which already raises).
Scope: only the cleanest "configured-but-missing → raise" cases were changed
(4.1 final-MP4 karaoke font dir, 4.3 themed title/end background). Font
*substitution* paths (title/end font, CDG arial, measurement font) were left as
graceful fallbacks because they overlap with legitimate CJK font handling.
"""
import pytest
from unittest.mock import MagicMock
from karaoke_gen.lyrics_transcriber.output.video import VideoGenerator as AssVideoGenerator
from karaoke_gen.video_generator import VideoGenerator as ScreenVideoGenerator
# ---- 4.1: final-MP4 karaoke font dir ----
def _make_ass_generator(styles):
"""Build just enough of the ASS VideoGenerator to exercise _build_ass_filter."""
gen = AssVideoGenerator.__new__(AssVideoGenerator)
gen.styles = styles
gen.logger = MagicMock()
return gen
def test_build_ass_filter_raises_when_configured_font_missing():
"""A theme font that's set but missing must raise, not silently drop fontsdir."""
gen = _make_ass_generator({"karaoke": {"font_path": "/nonexistent/Branded.ttf"}})
with pytest.raises(FileNotFoundError, match="Karaoke font not found"):
gen._build_ass_filter("/tmp/lyrics.ass")
def test_build_ass_filter_ok_when_no_font_configured():
"""No font configured is legitimate — no fontsdir, no raise."""
gen = _make_ass_generator({"karaoke": {}})
result = gen._build_ass_filter("/tmp/lyrics.ass")
assert "fontsdir" not in result
assert result.startswith("ass=")
# ---- 4.3: themed title/end background image ----
def _make_screen_generator():
gen = ScreenVideoGenerator.__new__(ScreenVideoGenerator)
gen.logger = MagicMock()
return gen
def test_create_background_raises_when_configured_image_missing():
"""A background image that's set but missing must raise, not silently use a flat color."""
gen = _make_screen_generator()
fmt = {"background_image": "/nonexistent/bg.png", "background_color": "black"}
with pytest.raises(FileNotFoundError, match="Background image not found"):
gen._create_background(fmt, (100, 100))
def test_create_background_uses_color_when_no_image_configured():
"""No background image configured is legitimate — flat color, no raise."""
gen = _make_screen_generator()
fmt = {"background_image": None, "background_color": "#000000"}
bg = gen._create_background(fmt, (10, 10))
assert bg.size == (10, 10)