mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 17:21:26 +09:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ca8dabf44 |
No files matched your search
+100
-328
@@ -515,35 +515,12 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build frontend into the package
|
||||
# The Next.js static export (karaoke_gen/nextjs_frontend/out) is gitignored
|
||||
# (#876) and bundled into the wheel via pyproject `include`. Build it here,
|
||||
# BEFORE `poetry build`, so the wheel contains the CLI local-review UI.
|
||||
# node_modules is already installed above, so this just builds + copies.
|
||||
# `make build-frontend` fails loudly if the frontend build fails.
|
||||
run: make build-frontend
|
||||
|
||||
- name: Build package
|
||||
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
|
||||
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
|
||||
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
|
||||
run: poetry build --format wheel
|
||||
|
||||
- name: Verify frontend is bundled in the wheel
|
||||
# Guard against silently shipping a frontend-less wheel.
|
||||
run: python scripts/verify_wheel_frontend.py dist/*.whl
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
pip install dist/*.whl
|
||||
@@ -856,25 +833,6 @@ jobs:
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build frontend into the package
|
||||
# The Next.js static export (karaoke_gen/nextjs_frontend/out) is gitignored
|
||||
# (#876) and bundled into the wheel via pyproject `include`. Build it here,
|
||||
# BEFORE `poetry build`, so the shipped wheel contains the CLI local-review
|
||||
# UI. node_modules is already installed above, so this just builds + copies.
|
||||
# `make build-frontend` fails loudly if the frontend build fails.
|
||||
run: make build-frontend
|
||||
|
||||
- name: Build package
|
||||
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
|
||||
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
|
||||
@@ -883,10 +841,6 @@ jobs:
|
||||
# source (the GCE encoding worker pulls the wheel from GCS).
|
||||
run: poetry build --format wheel
|
||||
|
||||
- name: Verify frontend is bundled in the wheel
|
||||
# Loud guard against shipping a frontend-less wheel to PyPI / the GCE worker.
|
||||
run: python scripts/verify_wheel_frontend.py dist/*.whl
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -1234,15 +1188,10 @@ jobs:
|
||||
data = doc.to_dict()
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
for key in ["primary_vm", "primary_ip", "primary_version",
|
||||
"secondary_vm", "secondary_ip",
|
||||
"active_override_vm", "active_override_ip", "active_override_zone"]:
|
||||
"secondary_vm", "secondary_ip"]:
|
||||
f.write(f"{key}={data.get(key, '')}\n")
|
||||
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
|
||||
# capacity_state is a map — emit as single-line JSON so the green
|
||||
# selection step can demote recently-stocked-out machine types.
|
||||
f.write(f"capacity_state={json.dumps(data.get('capacity_state') or {})}\n")
|
||||
print(f"Config: primary={data.get('primary_vm')}, secondary={data.get('secondary_vm')}, "
|
||||
f"active_override={data.get('active_override_vm')}")
|
||||
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
|
||||
PYEOF
|
||||
|
||||
- name: Wait for concurrent deploy
|
||||
@@ -1277,159 +1226,29 @@ jobs:
|
||||
print("Set deploy_in_progress=true")
|
||||
PYEOF
|
||||
|
||||
# Capacity-aware green (staging) target. us-central1 is often in a c4d Spot
|
||||
# stockout, so the c4d secondary can't start and the serving worker is an n2
|
||||
# fallback recorded as active_override. We validate the new wheel on a FRESH
|
||||
# green — the c4d secondary if it starts, else a different n2 fallback (never
|
||||
# the current override, so it keeps serving) — then promote the green. See
|
||||
# infrastructure/encoding-worker/deploy_promote.py.
|
||||
- name: Select & start green target
|
||||
id: green
|
||||
# Never hard-fail the whole backend deploy just because no encoding
|
||||
# worker could be validated — emit green_ok=false and let the gated
|
||||
# health/encode/promote steps skip while the Cloud Run deploy proceeds.
|
||||
continue-on-error: true
|
||||
- name: Start secondary VM
|
||||
run: |
|
||||
python3 << 'PYEOF'
|
||||
import json, os, subprocess, sys, time
|
||||
sys.path.insert(0, "infrastructure/encoding-worker")
|
||||
import deploy_promote
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
echo "Starting secondary VM: $SECONDARY_VM"
|
||||
gcloud compute instances start "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
try:
|
||||
capacity_state = json.loads(os.environ.get("CAPACITY_STATE") or "{}")
|
||||
except Exception:
|
||||
capacity_state = {}
|
||||
config = {
|
||||
"primary_vm": os.environ.get("PRIMARY_VM") or None,
|
||||
"primary_ip": os.environ.get("PRIMARY_IP") or None,
|
||||
"secondary_vm": os.environ.get("SECONDARY_VM") or None,
|
||||
"secondary_ip": os.environ.get("SECONDARY_IP") or None,
|
||||
"secondary_zone": "us-central1-c",
|
||||
"active_override_vm": os.environ.get("OVERRIDE_VM") or None,
|
||||
"capacity_state": capacity_state,
|
||||
}
|
||||
raw = subprocess.run(
|
||||
["gcloud", "secrets", "versions", "access", "latest",
|
||||
"--secret=encoding-worker-fallback-vms", "--project=nomadkaraoke"],
|
||||
capture_output=True, text=True)
|
||||
try:
|
||||
fallbacks = json.loads(raw.stdout) if raw.returncode == 0 and raw.stdout.strip() else []
|
||||
except Exception as e:
|
||||
print(f"::warning::Could not parse fallback VM secret: {e}")
|
||||
fallbacks = []
|
||||
|
||||
candidates = deploy_promote.select_green_candidates(config, fallbacks)
|
||||
print("Green candidates (in order):", [f"{c['vm']}({c['kind']})" for c in candidates])
|
||||
|
||||
def vm_status(vm, zone):
|
||||
r = subprocess.run(
|
||||
["gcloud", "compute", "instances", "describe", vm,
|
||||
f"--zone={zone}", "--project=nomadkaraoke", "--format=value(status)"],
|
||||
capture_output=True, text=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
green = None
|
||||
started = [] # every VM we issued `start` to — so we can stop losers
|
||||
for c in candidates:
|
||||
vm, zone = c["vm"], c["zone"]
|
||||
print(f"Trying green candidate: {vm} ({zone}, kind={c['kind']})")
|
||||
subprocess.run(["gcloud", "compute", "instances", "start", vm,
|
||||
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
|
||||
started.append((vm, zone))
|
||||
for i in range(12):
|
||||
st = vm_status(vm, zone)
|
||||
print(f" {vm} status={st} ({i+1}/12)")
|
||||
if st == "RUNNING":
|
||||
green = c
|
||||
break
|
||||
time.sleep(10)
|
||||
if green:
|
||||
break
|
||||
|
||||
# Stop every candidate we started but did NOT select, so a slow-booting
|
||||
# loser can't come up later unmanaged (and billed) after the deploy.
|
||||
selected_vm = green["vm"] if green else None
|
||||
for vm, zone in started:
|
||||
if vm != selected_vm:
|
||||
print(f"Stopping unselected candidate {vm} ({zone})")
|
||||
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
|
||||
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
|
||||
|
||||
started_fresh = "true"
|
||||
inplace_failed = False
|
||||
if green is None:
|
||||
# Last resort: no separate green could start. Restart the current
|
||||
# serving override in place (accepts a brief blip; auto-resubmit
|
||||
# covers any in-flight render). If there's no override either, fail.
|
||||
ov = os.environ.get("OVERRIDE_VM")
|
||||
if ov:
|
||||
zone = os.environ.get("OVERRIDE_ZONE") or "us-central1-f"
|
||||
print(f"::warning::No separate green could start; restarting serving override {ov} in place")
|
||||
subprocess.run(["gcloud", "compute", "instances", "stop", ov,
|
||||
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
|
||||
for _ in range(18):
|
||||
if vm_status(ov, zone) in ("TERMINATED", "STOPPED", ""):
|
||||
break
|
||||
time.sleep(5)
|
||||
subprocess.run(["gcloud", "compute", "instances", "start", ov,
|
||||
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
|
||||
final_status = ""
|
||||
for _ in range(18):
|
||||
final_status = vm_status(ov, zone)
|
||||
if final_status == "RUNNING":
|
||||
break
|
||||
time.sleep(10)
|
||||
# Record it either way so rollback can recover it (we stopped it,
|
||||
# so if it didn't come back we must be able to start it again).
|
||||
green = {"vm": ov, "ip": os.environ.get("OVERRIDE_IP"),
|
||||
"zone": zone, "kind": "fallback"}
|
||||
started_fresh = "false" # it's the serving worker — never stop on rollback
|
||||
if final_status != "RUNNING":
|
||||
inplace_failed = True
|
||||
print(f"::error::In-place restart of {ov} did not reach RUNNING (status={final_status or 'unknown'})")
|
||||
else:
|
||||
print("::error::No green target could be started and no active override exists")
|
||||
|
||||
def _out(**kv):
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
for k, v in kv.items():
|
||||
f.write(f"{k}={v}\n")
|
||||
|
||||
# green_ok gates the downstream health/encode/promote steps. A missing
|
||||
# green, a green with no IP, or an in-place restart that didn't come back
|
||||
# RUNNING is "not ok" — the deploy skips the encoding-worker promote but
|
||||
# does NOT fail; when a serving override is involved we still emit its
|
||||
# vm/zone so the (always-run) rollback step can recover it.
|
||||
if green is None:
|
||||
_out(green_ok="false")
|
||||
print("::warning::No green target selected; skipping encoding-worker promote")
|
||||
elif not green.get("ip") or inplace_failed:
|
||||
_out(green_ok="false", green_vm=green["vm"], green_zone=green["zone"],
|
||||
green_started_fresh=started_fresh)
|
||||
reason = "has no IP" if not green.get("ip") else "did not return to RUNNING"
|
||||
print(f"::error::Green {green['vm']} {reason}; skipping promote")
|
||||
else:
|
||||
_out(green_ok="true", green_vm=green["vm"], green_ip=green["ip"],
|
||||
green_zone=green["zone"], green_kind=green["kind"],
|
||||
green_started_fresh=started_fresh)
|
||||
print(f"Green: {green['vm']} ({green['zone']}, kind={green['kind']}, started_fresh={started_fresh})")
|
||||
PYEOF
|
||||
env:
|
||||
PRIMARY_VM: ${{ steps.config.outputs.primary_vm }}
|
||||
PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
|
||||
SECONDARY_VM: ${{ steps.config.outputs.secondary_vm }}
|
||||
SECONDARY_IP: ${{ steps.config.outputs.secondary_ip }}
|
||||
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
|
||||
OVERRIDE_IP: ${{ steps.config.outputs.active_override_ip }}
|
||||
OVERRIDE_ZONE: ${{ steps.config.outputs.active_override_zone }}
|
||||
CAPACITY_STATE: ${{ steps.config.outputs.capacity_state }}
|
||||
for i in $(seq 1 12); do
|
||||
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke \
|
||||
--format='value(status)')
|
||||
echo "VM status: $STATUS (attempt $i/12)"
|
||||
if [ "$STATUS" = "RUNNING" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
|
||||
- name: Wait for service health
|
||||
id: health
|
||||
if: steps.green.outputs.green_ok == 'true'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.green.outputs.green_ip }}"
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
|
||||
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
|
||||
|
||||
@@ -1458,7 +1277,7 @@ jobs:
|
||||
id: encode-test
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SECONDARY_IP="${{ steps.green.outputs.green_ip }}"
|
||||
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
@@ -1522,35 +1341,13 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Rollback on failure
|
||||
# always() so the deploy_in_progress flag is ALWAYS cleared, even when the
|
||||
# green step found no worker (its downstream steps skip, but the flag was
|
||||
# already set). Skips only on a fully successful promote (passed == true).
|
||||
if: always() && steps.encode-test.outputs.passed != 'true'
|
||||
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
|
||||
run: |
|
||||
GREEN_VM="${{ steps.green.outputs.green_vm }}"
|
||||
GREEN_ZONE="${{ steps.green.outputs.green_zone }}"
|
||||
STARTED_FRESH="${{ steps.green.outputs.green_started_fresh }}"
|
||||
# Only stop a green we started fresh. If green is the serving override
|
||||
# (last-resort in-place restart), leave it running — it's serving
|
||||
# known-good code and stopping it would take production down.
|
||||
if [ "$STARTED_FRESH" = "true" ] && [ -n "$GREEN_VM" ]; then
|
||||
echo "Stopping fresh green $GREEN_VM ($GREEN_ZONE) due to failed deploy"
|
||||
gcloud compute instances stop "$GREEN_VM" \
|
||||
--zone="$GREEN_ZONE" --project=nomadkaraoke || true
|
||||
elif [ -n "$GREEN_VM" ] && [ -n "$GREEN_ZONE" ]; then
|
||||
# Serving override (last-resort in-place restart). We stopped it during
|
||||
# the restart, so if it isn't RUNNING we must bring it back — otherwise
|
||||
# production stays down after a failed deploy.
|
||||
echo "Green is the serving worker; ensuring $GREEN_VM is RUNNING"
|
||||
STATUS=$(gcloud compute instances describe "$GREEN_VM" \
|
||||
--zone="$GREEN_ZONE" --project=nomadkaraoke --format='value(status)' 2>/dev/null || echo "")
|
||||
if [ "$STATUS" != "RUNNING" ]; then
|
||||
echo "::warning::Serving worker $GREEN_VM is '${STATUS:-unknown}'; starting it back up"
|
||||
gcloud compute instances start "$GREEN_VM" \
|
||||
--zone="$GREEN_ZONE" --project=nomadkaraoke || true
|
||||
fi
|
||||
else
|
||||
echo "No green VM recorded; nothing to stop or recover"
|
||||
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
|
||||
if [ -n "$SECONDARY_VM" ]; then
|
||||
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
|
||||
gcloud compute instances stop "$SECONDARY_VM" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
fi
|
||||
|
||||
python3 -c "
|
||||
@@ -1563,120 +1360,95 @@ jobs:
|
||||
print('Cleared deploy_in_progress flag')
|
||||
" || true
|
||||
|
||||
# Promote the validated green to serving. For a c4d secondary green this is
|
||||
# the classic primary/secondary swap (and clears any stale override); for a
|
||||
# fallback green it becomes the active_override. Then drain + stop whatever
|
||||
# VM(s) the promote plan says are no longer serving. See deploy_promote.py.
|
||||
- name: Promote green to serving
|
||||
- name: Swap primary in Firestore
|
||||
if: steps.encode-test.outputs.passed == 'true'
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
GREEN_VM: ${{ steps.green.outputs.green_vm }}
|
||||
GREEN_IP: ${{ steps.green.outputs.green_ip }}
|
||||
GREEN_ZONE: ${{ steps.green.outputs.green_zone }}
|
||||
GREEN_KIND: ${{ steps.green.outputs.green_kind }}
|
||||
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
|
||||
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
|
||||
NEW_VERSION: ${{ steps.version_check.outputs.version }}
|
||||
PRIMARY_VM: ${{ steps.config.outputs.primary_vm }}
|
||||
PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
|
||||
PRIMARY_VERSION: ${{ steps.config.outputs.primary_version }}
|
||||
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
|
||||
OVERRIDE_IP: ${{ steps.config.outputs.active_override_ip }}
|
||||
OVERRIDE_ZONE: ${{ steps.config.outputs.active_override_zone }}
|
||||
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
|
||||
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
|
||||
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
|
||||
run: |
|
||||
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
|
||||
python3 << 'PYEOF'
|
||||
import json, os, subprocess, sys, time, urllib.request
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
sys.path.insert(0, "infrastructure/encoding-worker")
|
||||
import deploy_promote
|
||||
from google.cloud import firestore
|
||||
|
||||
green = {"vm": os.environ["GREEN_VM"], "ip": os.environ["GREEN_IP"],
|
||||
"zone": os.environ["GREEN_ZONE"], "kind": os.environ["GREEN_KIND"]}
|
||||
config = {
|
||||
"primary_vm": os.environ.get("PRIMARY_VM") or None,
|
||||
"primary_ip": os.environ.get("PRIMARY_IP") or None,
|
||||
"primary_version": os.environ.get("PRIMARY_VERSION") or None,
|
||||
"primary_zone": "us-central1-c",
|
||||
"active_override_vm": os.environ.get("OVERRIDE_VM") or None,
|
||||
"active_override_ip": os.environ.get("OVERRIDE_IP") or None,
|
||||
"active_override_zone": os.environ.get("OVERRIDE_ZONE") or None,
|
||||
}
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
plan = deploy_promote.promote_plan(green, config, now=now, version=os.environ["NEW_VERSION"])
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
db.collection("config").document("encoding-worker").update(plan["firestore_updates"])
|
||||
print("Applied config update:", json.dumps(plan["firestore_updates"], default=str))
|
||||
print(f"Green {green['vm']} ({green['kind']}) is now serving")
|
||||
doc_ref = db.collection("config").document("encoding-worker")
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
def active_jobs(ip):
|
||||
# /health is unauthenticated; None == "unknown / maybe busy".
|
||||
if not ip:
|
||||
return None
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://{ip}:8080/health", timeout=5) as r:
|
||||
return json.load(r).get("active_jobs")
|
||||
except Exception:
|
||||
return None
|
||||
@firestore.transactional
|
||||
def swap(transaction):
|
||||
transaction.update(doc_ref, {
|
||||
"primary_vm": os.environ["NEW_PRIMARY"],
|
||||
"primary_ip": os.environ["NEW_PRIMARY_IP"],
|
||||
"primary_version": os.environ["NEW_VERSION"],
|
||||
"primary_deployed_at": now,
|
||||
"secondary_vm": os.environ["OLD_PRIMARY"],
|
||||
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
|
||||
"secondary_version": os.environ["OLD_VERSION"],
|
||||
"secondary_deployed_at": now,
|
||||
"last_swap_at": now,
|
||||
"deploy_in_progress": False,
|
||||
"deploy_in_progress_since": None,
|
||||
})
|
||||
|
||||
def vm_status(vm, zone):
|
||||
r = subprocess.run(
|
||||
["gcloud", "compute", "instances", "describe", vm,
|
||||
f"--zone={zone}", "--project=nomadkaraoke", "--format=value(status)"],
|
||||
capture_output=True, text=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
# Drain (bounded) then stop each VM the plan retired. A non-RUNNING target
|
||||
# is already gone — stop it (idempotent) without waiting. For a RUNNING one
|
||||
# we wait for a confirmed 0 active_jobs so we never stop mid-render (#908
|
||||
# resubmit would cover a loss, but we still avoid it). The drain budget is
|
||||
# SHARED across all targets (one 20-min deadline, not per-target) so a slow
|
||||
# or unreachable target can't stretch the step to N×20 min; the step also
|
||||
# has a hard timeout-minutes. New renders already route to the promoted green.
|
||||
deadline = time.monotonic() + 1200
|
||||
for tgt in plan["drain_and_stop"]:
|
||||
vm, ip, zone = tgt["vm"], tgt.get("ip"), tgt.get("zone")
|
||||
if not vm or not zone:
|
||||
print(f"::warning::Skipping drain/stop with incomplete target: {tgt}")
|
||||
continue
|
||||
status = vm_status(vm, zone)
|
||||
if status != "RUNNING" or not ip:
|
||||
why = f"status={status or 'unknown'}" if status != "RUNNING" else "no IP to probe"
|
||||
print(f"{vm} ({why}); stopping without drain")
|
||||
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
|
||||
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
|
||||
continue
|
||||
print(f"Draining {vm} ({zone}) before stop...")
|
||||
n = active_jobs(ip)
|
||||
while n != 0 and time.monotonic() < deadline:
|
||||
time.sleep(15)
|
||||
n = active_jobs(ip)
|
||||
print(f" {vm} active_jobs={n} ({int(deadline - time.monotonic())}s budget left)")
|
||||
if n == 0:
|
||||
print(f"Drain confirmed for {vm}; stopping")
|
||||
else:
|
||||
print(f"::warning::Drain budget exhausted for {vm} (last={n}); stopping anyway")
|
||||
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
|
||||
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
|
||||
transaction = db.transaction()
|
||||
swap(transaction)
|
||||
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
|
||||
PYEOF
|
||||
|
||||
# Safety net: the deploy_in_progress lock is set unconditionally earlier, and
|
||||
# both Rollback (on failure) and Promote (on success) clear it — but if the
|
||||
# Promote step itself errors or hits its timeout, neither runs. This always()
|
||||
# step guarantees the lock is released so the next deploy doesn't stall 10 min
|
||||
# in "Wait for concurrent deploy". Idempotent with the other clears.
|
||||
- name: Clear encoding-worker deploy lock
|
||||
if: always()
|
||||
- name: Drain and stop old primary
|
||||
if: steps.encode-test.outputs.passed == 'true'
|
||||
run: |
|
||||
python3 -c "
|
||||
from google.cloud import firestore
|
||||
db = firestore.Client(project='nomadkaraoke')
|
||||
db.collection('config').document('encoding-worker').update({
|
||||
'deploy_in_progress': False,
|
||||
'deploy_in_progress_since': None,
|
||||
})
|
||||
print('Ensured deploy_in_progress is cleared')
|
||||
" || true
|
||||
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
|
||||
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
|
||||
|
||||
# Probe the worker's active_jobs. Echoes a non-negative integer on a
|
||||
# successful /health response, or "unknown" if /health can't be
|
||||
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
|
||||
# encoder running a 4K render pins all 32 cores and can miss the 5s
|
||||
# health window, and treating that as idle previously let us stop the
|
||||
# VM mid-render — orphaning the job and surfacing as "lost contact
|
||||
# with worker ... not found" (incident 2026-06-15).
|
||||
probe_active_jobs() {
|
||||
local body n
|
||||
body=$(curl -sf --connect-timeout 3 --max-time 5 \
|
||||
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
|
||||
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
|
||||
case "$n" in
|
||||
''|*[!0-9]*) echo "unknown" ;;
|
||||
*) echo "$n" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
|
||||
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
|
||||
# waiting — we only stop on a definitive 0 (or after the timeout, so
|
||||
# a wedged worker can't block the deploy forever). 20 min comfortably
|
||||
# covers a full 4K render; the old primary only drains in-flight work
|
||||
# since new renders already route to the just-swapped new primary.
|
||||
DRAIN_TIMEOUT=1200
|
||||
ELAPSED=0
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "Initial active_jobs: $ACTIVE_JOBS"
|
||||
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(probe_active_jobs)
|
||||
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
done
|
||||
|
||||
if [ "$ACTIVE_JOBS" = "0" ]; then
|
||||
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
|
||||
else
|
||||
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
|
||||
fi
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: |
|
||||
|
||||
@@ -53,11 +53,7 @@ jobs:
|
||||
import os, sys, datetime, boto3
|
||||
|
||||
BUCKET = os.environ["BUCKET"]
|
||||
# (label, prefix, max_age_hours, require_suffix)
|
||||
# require_suffix: only objects with this key suffix count toward
|
||||
# freshness (None = any object). git-repos/ requires ".bundle" so the
|
||||
# always-written manifest.json can't mark the prefix fresh when every
|
||||
# bundle failed / nothing was bundled — 0 bundles then reads as stale.
|
||||
# (label, prefix, max_age_hours)
|
||||
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
|
||||
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
|
||||
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
|
||||
@@ -65,11 +61,10 @@ jobs:
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
|
||||
# files and secrets DO upload to S3 nightly, so they stay at 36h.
|
||||
TARGETS = [
|
||||
("Firestore", "firestore/", 192, None),
|
||||
("GCS job files", "gcs/job-files/", 36, None),
|
||||
("Encrypted secrets", "secrets/", 36, None),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
|
||||
("Git repos", "git-repos/", 36, ".bundle"),
|
||||
("Firestore", "firestore/", 192),
|
||||
("GCS job files", "gcs/job-files/", 36),
|
||||
("Encrypted secrets", "secrets/", 36),
|
||||
("BigQuery weekly", "bigquery/daily-refresh/", 192),
|
||||
]
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
@@ -80,12 +75,10 @@ jobs:
|
||||
# operates per-page, which silently breaks "newest across all pages"
|
||||
# queries on prefixes with >1000 objects (e.g. firestore/ has ~22k).
|
||||
paginator = s3.get_paginator("list_objects_v2")
|
||||
for label, prefix, max_hours, require_suffix in TARGETS:
|
||||
for label, prefix, max_hours in TARGETS:
|
||||
latest = None
|
||||
for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
if require_suffix and not obj["Key"].endswith(require_suffix):
|
||||
continue
|
||||
if latest is None or obj["LastModified"] > latest:
|
||||
latest = obj["LastModified"]
|
||||
|
||||
|
||||
@@ -28,9 +28,6 @@ frontend/.swc/
|
||||
frontend/.turbo/
|
||||
frontend/build/
|
||||
frontend/dist/
|
||||
# Generated Next.js static export copied into the Python package at build time (#876).
|
||||
# Bundled into the wheel via pyproject `include`; must not be tracked in git.
|
||||
karaoke_gen/nextjs_frontend/out/
|
||||
|
||||
# Next.js specific
|
||||
frontend/*.tsbuildinfo
|
||||
|
||||
@@ -96,10 +96,6 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- Never modify GCP resources directly via console or `gcloud` CLI
|
||||
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
|
||||
- Stop and notify user on auth issues
|
||||
- **GCS ops on macOS: never use `gsutil -m`** — its fork-based multiprocessing segfaults
|
||||
on macOS (crash-report popups + the parent process hangs forever). Use `gcloud storage`
|
||||
instead (`gcloud storage cp/rm/rsync …`) — no fork, and faster. Plain `gsutil` (no `-m`)
|
||||
is safe but slower. `~/.boto` pins `parallel_process_count=1` as a safety net; don't remove it.
|
||||
|
||||
### Internationalization (i18n)
|
||||
|
||||
@@ -149,18 +145,13 @@ EOF
|
||||
```
|
||||
|
||||
### GCE Encoding Worker
|
||||
The worker is a c4d blue-green primary pair (`encoding-worker-a`/`-b`, us-central1-c)
|
||||
plus 8 stopped fallback VMs across 6 machine families for stockout resilience
|
||||
(`encoding-worker-fallback-{a,b,n2c,n2f,c4a,n4db,c2df,n2da}`). The currently-serving
|
||||
VM is `active_override_vm` in `config/encoding-worker` if set, else `primary_vm`.
|
||||
Use that VM name + its zone below (there is no VM literally named `encoding-worker`):
|
||||
```bash
|
||||
# Check health (includes wheel_version). Example uses the primary pair's VM.
|
||||
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
|
||||
# Check health (includes wheel_version)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="curl -s http://localhost:8080/health"
|
||||
|
||||
# Restart the service (pick up new worker-side code after a deploy)
|
||||
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
|
||||
# Restart service (pick up new wheel after a deploy)
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
--command="sudo systemctl restart encoding-worker"
|
||||
```
|
||||
|
||||
|
||||
+25
-75
@@ -7,9 +7,7 @@ Handles:
|
||||
- Admin-only operations
|
||||
- Audio search cache management
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Tuple, List, Optional, Any, Dict
|
||||
|
||||
@@ -155,23 +153,10 @@ async def get_admin_stats_overview(
|
||||
- Credit statistics
|
||||
- Beta program stats
|
||||
"""
|
||||
# The Firestore streaming below is synchronous; run it in a worker thread so
|
||||
# it can't block the event loop and stall every other request on this instance.
|
||||
return await asyncio.to_thread(_compute_admin_stats_overview, user_service.db, exclude_test)
|
||||
|
||||
|
||||
# Field masks for the overview stats streams. Job documents carry large payloads
|
||||
# (state_data, timeline, corrections — ~100MB across the collection), so streaming
|
||||
# full documents just to count statuses takes ~15-20s; with these masks it's ~1s.
|
||||
_OVERVIEW_USER_FIELDS = ["email", "last_login_at", "credit_transactions"]
|
||||
_OVERVIEW_JOB_FIELDS = ["user_email", "created_at", "status"]
|
||||
|
||||
|
||||
def _compute_admin_stats_overview(db, exclude_test: bool) -> AdminStatsOverview:
|
||||
"""Synchronous stats computation — called via asyncio.to_thread from the route."""
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud.firestore_v1 import aggregation
|
||||
|
||||
db = user_service.db
|
||||
now = datetime.utcnow()
|
||||
seven_days_ago = now - timedelta(days=7)
|
||||
thirty_days_ago = now - timedelta(days=30)
|
||||
@@ -195,37 +180,20 @@ def _compute_admin_stats_overview(db, exclude_test: bool) -> AdminStatsOverview:
|
||||
|
||||
if exclude_test:
|
||||
# When excluding test data, we must stream and filter in Python
|
||||
# because Firestore doesn't support "not ends with" queries.
|
||||
# The two streams are independent, so run them concurrently.
|
||||
# because Firestore doesn't support "not ends with" queries
|
||||
|
||||
def _stream_users():
|
||||
users, fetched = [], 0
|
||||
for doc in users_collection.select(_OVERVIEW_USER_FIELDS).limit(USERS_STREAM_LIMIT).stream():
|
||||
fetched += 1
|
||||
user_data = doc.to_dict()
|
||||
if not is_test_email(user_data.get("email", "")):
|
||||
users.append(user_data)
|
||||
return users, fetched
|
||||
|
||||
def _stream_jobs():
|
||||
jobs, fetched = [], 0
|
||||
for doc in jobs_collection.select(_OVERVIEW_JOB_FIELDS).limit(JOBS_STREAM_LIMIT).stream():
|
||||
fetched += 1
|
||||
job_data = doc.to_dict()
|
||||
if not is_test_email(job_data.get("user_email", "")):
|
||||
jobs.append(job_data)
|
||||
return jobs, fetched
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
users_future = executor.submit(_stream_users)
|
||||
jobs_future = executor.submit(_stream_jobs)
|
||||
all_users, users_fetched = users_future.result()
|
||||
all_jobs, jobs_fetched = jobs_future.result()
|
||||
# Stream all users and filter
|
||||
all_users = []
|
||||
users_fetched = 0
|
||||
for doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
|
||||
users_fetched += 1
|
||||
user_data = doc.to_dict()
|
||||
email = user_data.get("email", "")
|
||||
if not is_test_email(email):
|
||||
all_users.append(user_data)
|
||||
|
||||
if users_fetched >= USERS_STREAM_LIMIT:
|
||||
logger.warning(f"Users stream hit limit ({USERS_STREAM_LIMIT}), stats may be incomplete")
|
||||
if jobs_fetched >= JOBS_STREAM_LIMIT:
|
||||
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
|
||||
|
||||
# Calculate user stats from filtered list
|
||||
total_users = len(all_users)
|
||||
@@ -248,6 +216,19 @@ def _compute_admin_stats_overview(db, exclude_test: bool) -> AdminStatsOverview:
|
||||
if amount > 0:
|
||||
total_credits_issued_30d += amount
|
||||
|
||||
# Stream all jobs and filter by user_email
|
||||
all_jobs = []
|
||||
jobs_fetched = 0
|
||||
for doc in jobs_collection.limit(JOBS_STREAM_LIMIT).stream():
|
||||
jobs_fetched += 1
|
||||
job_data = doc.to_dict()
|
||||
user_email = job_data.get("user_email", "")
|
||||
if not is_test_email(user_email):
|
||||
all_jobs.append(job_data)
|
||||
|
||||
if jobs_fetched >= JOBS_STREAM_LIMIT:
|
||||
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
|
||||
|
||||
# Calculate job stats from filtered list
|
||||
total_jobs = len(all_jobs)
|
||||
jobs_last_7d = sum(
|
||||
@@ -332,7 +313,7 @@ def _compute_admin_stats_overview(db, exclude_test: bool) -> AdminStatsOverview:
|
||||
total_credits_issued_30d = 0
|
||||
try:
|
||||
users_fetched = 0
|
||||
for user_doc in users_collection.select(["credit_transactions"]).limit(USERS_STREAM_LIMIT).stream():
|
||||
for user_doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
|
||||
users_fetched += 1
|
||||
user_data = user_doc.to_dict()
|
||||
transactions = user_data.get("credit_transactions", [])
|
||||
@@ -2996,37 +2977,6 @@ async def get_user_payments(
|
||||
return service.get_user_payment_history(email)
|
||||
|
||||
|
||||
@router.get("/users/{email}/emails")
|
||||
async def get_user_emails(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List every email ever sent to a user (Postmark + our persisted log)."""
|
||||
from backend.services.postmark_admin_service import get_postmark_admin_service
|
||||
service = get_postmark_admin_service()
|
||||
return service.get_user_email_history(email)
|
||||
|
||||
|
||||
@router.get("/emails/{message_id}")
|
||||
async def get_email_detail(
|
||||
message_id: str,
|
||||
source: str = "postmark",
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Full detail for a single email — rendered HTML + delivery metadata.
|
||||
|
||||
``source=log`` reads our persisted copy directly (for mail older than
|
||||
Postmark's ~45-day retention); otherwise Postmark is queried with a
|
||||
fallback to the stored log.
|
||||
"""
|
||||
from backend.services.postmark_admin_service import get_postmark_admin_service
|
||||
service = get_postmark_admin_service()
|
||||
result = service.get_email_detail(message_id, source=source)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Email not found")
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/payments/{session_id}")
|
||||
async def get_payment_detail(
|
||||
session_id: str,
|
||||
|
||||
@@ -55,7 +55,7 @@ from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from pathlib import Path
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -235,54 +235,6 @@ class AudioSelectRequest(BaseModel):
|
||||
acknowledged_credits: Optional[int] = Field(None, description="Expected total credits after this selection (anti-mismatch guard)")
|
||||
|
||||
|
||||
class ProvideUrlRequest(BaseModel):
|
||||
"""Request to attach a YouTube/yt-dlp URL to an existing parked job."""
|
||||
url: str = Field(..., description="Audio source URL (YouTube, SoundCloud, or other yt-dlp supported site)")
|
||||
|
||||
|
||||
class AttachUploadUrlsRequest(BaseModel):
|
||||
"""Request for a signed upload URL to attach a file to an existing parked job."""
|
||||
filename: str = Field(..., description="Original filename with extension")
|
||||
content_type: str = Field("application/octet-stream", description="MIME type of the file")
|
||||
|
||||
|
||||
class AttachUploadUrlsResponse(BaseModel):
|
||||
"""Signed URL to upload an audio file for an existing job."""
|
||||
job_id: str
|
||||
gcs_path: str
|
||||
upload_url: str
|
||||
|
||||
|
||||
class AttachUploadCompleteRequest(BaseModel):
|
||||
"""Finalise an upload; gcs_path (from attach-upload-url) pins the exact file."""
|
||||
gcs_path: Optional[str] = Field(None, description="The gcs_path returned by attach-upload-url")
|
||||
|
||||
|
||||
class AttachResponse(BaseModel):
|
||||
"""Response after attaching a URL/file source to a parked job."""
|
||||
status: str
|
||||
job_id: str
|
||||
message: str
|
||||
|
||||
|
||||
class ResearchRequest(BaseModel):
|
||||
"""Request to re-run the audio search for an existing parked job.
|
||||
|
||||
Both fields are optional: when a caller edits the artist/title (e.g. to fix
|
||||
a typo or shorten an over-long title that returned nothing), the corrected
|
||||
values are used for the search AND applied to the job. When omitted, the
|
||||
job's existing search terms are re-used (a plain retry of a failed search).
|
||||
"""
|
||||
artist: Optional[str] = Field(None, description="Corrected artist to search + apply (blank = keep existing)")
|
||||
title: Optional[str] = Field(None, description="Corrected title to search + apply (blank = keep existing)")
|
||||
|
||||
@validator('artist', 'title')
|
||||
def normalize_text_fields(cls, v):
|
||||
if v is not None and isinstance(v, str):
|
||||
return normalize_text(v)
|
||||
return v
|
||||
|
||||
|
||||
class AudioSelectResponse(BaseModel):
|
||||
"""Response from audio source selection."""
|
||||
status: str
|
||||
@@ -628,55 +580,6 @@ async def _download_audio_and_trigger_workers(
|
||||
job_manager.fail_job(job_id, f"Audio download failed: {e}")
|
||||
|
||||
|
||||
def _build_result_response(r: AudioSearchResult) -> AudioSearchResultResponse:
|
||||
"""Serialize an AudioSearchResult into the rich API response shape.
|
||||
|
||||
raw_result may be a dict (remote flacfetch API) or a Release object
|
||||
(local flacfetch); both expose the same enriched display fields.
|
||||
Shared by the search, standalone-search, and re-search endpoints so the
|
||||
result shape stays identical across all three.
|
||||
"""
|
||||
raw_dict: Dict[str, Any] = {}
|
||||
if r.raw_result:
|
||||
if isinstance(r.raw_result, dict):
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass # Not a Release object
|
||||
|
||||
return AudioSearchResultResponse(
|
||||
index=r.index,
|
||||
title=r.title,
|
||||
artist=r.artist,
|
||||
provider=r.provider,
|
||||
url=r.url,
|
||||
duration=r.duration,
|
||||
quality=r.quality,
|
||||
source_id=r.source_id,
|
||||
seeders=raw_dict.get('seeders') or r.seeders,
|
||||
target_file=raw_dict.get('target_file') or r.target_file,
|
||||
year=raw_dict.get('year'),
|
||||
label=raw_dict.get('label'),
|
||||
edition_info=raw_dict.get('edition_info'),
|
||||
release_type=raw_dict.get('release_type'),
|
||||
channel=raw_dict.get('channel'),
|
||||
view_count=raw_dict.get('view_count'),
|
||||
size_bytes=raw_dict.get('size_bytes'),
|
||||
target_file_size=raw_dict.get('target_file_size'),
|
||||
track_pattern=raw_dict.get('track_pattern'),
|
||||
match_score=raw_dict.get('match_score'),
|
||||
formatted_size=raw_dict.get('formatted_size'),
|
||||
formatted_duration=raw_dict.get('formatted_duration'),
|
||||
formatted_views=raw_dict.get('formatted_views'),
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
# Remote API uses 'quality_data', local uses 'quality' for the dict
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/audio-search/search", response_model=AudioSearchResponse)
|
||||
async def search_audio(
|
||||
request: Request,
|
||||
@@ -806,7 +709,6 @@ async def search_audio(
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -984,8 +886,59 @@ async def search_audio(
|
||||
)
|
||||
|
||||
# Convert to response format with full Release data for rich display
|
||||
result_responses = [_build_result_response(r) for r in search_results]
|
||||
|
||||
result_responses = []
|
||||
for r in search_results:
|
||||
# Get full serialized data from raw_result if available
|
||||
# raw_result can be either:
|
||||
# - A dict (from remote flacfetch API)
|
||||
# - A Release object (from local flacfetch)
|
||||
raw_dict = {}
|
||||
if r.raw_result:
|
||||
if isinstance(r.raw_result, dict):
|
||||
# Remote flacfetch API returns dicts directly
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
# Local flacfetch returns Release objects
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass # Not a Release object
|
||||
|
||||
result_responses.append(
|
||||
AudioSearchResultResponse(
|
||||
index=r.index,
|
||||
title=r.title,
|
||||
artist=r.artist,
|
||||
provider=r.provider,
|
||||
url=r.url,
|
||||
duration=r.duration,
|
||||
quality=r.quality,
|
||||
source_id=r.source_id,
|
||||
seeders=raw_dict.get('seeders') or r.seeders,
|
||||
target_file=raw_dict.get('target_file') or r.target_file,
|
||||
# Additional fields for rich display
|
||||
year=raw_dict.get('year'),
|
||||
label=raw_dict.get('label'),
|
||||
edition_info=raw_dict.get('edition_info'),
|
||||
release_type=raw_dict.get('release_type'),
|
||||
channel=raw_dict.get('channel'),
|
||||
view_count=raw_dict.get('view_count'),
|
||||
size_bytes=raw_dict.get('size_bytes'),
|
||||
target_file_size=raw_dict.get('target_file_size'),
|
||||
track_pattern=raw_dict.get('track_pattern'),
|
||||
match_score=raw_dict.get('match_score'),
|
||||
# Pre-computed display fields
|
||||
formatted_size=raw_dict.get('formatted_size'),
|
||||
formatted_duration=raw_dict.get('formatted_duration'),
|
||||
formatted_views=raw_dict.get('formatted_views'),
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
# Full quality object for Release.from_dict()
|
||||
# Remote API uses 'quality_data', local uses 'quality' for the dict
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
)
|
||||
|
||||
return AudioSearchResponse(
|
||||
status="awaiting_selection",
|
||||
job_id=job_id,
|
||||
@@ -1059,10 +1012,50 @@ async def search_audio_standalone(
|
||||
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
|
||||
|
||||
# Build result response objects
|
||||
result_responses: List[AudioSearchResultResponse] = [
|
||||
_build_result_response(r) for r in search_results
|
||||
]
|
||||
results_dicts: List[Dict[str, Any]] = [r.to_dict() for r in search_results]
|
||||
result_responses: List[AudioSearchResultResponse] = []
|
||||
results_dicts: List[Dict[str, Any]] = []
|
||||
for r in search_results:
|
||||
raw_dict: Dict[str, Any] = {}
|
||||
if r.raw_result:
|
||||
if isinstance(r.raw_result, dict):
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
result_responses.append(
|
||||
AudioSearchResultResponse(
|
||||
index=r.index,
|
||||
title=r.title,
|
||||
artist=r.artist,
|
||||
provider=r.provider,
|
||||
url=r.url,
|
||||
duration=r.duration,
|
||||
quality=r.quality,
|
||||
source_id=r.source_id,
|
||||
seeders=raw_dict.get('seeders') or r.seeders,
|
||||
target_file=raw_dict.get('target_file') or r.target_file,
|
||||
year=raw_dict.get('year'),
|
||||
label=raw_dict.get('label'),
|
||||
edition_info=raw_dict.get('edition_info'),
|
||||
release_type=raw_dict.get('release_type'),
|
||||
channel=raw_dict.get('channel'),
|
||||
view_count=raw_dict.get('view_count'),
|
||||
size_bytes=raw_dict.get('size_bytes'),
|
||||
target_file_size=raw_dict.get('target_file_size'),
|
||||
track_pattern=raw_dict.get('track_pattern'),
|
||||
match_score=raw_dict.get('match_score'),
|
||||
formatted_size=raw_dict.get('formatted_size'),
|
||||
formatted_duration=raw_dict.get('formatted_duration'),
|
||||
formatted_views=raw_dict.get('formatted_views'),
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
)
|
||||
results_dicts.append(r.to_dict())
|
||||
|
||||
# Store session in Firestore (TTL: 7 days)
|
||||
# Long TTL so users who leave a tab open mid-flow don't hit "Search expired".
|
||||
@@ -1136,394 +1129,6 @@ async def get_audio_search_results(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/research", response_model=AudioSearchResponse)
|
||||
async def research_audio(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
body: ResearchRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Re-run the audio search for an existing job that is awaiting selection.
|
||||
|
||||
Handles the dead-end where a search returned nothing (or a transient
|
||||
failure parked the job with no sources): the user can retry, or edit the
|
||||
artist/title and search again. The job stays in AWAITING_AUDIO_SELECTION;
|
||||
its cached results are replaced with the fresh ones (which may be empty —
|
||||
that is a normal outcome, returned as a 200 with an empty list, not an
|
||||
error, so the UI can offer the manual fallback).
|
||||
|
||||
Editing the artist/title also applies the correction to the job's display
|
||||
artist/title (used for title screens, filenames, lyrics), so the whole
|
||||
pipeline runs on the corrected metadata.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_require_audio_search_enabled(request, locale)
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "audioSearch.jobNotFound", job_id=job_id))
|
||||
|
||||
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job is not awaiting audio selection (status: {job.status})"
|
||||
)
|
||||
|
||||
# Resolve the terms to search. A non-blank edited value overrides; otherwise
|
||||
# fall back to the job's existing search terms (then its display fields).
|
||||
edited_artist = (body.artist or "").strip()
|
||||
edited_title = (body.title or "").strip()
|
||||
artist = edited_artist or job.audio_search_artist or job.artist or ""
|
||||
title = edited_title or job.audio_search_title or job.title or ""
|
||||
|
||||
if not artist or not title:
|
||||
raise HTTPException(status_code=400, detail="Both artist and title are required to search")
|
||||
|
||||
# Apply the edit to the job before searching so a corrected typo/title flows
|
||||
# through the rest of the pipeline (search terms + display metadata).
|
||||
prev_artist = job.audio_search_artist or job.artist
|
||||
prev_title = job.audio_search_title or job.title
|
||||
if artist != prev_artist or title != prev_title:
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_search_artist': artist,
|
||||
'audio_search_title': title,
|
||||
'artist': artist,
|
||||
'title': title,
|
||||
})
|
||||
logger.info(f"[job:{job_id}] Re-search with edited terms: {artist} - {title}")
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.SEARCHING_AUDIO,
|
||||
progress=5,
|
||||
message=f"Searching for: {artist} - {title}",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
audio_search_service = get_audio_search_service()
|
||||
try:
|
||||
search_results = await audio_search_service.search_async(artist, title)
|
||||
except NoResultsError:
|
||||
search_results = []
|
||||
except AudioSearchError as e:
|
||||
# Restore the awaiting state so the job isn't stranded, then surface the error.
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message="Search failed. Please try again or provide your own audio.",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
raise HTTPException(status_code=502, detail=f"Search failed: {e}")
|
||||
|
||||
# Replace cached results (empty is fine — the UI offers the manual fallback).
|
||||
results_dicts = [r.to_dict() for r in search_results]
|
||||
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
|
||||
job_manager.update_job(job_id, {
|
||||
'state_data.audio_search_results': results_dicts,
|
||||
'state_data.audio_search_count': len(results_dicts),
|
||||
# Overwrite (or clear) the stale remote_search_id from the prior search.
|
||||
'state_data.remote_search_id': remote_id,
|
||||
})
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=(
|
||||
f"Found {len(results_dicts)} audio sources. Waiting for selection."
|
||||
if results_dicts else
|
||||
"No audio sources found. Edit the details and search again, or provide your own audio."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
return AudioSearchResponse(
|
||||
status="awaiting_selection",
|
||||
job_id=job_id,
|
||||
message=f"Re-search complete: {len(results_dicts)} audio sources.",
|
||||
results=[_build_result_response(r) for r in search_results],
|
||||
results_count=len(results_dicts),
|
||||
auto_download=False,
|
||||
server_version=VERSION,
|
||||
)
|
||||
|
||||
|
||||
# Audio formats accepted by the manual file-upload fallback (case-insensitive).
|
||||
_AUDIO_UPLOAD_EXTENSIONS = {".mp3", ".wav", ".flac", ".m4a", ".ogg"}
|
||||
|
||||
# Upper bound on an inline (non-YouTube) URL download so a hung yt-dlp fetch can
|
||||
# never leave a parked job stuck in DOWNLOADING_AUDIO. Kept under typical proxy
|
||||
# request timeouts; YouTube URLs bypass this via the async download worker.
|
||||
URL_DOWNLOAD_TIMEOUT_SECONDS = 240
|
||||
|
||||
|
||||
def _require_audio_search_enabled(request: Request, locale: str) -> None:
|
||||
"""Apply the tenant `audio_search` feature gate (mirrors /search).
|
||||
|
||||
White-label portals that don't offer audio search must not be able to drive
|
||||
the recovery endpoints (re-search / provide-url / upload) either.
|
||||
"""
|
||||
tenant_config = get_tenant_config_from_request(request)
|
||||
if tenant_config and not tenant_config.features.audio_search:
|
||||
raise HTTPException(status_code=403, detail=t(locale, "audioSearch.notEnabled"))
|
||||
|
||||
|
||||
def _require_awaiting_selection(job_id: str, locale: str):
|
||||
"""Load a job and assert it is parked awaiting audio selection.
|
||||
|
||||
Shared guard for the manual-fallback endpoints (URL / file upload). Returns
|
||||
the job or raises 404 (missing) / 400 (wrong state).
|
||||
|
||||
Note: like the sibling /select endpoint (which Bulk Mode already relies on),
|
||||
this does not enforce per-user job ownership — bulk jobs are owned by a
|
||||
service account, so a per-user check here would lock the real submitter out
|
||||
of recovering their own parked job. Ownership hardening, if desired, must be
|
||||
applied uniformly across the whole audio-search surface, not just here.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "audioSearch.jobNotFound", job_id=job_id))
|
||||
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Job is not awaiting audio selection (status: {job.status})"
|
||||
)
|
||||
return job
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/provide-url", response_model=AttachResponse)
|
||||
async def provide_url_for_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: ProvideUrlRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Attach a YouTube/yt-dlp URL to a parked job and start processing.
|
||||
|
||||
The manual escape hatch when audio search finds nothing usable: the user
|
||||
pastes a source URL for a job already in AWAITING_AUDIO_SELECTION. The job
|
||||
was already created and charged, so we do NOT create a new job or deduct
|
||||
base credits — the post-download duration reconcile handles final billing.
|
||||
|
||||
YouTube URLs are handed to the async audio-download Cloud Run Job (survives
|
||||
request/instance shutdown, no long-blocking request). Generic yt-dlp URLs are
|
||||
downloaded inline (the worker has no generic path) but bounded by a timeout so
|
||||
a slow/hung download can never strand the job in DOWNLOADING_AUDIO.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_require_audio_search_enabled(request, locale)
|
||||
# Validation helpers live in file_upload; import lazily to avoid a heavy
|
||||
# import at module load (and any import cycle).
|
||||
from backend.api.routes.file_upload import (
|
||||
_is_youtube_url,
|
||||
_validate_url,
|
||||
_unsupported_url_platform,
|
||||
_drm_unsupported_detail,
|
||||
)
|
||||
|
||||
job = _require_awaiting_selection(job_id, locale)
|
||||
|
||||
url = (body.url or "").strip()
|
||||
|
||||
# Reject DRM-protected streaming links (Apple Music, Spotify, Tidal, …) upfront.
|
||||
unsupported_platform = _unsupported_url_platform(url)
|
||||
if unsupported_platform:
|
||||
raise HTTPException(status_code=400, detail=_drm_unsupported_detail(locale, unsupported_platform))
|
||||
|
||||
if not _validate_url(url):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL."
|
||||
)
|
||||
|
||||
youtube_service = get_youtube_download_service()
|
||||
is_youtube = _is_youtube_url(url)
|
||||
|
||||
# For YouTube URLs, check availability early (geo/private/removed/bot/age).
|
||||
if is_youtube:
|
||||
availability = await youtube_service.check_availability(url)
|
||||
if availability and not availability.get("available"):
|
||||
if availability.get("is_geo_restricted"):
|
||||
detail = ("This YouTube video is not available in our server's region. "
|
||||
"Try using a different source for this song.")
|
||||
elif availability.get("is_private"):
|
||||
detail = "This YouTube video is private and cannot be downloaded."
|
||||
elif availability.get("is_removed"):
|
||||
detail = "This YouTube video has been removed and cannot be downloaded."
|
||||
elif availability.get("is_bot_blocked"):
|
||||
detail = ("We're temporarily unable to access YouTube to download this video. "
|
||||
"Please try again in a few minutes, or search for this song from another source.")
|
||||
elif availability.get("is_age_restricted"):
|
||||
detail = "This YouTube video is age-restricted and cannot be downloaded."
|
||||
else:
|
||||
detail = f"This YouTube video is unavailable: {availability.get('error', 'unknown error')}"
|
||||
raise HTTPException(status_code=400, detail=detail)
|
||||
|
||||
# Point the job at the URL source and enter the download state. The
|
||||
# audio-download worker (and generic inline path below) read these fields
|
||||
# when selected_audio_index is unset (which it is for a parked job).
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_source_type': 'url',
|
||||
'url': url,
|
||||
'source_name': 'YouTube' if is_youtube else 'url',
|
||||
'download_url': url,
|
||||
})
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=10,
|
||||
message=f"Downloading from provided URL: {job.artist} - {job.title}",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
def _requeue(msg: str) -> None:
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=msg,
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
if is_youtube:
|
||||
# Async: the Cloud Run download job downloads + reconciles + triggers
|
||||
# workers itself, so the request returns immediately.
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_audio_download_worker(job_id)
|
||||
if not triggered:
|
||||
_requeue("Couldn't start the download. Please try again.")
|
||||
raise HTTPException(status_code=502, detail="Failed to trigger audio download worker")
|
||||
return AttachResponse(status="success", job_id=job_id, message="URL accepted, download started")
|
||||
|
||||
# Generic yt-dlp URL: no async worker path exists, so download inline —
|
||||
# bounded so a hung download can't strand the job in DOWNLOADING_AUDIO.
|
||||
try:
|
||||
audio_gcs_path = await asyncio.wait_for(
|
||||
youtube_service.download(url=url, job_id=job_id, artist=job.artist, title=job.title),
|
||||
timeout=URL_DOWNLOAD_TIMEOUT_SECONDS,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
_requeue("That download took too long. Try another URL or search again.")
|
||||
raise HTTPException(status_code=504, detail="Download timed out")
|
||||
except YouTubeDownloadError as e:
|
||||
_requeue("Download from that URL failed. Try another URL or search again.")
|
||||
raise HTTPException(status_code=502, detail=f"Download failed: {e}")
|
||||
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
# start_job_processing transitions DOWNLOADING_AUDIO → DOWNLOADING, runs the
|
||||
# duration reconcile (final billing), and triggers audio + lyrics workers.
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing, job_id, 15,
|
||||
"Audio downloaded, starting processing",
|
||||
)
|
||||
|
||||
return AttachResponse(status="success", job_id=job_id, message="URL accepted, download complete, processing started")
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/attach-upload-url", response_model=AttachUploadUrlsResponse)
|
||||
async def attach_upload_url(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
body: AttachUploadUrlsRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Issue a signed GCS upload URL to attach an audio file to a parked job.
|
||||
|
||||
Step 1 of the manual file-upload fallback: the client PUTs the file to the
|
||||
returned URL, then calls /attach-upload-complete. No job is created here.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_require_audio_search_enabled(request, locale)
|
||||
_require_awaiting_selection(job_id, locale)
|
||||
|
||||
# Normalise Windows separators before basename so "..\\evil.exe" can't be
|
||||
# stored verbatim, then validate the extension against the audio allow-list.
|
||||
raw = (body.filename or "").strip().replace("\\", "/")
|
||||
filename = os.path.basename(raw) or "audio"
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
if ext not in _AUDIO_UPLOAD_EXTENSIONS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Unsupported audio format. Use MP3, WAV, FLAC, M4A, or OGG.",
|
||||
)
|
||||
|
||||
gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
upload_url = storage_service.generate_signed_upload_url(
|
||||
gcs_path, content_type=body.content_type or "application/octet-stream", expiration_minutes=60,
|
||||
)
|
||||
return AttachUploadUrlsResponse(job_id=job_id, gcs_path=gcs_path, upload_url=upload_url)
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/attach-upload-complete", response_model=AttachResponse)
|
||||
async def attach_upload_complete(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: AttachUploadCompleteRequest = AttachUploadCompleteRequest(),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Finalise a file upload attached to a parked job and start processing.
|
||||
|
||||
Step 2 of the manual file-upload fallback: verifies the uploaded audio landed
|
||||
in GCS, points the job at it, and starts processing. Like the URL path, the
|
||||
job was already created/charged, so no new job and no base-credit deduction.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_require_audio_search_enabled(request, locale)
|
||||
from backend.api.routes.file_upload import _select_mixed_audio_files
|
||||
|
||||
job = _require_awaiting_selection(job_id, locale)
|
||||
|
||||
prefix = f"uploads/{job_id}/audio/"
|
||||
files = storage_service.list_files(prefix)
|
||||
audio_files = [f for f in files if not f.rstrip("/").endswith("/")]
|
||||
if not audio_files:
|
||||
raise HTTPException(status_code=400, detail="No uploaded audio file found. Upload the file first.")
|
||||
|
||||
# Prefer the exact object the client uploaded to (from attach-upload-url),
|
||||
# validated to live under this job's prefix and to actually exist — never
|
||||
# trust an arbitrary client path, and don't depend on list ordering.
|
||||
requested = (body.gcs_path or "").strip()
|
||||
if requested:
|
||||
if not requested.startswith(prefix) or requested not in audio_files:
|
||||
raise HTTPException(status_code=400, detail="Uploaded file not found for this job.")
|
||||
audio_gcs_path = requested
|
||||
else:
|
||||
selected = _select_mixed_audio_files(audio_files)
|
||||
audio_gcs_path = selected[0] if isinstance(selected, list) and selected else (selected or audio_files[0])
|
||||
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_source_type': 'upload',
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=10,
|
||||
message=f"File uploaded: {job.artist} - {job.title}",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing, job_id, 15,
|
||||
"File uploaded, starting processing",
|
||||
)
|
||||
|
||||
return AttachResponse(status="success", job_id=job_id, message="Upload accepted, processing started")
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/select", response_model=AudioSelectResponse)
|
||||
async def select_audio_source(
|
||||
job_id: str,
|
||||
|
||||
@@ -17,7 +17,6 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.i18n import get_full_locale_from_request
|
||||
from backend.services.auth_service import AuthResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -349,7 +348,6 @@ async def bulk_submit(
|
||||
dropbox_path=settings.default_dropbox_path,
|
||||
gdrive_folder_id=settings.default_gdrive_folder_id,
|
||||
request_metadata=request_metadata,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
try:
|
||||
job = job_manager.create_job(job_create, is_admin=is_admin)
|
||||
|
||||
@@ -44,7 +44,7 @@ from backend.services.youtube_download_service import (
|
||||
get_youtube_download_service,
|
||||
YouTubeDownloadError,
|
||||
)
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -685,8 +685,6 @@ async def upload_and_create_job(
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -1271,8 +1269,6 @@ async def create_job_with_upload_urls(
|
||||
is_private=effective_is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -1901,8 +1897,6 @@ async def create_job_from_url(
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
@@ -2208,8 +2202,6 @@ async def create_finalise_only_job(
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -15,7 +15,6 @@ 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
|
||||
@@ -444,26 +443,6 @@ 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,
|
||||
@@ -477,11 +456,6 @@ 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}")
|
||||
|
||||
@@ -18,7 +18,6 @@ from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud.exceptions import NotFound
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
@@ -39,7 +38,7 @@ from backend.services.tracing import add_span_attribute
|
||||
from backend.api.dependencies import require_admin, require_auth
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.middleware.tenant import get_tenant_from_request
|
||||
from backend.utils.test_data import is_test_email
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
@@ -164,7 +163,6 @@ async def create_job(
|
||||
user_email=user_email,
|
||||
is_private=request.is_private or False,
|
||||
credits=credits,
|
||||
locale=get_full_locale_from_request(http_request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
|
||||
@@ -1648,17 +1646,6 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
}
|
||||
|
||||
|
||||
def _cleanup_temp_file(path: Optional[str]) -> None:
|
||||
"""Best-effort removal of a temp file created for a download that failed
|
||||
before streaming started (so it never reaches the iterator's cleanup)."""
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@router.get("/{job_id}/download/{category}/{file_key}")
|
||||
async def download_file(
|
||||
job_id: str,
|
||||
@@ -1732,11 +1719,6 @@ async def download_file(
|
||||
else:
|
||||
filename = gcs_path.split('/')[-1] # Fallback to original
|
||||
|
||||
# Created below with delete=False; the streaming iterator's finally removes it
|
||||
# on the happy path. If download/setup raises before streaming starts, the
|
||||
# except handlers below unlink it so failed (e.g. 404) requests don't leak
|
||||
# temp files and fill local disk.
|
||||
tmp_path = None
|
||||
try:
|
||||
# Download to temp file and stream
|
||||
storage = StorageService()
|
||||
@@ -1772,16 +1754,7 @@ async def download_file(
|
||||
'Content-Disposition': content_disposition
|
||||
}
|
||||
)
|
||||
except NotFound:
|
||||
# The recorded output is gone from GCS (e.g. a stale download link hit
|
||||
# mid-reprocess after a visibility change / edit deleted the finals). This
|
||||
# is "not found", not a server error — return 404 and log at warning so it
|
||||
# doesn't trip the error-monitor.
|
||||
_cleanup_temp_file(tmp_path)
|
||||
logger.warning(f"Download requested for missing object {gcs_path}")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.fileNoLongerAvailable"))
|
||||
except Exception as e:
|
||||
_cleanup_temp_file(tmp_path)
|
||||
logger.error(f"Error downloading {gcs_path}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Error downloading file: {e}")
|
||||
|
||||
@@ -2542,7 +2515,6 @@ async def create_job_from_search(
|
||||
request_metadata=request_metadata,
|
||||
is_private=body.is_private,
|
||||
tenant_id=tenant_id,
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -19,10 +19,10 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Literal, Optional, Set, Tuple
|
||||
from typing import Dict, Any, List, Optional, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
@@ -372,15 +372,6 @@ async def get_correction_data(
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/vocals")
|
||||
async def get_vocals_audio(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the vocals audio file for playback."""
|
||||
return await _stream_audio(job_id, stem="vocals")
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
async def get_audio_with_hash(
|
||||
job_id: str,
|
||||
@@ -401,7 +392,7 @@ async def get_audio_no_hash(
|
||||
return await _stream_audio(job_id)
|
||||
|
||||
|
||||
async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"] = "input"):
|
||||
async def _stream_audio(job_id: str):
|
||||
"""
|
||||
Redirect to a signed GCS URL for audio playback in the review interface.
|
||||
|
||||
@@ -416,50 +407,12 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
audio_gcs_path = None
|
||||
if stem == "input":
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
elif stem == "vocals":
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
# Stem keys vary by separation model. We want the full vocal mix
|
||||
# (lead + backing) so every word can be lined up against the waveform:
|
||||
# - "vocals" : full vocal from a 2-stem split (rare)
|
||||
# - "vocals_clean" : full vocal from the primary vocal/instrumental
|
||||
# split (present on essentially all cloud jobs)
|
||||
# - "lead_vocals" : last-resort fallback (misses backing lines)
|
||||
# Use .get() so a missing key yields a clean 404 below, not a KeyError/500.
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals"):
|
||||
if stems.get(key):
|
||||
audio_gcs_path = stems[key]
|
||||
break
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
if not audio_gcs_path:
|
||||
# Audio separation is decoupled from the lyrics-review critical path, so a
|
||||
# user can open review before the vocal stems have been uploaded (the stem
|
||||
# arrives a minute or two later). Signal "not ready yet, retry" with a 202
|
||||
# so the frontend polls instead of treating it as a terminal 404.
|
||||
# state_data.audio_complete is set both when separation finishes and when
|
||||
# it's skipped entirely (existing-instrumental jobs), so a missing stem
|
||||
# with audio_complete=True really is a permanent 404.
|
||||
if stem == "vocals" and not job.state_data.get("audio_complete", False):
|
||||
logger.info(f"Job {job_id}: Vocal stem not yet available (separation in progress), returning 202")
|
||||
return Response(status_code=202, headers={"Retry-After": "15"})
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
transcoding = AudioTranscodingService()
|
||||
|
||||
if stem == "vocals":
|
||||
# Proxy the vocals bytes through the API rather than 302-redirecting to
|
||||
# a signed GCS URL. The waveform visualizer fetch()es + decodeAudioData()s
|
||||
# this (a cross-origin READ), and a cross-origin redirect makes the
|
||||
# browser send `Origin: null`, which the bucket CORS rejects. Serving
|
||||
# the (~3 MB) bytes from the API keeps it same-origin to api.* whose
|
||||
# CORS already allows the frontend. <audio> playback (stem="input")
|
||||
# doesn't need CORS, so it keeps the lighter redirect below.
|
||||
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
|
||||
logger.info(f"Job {job_id}: Proxying {len(audio_bytes)}B vocals audio for waveform")
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
signed_url = await transcoding.get_review_audio_url_async(audio_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for audio review")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
|
||||
+58
-187
@@ -9,7 +9,6 @@ Handles:
|
||||
- Admin user management
|
||||
"""
|
||||
import hashlib
|
||||
import html
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
@@ -36,7 +35,7 @@ def _mask_email(email: str) -> str:
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request, Header
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.models.user import (
|
||||
UserRole,
|
||||
@@ -438,22 +437,10 @@ async def verify_magic_link(
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
|
||||
|
||||
# Persist user's locale preference (from Accept-Language header).
|
||||
# `locale` is narrowed to en/es/de for email rendering; `ui_locale` is the
|
||||
# full UI language (any of 33) so admins know what language to communicate in.
|
||||
ui_locale = get_full_locale_from_request(http_request)
|
||||
has_accept_language = bool(http_request.headers.get("accept-language"))
|
||||
locale_updates = {}
|
||||
# Only touch locale when the client actually sent an Accept-Language header —
|
||||
# otherwise get_locale_from_request()'s "en" default would clobber a user's
|
||||
# real stored locale on token-only logins (e.g. magic-link scanners).
|
||||
if has_accept_language and locale and locale != (user.locale or "en"):
|
||||
locale_updates["locale"] = locale
|
||||
if ui_locale and ui_locale != user.ui_locale:
|
||||
locale_updates["ui_locale"] = ui_locale
|
||||
if locale_updates:
|
||||
# Persist user's locale preference (from Accept-Language header)
|
||||
if locale and locale != (user.locale or "en"):
|
||||
try:
|
||||
user_service.update_user(user.email, **locale_updates)
|
||||
user_service.update_user(user.email, locale=locale)
|
||||
except Exception:
|
||||
pass # Non-critical — don't block login
|
||||
|
||||
@@ -813,7 +800,6 @@ async def create_checkout(
|
||||
@router.post("/made-for-you/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_made_for_you_checkout(
|
||||
request: MadeForYouCheckoutRequest,
|
||||
http_request: Request,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
):
|
||||
"""
|
||||
@@ -838,7 +824,6 @@ async def create_made_for_you_checkout(
|
||||
source_type=request.source_type,
|
||||
youtube_url=request.youtube_url,
|
||||
notes=request.notes,
|
||||
locale=get_full_locale_from_request(http_request),
|
||||
)
|
||||
|
||||
if not success or not checkout_url:
|
||||
@@ -859,72 +844,6 @@ 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,
|
||||
@@ -973,10 +892,6 @@ 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()
|
||||
@@ -1022,8 +937,6 @@ async def _handle_made_for_you_order(
|
||||
brand_prefix=dist.brand_prefix,
|
||||
discord_webhook_url=dist.discord_webhook_url,
|
||||
youtube_description=dist.youtube_description,
|
||||
# UI language the customer ordered in (captured at checkout, admin-only signal)
|
||||
locale=metadata.get("locale") or None,
|
||||
)
|
||||
# Made-for-you jobs are created by admin (via Stripe webhook) - bypass rate limits
|
||||
job = job_manager.create_job(job_create, is_admin=True)
|
||||
@@ -1064,48 +977,6 @@ 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
|
||||
@@ -1228,59 +1099,66 @@ 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
|
||||
|
||||
# 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,
|
||||
)
|
||||
# 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,
|
||||
)
|
||||
|
||||
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,
|
||||
# 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,
|
||||
customer_email=customer_email,
|
||||
artist=artist,
|
||||
title=title,
|
||||
job_id=job_id,
|
||||
error=e,
|
||||
admin_login_token=admin_login.token,
|
||||
notes=notes,
|
||||
audio_source_count=audio_source_count,
|
||||
)
|
||||
# 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
|
||||
|
||||
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}")
|
||||
|
||||
|
||||
@router.post("/webhooks/stripe")
|
||||
@@ -1774,10 +1652,6 @@ class UserDetailResponse(BaseModel):
|
||||
display_name: Optional[str] = None
|
||||
is_active: bool = True
|
||||
email_verified: bool = False
|
||||
# Language: `locale` is the email locale (en/es/de); `ui_locale` is the full UI
|
||||
# language (any of 33) the user browses in — what admins should communicate in.
|
||||
locale: Optional[str] = None
|
||||
ui_locale: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
last_login_at: Optional[str] = None
|
||||
@@ -1942,7 +1816,6 @@ async def get_user_detail(
|
||||
"artist": job_data.get("artist"),
|
||||
"title": job_data.get("title"),
|
||||
"created_at": created_at_str,
|
||||
"locale": job_data.get("locale"),
|
||||
})
|
||||
|
||||
# Get active sessions with details
|
||||
@@ -1979,8 +1852,6 @@ async def get_user_detail(
|
||||
display_name=user.display_name,
|
||||
is_active=user.is_active,
|
||||
email_verified=user.email_verified,
|
||||
locale=user.locale,
|
||||
ui_locale=user.ui_locale,
|
||||
created_at=user.created_at.isoformat() if user.created_at else None,
|
||||
updated_at=user.updated_at.isoformat() if user.updated_at else None,
|
||||
last_login_at=user.last_login_at.isoformat() if user.last_login_at else None,
|
||||
|
||||
+6
-57
@@ -85,8 +85,7 @@ 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-CLOSED: if evaluation fails, the decision becomes
|
||||
# "pending_review" (no auto-grant; an admin is notified to decide).
|
||||
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
|
||||
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")
|
||||
|
||||
@@ -107,13 +106,11 @@ class Settings(BaseSettings):
|
||||
# Models used by the multi-model "compare" mode (semicolon-separated —
|
||||
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
|
||||
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
|
||||
# Proactively generate (and cache) auto-correct suggestions once
|
||||
# transcription + references are ready, so the review UI has them instantly.
|
||||
# This flag gates whether the lyrics worker fires the trigger; the actual
|
||||
# multi-model LLM call + caching runs on the API service (auto_correct_worker),
|
||||
# which holds the model credentials — the lyrics-transcription-job itself does
|
||||
# NOT need ANTHROPIC_API_KEY / AUTO_CORRECT_COMPARE_MODELS. Best-effort:
|
||||
# failures never block or fail the job. Default off.
|
||||
# Proactively generate (and cache) auto-correct suggestions in the lyrics
|
||||
# worker once transcription + references are ready, so the review UI has
|
||||
# them instantly. Best-effort: failures never block or fail the job. Only
|
||||
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
|
||||
# (the lyrics-transcription-job, via ci.yml). Default off.
|
||||
auto_correct_proactive_enabled: bool = os.getenv(
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
@@ -309,51 +306,3 @@ 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)."
|
||||
)
|
||||
|
||||
@@ -92,37 +92,6 @@ def get_locale_from_request(request: Request) -> str:
|
||||
return DEFAULT_LOCALE
|
||||
|
||||
|
||||
def get_full_locale_from_request(request: Request) -> str | None:
|
||||
"""Extract the user's actual UI language tag from Accept-Language.
|
||||
|
||||
Unlike :func:`get_locale_from_request`, this does NOT narrow to the 3
|
||||
email-supported locales (en/es/de). It returns the primary language subtag
|
||||
of the first entry in the header (e.g. ``pt``, ``ja``, ``zh``) so the admin
|
||||
UI can show the real language a customer was using the product in.
|
||||
|
||||
Returns the lowercased language subtag, or ``None`` if the header is absent
|
||||
or unparseable.
|
||||
"""
|
||||
accept_lang = request.headers.get("accept-language", "")
|
||||
|
||||
for part in accept_lang.split(","):
|
||||
# Each part looks like "en-US;q=0.9" — take the language-region token
|
||||
# before the quality factor, then the primary subtag before any region.
|
||||
segments = part.split(";")
|
||||
token = segments[0].strip()
|
||||
if not token or token == "*":
|
||||
continue
|
||||
# Skip ranges the client explicitly rejects with q=0.
|
||||
if any(seg.strip().lower().replace(" ", "") in ("q=0", "q=0.0", "q=0.00", "q=0.000")
|
||||
for seg in segments[1:]):
|
||||
continue
|
||||
lang = token.split("-")[0].strip().lower()
|
||||
if lang.isalpha() and len(lang) >= 2:
|
||||
return lang
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_locale_prefix(locale: str) -> str:
|
||||
"""Get URL locale prefix for frontend URLs (e.g., '/en', '/es')."""
|
||||
if locale not in SUPPORTED_LOCALES:
|
||||
|
||||
+1
-6
@@ -9,7 +9,7 @@ from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings, validate_production_config
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, 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,11 +77,6 @@ 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
|
||||
|
||||
|
||||
@@ -26,14 +26,9 @@ from backend.models.tenant import TenantConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 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.)
|
||||
# Only allow query param tenant override in non-production environments
|
||||
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
|
||||
os.environ.get("ENVIRONMENT", "").lower() == "production" or \
|
||||
bool(os.environ.get("K_SERVICE"))
|
||||
os.environ.get("ENVIRONMENT", "").lower() == "production"
|
||||
|
||||
|
||||
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
|
||||
|
||||
+1
-11
@@ -274,13 +274,7 @@ class Job(BaseModel):
|
||||
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
|
||||
# UI language the job was submitted in (primary Accept-Language subtag, e.g.
|
||||
# "pt", "ja", "zh"). Any of the 33 supported UI locales — NOT narrowed to the
|
||||
# 3 email locales. Admin-only signal for support/intervention. None for jobs
|
||||
# created before this field existed or where the header was absent.
|
||||
locale: Optional[str] = None
|
||||
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
@@ -637,10 +631,6 @@ class JobCreate(BaseModel):
|
||||
# Tenant scoping for white-label portals ("" = consumer, "vocalstar"/etc = tenant)
|
||||
tenant_id: str = "" # Tenant ID for job scoping
|
||||
|
||||
# UI language the job was submitted in (primary Accept-Language subtag, e.g.
|
||||
# "pt", "ja"). Set by the API endpoint from the request header; admin-only.
|
||||
locale: Optional[str] = None
|
||||
|
||||
@validator('url')
|
||||
def validate_url(cls, v):
|
||||
"""Validate URL is not empty."""
|
||||
|
||||
@@ -91,16 +91,9 @@ class User(BaseModel):
|
||||
# Optional profile fields for future use
|
||||
display_name: Optional[str] = None
|
||||
|
||||
# i18n locale preference (set from Accept-Language on login, used for emails/push).
|
||||
# Narrowed to the 3 email-supported locales (en/es/de) — do NOT widen, email
|
||||
# rendering depends on it.
|
||||
# i18n locale preference (set from Accept-Language on login, used for emails/push)
|
||||
locale: Optional[str] = None
|
||||
|
||||
# Actual UI language the user browses in (primary Accept-Language subtag, any
|
||||
# of the 33 supported locales, e.g. "pt", "ja"). Captured on login and job
|
||||
# creation. Admin-only signal so support knows what language to communicate in.
|
||||
ui_locale: Optional[str] = None
|
||||
|
||||
# Push notification subscriptions (Web Push API)
|
||||
# Users can subscribe from multiple devices/browsers
|
||||
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
|
||||
|
||||
@@ -368,17 +368,12 @@ class AudioSearchService:
|
||||
return results
|
||||
|
||||
except FlacfetchServiceError as e:
|
||||
# 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.
|
||||
logger.warning(f"Remote flacfetch search failed, falling back to local: {e}")
|
||||
# Fallback to local search
|
||||
self._remote_search_id = None
|
||||
self._cached_results = []
|
||||
raise AudioSearchError(f"Remote flacfetch search failed: {e}") from e
|
||||
results = self._fetcher.search(artist, title)
|
||||
self._cached_results = results
|
||||
return results
|
||||
|
||||
def select_best(self, results: List[AudioSearchResult]) -> int:
|
||||
"""
|
||||
|
||||
@@ -137,34 +137,6 @@ class AudioTranscodingService:
|
||||
self.get_review_audio_url, source_gcs_path, expiration_minutes
|
||||
)
|
||||
|
||||
def get_review_audio_bytes(self, source_gcs_path: str) -> tuple[bytes, str]:
|
||||
"""Return (bytes, content_type) of the transcoded review audio.
|
||||
|
||||
Used to proxy the audio through the API instead of 302-redirecting to a
|
||||
signed GCS URL. The waveform visualizer fetch()es + decodeAudioData()s
|
||||
this, which is a cross-origin read; a redirect to storage.googleapis.com
|
||||
makes the browser send `Origin: null` on the redirected request, which
|
||||
the bucket CORS rejects. Proxying keeps it same-origin to the API (which
|
||||
sets the right CORS headers). The transcoded OGG is small (~3 MB), well
|
||||
under Cloud Run's 32 MB response cap.
|
||||
|
||||
Falls back to the original (FLAC) source if transcoding fails, mirroring
|
||||
get_review_audio_url, so a transient ffmpeg/cache error doesn't blank the
|
||||
waveform while the source still exists. (A very long FLAC could exceed
|
||||
Cloud Run's 32 MB cap on that rare fallback path — the frontend then just
|
||||
hides the waveform, which is acceptable degradation.)
|
||||
"""
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_gcs_path)
|
||||
return self.storage.download_bytes(cache_path), "audio/ogg"
|
||||
except Exception as e:
|
||||
logger.warning(f"Transcoding failed for {source_gcs_path}, serving source audio: {e}")
|
||||
return self.storage.download_bytes(source_gcs_path), "audio/flac"
|
||||
|
||||
async def get_review_audio_bytes_async(self, source_gcs_path: str) -> tuple[bytes, str]:
|
||||
"""Async wrapper around get_review_audio_bytes via asyncio.to_thread."""
|
||||
return await asyncio.to_thread(self.get_review_audio_bytes, source_gcs_path)
|
||||
|
||||
def prepare_review_audio_for_job(self, job) -> list[str]:
|
||||
"""
|
||||
Transcode all review audio files for a job (eager transcoding).
|
||||
|
||||
@@ -87,15 +87,7 @@ class AuthService:
|
||||
if self.admin_tokens:
|
||||
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
|
||||
else:
|
||||
# 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."
|
||||
)
|
||||
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
|
||||
|
||||
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
|
||||
"""
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
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-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).
|
||||
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
|
||||
the AI call fails for any reason, credits are granted.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
@@ -26,7 +25,7 @@ class CreditEvaluation:
|
||||
decision: str # "grant" or "deny"
|
||||
reasoning: str
|
||||
confidence: float
|
||||
error: Optional[str] = None # Set if evaluation failed (decision defaults to "pending_review")
|
||||
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
|
||||
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
|
||||
|
||||
|
||||
|
||||
@@ -30,13 +30,8 @@ class DropboxService:
|
||||
"""Load OAuth credentials from Secret Manager."""
|
||||
try:
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
# 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", "")
|
||||
# Try to get the project ID from environment or use default
|
||||
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "karaoke-gen")
|
||||
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"))
|
||||
|
||||
@@ -138,24 +138,7 @@ async def reconcile_and_maybe_pause(job_id: str) -> bool:
|
||||
user_service = get_user_service()
|
||||
storage = StorageService()
|
||||
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
|
||||
#
|
||||
# Email is only actually sent on the rare over-limit *cancel* branch. Building
|
||||
# the service must never crash an otherwise-successful download: EmailService()
|
||||
# raises in production when POSTMARK_SERVER_TOKEN is unset (the "fail loudly"
|
||||
# guard from the 2026-06-09 fallback audit), and this worker runs as the
|
||||
# audio-download-job Cloud Run Job. If the provider can't be built, reconcile
|
||||
# still proceeds (reconcile_duration tolerates email_service=None); we log
|
||||
# loudly so a config regression is visible rather than silently dropping a
|
||||
# customer notification. (Job a453d1d5: token missing on the job crashed the
|
||||
# download entirely.)
|
||||
try:
|
||||
email_service = get_email_service()
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"Job %s: could not construct email service for duration reconcile "
|
||||
"(%s); proceeding without customer email notifications", job_id, e,
|
||||
)
|
||||
email_service = None
|
||||
email_service = get_email_service()
|
||||
|
||||
result = await asyncio.get_running_loop().run_in_executor(
|
||||
None,
|
||||
|
||||
@@ -10,16 +10,14 @@ Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
|
||||
import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import NamedTuple, Optional, List
|
||||
from typing import Optional, List
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
|
||||
from backend.config import get_settings, is_production
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_prefix
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
@@ -27,18 +25,6 @@ from karaoke_gen.utils import sanitize_filename
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SendResult(NamedTuple):
|
||||
"""Outcome of a provider send.
|
||||
|
||||
``message_id`` is the provider's unique id for the sent message (Postmark's
|
||||
``MessageID``) when available — used to link a send to its Postmark record and
|
||||
to dedupe the persisted ``email_log`` entry. ``None`` for providers that don't
|
||||
expose one (console/preview).
|
||||
"""
|
||||
success: bool
|
||||
message_id: Optional[str] = None
|
||||
|
||||
|
||||
class EmailProvider(ABC):
|
||||
"""Abstract base class for email providers."""
|
||||
|
||||
@@ -67,32 +53,6 @@ class EmailProvider(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def send_email_detailed(
|
||||
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,
|
||||
) -> SendResult:
|
||||
"""Send an email and report the provider message id when available.
|
||||
|
||||
Default implementation delegates to :meth:`send_email` and reports no
|
||||
message id. Providers that expose one (Postmark) override this.
|
||||
"""
|
||||
success = self.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,
|
||||
)
|
||||
return SendResult(success=success, message_id=None)
|
||||
|
||||
|
||||
class ConsoleEmailProvider(EmailProvider):
|
||||
"""
|
||||
@@ -173,9 +133,6 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
self.server_token = server_token
|
||||
self.from_email = from_email
|
||||
self.from_name = from_name
|
||||
# Postmark MessageID of the most recent successful send, so the email_log
|
||||
# chokepoint can link a persisted record to its Postmark message.
|
||||
self.last_message_id: Optional[str] = None
|
||||
|
||||
def send_email(
|
||||
self,
|
||||
@@ -187,26 +144,6 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> bool:
|
||||
return self.send_email_detailed(
|
||||
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,
|
||||
).success
|
||||
|
||||
def send_email_detailed(
|
||||
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,
|
||||
) -> SendResult:
|
||||
try:
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
@@ -239,15 +176,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
bcc_info = f" (BCC: {', '.join(bcc_emails)})" if bcc_emails else ""
|
||||
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via Postmark")
|
||||
# Capture Postmark's MessageID so the send can be linked to its
|
||||
# Postmark record and the persisted email_log entry deduped.
|
||||
message_id = None
|
||||
try:
|
||||
message_id = response.json().get("MessageID")
|
||||
except ValueError:
|
||||
pass
|
||||
self.last_message_id = message_id
|
||||
return SendResult(success=True, message_id=message_id)
|
||||
return True
|
||||
|
||||
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
|
||||
try:
|
||||
@@ -258,25 +187,11 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
)
|
||||
except ValueError:
|
||||
logger.error(f"Postmark returned status {response.status_code}: {response.text[:200]}")
|
||||
return SendResult(success=False, message_id=None)
|
||||
return False
|
||||
|
||||
except requests.RequestException:
|
||||
logger.exception("Failed to send email via Postmark")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
|
||||
# Query params that carry single-use auth/capability tokens (magic-link sign-in,
|
||||
# lyrics/instrumental review access, referral codes). We persist a redacted copy
|
||||
# so the admin email-history log never becomes a store of live credentials — the
|
||||
# email still renders faithfully, only the secret value is masked.
|
||||
_SENSITIVE_QUERY_PARAM = re.compile(r"([?&](?:token|ref|review_token|instrumental_token)=)[^&\"'\s<]+", re.IGNORECASE)
|
||||
|
||||
|
||||
def _redact_sensitive_tokens(content: Optional[str]) -> Optional[str]:
|
||||
"""Mask token/ref query-param values in email content before persistence."""
|
||||
if not content:
|
||||
return content
|
||||
return _SENSITIVE_QUERY_PARAM.sub(r"\1[REDACTED]", content)
|
||||
return False
|
||||
|
||||
|
||||
def _dedupe_emails(emails: List[str]) -> List[str]:
|
||||
@@ -316,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 only).
|
||||
back to console logging (dev/test).
|
||||
"""
|
||||
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
|
||||
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
@@ -326,159 +241,13 @@ class EmailService:
|
||||
logger.info("Using Postmark email provider")
|
||||
return PostmarkEmailProvider(postmark_token, from_email, from_name)
|
||||
|
||||
# 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)")
|
||||
logger.warning("No email provider configured, using console logging")
|
||||
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._log_and_send(
|
||||
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,
|
||||
email_type="raw",
|
||||
)
|
||||
|
||||
def _log_and_send(
|
||||
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,
|
||||
email_type: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Single send chokepoint: dispatch via the provider, then persist a
|
||||
record of the send for the admin email-history view.
|
||||
|
||||
Every ``send_*`` template method routes through here so the persisted
|
||||
``email_log`` mirrors exactly what left the building. Persistence is
|
||||
strictly best-effort — a Firestore failure must never break or delay a
|
||||
real email send.
|
||||
"""
|
||||
# Categorize by the calling send_* method name (e.g. send_magic_link →
|
||||
# "magic_link") so the admin UI can group emails without threading an
|
||||
# explicit type through every template method.
|
||||
if email_type is None:
|
||||
try:
|
||||
caller = sys._getframe(1).f_code.co_name
|
||||
email_type = caller[len("send_"):] if caller.startswith("send_") else caller
|
||||
except Exception:
|
||||
email_type = None
|
||||
|
||||
# Dispatch via the provider's public send_email (as keyword args) so
|
||||
# callers/mocks that observe that method still see it. PostmarkEmailProvider
|
||||
# records the returned MessageID on ``last_message_id`` for us to link the
|
||||
# log entry.
|
||||
success = 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,
|
||||
)
|
||||
|
||||
# Only persist genuine outbound mail (Postmark). Console/preview providers
|
||||
# are dev/test only and have no real inbox to reflect.
|
||||
if success and isinstance(self.provider, PostmarkEmailProvider):
|
||||
try:
|
||||
self._record_sent_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=from_email_override or getattr(self.provider, "from_email", None),
|
||||
email_type=email_type,
|
||||
message_id=getattr(self.provider, "last_message_id", None),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to persist email_log record (the email itself was sent OK)"
|
||||
)
|
||||
|
||||
return success
|
||||
|
||||
def _record_sent_email(
|
||||
self,
|
||||
*,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str],
|
||||
cc_emails: Optional[List[str]],
|
||||
bcc_emails: Optional[List[str]],
|
||||
from_email: Optional[str],
|
||||
email_type: Optional[str],
|
||||
message_id: Optional[str],
|
||||
) -> None:
|
||||
"""Write one Firestore ``email_log`` doc mirroring a sent email.
|
||||
|
||||
Keyed by the Postmark MessageID when available (idempotent), else an
|
||||
auto-id. Stores the rendered HTML so the admin UI can show older mail
|
||||
after Postmark's ~45-day content retention expires — with single-use
|
||||
auth/capability tokens redacted so the log never holds live credentials.
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
db = FirestoreService().db
|
||||
doc = {
|
||||
"recipient": (to_email or "").strip().lower(),
|
||||
"recipient_raw": to_email,
|
||||
"cc": _dedupe_emails(cc_emails) if cc_emails else [],
|
||||
"bcc": _dedupe_emails(bcc_emails) if bcc_emails else [],
|
||||
"from_email": from_email,
|
||||
"subject": subject,
|
||||
"html_content": _redact_sensitive_tokens(html_content),
|
||||
"text_content": _redact_sensitive_tokens(text_content),
|
||||
"email_type": email_type,
|
||||
"message_stream": "outbound",
|
||||
"postmark_message_id": message_id,
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
collection = db.collection("email_log")
|
||||
if message_id:
|
||||
collection.document(message_id).set(doc)
|
||||
else:
|
||||
collection.add(doc)
|
||||
|
||||
def send_magic_link(
|
||||
self,
|
||||
email: str,
|
||||
@@ -572,7 +341,7 @@ class EmailService:
|
||||
© {self._get_year()} {brand_name}
|
||||
"""
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
email, subject, html_content, text_content, from_email_override=sender_email
|
||||
)
|
||||
|
||||
@@ -645,7 +414,7 @@ class EmailService:
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self._log_and_send(email, subject, html_content, text_content)
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
|
||||
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
|
||||
"""
|
||||
@@ -787,7 +556,7 @@ class EmailService:
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self._log_and_send(email, subject, html_content, text_content)
|
||||
return self.provider.send_email(email, subject, html_content, text_content)
|
||||
|
||||
def _get_year(self) -> int:
|
||||
"""Get current year for copyright notices."""
|
||||
@@ -1167,7 +936,7 @@ class EmailService:
|
||||
|
||||
cc_emails = ["gen@nomadkaraoke.com"] if cc_admin else None
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1244,7 +1013,7 @@ class EmailService:
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1344,7 +1113,7 @@ class EmailService:
|
||||
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
|
||||
)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1486,7 +1255,7 @@ class EmailService:
|
||||
f"If you have any questions, just reply to this email — we're happy to help."
|
||||
)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1579,7 +1348,7 @@ class EmailService:
|
||||
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
|
||||
)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1721,7 +1490,7 @@ class EmailService:
|
||||
f"If you have any questions, just reply to this email — we're happy to help."
|
||||
)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1771,7 +1540,7 @@ class EmailService:
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1864,7 +1633,7 @@ class EmailService:
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -1974,7 +1743,7 @@ Open Job: {app_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -2106,7 +1875,7 @@ View all feedback: {admin_url}
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=admin_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -2221,7 +1990,7 @@ If the user looks legitimate, grant them credits from their admin page.
|
||||
|
||||
html_content = self._build_email_html(content)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email="andrew@beveridge.uk",
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
@@ -2276,7 +2045,7 @@ If the user looks legitimate, grant them credits from their admin page.
|
||||
|
||||
html_content = self._build_email_html(content, locale=locale)
|
||||
|
||||
return self._log_and_send(
|
||||
return self.provider.send_email(
|
||||
to_email=email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
|
||||
@@ -44,37 +44,6 @@ class EncodingWorkerCapacityError(EncodingWorkerStartError):
|
||||
"""
|
||||
|
||||
|
||||
# Marker the encoding worker writes into a job's status when it was interrupted
|
||||
# by a worker-process restart (OOM, deploy, crash). Kept in sync with
|
||||
# gce_encoding/persistence.py `_RESTART_FAIL_CODE`.
|
||||
ENCODING_RESTART_FAILURE_CODE = "encoding_worker_restart"
|
||||
|
||||
|
||||
class EncodingJobNotFoundError(RuntimeError):
|
||||
"""The encoding worker returned HTTP 404 for a job status poll.
|
||||
|
||||
Subclasses RuntimeError so existing `except RuntimeError` handlers and
|
||||
`"not found" in str(e)` checks keep working, while giving callers a precise
|
||||
type to branch on (e.g. distinguishing a lost job from other RuntimeErrors)
|
||||
without parsing the message text. Keep the message containing "not found".
|
||||
"""
|
||||
|
||||
|
||||
class EncodingJobLostError(Exception):
|
||||
"""The encoding worker lost a job mid-run (restart wiped its in-memory state).
|
||||
|
||||
Distinct from a transient poll blip: the ffmpeg process and temp work dir
|
||||
are gone, so the *same* job will never complete. The only recovery is to
|
||||
resubmit the work as a fresh job. Deliberately NOT a subclass of
|
||||
RuntimeError so it escapes the poll-failure tolerance in
|
||||
`wait_for_completion` instead of being swallowed as a retryable blip.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, job_id: str = "") -> None:
|
||||
super().__init__(message)
|
||||
self.job_id = job_id
|
||||
|
||||
|
||||
def classify_gce_error(code: str, message: str, *, vm_name: str, zone: str) -> EncodingWorkerStartError:
|
||||
"""Wrap a GCE error code/message in the appropriate typed exception."""
|
||||
if code in CAPACITY_ERROR_CODES:
|
||||
|
||||
@@ -14,8 +14,6 @@ from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Any
|
||||
|
||||
from backend.services.encoding_errors import EncodingJobLostError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -73,11 +71,6 @@ class EncodingOutput:
|
||||
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
|
||||
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
|
||||
|
||||
# Portrait (9:16) karaoke video for phone viewing / social sharing. Additive;
|
||||
# distributed to GCS + Dropbox only (never Drive/YouTube). May be absent when the
|
||||
# portrait render is disabled or fails (it is best-effort).
|
||||
portrait_mp4_path: Optional[str] = None # "<artist> - <title> (Final Karaoke Portrait 1080x1920).mp4"
|
||||
|
||||
# All output files as a dict for convenience
|
||||
output_files: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@@ -394,8 +387,6 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
output_files["mp4_4k_lossless"] = path
|
||||
elif "lossy 4k" in filename_lower:
|
||||
output_files["mp4_4k_lossy"] = path
|
||||
elif "portrait" in filename_lower:
|
||||
output_files["portrait_mp4"] = path
|
||||
elif "720p" in filename_lower:
|
||||
output_files["mp4_720p"] = path
|
||||
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
|
||||
@@ -417,18 +408,11 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
|
||||
title_mov_path=output_files.get("title_mov"),
|
||||
end_mov_path=output_files.get("end_mov"),
|
||||
portrait_mp4_path=output_files.get("portrait_mp4"),
|
||||
output_files=output_files,
|
||||
encoding_time_seconds=encoding_time,
|
||||
encoding_backend=self.name
|
||||
)
|
||||
|
||||
except EncodingJobLostError:
|
||||
# The worker lost this job mid-run (OOM/deploy restart). This is
|
||||
# recoverable by resubmitting a fresh job id, so let the orchestrator
|
||||
# decide — do NOT flatten it into success=False (which would fail the
|
||||
# whole render). See video_worker_orchestrator's resubmit wrapper.
|
||||
raise
|
||||
except Exception as e:
|
||||
encoding_time = time.time() - start_time
|
||||
self.logger.error(f"GCE encoding failed: {e}")
|
||||
|
||||
@@ -19,17 +19,13 @@ import asyncio
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator
|
||||
from typing import Optional, Dict, Any, AsyncIterator
|
||||
|
||||
import aiohttp
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.encoding_errors import (
|
||||
ENCODING_RESTART_FAILURE_CODE,
|
||||
EncodingJobLostError,
|
||||
EncodingJobNotFoundError,
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
)
|
||||
@@ -69,94 +65,6 @@ MAX_BACKOFF_SECONDS = 15.0
|
||||
# long-running encoding job. Similar pattern to flacfetch status polling (PR #446).
|
||||
MAX_CONSECUTIVE_POLL_FAILURES = 5
|
||||
|
||||
_DEFAULT_QUEUE_TIMEOUT_SECONDS = float(4 * 3600)
|
||||
|
||||
|
||||
def _parse_queue_timeout() -> float:
|
||||
"""How long a job may sit *queued* (status "pending") before we give up.
|
||||
|
||||
Parsed defensively: a malformed / non-finite / non-positive value must not
|
||||
crash the module at import nor make pending jobs fail immediately — fall back
|
||||
to the generous default. Separate from the per-run `timeout`, which only
|
||||
starts once the job is actually "running".
|
||||
"""
|
||||
raw = os.environ.get("ENCODING_QUEUE_TIMEOUT")
|
||||
if raw is None:
|
||||
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
|
||||
try:
|
||||
value = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("Invalid ENCODING_QUEUE_TIMEOUT=%r; using default", raw)
|
||||
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
|
||||
if not (value > 0) or value == float("inf"):
|
||||
logger.warning("ENCODING_QUEUE_TIMEOUT=%r not a positive finite number; using default", raw)
|
||||
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
|
||||
return value
|
||||
|
||||
|
||||
def _parse_resubmit_max() -> int:
|
||||
"""Bounded automatic resubmits when the worker loses a job mid-run.
|
||||
|
||||
Each resubmit is a fresh job id; see `run_with_lost_job_resubmit`. A bad
|
||||
value falls back to 2; negatives clamp to 0 (no resubmits).
|
||||
"""
|
||||
raw = os.environ.get("ENCODING_RESUBMIT_MAX", "2")
|
||||
try:
|
||||
return max(0, int(raw))
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("Invalid ENCODING_RESUBMIT_MAX=%r; using 2", raw)
|
||||
return 2
|
||||
|
||||
|
||||
QUEUE_TIMEOUT_SECONDS = _parse_queue_timeout()
|
||||
ENCODING_RESUBMIT_MAX = _parse_resubmit_max()
|
||||
|
||||
|
||||
async def run_with_lost_job_resubmit(
|
||||
operation: Callable[[str], Awaitable[Any]],
|
||||
base_job_id: str,
|
||||
*,
|
||||
log: logging.Logger = logger,
|
||||
max_resubmits: int = ENCODING_RESUBMIT_MAX,
|
||||
) -> Any:
|
||||
"""Run a submit+wait `operation(job_id)`, resubmitting if the worker loses it.
|
||||
|
||||
The encoding worker keeps job state in memory; an OOM/deploy restart wipes it
|
||||
and the in-flight ffmpeg, so the original job id can never complete. When
|
||||
`wait_for_completion` detects that (via `EncodingJobLostError`), we resubmit
|
||||
the same work under a fresh `<base>_retry_<hex8>` id (the worker treats a new
|
||||
id as a brand-new job). Bounded by `max_resubmits`.
|
||||
|
||||
`operation` must be an async callable taking the job id to use and performing
|
||||
the whole submit-and-wait, returning the encode result. It should raise
|
||||
`EncodingJobLostError` (propagated from `wait_for_completion`) when the job is
|
||||
lost; any other exception aborts immediately.
|
||||
|
||||
Idempotency: only the *worker-side* job id changes between attempts — output
|
||||
GCS paths are keyed by the real job (fixed input/output prefixes), so a
|
||||
resubmit re-encodes and *overwrites* the same objects rather than producing
|
||||
duplicates. Downstream side effects (uploads, distribution) run in the
|
||||
orchestrator only after a successful encode, so a resubmit before "complete"
|
||||
cannot double them.
|
||||
"""
|
||||
attempt = 0
|
||||
while True:
|
||||
job_id = base_job_id if attempt == 0 else f"{base_job_id}_retry_{uuid.uuid4().hex[:8]}"
|
||||
try:
|
||||
return await operation(job_id)
|
||||
except EncodingJobLostError as e:
|
||||
attempt += 1
|
||||
if attempt > max_resubmits:
|
||||
log.error(
|
||||
f"[job:{base_job_id}] Encoding worker lost the job {attempt} time(s); "
|
||||
f"giving up after {max_resubmits} resubmit(s): {e}"
|
||||
)
|
||||
raise
|
||||
log.warning(
|
||||
f"[job:{base_job_id}] Encoding worker lost the job (restart/OOM); "
|
||||
f"resubmitting as a fresh job (attempt {attempt + 1}/{max_resubmits + 1})"
|
||||
)
|
||||
|
||||
|
||||
def _format_exception(e: BaseException) -> str:
|
||||
"""Render an exception with type info.
|
||||
@@ -265,15 +173,12 @@ class EncodingService:
|
||||
yield
|
||||
|
||||
def _build_worker_candidates(self) -> list:
|
||||
"""Build the ranked candidate list for ensure_any_running.
|
||||
"""Build the ordered candidate list for ensure_any_running.
|
||||
|
||||
Reads optional fallback VMs from settings (env var
|
||||
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip, machine_type?}).
|
||||
The primary + all fallbacks are ranked by the shared preference logic
|
||||
(fastest-first, demoting recently-stocked-out types) so runtime selection
|
||||
stays in lock-step with the deploy green selection. Returns an empty list
|
||||
when no worker manager / no configured fallbacks — caller falls back to
|
||||
the single-VM ensure_primary_running path.
|
||||
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip}). Returns
|
||||
an empty list when no worker manager / no configured fallbacks —
|
||||
caller falls back to the single-VM ensure_primary_running path.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return []
|
||||
@@ -284,69 +189,42 @@ class EncodingService:
|
||||
return []
|
||||
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerCandidate
|
||||
from backend.services.encoding_worker_preference import (
|
||||
PRIMARY_MACHINE_TYPE,
|
||||
ordered_candidates,
|
||||
)
|
||||
|
||||
# Build a dict pool (primary + fallbacks), each tagged with machine_type so
|
||||
# the shared preference logic can rank them. The primary/secondary pair is
|
||||
# always c4d; the config may override via primary_machine_type.
|
||||
primary_mt = getattr(config, "primary_machine_type", None) or PRIMARY_MACHINE_TYPE
|
||||
pool = [{
|
||||
"vm": config.primary_vm,
|
||||
"zone": self._worker_manager._zone,
|
||||
"ip": config.primary_ip,
|
||||
"machine_type": primary_mt,
|
||||
"kind": "primary",
|
||||
"is_primary": True,
|
||||
}]
|
||||
# Primary always goes first. Single-zone deployments stop here.
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(
|
||||
vm_name=config.primary_vm,
|
||||
zone=self._worker_manager._zone,
|
||||
ip=config.primary_ip,
|
||||
)
|
||||
]
|
||||
|
||||
# Optional capacity-fallback VMs in alternate zones/families, configured via
|
||||
# env var. Schema: '[{"vm":"encoding-worker-fallback-c4a","zone":"us-central1-a",
|
||||
# "ip":"34.x.x.x","machine_type":"c4-highcpu-32"}, ...]'. machine_type is
|
||||
# optional (inferred from the VM name for legacy entries). Empty by default;
|
||||
# populated after `pulumi up` provisions the fallback VMs.
|
||||
# Optional capacity-fallback VMs in alternate zones, configured via
|
||||
# env var. Schema: '[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"34.x.x.x"}, ...]'
|
||||
# The list is empty by default; user populates after `pulumi up`
|
||||
# provisions the fallback VMs.
|
||||
import json as _json
|
||||
raw = self.settings.encoding_worker_fallback_vms
|
||||
if raw:
|
||||
try:
|
||||
parsed = _json.loads(raw)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
|
||||
parsed = []
|
||||
# A non-list root (null, dict, scalar) parses fine but would blow up
|
||||
# `for item in parsed` and escape this method during connection
|
||||
# recovery — degrade to no fallbacks instead.
|
||||
if not isinstance(parsed, list):
|
||||
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
|
||||
parsed = []
|
||||
for item in parsed:
|
||||
try:
|
||||
pool.append({
|
||||
"vm": item["vm"],
|
||||
"zone": item["zone"],
|
||||
"ip": item["ip"],
|
||||
"machine_type": item.get("machine_type"),
|
||||
"kind": "fallback",
|
||||
})
|
||||
except (KeyError, TypeError) as e:
|
||||
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
|
||||
continue
|
||||
if not raw:
|
||||
return candidates
|
||||
try:
|
||||
parsed = _json.loads(raw)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
|
||||
return candidates
|
||||
|
||||
# Rank fastest-first, demoting types that recently stocked out. Keeps the
|
||||
# primary (c4d) at the top whenever it has capacity.
|
||||
ranked = ordered_candidates(pool, capacity_state=config.capacity_state)
|
||||
return [
|
||||
EncodingWorkerCandidate(
|
||||
vm_name=c["vm"],
|
||||
zone=c["zone"],
|
||||
ip=c["ip"],
|
||||
machine_type=c.get("machine_type"),
|
||||
is_primary=c.get("is_primary", False),
|
||||
)
|
||||
for c in ranked
|
||||
]
|
||||
for item in parsed:
|
||||
try:
|
||||
candidates.append(EncodingWorkerCandidate(
|
||||
vm_name=item["vm"],
|
||||
zone=item["zone"],
|
||||
ip=item["ip"],
|
||||
))
|
||||
except (KeyError, TypeError) as e:
|
||||
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
|
||||
continue
|
||||
|
||||
return candidates
|
||||
|
||||
def _load_credentials(self):
|
||||
"""Load encoding worker URL and API key from config/secrets."""
|
||||
@@ -708,7 +586,7 @@ class EncodingService:
|
||||
if resp["status"] == 401:
|
||||
raise RuntimeError("Invalid API key for encoding worker")
|
||||
if resp["status"] == 404:
|
||||
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
|
||||
raise RuntimeError(f"Encoding job {job_id} not found")
|
||||
if resp["status"] != 200:
|
||||
raise RuntimeError(f"Failed to get job status: {resp['status']} - {resp['text']}")
|
||||
|
||||
@@ -721,7 +599,6 @@ class EncodingService:
|
||||
timeout: float = 3600.0,
|
||||
progress_callback=None,
|
||||
worker_url: Optional[str] = None,
|
||||
queue_timeout: float = QUEUE_TIMEOUT_SECONDS,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Poll for encoding job completion with tolerance for transient failures.
|
||||
@@ -754,25 +631,11 @@ class EncodingService:
|
||||
start_time = asyncio.get_event_loop().time()
|
||||
last_progress = 0
|
||||
consecutive_failures = 0
|
||||
# Set to True after the first successful poll. Once we've seen the job,
|
||||
# a later 404 means the worker LOST it (restart wiped in-memory state),
|
||||
# not that it never existed — that is unrecoverable for this job id, so
|
||||
# we resubmit rather than burn the transient-blip tolerance.
|
||||
job_seen = False
|
||||
# Set once the job is actually "running". The per-run `timeout` only
|
||||
# counts from here; time spent "pending" in the worker's serialized
|
||||
# heavy queue counts against `queue_timeout` instead.
|
||||
run_started_at: Optional[float] = None
|
||||
|
||||
while True:
|
||||
now = asyncio.get_event_loop().time()
|
||||
if run_started_at is not None:
|
||||
if now - run_started_at > timeout:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
elif now - start_time > queue_timeout:
|
||||
raise TimeoutError(
|
||||
f"Encoding job {job_id} stuck in worker queue longer than {queue_timeout}s"
|
||||
)
|
||||
elapsed = asyncio.get_event_loop().time() - start_time
|
||||
if elapsed > timeout:
|
||||
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
|
||||
|
||||
try:
|
||||
status = await self.get_job_status(job_id, worker_url=worker_url)
|
||||
@@ -780,20 +643,6 @@ class EncodingService:
|
||||
consecutive_failures = 0
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
|
||||
asyncio.TimeoutError, RuntimeError) as e:
|
||||
# A 404 *after* we've already seen the job = the worker lost it
|
||||
# (OOM/deploy restart wiped its in-memory registry). Resubmitting
|
||||
# the same id can never recover it, so surface a distinct signal
|
||||
# immediately instead of polling 4 more times and mislabelling it
|
||||
# "lost contact" (which callers treat as unrecoverable).
|
||||
if job_seen and isinstance(e, EncodingJobNotFoundError):
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Worker no longer has this job after previously "
|
||||
f"reporting it — treating as lost (worker restart): {e}"
|
||||
)
|
||||
raise EncodingJobLostError(
|
||||
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
|
||||
job_id=job_id,
|
||||
) from e
|
||||
consecutive_failures += 1
|
||||
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
|
||||
logger.error(
|
||||
@@ -818,19 +667,12 @@ class EncodingService:
|
||||
logger.error(f"[job:{job_id}] Unexpected status type: {type(status)}")
|
||||
status = {}
|
||||
|
||||
job_seen = True
|
||||
job_status = status.get("status", "unknown")
|
||||
progress = status.get("progress", 0)
|
||||
if run_started_at is None and (job_status == "running" or progress):
|
||||
run_started_at = now
|
||||
|
||||
# Report progress
|
||||
if progress != last_progress:
|
||||
queue_position = status.get("queue_position")
|
||||
if job_status == "pending" and queue_position:
|
||||
logger.info(f"[job:{job_id}] Queued on worker (position {queue_position})")
|
||||
else:
|
||||
logger.info(f"[job:{job_id}] Encoding progress: {progress}%")
|
||||
logger.info(f"[job:{job_id}] Encoding progress: {progress}%")
|
||||
last_progress = progress
|
||||
if progress_callback:
|
||||
try:
|
||||
@@ -839,21 +681,11 @@ class EncodingService:
|
||||
logger.warning(f"Progress callback failed: {e}")
|
||||
|
||||
if job_status == "complete":
|
||||
logger.info(f"[job:{job_id}] GCE encoding complete in {now - start_time:.1f}s")
|
||||
logger.info(f"[job:{job_id}] GCE encoding complete in {elapsed:.1f}s")
|
||||
return status
|
||||
|
||||
if job_status == "failed":
|
||||
error = status.get("error", "Unknown error")
|
||||
# A restart-marked failure is recoverable by resubmission, same
|
||||
# as a mid-run vanish — surface the typed signal so callers retry.
|
||||
if status.get("restart_failure_code") == ENCODING_RESTART_FAILURE_CODE:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Worker marked job failed after a restart — treating as lost: {error}"
|
||||
)
|
||||
raise EncodingJobLostError(
|
||||
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
|
||||
job_id=job_id,
|
||||
)
|
||||
raise RuntimeError(f"Encoding job {job_id} failed: {error}")
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
@@ -1042,16 +874,12 @@ class EncodingService:
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion with a short timeout. Previews are interactive
|
||||
# (a user is waiting in the review UI), so cap the *total* wait at the
|
||||
# same short bound — don't let a queued preview sit for the long default
|
||||
# queue_timeout before its per-run timeout even starts.
|
||||
# Wait for completion with shorter timeout
|
||||
return await self.wait_for_completion(
|
||||
job_id=job_id,
|
||||
poll_interval=poll_interval,
|
||||
timeout=timeout,
|
||||
worker_url=pinned_url,
|
||||
queue_timeout=timeout,
|
||||
)
|
||||
|
||||
async def submit_render_video_job(
|
||||
|
||||
@@ -28,7 +28,7 @@ Usage:
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, UTC
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -106,11 +106,6 @@ class EncodingWorkerConfig:
|
||||
active_override_ip: Optional[str] = None
|
||||
active_override_zone: Optional[str] = None
|
||||
active_override_set_at: Optional[str] = None
|
||||
# Availability-awareness state: {"<machine_type>@<zone>": last_stockout_iso}.
|
||||
# Written when a candidate start hits a capacity/stockout error, read by the
|
||||
# shared preference logic to demote recently-exhausted types. See
|
||||
# backend/services/encoding_worker_preference.py.
|
||||
capacity_state: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def primary_url(self) -> str:
|
||||
@@ -140,29 +135,17 @@ class EncodingWorkerCandidate:
|
||||
|
||||
Carries everything needed to talk to the worker: VM name + zone (so the
|
||||
GCE compute client targets the right zone) and external IP (so successful
|
||||
starts can be persisted as the active URL override). ``machine_type`` (e.g.
|
||||
"c4d-highcpu-32") lets the manager record/clear per-(type,zone) capacity
|
||||
state so the shared preference logic can demote a stocked-out type.
|
||||
starts can be persisted as the active URL override).
|
||||
"""
|
||||
|
||||
vm_name: str
|
||||
zone: str
|
||||
ip: str
|
||||
machine_type: Optional[str] = None
|
||||
# True iff this candidate is the blue-green PRIMARY VM. The override routing
|
||||
# (set on fallback, clear on primary) keys off this flag, NOT list position —
|
||||
# the preference logic may rank a fallback ahead of a stocked-out primary, so
|
||||
# "first candidate" is no longer synonymous with "primary".
|
||||
is_primary: bool = False
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return f"http://{self.ip}:{ENCODING_WORKER_PORT}"
|
||||
|
||||
def _cooldown_dict(self) -> dict:
|
||||
"""Dict view for the shared preference helpers (cooldown_key)."""
|
||||
return {"vm": self.vm_name, "zone": self.zone, "machine_type": self.machine_type}
|
||||
|
||||
|
||||
class EncodingWorkerManager:
|
||||
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
|
||||
@@ -207,7 +190,6 @@ class EncodingWorkerManager:
|
||||
active_override_ip=data.get("active_override_ip"),
|
||||
active_override_zone=data.get("active_override_zone"),
|
||||
active_override_set_at=data.get("active_override_set_at"),
|
||||
capacity_state=data.get("capacity_state") or {},
|
||||
)
|
||||
|
||||
def update_activity(self) -> None:
|
||||
@@ -439,9 +421,6 @@ class EncodingWorkerManager:
|
||||
last_capacity_error: Optional[EncodingWorkerCapacityError] = None
|
||||
last_start_error: Optional[EncodingWorkerStartError] = None
|
||||
last_non_transient_error: Optional[EncodingWorkerStartError] = None
|
||||
# When the caller marks a primary explicitly, route override off that flag;
|
||||
# otherwise preserve the legacy "index 0 is the primary" behaviour.
|
||||
has_explicit_primary = any(getattr(c, "is_primary", False) for c in candidates)
|
||||
for index, candidate in enumerate(candidates):
|
||||
try:
|
||||
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
|
||||
@@ -456,15 +435,7 @@ class EncodingWorkerManager:
|
||||
started = True
|
||||
|
||||
self.update_activity()
|
||||
# A clean start means this type/zone has capacity again — clear
|
||||
# any stale cooldown so the preference logic stops demoting it.
|
||||
self._clear_stockout(candidate)
|
||||
# "Fell back" = we did NOT land on the primary VM. Keyed off the
|
||||
# explicit flag when present (ordering can rank a fallback ahead of
|
||||
# a stocked-out primary, so it may not be index 0); otherwise the
|
||||
# legacy position-based rule.
|
||||
is_primary = candidate.is_primary if has_explicit_primary else (index == 0)
|
||||
fell_back = not is_primary
|
||||
fell_back = index > 0
|
||||
if fell_back:
|
||||
self._set_active_override(candidate)
|
||||
else:
|
||||
@@ -482,9 +453,6 @@ class EncodingWorkerManager:
|
||||
"Candidate %s in %s exhausted (%s), trying next candidate",
|
||||
candidate.vm_name, candidate.zone, cap_err.code,
|
||||
)
|
||||
# Record the stockout so the shared preference logic demotes this
|
||||
# (type,zone) for a cooldown window instead of re-probing it first.
|
||||
self._record_stockout(candidate)
|
||||
last_capacity_error = cap_err
|
||||
last_start_error = cap_err
|
||||
continue
|
||||
@@ -517,42 +485,6 @@ class EncodingWorkerManager:
|
||||
assert last_start_error is not None
|
||||
raise last_start_error
|
||||
|
||||
def _record_stockout(self, candidate) -> None:
|
||||
"""Mark a candidate's (machine_type, zone) as recently stocked out.
|
||||
|
||||
Merges a single key into the ``capacity_state`` map so concurrent starts
|
||||
don't clobber each other's entries. Best-effort — a Firestore hiccup here
|
||||
must never break the start path, so failures are logged and swallowed.
|
||||
"""
|
||||
from backend.services.encoding_worker_preference import cooldown_key
|
||||
|
||||
key = cooldown_key(candidate._cooldown_dict())
|
||||
if not key:
|
||||
return
|
||||
try:
|
||||
self._doc_ref().set(
|
||||
{"capacity_state": {key: datetime.now(UTC).isoformat()}}, merge=True
|
||||
)
|
||||
logger.info("Recorded stockout for %s", key)
|
||||
except Exception as e: # noqa: BLE001 — never fail the start path on telemetry
|
||||
logger.warning("Could not record stockout for %s: %s", key, e)
|
||||
|
||||
def _clear_stockout(self, candidate) -> None:
|
||||
"""Clear a candidate's (machine_type, zone) cooldown after a clean start.
|
||||
|
||||
Sets the key to None (parsed as "not stocked out") via a merge so other
|
||||
keys are untouched. Best-effort, like _record_stockout.
|
||||
"""
|
||||
from backend.services.encoding_worker_preference import cooldown_key
|
||||
|
||||
key = cooldown_key(candidate._cooldown_dict())
|
||||
if not key:
|
||||
return
|
||||
try:
|
||||
self._doc_ref().set({"capacity_state": {key: None}}, merge=True)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Could not clear stockout for %s: %s", key, e)
|
||||
|
||||
def _set_active_override(self, candidate) -> None:
|
||||
"""Record a fallback VM as the active worker URL in Firestore."""
|
||||
now = datetime.now(UTC).isoformat()
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
"""Shared, pure preference logic for encoding-worker candidate ordering.
|
||||
|
||||
This is the SINGLE SOURCE OF TRUTH for how encode-worker VM candidates are ranked,
|
||||
used by BOTH:
|
||||
|
||||
* runtime worker selection —
|
||||
``backend/services/encoding_service._build_worker_candidates`` →
|
||||
``encoding_worker_manager.ensure_any_running``
|
||||
* deploy green (staging) selection —
|
||||
``infrastructure/encoding-worker/deploy_promote.select_green_candidates``
|
||||
|
||||
Keeping the ordering in one place stops the two call-sites from drifting (they
|
||||
previously used different ad-hoc heuristics: runtime = secret order, deploy =
|
||||
"n2 before c4d").
|
||||
|
||||
Design:
|
||||
* **Fastest-first base order.** Candidates sort by ``SPEED_RANK`` (lower =
|
||||
faster), so the fastest available type (c4d) is always preferred when it can
|
||||
start — the whole reason c4d was chosen. No behaviour change on a healthy day.
|
||||
* **Availability-aware cooldown.** A type that recently failed to start with a
|
||||
capacity/stockout error (recorded in Firestore ``capacity_state``) is
|
||||
*demoted to the back* for ``COOLDOWN_SECONDS`` — long enough to stop paying
|
||||
the ~2-min-per-attempt probe cost on a known-dead type, short enough to
|
||||
re-probe and snap back to the faster type the moment capacity returns. It is
|
||||
demoted, never dropped, so the pool always stays fully available.
|
||||
|
||||
This module is intentionally **dependency-free (stdlib only)** so that
|
||||
``deploy_promote`` — which is loaded by path in CI with no backend package deps —
|
||||
can import it without pulling the heavy backend tree.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
# Lower rank = faster = preferred. Seeded from CPU architecture; refine with the
|
||||
# measured medians from infrastructure/encoding-worker/benchmark_types.py.
|
||||
# c4d AMD EPYC Turin (Zen5) — current primary, fastest
|
||||
# c4 Intel Emerald Rapids — newest Intel perf tier
|
||||
# n4d AMD (Titanium) — flexible/deep AMD
|
||||
# c2d AMD Milan (Zen3) — mature, deep pool
|
||||
# n2d AMD Rome/Milan — deep pool (32 GB floor)
|
||||
# n2 Intel Cascade/Ice Lake — current fallback (32 GB floor)
|
||||
SPEED_RANK: Dict[str, int] = {
|
||||
"c4d-highcpu-32": 10,
|
||||
"c4-highcpu-32": 20,
|
||||
"n4d-highcpu-32": 30,
|
||||
"c2d-highcpu-32": 50,
|
||||
"n2d-highcpu-32": 60,
|
||||
"n2-highcpu-32": 70,
|
||||
}
|
||||
|
||||
# Rank for a candidate whose machine type is unknown and cannot be inferred:
|
||||
# treat as slowest-but-usable so it sorts LAST without ever being dropped.
|
||||
UNKNOWN_RANK = 1000
|
||||
|
||||
# How long a type that just stocked out is demoted before it is re-probed.
|
||||
COOLDOWN_SECONDS = 900 # 15 minutes
|
||||
|
||||
# Machine type of the blue-green primary/secondary pair (encoding-worker-a/-b).
|
||||
# They are always c4d; used when a candidate carries no explicit machine_type.
|
||||
PRIMARY_MACHINE_TYPE = "c4d-highcpu-32"
|
||||
|
||||
# vm-name substring → machine type, for backward-compat inference when a fallback
|
||||
# entry predates the machine_type field. Checked in order — longer / more-specific
|
||||
# family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d" by "c4".
|
||||
_NAME_TOKEN_TO_TYPE = (
|
||||
("c4d", "c4d-highcpu-32"),
|
||||
("n4d", "n4d-highcpu-32"),
|
||||
("n2d", "n2d-highcpu-32"),
|
||||
("c2d", "c2d-highcpu-32"),
|
||||
("c4", "c4-highcpu-32"),
|
||||
("n2", "n2-highcpu-32"),
|
||||
)
|
||||
|
||||
|
||||
def _candidate_name(candidate: Dict[str, Any]) -> str:
|
||||
"""VM name from either dict shape ({"vm"} for deploy, {"vm_name"} for runtime)."""
|
||||
return (candidate.get("vm") or candidate.get("vm_name") or "")
|
||||
|
||||
|
||||
def infer_machine_type(candidate: Dict[str, Any]) -> Optional[str]:
|
||||
"""Best-effort machine type: explicit ``machine_type`` field, else vm-name token.
|
||||
|
||||
Fallback secret entries created before the ``machine_type`` field carry only
|
||||
vm/zone/ip; the VM-name family token (…-fallback-n2c, …-fallback-c4a) is the
|
||||
only hint. Returns None when nothing matches (caller treats as UNKNOWN_RANK).
|
||||
"""
|
||||
explicit = candidate.get("machine_type")
|
||||
if explicit:
|
||||
return explicit
|
||||
name = _candidate_name(candidate).lower()
|
||||
for token, mtype in _NAME_TOKEN_TO_TYPE:
|
||||
if token in name:
|
||||
return mtype
|
||||
return None
|
||||
|
||||
|
||||
def _speed_rank(candidate: Dict[str, Any]) -> int:
|
||||
return SPEED_RANK.get(infer_machine_type(candidate), UNKNOWN_RANK)
|
||||
|
||||
|
||||
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
|
||||
"""Firestore ``capacity_state`` key for a candidate: ``"<machine_type>@<zone>"``.
|
||||
|
||||
Zone-scoped because a stockout is per (machine family × zone). Returns None
|
||||
when the machine type can't be determined (no cooldown tracking possible).
|
||||
NOTE: keys deliberately avoid ``.`` so they are safe as Firestore map keys.
|
||||
"""
|
||||
mtype = infer_machine_type(candidate)
|
||||
if not mtype:
|
||||
return None
|
||||
zone = candidate.get("zone")
|
||||
return f"{mtype}@{zone}" if zone else mtype
|
||||
|
||||
|
||||
def _parse_iso(value: Any) -> Optional[datetime]:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(value)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
if dt.tzinfo is None: # tolerate naive timestamps — assume UTC
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt
|
||||
|
||||
|
||||
def _recently_stocked_out(
|
||||
candidate: Dict[str, Any],
|
||||
capacity_state: Optional[Dict[str, Any]],
|
||||
now: datetime,
|
||||
cooldown_seconds: float,
|
||||
) -> bool:
|
||||
"""True if this candidate's (type@zone) — or its coarser type-only key — is in cooldown."""
|
||||
if not capacity_state:
|
||||
return False
|
||||
key = cooldown_key(candidate)
|
||||
if not key:
|
||||
return False
|
||||
ts = _parse_iso(capacity_state.get(key))
|
||||
if ts is None:
|
||||
# Fall back to a type-only signal (a coarser "this family is short").
|
||||
mtype = infer_machine_type(candidate)
|
||||
if mtype:
|
||||
ts = _parse_iso(capacity_state.get(mtype))
|
||||
if ts is None:
|
||||
return False
|
||||
return (now - ts).total_seconds() < cooldown_seconds
|
||||
|
||||
|
||||
def ordered_candidates(
|
||||
pool: List[Dict[str, Any]],
|
||||
capacity_state: Optional[Dict[str, Any]] = None,
|
||||
now: Optional[datetime] = None,
|
||||
cooldown_seconds: float = COOLDOWN_SECONDS,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Rank ``pool`` fastest-first, demoting recently-stocked-out types to the back.
|
||||
|
||||
Args:
|
||||
pool: candidate dicts, each ``{vm|vm_name, zone, ip, machine_type?, kind?}``.
|
||||
Objects are returned as-is (not copied), only reordered — so callers can
|
||||
round-trip their own richer objects through a dict view.
|
||||
capacity_state: Firestore map ``{"<type>@<zone>"|"<type>": last_stockout_iso}``.
|
||||
Absent/empty ⇒ pure fastest-first order (today's behaviour).
|
||||
now: current UTC time (injectable for tests); defaults to ``datetime.now(UTC)``.
|
||||
cooldown_seconds: demotion window; defaults to ``COOLDOWN_SECONDS``.
|
||||
|
||||
The speed sort is STABLE, so equal-rank candidates keep their input order —
|
||||
callers express a secondary preference (e.g. zone spread) purely via input
|
||||
ordering. The hot/cold partition is likewise stable within each group.
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
ranked = sorted(pool, key=_speed_rank) # stable: fastest first
|
||||
hot = [c for c in ranked if not _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
|
||||
cold = [c for c in ranked if _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
|
||||
return hot + cold
|
||||
@@ -3,7 +3,7 @@ Firestore database operations for job management.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
@@ -87,9 +87,7 @@ class FirestoreService:
|
||||
# Create timeline event
|
||||
timeline_event = TimelineEvent(
|
||||
status=status.value,
|
||||
# Timezone-aware UTC so the serialized ISO string carries a
|
||||
# "+00:00" offset (see job_manager.create_job for rationale).
|
||||
timestamp=datetime.now(timezone.utc).isoformat(),
|
||||
timestamp=datetime.utcnow().isoformat(),
|
||||
progress=progress,
|
||||
message=message,
|
||||
metadata=timeline_metadata,
|
||||
@@ -200,7 +198,7 @@ class FirestoreService:
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'made_for_you', 'customer_email', 'locale',
|
||||
'made_for_you', 'customer_email',
|
||||
'url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import glob as glob_module
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
@@ -8,7 +9,6 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -30,50 +30,7 @@ logger = logging.getLogger(__name__)
|
||||
# so polls after a worker restart return the *last known* status instead of
|
||||
# 404. Hot path stays in-memory; persistence is best-effort.
|
||||
jobs: dict[str, dict] = {}
|
||||
|
||||
# Two execution lanes with very different memory profiles:
|
||||
#
|
||||
# heavy_executor — full renders (`run_render_video`) and final encodes
|
||||
# (`run_encoding`). Each of these spawns an ffmpeg that already saturates
|
||||
# every core, so running two in parallel gains no throughput but doubles
|
||||
# peak RAM (a single 4K encode can use ~18 GB). Three concurrent encodes
|
||||
# OOM-killed the 32 GB n2 fallback worker on 2026-08-15, which restarted
|
||||
# the service and lost every in-flight job. Default to ONE heavy job at a
|
||||
# time so the worker is OOM-proof on any machine type; the rest queue as
|
||||
# `status="pending"` (surfaced via /health `queue_length` and /status
|
||||
# `queue_position`). Override with ENCODING_HEAVY_CONCURRENCY only on
|
||||
# boxes with headroom to spare.
|
||||
#
|
||||
# light_executor — wheel installs (`ensure_latest_wheel`) and interactive
|
||||
# review previews (`run_preview_encoding`). These are small/fast and
|
||||
# latency-sensitive, so they get their own lane and never wait behind a
|
||||
# multi-minute encode.
|
||||
def _heavy_concurrency() -> int:
|
||||
"""Parse ENCODING_HEAVY_CONCURRENCY, clamped to a sane [1, 4] range.
|
||||
|
||||
A malformed/zero/negative value must never crash the worker at boot or
|
||||
(via max_workers=0) wedge every encode — fall back to the OOM-safe default
|
||||
of 1. The upper bound guards against an operator accidentally reintroducing
|
||||
the concurrent-encode OOM on a small box.
|
||||
"""
|
||||
raw = os.environ.get("ENCODING_HEAVY_CONCURRENCY", "1")
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("Invalid ENCODING_HEAVY_CONCURRENCY=%r; defaulting to 1", raw)
|
||||
return 1
|
||||
if value < 1:
|
||||
logger.warning("ENCODING_HEAVY_CONCURRENCY=%d < 1; clamping to 1", value)
|
||||
return 1
|
||||
if value > 4:
|
||||
logger.warning("ENCODING_HEAVY_CONCURRENCY=%d > 4; clamping to 4", value)
|
||||
return 4
|
||||
return value
|
||||
|
||||
|
||||
HEAVY_CONCURRENCY = _heavy_concurrency()
|
||||
heavy_executor = ThreadPoolExecutor(max_workers=HEAVY_CONCURRENCY)
|
||||
light_executor = ThreadPoolExecutor(max_workers=2)
|
||||
executor = ThreadPoolExecutor(max_workers=4) # 4 parallel encoding jobs
|
||||
|
||||
# Persister is initialized lazily — see persistence.py — so import-time
|
||||
# stays free of GCP creds. Tests can monkey-patch this attribute.
|
||||
@@ -163,15 +120,6 @@ class JobStatus(BaseModel):
|
||||
error: Optional[str] = None
|
||||
output_files: Optional[list[str]] = None
|
||||
metadata: Optional[dict] = None
|
||||
# Set when a job was interrupted by a worker-process restart (OOM, deploy,
|
||||
# crash). Its work_dir is gone, so the client should resubmit rather than
|
||||
# treat this as a permanent failure. See persistence.mark_orphans_failed_on_startup.
|
||||
restart_failure_code: Optional[str] = None
|
||||
# How many heavy jobs (renders/encodes) are ahead of this one in the
|
||||
# serialized heavy lane (0 = running or next up). None for previews /
|
||||
# terminal jobs. Lets the client wait through a deep queue without
|
||||
# tripping the encode timeout.
|
||||
queue_position: Optional[int] = None
|
||||
|
||||
|
||||
def download_from_gcs(gcs_uri: str, local_path: Path):
|
||||
@@ -591,211 +539,59 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
raise
|
||||
|
||||
|
||||
# Wheel install/verification tuning.
|
||||
#
|
||||
# On a freshly-provisioned worker the Packer image only pre-installs a handful
|
||||
# of packages (fastapi/uvicorn/gcs/...) and boot installs the wheel with
|
||||
# --no-deps, so the FIRST job's install here has to resolve the entire
|
||||
# karaoke-gen dependency tree (torch, langchain, tenacity, ...). That can take
|
||||
# well over 5 minutes and, if it times out or partially completes, leaves the
|
||||
# environment importable-but-broken (e.g. "No module named 'tenacity'"). We
|
||||
# therefore retry, and — critically — verify the import chain actually works
|
||||
# before declaring success, since pip can return 0 while a dependency is still
|
||||
# missing.
|
||||
WHEEL_INSTALL_TIMEOUT = int(os.environ.get("WHEEL_INSTALL_TIMEOUT", "900"))
|
||||
WHEEL_INSTALL_ATTEMPTS = int(os.environ.get("WHEEL_INSTALL_ATTEMPTS", "3"))
|
||||
|
||||
# Serialize wheel checks. ensure_latest_wheel() runs on the light executor
|
||||
# (>1 thread) and is invoked at the start of every job, so without a lock two
|
||||
# concurrent jobs race on the same /tmp wheel path (`gsutil cp` clobbers the
|
||||
# file mid-copy) and the same venv (`pip install` runs twice at once) —
|
||||
# corrupting each other so one job fails with "wheel/dependencies not ready"
|
||||
# (incident 2026-08-15, job 374dec26, three jobs hitting a fresh fallback boot).
|
||||
# The lock makes the first caller do the work while the rest wait, then take the
|
||||
# already-verified fast path below.
|
||||
_wheel_lock = threading.Lock()
|
||||
# Version we've already downloaded+installed+verified in THIS process. Lets a
|
||||
# job skip the whole download/install/verify when the environment is already
|
||||
# current — the common case, since startup.sh installs the wheel at boot and
|
||||
# only the first job after a new deploy actually needs to install.
|
||||
_verified_wheel_version: Optional[str] = None
|
||||
|
||||
|
||||
def _installed_karaoke_gen_version() -> Optional[str]:
|
||||
'''Return the karaoke-gen version currently importable in this venv, or None.'''
|
||||
try:
|
||||
from importlib.metadata import version as _get_version
|
||||
return _get_version("karaoke-gen")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# Modules exercised by the render (OutputGenerator) and encode
|
||||
# (LocalEncodingService) code paths. Importing these confirms the whole
|
||||
# dependency tree they pull in — including transitive deps like tenacity — is
|
||||
# actually present, not just that `pip install` exited 0.
|
||||
_WHEEL_IMPORT_CHECK = (
|
||||
"import tenacity; "
|
||||
"from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator; "
|
||||
"from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations; "
|
||||
"from backend.services.local_encoding_service import LocalEncodingService"
|
||||
)
|
||||
|
||||
|
||||
def verify_wheel_imports():
|
||||
'''Verify the karaoke-gen render/encode import chain is fully importable.
|
||||
|
||||
Runs in a subprocess so a broken/partial install surfaces as a clean
|
||||
boolean instead of crashing (or half-importing into) the worker process.
|
||||
Returns True if every module imports, False otherwise.
|
||||
'''
|
||||
try:
|
||||
check = subprocess.run(
|
||||
[sys.executable, "-c", _WHEEL_IMPORT_CHECK],
|
||||
capture_output=True, text=True, timeout=180,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("Wheel import verification timed out")
|
||||
return False
|
||||
if check.returncode != 0:
|
||||
# Tail of stderr carries the actionable ModuleNotFoundError.
|
||||
logger.warning(f"Wheel import verification failed: {check.stderr.strip()[-500:]}")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def ensure_latest_wheel():
|
||||
'''Ensure the latest karaoke-gen wheel is installed & verified (thread-safe).
|
||||
'''Download and install latest karaoke-gen wheel from GCS.
|
||||
|
||||
Called at the start of each job to enable hot code updates without restart.
|
||||
Serialized via `_wheel_lock` so concurrent jobs can't race on the shared
|
||||
/tmp wheel path or venv; the first caller installs/verifies while the rest
|
||||
wait and then hit the already-verified fast path.
|
||||
In-progress jobs continue with their version, new jobs get latest code.
|
||||
'''
|
||||
with _wheel_lock:
|
||||
return _ensure_latest_wheel_locked()
|
||||
|
||||
|
||||
def _ensure_latest_wheel_locked():
|
||||
'''Download, install, and verify the latest karaoke-gen wheel from GCS.
|
||||
|
||||
MUST be called holding `_wheel_lock`. In-progress jobs continue with their
|
||||
version, new jobs get latest code.
|
||||
|
||||
Retries the install and verifies the full import chain before returning, so
|
||||
a transient/partial dependency install can't leave the worker running jobs
|
||||
against a broken environment. Returns True only when the wheel is installed
|
||||
AND its render/encode imports succeed.
|
||||
'''
|
||||
global _verified_wheel_version
|
||||
try:
|
||||
logger.info("Checking for latest karaoke-gen wheel in GCS...")
|
||||
|
||||
# Sort helper: extract version from a wheel name/URI like
|
||||
# karaoke_gen-0.116.1-py3-none-any.whl
|
||||
# Download latest wheel
|
||||
result = subprocess.run(
|
||||
["gsutil", "cp", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl", "/tmp/"],
|
||||
capture_output=True, text=True, timeout=60
|
||||
)
|
||||
|
||||
# Find the downloaded wheel (get the latest by version sorting)
|
||||
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
|
||||
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
|
||||
wheels = [w for w in wheels if '-current' not in w]
|
||||
|
||||
if not wheels:
|
||||
logger.warning("No wheel found in GCS, using fallback encoding logic")
|
||||
return False
|
||||
|
||||
# Sort to get latest version (by semantic version, not alphabetically)
|
||||
def extract_version(wheel_path):
|
||||
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
|
||||
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
|
||||
if match:
|
||||
return Version(match.group(1))
|
||||
return Version("0.0.0") # Fallback for unparseable filenames
|
||||
|
||||
# List wheel names only (fast), then copy just the single latest one.
|
||||
# NOTE: `gsutil cp gs://.../karaoke_gen-*.whl /tmp/` would download the
|
||||
# ENTIRE wheels/ directory (hundreds of wheels, multiple GiB) on every
|
||||
# job and blow the timeout on fresh workers — the historical cause of
|
||||
# "no wheel found" / partial installs. Listing + single copy is ~2s.
|
||||
ls_result = subprocess.run(
|
||||
["gsutil", "ls", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl"],
|
||||
capture_output=True, text=True, timeout=60
|
||||
)
|
||||
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
|
||||
wheel_uris = [
|
||||
line.strip() for line in ls_result.stdout.splitlines()
|
||||
if line.strip() and '-current' not in line
|
||||
]
|
||||
wheels.sort(key=extract_version, reverse=True)
|
||||
wheel_path = wheels[0]
|
||||
logger.info(f"Installing wheel: {wheel_path}")
|
||||
|
||||
if not wheel_uris:
|
||||
logger.warning("No versioned wheel found in GCS, using fallback encoding logic")
|
||||
# Install (or upgrade) the wheel
|
||||
# Use 5-minute timeout - first install at job start may need to resolve dependencies
|
||||
# Subsequent installs are faster since dependencies are cached
|
||||
install_result = subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
|
||||
capture_output=True, text=True, timeout=300
|
||||
)
|
||||
|
||||
if install_result.returncode != 0:
|
||||
logger.warning(f"Wheel installation failed: {install_result.stderr}")
|
||||
return False
|
||||
|
||||
wheel_uris.sort(key=extract_version)
|
||||
latest_uri = wheel_uris[-1]
|
||||
latest_version = str(extract_version(latest_uri))
|
||||
wheel_path = os.path.join("/tmp", latest_uri.rsplit("/", 1)[-1])
|
||||
|
||||
# Fast path: if the environment is already at the latest version, skip
|
||||
# the download/install entirely. This is the common case (startup.sh
|
||||
# installs the wheel at boot) and — together with `_wheel_lock` — is what
|
||||
# stops concurrent jobs from re-downloading/re-installing and racing.
|
||||
if _verified_wheel_version == latest_version:
|
||||
# Already validated in this process — nothing to do.
|
||||
return True
|
||||
installed_version = _installed_karaoke_gen_version()
|
||||
if installed_version == latest_version:
|
||||
# Right version is present but not yet verified in this process.
|
||||
# Confirm the import chain (cheap) rather than reinstalling; only
|
||||
# fall through to a full reinstall if a prior install was partial.
|
||||
if verify_wheel_imports():
|
||||
_verified_wheel_version = latest_version
|
||||
logger.info(f"karaoke-gen {latest_version} already installed and verified; skipping wheel install")
|
||||
return True
|
||||
logger.warning(
|
||||
f"karaoke-gen {latest_version} present but import chain incomplete; reinstalling"
|
||||
)
|
||||
|
||||
cp_result = subprocess.run(
|
||||
["gsutil", "cp", latest_uri, wheel_path],
|
||||
capture_output=True, text=True, timeout=120
|
||||
)
|
||||
if cp_result.returncode != 0:
|
||||
logger.warning(f"Failed to download wheel {latest_uri}: {cp_result.stderr.strip()[-500:]}")
|
||||
return False
|
||||
|
||||
# Install (with deps), then verify the import chain is complete. Retry a
|
||||
# failed or partial install: pip is resumable, so a second pass fills in
|
||||
# dependencies a timed-out first pass left missing (e.g. tenacity).
|
||||
for attempt in range(1, WHEEL_INSTALL_ATTEMPTS + 1):
|
||||
logger.info(f"Installing wheel (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): {wheel_path}")
|
||||
try:
|
||||
install_result = subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
|
||||
capture_output=True, text=True, timeout=WHEEL_INSTALL_TIMEOUT
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning(
|
||||
f"Wheel install timed out after {WHEEL_INSTALL_TIMEOUT}s "
|
||||
f"(attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS})"
|
||||
)
|
||||
install_result = None
|
||||
|
||||
if install_result is not None and install_result.returncode != 0:
|
||||
logger.warning(
|
||||
f"Wheel installation failed (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): "
|
||||
f"{install_result.stderr.strip()[-500:]}"
|
||||
)
|
||||
elif install_result is not None:
|
||||
logger.info(f"pip install completed for wheel: {wheel_path}")
|
||||
|
||||
# A clean `pip install` exit is not sufficient — confirm the deps
|
||||
# the render/encode paths need are actually importable before we let
|
||||
# a job run against this environment.
|
||||
if verify_wheel_imports():
|
||||
_verified_wheel_version = latest_version
|
||||
logger.info(f"Successfully installed and verified wheel: {wheel_path}")
|
||||
return True
|
||||
|
||||
logger.warning(
|
||||
f"Wheel environment incomplete after attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}; "
|
||||
"dependencies are missing or failed to import"
|
||||
)
|
||||
|
||||
logger.error(
|
||||
f"Wheel not ready after {WHEEL_INSTALL_ATTEMPTS} attempts: import verification "
|
||||
"still failing (environment is missing dependencies)"
|
||||
)
|
||||
return False
|
||||
logger.info(f"Successfully installed wheel: {wheel_path}")
|
||||
return True
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("Wheel download timed out, using fallback")
|
||||
logger.warning("Wheel download/install timed out, using fallback")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to ensure latest wheel: {e}")
|
||||
@@ -848,110 +644,6 @@ def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) ->
|
||||
return mov_path
|
||||
|
||||
|
||||
# Portrait (9:16) karaoke render is default-on; set PORTRAIT_RENDER_ENABLED=false to disable.
|
||||
PORTRAIT_RENDER_ENABLED = os.environ.get("PORTRAIT_RENDER_ENABLED", "true").lower() == "true"
|
||||
PORTRAIT_SUFFIX = "(Final Karaoke Portrait 1080x1920)"
|
||||
|
||||
|
||||
def _resolve_portrait_font(styles: dict, work_dir: Path) -> Optional[str]:
|
||||
"""Resolve a usable .ttf file for the portrait header (PIL needs a file path).
|
||||
|
||||
libass resolves the lyrics font via fontconfig (the theme font is registered by
|
||||
the earlier render step on the same VM), but PIL needs an actual file. Ask
|
||||
fontconfig for the theme font family's file; fall back to any bundled style font.
|
||||
"""
|
||||
family = (styles.get("karaoke", {}) or {}).get("font") or "Avenir Next Bold"
|
||||
try:
|
||||
res = subprocess.run(
|
||||
["fc-match", "--format=%{file}", family],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
if res.returncode == 0 and res.stdout and os.path.isfile(res.stdout.strip()):
|
||||
return res.stdout.strip()
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
for pattern in ("style/*.ttf", "style/*.otf", "*.ttf"):
|
||||
hit = next(iter(work_dir.glob(pattern)), None)
|
||||
if hit:
|
||||
return str(hit)
|
||||
return None
|
||||
|
||||
|
||||
def render_portrait_into_outputs(
|
||||
job_id: str, work_dir: Path, output_dir: Path, base_name: str,
|
||||
artist: str, title: str, instrumental: Path, config: dict,
|
||||
) -> Optional[str]:
|
||||
"""Render the portrait (9:16) karaoke video into ``output_dir`` (best-effort).
|
||||
|
||||
Reuses the same corrected-lyrics data + theme as the landscape render. Uses the
|
||||
un-padded instrumental and un-countdown-processed segments so the two stay in
|
||||
sync without the countdown offset (the portrait title card provides lead-in).
|
||||
|
||||
This is additive and non-fatal: any failure logs and returns ``None`` so the
|
||||
landscape outputs and distribution proceed unaffected.
|
||||
"""
|
||||
if not PORTRAIT_RENDER_ENABLED:
|
||||
logger.info(f"[job:{job_id}] Portrait render disabled via PORTRAIT_RENDER_ENABLED")
|
||||
return None
|
||||
try:
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.portrait import render_portrait_video, PortraitBrandConfig
|
||||
|
||||
# Corrected lyrics: prefer the reviewed corrections_updated.json.
|
||||
corrections_file = None
|
||||
for candidate in ("lyrics/corrections_updated.json", "lyrics/corrections.json"):
|
||||
p = work_dir / candidate
|
||||
if p.is_file():
|
||||
corrections_file = p
|
||||
break
|
||||
if corrections_file is None:
|
||||
found = next(iter(work_dir.glob("**/corrections*.json")), None)
|
||||
corrections_file = found
|
||||
if corrections_file is None:
|
||||
logger.warning(f"[job:{job_id}] Portrait skipped: no corrections JSON found")
|
||||
return None
|
||||
with open(corrections_file, "r", encoding="utf-8") as f:
|
||||
correction_result = CorrectionResult.from_dict(json.load(f))
|
||||
|
||||
# Theme styles (optional — renderer fills defaults).
|
||||
styles = {}
|
||||
style_params = work_dir / "style" / "style_params.json"
|
||||
if not style_params.is_file():
|
||||
style_params = next(iter(work_dir.glob("**/style_params.json")), None)
|
||||
if style_params and Path(style_params).is_file():
|
||||
with open(style_params, "r", encoding="utf-8") as f:
|
||||
styles = json.load(f)
|
||||
|
||||
font_path = _resolve_portrait_font(styles, work_dir)
|
||||
brand = PortraitBrandConfig(
|
||||
brand_text=config.get("portrait_brand_text", "NOMAD KARAOKE"),
|
||||
footer_text=config.get("portrait_footer_text", "nomadkaraoke.com"),
|
||||
font_path=font_path,
|
||||
)
|
||||
out_path = output_dir / f"{base_name} {PORTRAIT_SUFFIX}.mp4"
|
||||
logger.info(f"[job:{job_id}] Rendering portrait karaoke video -> {out_path.name}")
|
||||
render_portrait_video(
|
||||
correction_result=correction_result,
|
||||
instrumental_path=str(instrumental),
|
||||
styles=styles,
|
||||
artist=artist,
|
||||
title=title,
|
||||
output_path=str(out_path),
|
||||
brand=brand,
|
||||
font_path=font_path,
|
||||
work_dir=str(work_dir / "portrait_tmp"),
|
||||
logger=logger,
|
||||
)
|
||||
if out_path.is_file():
|
||||
logger.info(f"[job:{job_id}] Portrait render complete ({out_path.stat().st_size} bytes)")
|
||||
return str(out_path)
|
||||
logger.warning(f"[job:{job_id}] Portrait render produced no file")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Portrait render failed (non-fatal): {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
'''Run encoding using LocalEncodingService (single source of truth).
|
||||
|
||||
@@ -1149,13 +841,6 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to stage {suffix} MOV into outputs: {e}")
|
||||
|
||||
# Portrait (9:16) karaoke render — additive, non-fatal. Written into output_dir
|
||||
# so it rides the same GCS upload + Dropbox distribution as the other finals.
|
||||
jobs[job_id]["progress"] = 92
|
||||
render_portrait_into_outputs(
|
||||
job_id, work_dir, output_dir, base_name, artist, title, instrumental, config,
|
||||
)
|
||||
|
||||
# Collect output files
|
||||
output_files = [str(f) for f in output_dir.glob("*") if f.is_file()]
|
||||
jobs[job_id]["output_files"] = output_files
|
||||
@@ -1188,18 +873,8 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
# Process an encoding job asynchronously
|
||||
try:
|
||||
# Download and install latest wheel at job start (allows hot updates without restart)
|
||||
# This means in-progress jobs continue with their version, new jobs get latest code.
|
||||
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
|
||||
# confusing "No module named ..." ImportError deep in encoding.
|
||||
# ensure_latest_wheel() makes blocking subprocess calls (install can retry for many
|
||||
# minutes) — run it in the thread pool so the async event loop keeps serving health
|
||||
# checks and status polls.
|
||||
loop = asyncio.get_event_loop()
|
||||
if not await loop.run_in_executor(light_executor, ensure_latest_wheel):
|
||||
raise RuntimeError(
|
||||
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
|
||||
"job should be retried on a healthy worker"
|
||||
)
|
||||
# This means in-progress jobs continue with their version, new jobs get latest code
|
||||
ensure_latest_wheel()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
@@ -1221,11 +896,10 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
logger.info(f"Downloading existing instrumental: {gcs_uri} -> {dest}")
|
||||
download_single_file_from_gcs(gcs_uri, dest)
|
||||
|
||||
# Run encoding in the heavy lane (CPU/RAM-bound; serialized to
|
||||
# avoid OOM — see heavy_executor comment).
|
||||
# Run encoding in thread pool (CPU-bound)
|
||||
loop = asyncio.get_event_loop()
|
||||
output_dir = await loop.run_in_executor(
|
||||
heavy_executor,
|
||||
executor,
|
||||
run_encoding,
|
||||
job_id,
|
||||
work_dir,
|
||||
@@ -1271,11 +945,11 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
work_dir.mkdir()
|
||||
|
||||
# Run preview encoding in the light lane so interactive review
|
||||
# previews never queue behind a multi-minute full encode.
|
||||
# Run preview encoding in thread pool (CPU-bound)
|
||||
# Note: run_preview_encoding handles download/upload internally
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(
|
||||
light_executor,
|
||||
executor,
|
||||
run_preview_encoding,
|
||||
job_id,
|
||||
work_dir,
|
||||
@@ -1297,27 +971,17 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
# Process a render-video job asynchronously
|
||||
try:
|
||||
# Download and install latest wheel at job start (allows hot updates without restart).
|
||||
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
|
||||
# confusing "No module named 'tenacity'" ImportError inside render_video.
|
||||
# Run in the thread pool: ensure_latest_wheel() blocks on subprocess installs (which
|
||||
# can retry for many minutes) and must not stall the async event loop.
|
||||
loop = asyncio.get_event_loop()
|
||||
if not await loop.run_in_executor(light_executor, ensure_latest_wheel):
|
||||
raise RuntimeError(
|
||||
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
|
||||
"job should be retried on a healthy worker"
|
||||
)
|
||||
# Download and install latest wheel at job start (allows hot updates without restart)
|
||||
ensure_latest_wheel()
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
work_dir.mkdir()
|
||||
|
||||
# Run render-video in the heavy lane (CPU/RAM-bound; serialized to
|
||||
# avoid OOM — see heavy_executor comment).
|
||||
# Run render-video in thread pool (CPU-bound)
|
||||
loop = asyncio.get_event_loop()
|
||||
await loop.run_in_executor(
|
||||
heavy_executor,
|
||||
executor,
|
||||
run_render_video,
|
||||
job_id,
|
||||
work_dir,
|
||||
@@ -1360,7 +1024,6 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
"kind": "preview", # light lane — never counted in the heavy queue
|
||||
}
|
||||
_persist(job_id)
|
||||
|
||||
@@ -1393,7 +1056,6 @@ async def submit_render_video_job(request: RenderVideoRequest, background_tasks:
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
"metadata": None,
|
||||
"kind": "render", # heavy lane
|
||||
}
|
||||
_persist(job_id)
|
||||
|
||||
@@ -1426,7 +1088,6 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"output_files": None,
|
||||
"kind": "encode", # heavy lane
|
||||
}
|
||||
_persist(job_id)
|
||||
|
||||
@@ -1435,37 +1096,12 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
|
||||
return {"status": "accepted", "job_id": job_id}
|
||||
|
||||
|
||||
_HEAVY_KINDS = frozenset({"encode", "render"})
|
||||
|
||||
|
||||
def _heavy_queue_position(job_id: str) -> Optional[int]:
|
||||
"""Number of heavy jobs ahead of `job_id` in the serialized heavy lane.
|
||||
|
||||
0 means this job is running or next up; None means it isn't a queued heavy
|
||||
job (a preview, a terminal job, or unknown-kind). Relies on `jobs` being
|
||||
insertion-ordered (dict order) so "ahead" == submitted earlier and still
|
||||
pending/running.
|
||||
"""
|
||||
job = jobs.get(job_id)
|
||||
if job is None or job.get("kind") not in _HEAVY_KINDS:
|
||||
return None
|
||||
if job.get("status") not in ("pending", "running"):
|
||||
return None
|
||||
ahead = 0
|
||||
for other_id, other in jobs.items():
|
||||
if other_id == job_id:
|
||||
break
|
||||
if other.get("kind") in _HEAVY_KINDS and other.get("status") in ("pending", "running"):
|
||||
ahead += 1
|
||||
return ahead
|
||||
|
||||
|
||||
@app.get("/status/{job_id}")
|
||||
async def get_job_status(job_id: str, _auth: bool = Depends(verify_api_key)) -> JobStatus:
|
||||
# Get the status of an encoding job
|
||||
if job_id not in jobs:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
return JobStatus(**jobs[job_id], queue_position=_heavy_queue_position(job_id))
|
||||
return JobStatus(**jobs[job_id])
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
|
||||
@@ -10,7 +10,7 @@ This module handles the complete job lifecycle including:
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, Any, List
|
||||
|
||||
from backend.config import settings
|
||||
@@ -80,10 +80,7 @@ class JobManager:
|
||||
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
|
||||
# Timezone-aware UTC so the serialized ISO string carries a "+00:00"
|
||||
# offset. A naive datetime.utcnow() serializes with no offset, and the
|
||||
# frontend's Date() parser then mis-reads it as local time.
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.utcnow()
|
||||
job = Job(
|
||||
job_id=job_id,
|
||||
status=JobStatus.PENDING, # New state machine starts with PENDING
|
||||
@@ -119,8 +116,6 @@ class JobManager:
|
||||
request_metadata=job_create.request_metadata,
|
||||
# Tenant scoping
|
||||
tenant_id=job_create.tenant_id,
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=job_create.locale,
|
||||
# Made-for-you order fields
|
||||
made_for_you=job_create.made_for_you,
|
||||
customer_email=job_create.customer_email,
|
||||
|
||||
@@ -325,29 +325,10 @@ class LocalEncodingService:
|
||||
output_file: str,
|
||||
) -> bool:
|
||||
"""
|
||||
Convert the source "With Vocals" video (MOV/MKV) to a standard, portable MP4.
|
||||
|
||||
This produces the "(With Vocals).mp4" sing-along deliverable. It is a leaf
|
||||
output — no later encode reads it — so the encode is chosen purely for the
|
||||
deliverable itself:
|
||||
- ``-pix_fmt yuv420p``: the renderer emits High 4:4:4 (yuv444p), which many
|
||||
browsers/TVs/phones cannot decode. Normalize to 4:2:0 so it plays
|
||||
everywhere and matches every other output. (Also ~halves this stage's CPU
|
||||
time vs. re-encoding 4:4:4, and yields a slightly smaller file.)
|
||||
- ``-preset veryfast``: this is the single longest finalization stage; a fast
|
||||
preset roughly halves it (~56s → ~28s on a 32-vCPU worker) with negligible
|
||||
quality difference for karaoke content (static background + text).
|
||||
- ``-c:a aac``: the source audio is FLAC; FLAC-in-MP4 is non-standard. Encode
|
||||
AAC 320k so the file is fully portable. Matches the documented spec
|
||||
("4k H264/AAC with original vocals", see template_service.py).
|
||||
|
||||
Both commands force ``-pix_fmt yuv420p`` (h264_nvenc can otherwise *preserve* a
|
||||
yuv444p input). Prod encoding workers are CPU-only, so ``cpu_command`` is the
|
||||
real path; if the NVENC command ever errors, ``_execute_command_with_fallback``
|
||||
drops to the (correct) CPU command.
|
||||
Convert MOV to MP4 format.
|
||||
|
||||
Args:
|
||||
input_file: Path to input MOV/MKV file (source "With Vocals" video)
|
||||
input_file: Path to input MOV file
|
||||
output_file: Path for output MP4 file
|
||||
|
||||
Returns:
|
||||
@@ -355,13 +336,11 @@ class LocalEncodingService:
|
||||
"""
|
||||
gpu_command = (
|
||||
f'{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i "{input_file}" '
|
||||
f'-c:v {self.video_encoder} -pix_fmt yuv420p -c:a {self.aac_codec} -ar 48000 -b:a 320k '
|
||||
f'{self.MP4_FLAGS} "{output_file}"'
|
||||
f'-c:v {self.video_encoder} -c:a copy {self.MP4_FLAGS} "{output_file}"'
|
||||
)
|
||||
cpu_command = (
|
||||
f'{self._ffmpeg_base_command} -i "{input_file}" '
|
||||
f'-c:v libx264 -pix_fmt yuv420p -preset veryfast '
|
||||
f'-c:a {self.aac_codec} -ar 48000 -b:a 320k {self.MP4_FLAGS} "{output_file}"'
|
||||
f'-c:v libx264 -c:a copy {self.MP4_FLAGS} "{output_file}"'
|
||||
)
|
||||
return self._execute_command_with_fallback(
|
||||
gpu_command, cpu_command, "Converting MOV to MP4"
|
||||
|
||||
@@ -1,306 +0,0 @@
|
||||
"""Postmark admin service — email history for the admin user-detail view.
|
||||
|
||||
Surfaces "every email ever sent to a user" by merging two sources:
|
||||
|
||||
1. **Postmark Messages API** (``GET /messages/outbound``) — authoritative for the
|
||||
last ~45 days, with the exact rendered HTML and rich delivery metadata
|
||||
(delivered / opened / clicked / bounced).
|
||||
2. **Our Firestore ``email_log``** — every send persisted at send time (see
|
||||
``EmailService._record_sent_email``), so history survives beyond Postmark's
|
||||
45-day content retention.
|
||||
|
||||
The same per-server ``POSTMARK_SERVER_TOKEN`` used for sending is sufficient to
|
||||
read outbound message history (no separate Account API token needed).
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import requests
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
POSTMARK_API_BASE = "https://api.postmarkapp.com"
|
||||
EMAIL_LOG_COLLECTION = "email_log"
|
||||
|
||||
# Postmark's outbound list is paginated (count+offset, count max 500). We page
|
||||
# through until exhausted or the safety cap, so a user with a long history isn't
|
||||
# silently truncated at one batch.
|
||||
_PAGE_SIZE = 100
|
||||
_MAX_RECORDS = 500 # safety cap per source (admin view; avoids unbounded fetches)
|
||||
_HTTP_TIMEOUT = 12
|
||||
|
||||
|
||||
def _iso(value: Any) -> Optional[str]:
|
||||
"""Normalize a timestamp (datetime or str) to an ISO-8601 string."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.isoformat()
|
||||
return str(value)
|
||||
|
||||
|
||||
class PostmarkAdminService:
|
||||
"""Read-only email history queries for the admin UI."""
|
||||
|
||||
def __init__(self, server_token: Optional[str] = None):
|
||||
self.server_token = server_token if server_token is not None else os.getenv("POSTMARK_SERVER_TOKEN")
|
||||
self._db: Optional[firestore.Client] = None
|
||||
|
||||
# -- infra -------------------------------------------------------------
|
||||
@property
|
||||
def db(self) -> firestore.Client:
|
||||
# Lazy so the service can be constructed (and Postmark-only paths used)
|
||||
# without a Firestore client in contexts that don't need one.
|
||||
if self._db is None:
|
||||
self._db = firestore.Client()
|
||||
return self._db
|
||||
|
||||
def _postmark_headers(self) -> Dict[str, str]:
|
||||
return {
|
||||
"Accept": "application/json",
|
||||
"X-Postmark-Server-Token": self.server_token or "",
|
||||
}
|
||||
|
||||
# -- Postmark queries --------------------------------------------------
|
||||
def _fetch_postmark_messages(self, email: str) -> List[Dict[str, Any]]:
|
||||
"""List outbound Postmark messages sent to ``email`` (best-effort, paginated)."""
|
||||
if not self.server_token:
|
||||
return []
|
||||
|
||||
messages: List[Dict[str, Any]] = []
|
||||
offset = 0
|
||||
while len(messages) < _MAX_RECORDS:
|
||||
try:
|
||||
resp = requests.get(
|
||||
f"{POSTMARK_API_BASE}/messages/outbound",
|
||||
headers=self._postmark_headers(),
|
||||
params={"recipient": email, "count": _PAGE_SIZE, "offset": offset},
|
||||
timeout=_HTTP_TIMEOUT,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
logger.warning(
|
||||
"Postmark outbound list returned %s for recipient=%s: %s",
|
||||
resp.status_code, email, resp.text[:200],
|
||||
)
|
||||
break
|
||||
body = resp.json()
|
||||
batch = body.get("Messages", []) or []
|
||||
except (requests.RequestException, ValueError):
|
||||
logger.exception("Failed to fetch Postmark outbound messages for %s", email)
|
||||
break
|
||||
|
||||
messages.extend(batch)
|
||||
total = body.get("TotalCount", 0)
|
||||
offset += _PAGE_SIZE
|
||||
# Stop when this batch was short or we've read everything Postmark has.
|
||||
if len(batch) < _PAGE_SIZE or offset >= total:
|
||||
break
|
||||
|
||||
if len(messages) >= _MAX_RECORDS:
|
||||
logger.info("Postmark history for %s capped at %d records", email, _MAX_RECORDS)
|
||||
|
||||
summaries = []
|
||||
for m in messages:
|
||||
summaries.append({
|
||||
"message_id": m.get("MessageID"),
|
||||
"source": "postmark",
|
||||
"subject": m.get("Subject"),
|
||||
"to": ", ".join(m.get("Recipients") or []) or email,
|
||||
"from_email": m.get("From"),
|
||||
"sent_at": _iso(m.get("ReceivedAt")),
|
||||
"status": m.get("Status"),
|
||||
# Postmark tags map to our email_type when we set them; not used yet.
|
||||
"email_type": (m.get("Metadata") or {}).get("email_type"),
|
||||
"has_stored_html": False,
|
||||
})
|
||||
return summaries
|
||||
|
||||
def _fetch_log_docs(self, email: str) -> List[Dict[str, Any]]:
|
||||
"""Read persisted email_log docs for ``email`` (best-effort)."""
|
||||
recipient = (email or "").strip().lower()
|
||||
try:
|
||||
query = (
|
||||
self.db.collection(EMAIL_LOG_COLLECTION)
|
||||
.where(filter=FieldFilter("recipient", "==", recipient))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
.limit(_MAX_RECORDS)
|
||||
)
|
||||
docs = list(query.stream())
|
||||
except Exception:
|
||||
# Missing composite index or emulator quirk — degrade gracefully.
|
||||
logger.exception("Failed to read email_log for %s", email)
|
||||
return []
|
||||
|
||||
out = []
|
||||
for doc in docs:
|
||||
data = doc.to_dict() or {}
|
||||
out.append({
|
||||
"doc_id": doc.id,
|
||||
"message_id": data.get("postmark_message_id"),
|
||||
"source": "log",
|
||||
"subject": data.get("subject"),
|
||||
"to": data.get("recipient_raw") or data.get("recipient"),
|
||||
"from_email": data.get("from_email"),
|
||||
"sent_at": _iso(data.get("created_at")),
|
||||
"status": None,
|
||||
"email_type": data.get("email_type"),
|
||||
"has_stored_html": bool(data.get("html_content")),
|
||||
})
|
||||
return out
|
||||
|
||||
# -- public API --------------------------------------------------------
|
||||
def get_user_email_history(self, email: str) -> Dict[str, Any]:
|
||||
"""Merged, de-duplicated list of emails sent to ``email`` (newest first)."""
|
||||
postmark = self._fetch_postmark_messages(email)
|
||||
logged = self._fetch_log_docs(email)
|
||||
|
||||
# Postmark wins for a message present in both (richer status); note that we
|
||||
# also have stored HTML so the UI can fall back after the 45-day window.
|
||||
by_id: Dict[str, Dict[str, Any]] = {}
|
||||
logged_by_mid: Dict[str, Dict[str, Any]] = {
|
||||
d["message_id"]: d for d in logged if d.get("message_id")
|
||||
}
|
||||
for pm in postmark:
|
||||
mid = pm.get("message_id")
|
||||
if mid and mid in logged_by_mid:
|
||||
pm["has_stored_html"] = True
|
||||
if mid:
|
||||
by_id[mid] = pm
|
||||
|
||||
merged = list(by_id.values())
|
||||
for d in logged:
|
||||
mid = d.get("message_id")
|
||||
if mid and mid in by_id:
|
||||
continue # already represented by the Postmark summary
|
||||
merged.append(d)
|
||||
|
||||
merged.sort(key=lambda x: x.get("sent_at") or "", reverse=True)
|
||||
return {
|
||||
"email": email,
|
||||
"count": len(merged),
|
||||
"postmark_available": bool(self.server_token),
|
||||
"emails": merged,
|
||||
}
|
||||
|
||||
def _log_doc_to_detail(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"message_id": data.get("postmark_message_id"),
|
||||
"source": "log",
|
||||
"subject": data.get("subject"),
|
||||
"from_email": data.get("from_email"),
|
||||
"to": data.get("recipient_raw") or data.get("recipient"),
|
||||
"cc": data.get("cc") or [],
|
||||
"bcc": data.get("bcc") or [],
|
||||
"sent_at": _iso(data.get("created_at")),
|
||||
"email_type": data.get("email_type"),
|
||||
"message_stream": data.get("message_stream"),
|
||||
"html_body": data.get("html_content"),
|
||||
"text_body": data.get("text_content"),
|
||||
"status": None,
|
||||
"events": [],
|
||||
}
|
||||
|
||||
def _fetch_log_detail_by_message_id(self, message_id: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
snap = self.db.collection(EMAIL_LOG_COLLECTION).document(message_id).get()
|
||||
if snap.exists:
|
||||
return self._log_doc_to_detail(snap.to_dict() or {})
|
||||
except Exception:
|
||||
logger.exception("email_log fallback lookup failed for %s", message_id)
|
||||
return None
|
||||
|
||||
def get_email_detail(self, message_id: str, source: str = "postmark") -> Optional[Dict[str, Any]]:
|
||||
"""Full detail for one email — rendered HTML + delivery metadata.
|
||||
|
||||
``source="log"`` reads our Firestore record directly (for messages older
|
||||
than Postmark's retention). Otherwise we query Postmark and fall back to
|
||||
the Firestore log on 404/unavailable.
|
||||
"""
|
||||
if source == "log":
|
||||
return self._fetch_log_detail_by_message_id(message_id)
|
||||
|
||||
if self.server_token:
|
||||
try:
|
||||
resp = requests.get(
|
||||
f"{POSTMARK_API_BASE}/messages/outbound/{message_id}/details",
|
||||
headers=self._postmark_headers(),
|
||||
timeout=_HTTP_TIMEOUT,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return self._postmark_detail(resp.json())
|
||||
logger.info(
|
||||
"Postmark message %s details returned %s; trying stored log",
|
||||
message_id, resp.status_code,
|
||||
)
|
||||
except (requests.RequestException, ValueError):
|
||||
logger.exception("Failed to fetch Postmark details for %s", message_id)
|
||||
|
||||
# Fallback: our persisted copy (older than 45 days, or Postmark down).
|
||||
return self._fetch_log_detail_by_message_id(message_id)
|
||||
|
||||
def _postmark_detail(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Shape a Postmark message-details payload for the admin modal."""
|
||||
events = []
|
||||
opened = 0
|
||||
clicked = 0
|
||||
bounced_detail = None
|
||||
delivered_at = None
|
||||
for ev in data.get("MessageEvents", []) or []:
|
||||
etype = ev.get("Type")
|
||||
events.append({
|
||||
"type": etype,
|
||||
"received_at": _iso(ev.get("ReceivedAt")),
|
||||
"details": ev.get("Details") or {},
|
||||
})
|
||||
if etype == "Delivered":
|
||||
delivered_at = _iso(ev.get("ReceivedAt"))
|
||||
elif etype == "Opened":
|
||||
opened += 1
|
||||
elif etype in ("LinkClicked", "Clicked"):
|
||||
clicked += 1
|
||||
elif etype == "Bounced":
|
||||
bounced_detail = ev.get("Details") or {}
|
||||
|
||||
# Derive a coarse status from events when present.
|
||||
status = data.get("Status")
|
||||
if bounced_detail:
|
||||
status = "Bounced"
|
||||
elif delivered_at:
|
||||
status = "Delivered"
|
||||
|
||||
return {
|
||||
"message_id": data.get("MessageID"),
|
||||
"source": "postmark",
|
||||
"subject": data.get("Subject"),
|
||||
"from_email": data.get("From"),
|
||||
"to": ", ".join(data.get("Recipients") or []) or data.get("To"),
|
||||
"cc": data.get("Cc"),
|
||||
"bcc": data.get("Bcc"),
|
||||
"sent_at": _iso(data.get("ReceivedAt")),
|
||||
"message_stream": data.get("MessageStream"),
|
||||
"html_body": data.get("HtmlBody"),
|
||||
"text_body": data.get("TextBody"),
|
||||
"status": status,
|
||||
"delivered_at": delivered_at,
|
||||
"open_count": opened,
|
||||
"click_count": clicked,
|
||||
"bounce": bounced_detail,
|
||||
"events": events,
|
||||
}
|
||||
|
||||
|
||||
_postmark_admin_service: Optional[PostmarkAdminService] = None
|
||||
|
||||
|
||||
def get_postmark_admin_service() -> PostmarkAdminService:
|
||||
"""Get the global Postmark admin service instance."""
|
||||
global _postmark_admin_service
|
||||
if _postmark_admin_service is None:
|
||||
_postmark_admin_service = PostmarkAdminService()
|
||||
return _postmark_admin_service
|
||||
@@ -55,29 +55,10 @@ class StorageService:
|
||||
blob.download_to_filename(destination_path)
|
||||
logger.info(f"Downloaded gs://{settings.gcs_bucket_name}/{source_path} to {destination_path}")
|
||||
return destination_path
|
||||
except NotFound:
|
||||
# A missing object is a routine "not found", not a server-side failure.
|
||||
# Log at warning so it doesn't trip the error-monitor, and let the caller
|
||||
# decide how to surface it (e.g. the download route returns HTTP 404).
|
||||
logger.warning(f"Object not found downloading {source_path}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error downloading file {source_path}: {e}")
|
||||
raise
|
||||
|
||||
def download_bytes(self, source_path: str) -> bytes:
|
||||
"""Download an object from GCS fully into memory. Only use for small
|
||||
objects (e.g. transcoded review audio); large files should stream."""
|
||||
try:
|
||||
blob = self.bucket.blob(source_path)
|
||||
return blob.download_as_bytes()
|
||||
except NotFound:
|
||||
logger.warning(f"Object not found downloading {source_path}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error downloading bytes {source_path}: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def copy_blob(self, source_path: str, destination_path: str) -> str:
|
||||
"""Server-side copy of a blob within the bucket (no download/upload)."""
|
||||
try:
|
||||
|
||||
@@ -185,7 +185,6 @@ class StripeService:
|
||||
notes: Optional[str] = None,
|
||||
success_url: Optional[str] = None,
|
||||
cancel_url: Optional[str] = None,
|
||||
locale: Optional[str] = None,
|
||||
) -> Tuple[bool, Optional[str], str]:
|
||||
"""
|
||||
Create a Stripe Checkout session for a made-for-you order.
|
||||
@@ -229,9 +228,6 @@ class StripeService:
|
||||
if notes:
|
||||
# Truncate notes to fit Stripe's 500 char limit per metadata value
|
||||
metadata['notes'] = notes[:500] if len(notes) > 500 else notes
|
||||
if locale:
|
||||
# UI language the customer ordered in — surfaced admin-side on the job
|
||||
metadata['locale'] = locale
|
||||
|
||||
# Build checkout session params
|
||||
session_params = {
|
||||
|
||||
@@ -57,93 +57,61 @@ class VisibilityChangeService:
|
||||
"""
|
||||
Change a public job to private (fast path).
|
||||
|
||||
Distribute-then-delete: the track is first redistributed to the private
|
||||
destination (private Dropbox archive + NOMADNP code, no YouTube/GDrive),
|
||||
and only *after* that succeeds are the public outputs (YouTube, public
|
||||
Dropbox folder, public GDrive files) deleted and the public NOMAD number
|
||||
recycled. GCS finals are always kept.
|
||||
|
||||
This ordering is deliberate: YouTube deletion is irreversible, so nothing
|
||||
public may be destroyed until the private archive exists. If redistribution
|
||||
fails, the job is reverted to public and left fully intact (no partial
|
||||
deletion, no leaked NOMADNP code — see redistribute_video's failure path).
|
||||
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
|
||||
then redistributes to private destination.
|
||||
"""
|
||||
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
|
||||
|
||||
db = self.job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
|
||||
# Capture the public output references BEFORE redistribution overwrites
|
||||
# state_data with the new private values — we need them to delete the
|
||||
# public outputs afterwards.
|
||||
state_data = job.state_data or {}
|
||||
public_outputs = {
|
||||
"youtube_url": state_data.get("youtube_url"),
|
||||
"brand_code": state_data.get("brand_code"),
|
||||
"gdrive_files": state_data.get("gdrive_files"),
|
||||
"dropbox_path": getattr(job, "dropbox_path", None),
|
||||
"artist": job.artist,
|
||||
"title": job.title,
|
||||
}
|
||||
|
||||
# Set guard flag + flip to private so redistribution targets the private
|
||||
# destination. Public outputs remain live until the private archive exists.
|
||||
# No "changed to private" timeline event yet — it is only recorded once the
|
||||
# move actually succeeds (this is reverted if redistribution fails).
|
||||
# Set guard flag
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": True,
|
||||
"is_private": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
|
||||
# Step 1: Redistribute to the private destination FIRST (public outputs
|
||||
# still live). This is the only phase whose failure is safe to fully roll
|
||||
# back — nothing public has been touched yet. redistribute_video verifies
|
||||
# the archive actually materialized and recycles any NOMADNP code it
|
||||
# allocated on failure, so a False return means "no-op, still public".
|
||||
try:
|
||||
# Step 1: Delete distributed outputs (keep GCS finals)
|
||||
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
|
||||
|
||||
# Step 2: Update job to private
|
||||
job_ref.update({
|
||||
"is_private": True,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility changed to private by {user_email}",
|
||||
}]),
|
||||
})
|
||||
|
||||
# Step 3: Trigger redistribution via video worker
|
||||
from backend.workers.video_worker import redistribute_video
|
||||
success = await redistribute_video(job_id)
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Redistribution raised during visibility change: {e}", exc_info=True)
|
||||
success = False
|
||||
|
||||
if not success:
|
||||
# Roll back to public: no public outputs were deleted, so restoring
|
||||
# is_private=False leaves the job fully intact and public.
|
||||
logger.error(f"[job:{job_id}] Visibility change to private failed: redistribution did not succeed")
|
||||
if not success:
|
||||
raise RuntimeError("Redistribution failed - check worker logs")
|
||||
|
||||
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
|
||||
job_ref.update({
|
||||
"is_private": False,
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
raise RuntimeError("Redistribution failed - check worker logs")
|
||||
|
||||
# Step 2: Private archive now exists. From here we do NOT revert to public,
|
||||
# even if public cleanup hiccups — the private move has committed. Deleting
|
||||
# the public outputs + recycling the public NOMAD number is best-effort
|
||||
# (each failure is logged inside the helper, never raised), so a stray
|
||||
# orphaned public artifact cannot undo the successful private move.
|
||||
await self._delete_public_outputs(job_id, public_outputs)
|
||||
logger.info(f"[job:{job_id}] Visibility change to private complete")
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"reprocessing_required": False,
|
||||
}
|
||||
|
||||
# Record the completed move and clear the guard flag. redistribute_video
|
||||
# already updated state_data with the new private brand_code etc.
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
"timeline": ArrayUnion([{
|
||||
"status": "complete",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": f"Visibility changed to private by {user_email}",
|
||||
}]),
|
||||
})
|
||||
|
||||
logger.info(f"[job:{job_id}] Visibility change to private complete")
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Job changed to private. Outputs redistributed to private destination.",
|
||||
"reprocessing_required": False,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
|
||||
# Clear guard flag on failure
|
||||
job_ref.update({
|
||||
"state_data.visibility_change_in_progress": DELETE_FIELD,
|
||||
})
|
||||
raise
|
||||
|
||||
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
|
||||
"""
|
||||
@@ -173,11 +141,7 @@ class VisibilityChangeService:
|
||||
f"jobs/{job_id}/videos/with_vocals.mov",
|
||||
]:
|
||||
try:
|
||||
# Best-effort delete over a template of possible artifacts; many of
|
||||
# these intermediates legitimately never existed for a given render
|
||||
# path. ignore_missing keeps a 404 a quiet no-op instead of a noisy
|
||||
# ERROR log (which would otherwise trip the error-monitor).
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
storage.delete_file(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -248,103 +212,6 @@ class VisibilityChangeService:
|
||||
"reprocessing_required": True,
|
||||
}
|
||||
|
||||
async def _delete_public_outputs(self, job_id: str, public_outputs: dict):
|
||||
"""Delete the captured PUBLIC outputs and recycle the public NOMAD number.
|
||||
|
||||
Used by change_to_private AFTER a successful private redistribution. Operates
|
||||
on references captured before redistribution (which overwrites state_data with
|
||||
private values). Does not touch GCS finals and does not clear state_data keys
|
||||
(redistribution already set the new private values). Best-effort: individual
|
||||
failures are logged, not raised, so one orphaned artifact can't undo the move.
|
||||
"""
|
||||
import re
|
||||
|
||||
# Track whether each public destination was fully cleaned. The NOMAD number
|
||||
# is only recycled when every deletion succeeded — otherwise a future public
|
||||
# track could reuse the number while the old public files still linger,
|
||||
# producing a duplicate. (Mirrors the admin delete-outputs recycle gate.)
|
||||
youtube_ok = True
|
||||
dropbox_ok = True
|
||||
gdrive_ok = True
|
||||
|
||||
youtube_url = public_outputs.get("youtube_url")
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False, non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
finalise.delete_youtube_video(video_id)
|
||||
logger.info(f"[job:{job_id}] Deleted public YouTube video {video_id}")
|
||||
except Exception as e:
|
||||
youtube_ok = False
|
||||
logger.warning(f"[job:{job_id}] Failed to delete public YouTube video: {e}")
|
||||
|
||||
brand_code = public_outputs.get("brand_code")
|
||||
dropbox_path = public_outputs.get("dropbox_path")
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
safe_artist = sanitize_filename(public_outputs.get("artist")) if public_outputs.get("artist") else "Unknown"
|
||||
safe_title = sanitize_filename(public_outputs.get("title")) if public_outputs.get("title") else "Unknown"
|
||||
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
dropbox.delete_folder(full_path)
|
||||
logger.info(f"[job:{job_id}] Deleted public Dropbox folder {full_path}")
|
||||
except Exception as e:
|
||||
dropbox_ok = False
|
||||
logger.warning(f"[job:{job_id}] Failed to delete public Dropbox folder: {e}")
|
||||
|
||||
gdrive_files = public_outputs.get("gdrive_files")
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
gdrive.delete_files(file_ids)
|
||||
logger.info(f"[job:{job_id}] Deleted public Google Drive files")
|
||||
except Exception as e:
|
||||
gdrive_ok = False
|
||||
logger.warning(f"[job:{job_id}] Failed to delete public Google Drive files: {e}")
|
||||
|
||||
# A track going private should also leave the public Nomad GCS fast-sync
|
||||
# mirror (and thus kjbox). Prefix-keyed by the public brand_code, non-fatal.
|
||||
if brand_code:
|
||||
try:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to clean up Nomad mirror for {brand_code}: {e}")
|
||||
|
||||
# Recycle the public NOMAD number so the next public track fills the gap —
|
||||
# but only if every public deletion succeeded. If any lingered, keep the
|
||||
# number reserved (a permanent gap the validator will flag) rather than
|
||||
# risk a future duplicate; the leftover artifacts can then be cleaned up.
|
||||
if brand_code and youtube_ok and dropbox_ok and gdrive_ok:
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
get_brand_code_service().recycle_brand_code(prefix, number)
|
||||
logger.info(f"[job:{job_id}] Recycled public brand code {brand_code}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Failed to recycle public brand code {brand_code}: {e}")
|
||||
elif brand_code:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] NOT recycling public brand code {brand_code}: "
|
||||
f"public cleanup incomplete (youtube={youtube_ok}, dropbox={dropbox_ok}, gdrive={gdrive_ok})"
|
||||
)
|
||||
|
||||
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
|
||||
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
|
||||
import re
|
||||
|
||||
@@ -2,15 +2,13 @@
|
||||
YouTube download service for cloud backend.
|
||||
|
||||
This service provides a single entry point for all YouTube downloads in the cloud.
|
||||
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.
|
||||
It automatically routes downloads through the remote flacfetch service when configured,
|
||||
avoiding YouTube bot detection issues on Cloud Run IPs.
|
||||
|
||||
The flow is:
|
||||
1. Check if remote flacfetch is configured (FLACFETCH_API_URL)
|
||||
2. If yes: Use FlacfetchClient.download_by_id() - downloads on VM, uploads to GCS
|
||||
3. If no: 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).
|
||||
3. If no: Use local yt_dlp (with warning about bot detection risk)
|
||||
|
||||
All entry points (audio search selection, direct URL submission) should use this
|
||||
service for YouTube downloads to ensure consistent behavior.
|
||||
@@ -36,8 +34,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, this raises YouTubeDownloadError. There is no
|
||||
local yt-dlp fallback — flacfetch is the sole downloader.
|
||||
When remote is not configured, falls back to local yt_dlp with a warning
|
||||
that downloads may be blocked on Cloud Run IPs.
|
||||
|
||||
Usage:
|
||||
service = get_youtube_download_service()
|
||||
|
||||
@@ -1,436 +0,0 @@
|
||||
"""
|
||||
Tests for the parked-job recovery endpoints on audio-search:
|
||||
|
||||
- POST /api/audio-search/{job_id}/research — retry / edit-and-re-search
|
||||
- POST /api/audio-search/{job_id}/provide-url — attach a YouTube/yt-dlp URL
|
||||
- POST /api/audio-search/{job_id}/attach-upload-url — signed URL for upload
|
||||
- POST /api/audio-search/{job_id}/attach-upload-complete — finalise an upload
|
||||
|
||||
These cover the "0 results / dead-end" bulk-mode scenario where a job is parked
|
||||
in AWAITING_AUDIO_SELECTION with no usable sources and the user needs a way out.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.audio_search_service import AudioSearchResult, NoResultsError, AudioSearchError
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.services.youtube_download_service import YouTubeDownloadError
|
||||
|
||||
NOW = datetime.now(UTC)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _auth_overrides():
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.main import app
|
||||
|
||||
async def mock_require_auth():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.STRIPE, remaining_uses=5,
|
||||
message="test", is_admin=False, user_email="buyer@example.com",
|
||||
)
|
||||
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_admin] = mock_require_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
|
||||
|
||||
def _parked_job(job_id="park-1", artist="Arctic Monkeys", title="The View From the Afternoon",
|
||||
status=JobStatus.AWAITING_AUDIO_SELECTION) -> Job:
|
||||
return Job(
|
||||
job_id=job_id, status=status, created_at=NOW, updated_at=NOW,
|
||||
user_email="buyer@example.com", artist=artist, title=title,
|
||||
audio_search_artist=artist, audio_search_title=title,
|
||||
state_data={"credits_charged": 1, "audio_search_results": []},
|
||||
)
|
||||
|
||||
|
||||
def _result(idx=0, title="The View From the Afternoon", artist="Arctic Monkeys"):
|
||||
r = AudioSearchResult(
|
||||
index=idx, title=title, artist=artist, provider="RED",
|
||||
url="", duration=180, quality="FLAC", source_id=f"id{idx}",
|
||||
)
|
||||
r.raw_result = {"target_file": f"{title}.flac", "is_lossless": True, "seeders": 20}
|
||||
return r
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager():
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _parked_job()
|
||||
jm.update_job.return_value = None
|
||||
jm.transition_to_state.return_value = True
|
||||
jm.start_job_processing = AsyncMock(return_value=None)
|
||||
return jm
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# research (re-search)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestResearch:
|
||||
def _patched(self, jm, search_mock):
|
||||
return patch.multiple(
|
||||
"backend.api.routes.audio_search",
|
||||
job_manager=jm,
|
||||
), patch(
|
||||
"backend.api.routes.audio_search.get_audio_search_service",
|
||||
return_value=search_mock,
|
||||
)
|
||||
|
||||
def test_research_returns_results(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
search = MagicMock()
|
||||
search.search_async = AsyncMock(return_value=[_result(0), _result(1)])
|
||||
search.last_remote_search_id = "remote-xyz"
|
||||
|
||||
p1, p2 = self._patched(mock_job_manager, search)
|
||||
with p1, p2:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/audio-search/park-1/research", json={})
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
data = resp.json()
|
||||
assert data["results_count"] == 2
|
||||
assert len(data["results"]) == 2
|
||||
# results were cached back onto the job
|
||||
cached = [c for c in mock_job_manager.update_job.call_args_list
|
||||
if "state_data.audio_search_results" in c.args[1]]
|
||||
assert cached, "expected results to be cached on the job"
|
||||
|
||||
def test_research_empty_is_200_not_error(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
search = MagicMock()
|
||||
search.search_async = AsyncMock(side_effect=NoResultsError("nothing"))
|
||||
search.last_remote_search_id = None
|
||||
|
||||
p1, p2 = self._patched(mock_job_manager, search)
|
||||
with p1, p2:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/audio-search/park-1/research", json={})
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["results_count"] == 0
|
||||
|
||||
def test_research_applies_edited_terms(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
search = MagicMock()
|
||||
search.search_async = AsyncMock(return_value=[_result(0)])
|
||||
search.last_remote_search_id = None
|
||||
|
||||
p1, p2 = self._patched(mock_job_manager, search)
|
||||
with p1, p2:
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/research",
|
||||
json={"artist": "Arctic Monkeys", "title": "The View from the Afternoon"},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
# search ran with the edited (normalized) title
|
||||
search.search_async.assert_awaited_once()
|
||||
args = search.search_async.await_args.args
|
||||
assert args[0] == "Arctic Monkeys"
|
||||
assert args[1] == "The View from the Afternoon"
|
||||
# edit applied to the job (search terms + display metadata)
|
||||
applied = [c for c in mock_job_manager.update_job.call_args_list
|
||||
if c.args[1].get("title") == "The View from the Afternoon"]
|
||||
assert applied, "expected edited title applied to job"
|
||||
|
||||
def test_research_502_on_search_error(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
search = MagicMock()
|
||||
search.search_async = AsyncMock(side_effect=AudioSearchError("boom"))
|
||||
|
||||
p1, p2 = self._patched(mock_job_manager, search)
|
||||
with p1, p2:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/audio-search/park-1/research", json={})
|
||||
|
||||
assert resp.status_code == 502
|
||||
|
||||
def test_research_rejects_wrong_status(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
mock_job_manager.get_job.return_value = _parked_job(status=JobStatus.DOWNLOADING)
|
||||
search = MagicMock()
|
||||
search.search_async = AsyncMock(return_value=[])
|
||||
|
||||
p1, p2 = self._patched(mock_job_manager, search)
|
||||
with p1, p2:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/audio-search/park-1/research", json={})
|
||||
|
||||
assert resp.status_code == 400
|
||||
search.search_async.assert_not_awaited()
|
||||
|
||||
def test_research_404_missing_job(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
mock_job_manager.get_job.return_value = None
|
||||
search = MagicMock()
|
||||
p1, p2 = self._patched(mock_job_manager, search)
|
||||
with p1, p2:
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/audio-search/nope/research", json={})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# provide-url
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestProvideUrl:
|
||||
def test_youtube_url_uses_async_worker(self, mock_job_manager):
|
||||
"""YouTube URLs go through the async download worker (no blocking request)."""
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
yt = MagicMock()
|
||||
yt.check_availability = AsyncMock(return_value={"available": True})
|
||||
yt.download = AsyncMock()
|
||||
ws = MagicMock()
|
||||
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
|
||||
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
ws.trigger_audio_download_worker.assert_awaited_once_with("park-1")
|
||||
yt.download.assert_not_awaited() # async worker does the download, not inline
|
||||
# job pointed at the URL source for the worker's job-level fallback
|
||||
srcd = [c for c in mock_job_manager.update_job.call_args_list
|
||||
if c.args[1].get("source_name") == "YouTube" and c.args[1].get("download_url")]
|
||||
assert srcd
|
||||
|
||||
def test_youtube_worker_trigger_failure_requeues(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
yt = MagicMock()
|
||||
yt.check_availability = AsyncMock(return_value={"available": True})
|
||||
ws = MagicMock()
|
||||
ws.trigger_audio_download_worker = AsyncMock(return_value=False)
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
|
||||
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
|
||||
)
|
||||
assert resp.status_code == 502
|
||||
statuses = [c.kwargs.get("new_status") for c in mock_job_manager.transition_to_state.call_args_list]
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in statuses
|
||||
|
||||
def test_generic_url_downloads_inline_and_starts(self, mock_job_manager):
|
||||
"""Non-YouTube (yt-dlp) URLs download inline, then start processing."""
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
yt = MagicMock()
|
||||
yt.download = AsyncMock(return_value="uploads/park-1/audio/song.opus")
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://soundcloud.com/artist/track"},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
yt.download.assert_awaited_once()
|
||||
pathed = [c for c in mock_job_manager.update_job.call_args_list
|
||||
if c.args[1].get("input_media_gcs_path") == "uploads/park-1/audio/song.opus"]
|
||||
assert pathed
|
||||
mock_job_manager.start_job_processing.assert_awaited()
|
||||
|
||||
def test_drm_url_rejected(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
yt = MagicMock()
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://open.spotify.com/track/xyz"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
def test_unavailable_youtube_rejected(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
yt = MagicMock()
|
||||
yt.check_availability = AsyncMock(return_value={"available": False, "is_private": True})
|
||||
ws = MagicMock()
|
||||
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
|
||||
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
ws.trigger_audio_download_worker.assert_not_awaited()
|
||||
|
||||
def test_generic_download_failure_requeues_and_502(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
yt = MagicMock()
|
||||
yt.download = AsyncMock(side_effect=YouTubeDownloadError("dead"))
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://soundcloud.com/artist/track"},
|
||||
)
|
||||
assert resp.status_code == 502
|
||||
# restored to awaiting so the user can retry
|
||||
statuses = [c.kwargs.get("new_status") for c in mock_job_manager.transition_to_state.call_args_list]
|
||||
assert JobStatus.AWAITING_AUDIO_SELECTION in statuses
|
||||
|
||||
def test_provide_url_rejects_wrong_status(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
mock_job_manager.get_job.return_value = _parked_job(status=JobStatus.DOWNLOADING)
|
||||
yt = MagicMock()
|
||||
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
|
||||
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/provide-url",
|
||||
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# attach upload
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestAttachUpload:
|
||||
def test_attach_upload_url_returns_signed_url(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
storage = MagicMock()
|
||||
storage.generate_signed_upload_url.return_value = "https://signed.example/put"
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search",
|
||||
job_manager=mock_job_manager, storage_service=storage):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/attach-upload-url",
|
||||
json={"filename": "my song.flac", "content_type": "audio/flac"},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
data = resp.json()
|
||||
assert data["gcs_path"] == "uploads/park-1/audio/my song.flac"
|
||||
assert data["upload_url"] == "https://signed.example/put"
|
||||
|
||||
def test_attach_upload_url_rejects_bad_extension(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
storage = MagicMock()
|
||||
storage.generate_signed_upload_url.return_value = "https://signed.example/put"
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search",
|
||||
job_manager=mock_job_manager, storage_service=storage):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/attach-upload-url",
|
||||
json={"filename": "..\\evil.exe", "content_type": "application/octet-stream"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
storage.generate_signed_upload_url.assert_not_called()
|
||||
|
||||
def test_attach_complete_starts_processing(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
storage = MagicMock()
|
||||
storage.list_files.return_value = ["uploads/park-1/audio/my_song.flac"]
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search",
|
||||
job_manager=mock_job_manager, storage_service=storage):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/attach-upload-complete",
|
||||
json={"gcs_path": "uploads/park-1/audio/my_song.flac"},
|
||||
)
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
pathed = [c for c in mock_job_manager.update_job.call_args_list
|
||||
if c.args[1].get("input_media_gcs_path") == "uploads/park-1/audio/my_song.flac"]
|
||||
assert pathed
|
||||
mock_job_manager.start_job_processing.assert_awaited()
|
||||
|
||||
def test_attach_complete_rejects_gcs_path_outside_prefix(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
storage = MagicMock()
|
||||
storage.list_files.return_value = ["uploads/park-1/audio/my_song.flac"]
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search",
|
||||
job_manager=mock_job_manager, storage_service=storage):
|
||||
client = TestClient(app)
|
||||
resp = client.post(
|
||||
"/api/audio-search/park-1/attach-upload-complete",
|
||||
json={"gcs_path": "uploads/other-job/audio/steal.flac"},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
mock_job_manager.start_job_processing.assert_not_awaited()
|
||||
|
||||
def test_attach_complete_400_when_no_file(self, mock_job_manager):
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.main import app
|
||||
|
||||
storage = MagicMock()
|
||||
storage.list_files.return_value = []
|
||||
|
||||
with patch.multiple("backend.api.routes.audio_search",
|
||||
job_manager=mock_job_manager, storage_service=storage):
|
||||
client = TestClient(app)
|
||||
resp = client.post("/api/audio-search/park-1/attach-upload-complete", json={})
|
||||
assert resp.status_code == 400
|
||||
mock_job_manager.start_job_processing.assert_not_awaited()
|
||||
@@ -502,12 +502,8 @@ class TestMadeForYouYouTubeErrorHandling:
|
||||
youtube_order_metadata
|
||||
):
|
||||
"""
|
||||
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.
|
||||
Test that exceptions during processing send failure notification to admin.
|
||||
"""
|
||||
import pytest
|
||||
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
|
||||
|
||||
# Make job creation fail
|
||||
@@ -520,16 +516,15 @@ 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)):
|
||||
|
||||
# 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,
|
||||
)
|
||||
# Should not raise - error is handled internally
|
||||
await _handle_made_for_you_order(
|
||||
session_id="sess_test_error",
|
||||
metadata=youtube_order_metadata,
|
||||
user_service=mock_user_service_for_webhook,
|
||||
email_service=mock_email_service,
|
||||
)
|
||||
|
||||
# Verify failure email was sent to admin before re-raising
|
||||
# Verify failure email was sent to admin
|
||||
mock_email_service.send_email.assert_called()
|
||||
call_args = mock_email_service.send_email.call_args
|
||||
assert call_args.kwargs['to_email'] == ADMIN_EMAIL
|
||||
|
||||
@@ -231,7 +231,7 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
|
||||
sent = {}
|
||||
|
||||
class _CapturingProvider:
|
||||
def send_email(self, to_email, subject, html_content, text_content=None, **kwargs):
|
||||
def send_email(self, to_email, subject, html_content, text_content):
|
||||
sent['subject'] = subject
|
||||
sent['text'] = text_content
|
||||
return True
|
||||
@@ -258,58 +258,3 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
|
||||
assert "48" not in sent['subject'] and "not confirmed" not in sent['subject'], (
|
||||
f"over_limit email should not say '48 hours'. subject={sent.get('subject')!r}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Regression (job a453d1d5): a failing email-service construction must NOT
|
||||
# crash an otherwise-successful audio download. reconcile_and_maybe_pause runs
|
||||
# in the audio-download-job Cloud Run Job; EmailService() raises in production
|
||||
# when POSTMARK_SERVER_TOKEN is unset. Reconcile must degrade to no-email.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds):
|
||||
"""Patch the function-scoped imports reconcile_and_maybe_pause pulls in.
|
||||
|
||||
These are imported inside the function (to avoid circular imports), so they
|
||||
must be patched at their source modules, not on duration_reconciliation.
|
||||
"""
|
||||
from backend.services import duration_reconciliation as dr
|
||||
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
|
||||
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: us)
|
||||
monkeypatch.setattr("backend.services.storage_service.StorageService", lambda: MagicMock())
|
||||
monkeypatch.setattr(
|
||||
"backend.services.email_service.get_email_service",
|
||||
MagicMock(side_effect=RuntimeError("POSTMARK_SERVER_TOKEN is not set in production")),
|
||||
)
|
||||
monkeypatch.setattr(dr, "_ffprobe_seconds", lambda job, storage: actual_seconds)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_and_maybe_pause_survives_email_service_failure(monkeypatch):
|
||||
from backend.services import duration_reconciliation as dr
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _job(credits_charged=2)
|
||||
# Duration matches estimate → proceed, no email needed anyway.
|
||||
_patch_reconcile_singletons(monkeypatch, jm, MagicMock(), actual_seconds=900.0) # 15min -> 2 credits
|
||||
|
||||
# Must not raise despite email service construction failing.
|
||||
blocked = await dr.reconcile_and_maybe_pause("job1")
|
||||
assert blocked is False # proceeds normally
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_and_maybe_pause_over_limit_still_cancels_without_email(monkeypatch):
|
||||
"""Over-limit cancel must still refund+cancel even if email can't be built."""
|
||||
from backend.services import duration_reconciliation as dr
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _job(credits_charged=2)
|
||||
us = MagicMock()
|
||||
us.add_credits.return_value = (True, 99, "ok")
|
||||
_patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds=4000.0) # >60min
|
||||
|
||||
blocked = await dr.reconcile_and_maybe_pause("job1")
|
||||
assert blocked is True # cancelled
|
||||
jm.cancel_job.assert_called_once()
|
||||
us.add_credits.assert_called_once() # full refund still happens
|
||||
@@ -1,149 +0,0 @@
|
||||
"""
|
||||
Unit tests for the admin stats overview endpoint.
|
||||
|
||||
Covers the exclude_test=True path (the admin dashboard default), which streams
|
||||
users and jobs with Firestore field masks. The field masks are load-bearing:
|
||||
without them the endpoint streams full job documents (~100MB collection-wide)
|
||||
and takes 15-20s, blocking the event loop for every other request.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.admin import (
|
||||
router,
|
||||
_compute_admin_stats_overview,
|
||||
_OVERVIEW_USER_FIELDS,
|
||||
_OVERVIEW_JOB_FIELDS,
|
||||
)
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.user_service import get_user_service, USERS_COLLECTION
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
def make_docs(dicts):
|
||||
docs = []
|
||||
for d in dicts:
|
||||
m = Mock()
|
||||
m.to_dict.return_value = d
|
||||
docs.append(m)
|
||||
return docs
|
||||
|
||||
|
||||
def make_db(user_dicts, job_dicts):
|
||||
"""Fake Firestore db supporting .collection(...).select(...).limit(...).stream()."""
|
||||
users_coll = Mock()
|
||||
users_coll.select.return_value.limit.return_value.stream.return_value = make_docs(user_dicts)
|
||||
jobs_coll = Mock()
|
||||
jobs_coll.select.return_value.limit.return_value.stream.return_value = make_docs(job_dicts)
|
||||
|
||||
db = Mock()
|
||||
db.collection.side_effect = lambda name: users_coll if name == USERS_COLLECTION else jobs_coll
|
||||
return db, users_coll, jobs_coll
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def now():
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_data(now):
|
||||
users = [
|
||||
{"email": "real1@example.com", "last_login_at": now - timedelta(days=1),
|
||||
"credit_transactions": [{"amount": 5, "created_at": now - timedelta(days=2)}]},
|
||||
{"email": "real2@example.com", "last_login_at": now - timedelta(days=20),
|
||||
"credit_transactions": [{"amount": -1, "created_at": now - timedelta(days=2)},
|
||||
{"amount": 3, "created_at": now - timedelta(days=45)}]},
|
||||
# Test user — must be excluded from all counts
|
||||
{"email": "abc@inbox.testmail.app", "last_login_at": now - timedelta(days=1),
|
||||
"credit_transactions": [{"amount": 100, "created_at": now - timedelta(days=1)}]},
|
||||
]
|
||||
jobs = [
|
||||
{"user_email": "real1@example.com", "created_at": now - timedelta(days=1), "status": "complete"},
|
||||
{"user_email": "real1@example.com", "created_at": now - timedelta(days=10), "status": "failed"},
|
||||
{"user_email": "real2@example.com", "created_at": now - timedelta(days=40), "status": "transcribing"},
|
||||
{"user_email": "real2@example.com", "created_at": now - timedelta(days=1), "status": "awaiting_review"},
|
||||
# Test-user job — must be excluded
|
||||
{"user_email": "abc@inbox.testmail.app", "created_at": now - timedelta(days=1), "status": "complete"},
|
||||
]
|
||||
return users, jobs
|
||||
|
||||
|
||||
def test_compute_overview_counts_and_filters_test_data(sample_data):
|
||||
users, jobs = sample_data
|
||||
db, _, _ = make_db(users, jobs)
|
||||
|
||||
result = _compute_admin_stats_overview(db, exclude_test=True)
|
||||
|
||||
assert result.total_users == 2
|
||||
assert result.active_users_7d == 1
|
||||
assert result.active_users_30d == 2
|
||||
assert result.total_jobs == 4
|
||||
assert result.jobs_last_7d == 2
|
||||
assert result.jobs_last_30d == 3
|
||||
assert result.jobs_by_status.complete == 1
|
||||
assert result.jobs_by_status.failed == 1
|
||||
assert result.jobs_by_status.processing == 1 # transcribing
|
||||
assert result.jobs_by_status.awaiting_review == 1
|
||||
# 5 (recent) — excludes the 3 older than 30d, the negative txn, and the test user's 100
|
||||
assert result.total_credits_issued_30d == 5
|
||||
|
||||
|
||||
def test_compute_overview_uses_field_masks(sample_data):
|
||||
"""The .select() field masks are a performance guarantee — full job docs are huge."""
|
||||
users, jobs = sample_data
|
||||
db, users_coll, jobs_coll = make_db(users, jobs)
|
||||
|
||||
_compute_admin_stats_overview(db, exclude_test=True)
|
||||
|
||||
users_coll.select.assert_called_once_with(_OVERVIEW_USER_FIELDS)
|
||||
jobs_coll.select.assert_called_once_with(_OVERVIEW_JOB_FIELDS)
|
||||
|
||||
|
||||
def test_overview_endpoint_returns_stats(sample_data):
|
||||
users, jobs = sample_data
|
||||
db, _, _ = make_db(users, jobs)
|
||||
mock_service = Mock()
|
||||
mock_service.db = db
|
||||
app.dependency_overrides[get_user_service] = lambda: mock_service
|
||||
try:
|
||||
client = TestClient(app)
|
||||
resp = client.get("/api/admin/stats/overview?exclude_test=true")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["total_users"] == 2
|
||||
assert body["total_jobs"] == 4
|
||||
assert body["jobs_by_status"]["failed"] == 1
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_user_service, None)
|
||||
|
||||
|
||||
def test_overview_handles_empty_collections():
|
||||
db, _, _ = make_db([], [])
|
||||
result = _compute_admin_stats_overview(db, exclude_test=True)
|
||||
assert result.total_users == 0
|
||||
assert result.total_jobs == 0
|
||||
assert result.total_credits_issued_30d == 0
|
||||
@@ -321,22 +321,6 @@ 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 = []
|
||||
|
||||
@@ -394,52 +394,3 @@ class TestGetReviewAudioUrlAsync:
|
||||
result = await service.get_review_audio_url_async("jobs/abc/input/song.flac")
|
||||
|
||||
assert result == "https://signed/url"
|
||||
|
||||
|
||||
class TestGetReviewAudioBytes:
|
||||
"""get_review_audio_bytes() proxies the audio through the API (CORS-safe)."""
|
||||
|
||||
def test_returns_ogg_bytes_on_success(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True # cache hit
|
||||
mock_storage.download_bytes.return_value = b"OggS-transcoded-bytes"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
data, content_type = service.get_review_audio_bytes("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
assert data == b"OggS-transcoded-bytes"
|
||||
assert content_type == "audio/ogg"
|
||||
mock_storage.download_bytes.assert_called_once_with("jobs/abc/review-audio/vocals_clean.ogg")
|
||||
|
||||
def test_falls_back_to_source_bytes_on_transcode_error(self):
|
||||
"""A transient transcode failure serves the original source, not a 500."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = False # cache miss → transcode path
|
||||
mock_storage.download_file.side_effect = Exception("ffmpeg input download failed")
|
||||
mock_storage.download_bytes.return_value = b"fLaC-source-bytes"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
data, content_type = service.get_review_audio_bytes("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
assert data == b"fLaC-source-bytes"
|
||||
assert content_type == "audio/flac"
|
||||
# Fell back to proxying the original source object.
|
||||
mock_storage.download_bytes.assert_called_once_with("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_wrapper_delegates(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.download_bytes.return_value = b"OggS"
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
data, content_type = await service.get_review_audio_bytes_async("jobs/abc/stems/vocals_clean.flac")
|
||||
|
||||
assert data == b"OggS"
|
||||
assert content_type == "audio/ogg"
|
||||
@@ -1,42 +0,0 @@
|
||||
"""
|
||||
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()
|
||||
@@ -101,9 +101,7 @@ class TestChangeToPrivate:
|
||||
"""Test public -> private visibility change."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_redistributes_then_deletes_public(self):
|
||||
"""Distribute-then-delete: redistribute runs, then public outputs are deleted
|
||||
with the references captured before redistribution overwrote state."""
|
||||
async def test_calls_redistribute(self):
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
@@ -112,29 +110,18 @@ class TestChangeToPrivate:
|
||||
job = _make_job(is_private=False, state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"gdrive_files": {"mp4": "id1"},
|
||||
"dropbox_link": "https://dropbox.com/test",
|
||||
})
|
||||
|
||||
call_order = []
|
||||
mock_redist = AsyncMock(return_value=True, side_effect=lambda *a, **k: call_order.append("redist") or True)
|
||||
mock_delete = AsyncMock(side_effect=lambda *a, **k: call_order.append("delete"))
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
|
||||
patch("backend.workers.video_worker.redistribute_video", mock_redist):
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
|
||||
|
||||
result = await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
assert result["status"] == "success"
|
||||
assert result["reprocessing_required"] is False
|
||||
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
|
||||
mock_redist.assert_called_once_with("test-123")
|
||||
# Redistribution must happen BEFORE any public deletion.
|
||||
assert call_order == ["redist", "delete"]
|
||||
# Public deletion receives the references captured before redistribution.
|
||||
captured = mock_delete.call_args.args[1]
|
||||
assert captured["youtube_url"] == "https://youtube.com/watch?v=abc"
|
||||
assert captured["brand_code"] == "NOMAD-0001"
|
||||
assert captured["gdrive_files"] == {"mp4": "id1"}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sets_is_private_true(self):
|
||||
@@ -145,7 +132,7 @@ class TestChangeToPrivate:
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", new_callable=AsyncMock), \
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
|
||||
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
@@ -192,37 +179,6 @@ class TestChangeToPublic:
|
||||
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
|
||||
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_intermediate_deletes_ignore_missing(self):
|
||||
"""Best-effort deletes of intermediate render artifacts must pass
|
||||
ignore_missing=True so absent .mov/.mkv files are a quiet no-op instead
|
||||
of a noisy ERROR log that trips the error-monitor (regression)."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
assert mock_storage.delete_file.call_count > 0
|
||||
for call in mock_storage.delete_file.call_args_list:
|
||||
assert call.kwargs.get("ignore_missing") is True, (
|
||||
f"delete_file called without ignore_missing=True: {call}"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_styles_to_nomad_theme(self):
|
||||
mock_job_manager = MagicMock()
|
||||
@@ -296,33 +252,22 @@ class TestChangeToPrivateErrors:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rollback_on_redistribute_failure(self):
|
||||
"""On redistribution failure NOTHING public is deleted and the job is
|
||||
reverted to public — a failed going-private is a no-op, not a partial."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=False, state_data={
|
||||
"youtube_url": "https://youtube.com/watch?v=abc",
|
||||
"brand_code": "NOMAD-0001",
|
||||
"gdrive_files": {"mp4": "id1"},
|
||||
})
|
||||
job = _make_job(is_private=False, state_data={})
|
||||
|
||||
mock_delete = AsyncMock()
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
|
||||
|
||||
with pytest.raises(RuntimeError, match="Redistribution failed"):
|
||||
await service.change_to_private("test-123", job, "user@example.com")
|
||||
|
||||
# Public outputs must NOT be deleted when redistribution fails.
|
||||
mock_delete.assert_not_called()
|
||||
|
||||
# Job reverted to public + guard flag cleared (DELETE_FIELD sentinel).
|
||||
last_update = mock_job_ref.update.call_args_list[-1].args[0]
|
||||
assert last_update.get("is_private") is False
|
||||
val = last_update.get("state_data.visibility_change_in_progress")
|
||||
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
|
||||
last_update = mock_job_ref.update.call_args_list[-1]
|
||||
val = last_update.args[0].get("state_data.visibility_change_in_progress")
|
||||
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
|
||||
|
||||
|
||||
@@ -347,65 +292,6 @@ class TestDeleteDistributedOutputs:
|
||||
|
||||
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_public_outputs_recycles_public_code(self):
|
||||
"""_delete_public_outputs recycles the captured public NOMAD number."""
|
||||
mock_job_manager = MagicMock()
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
|
||||
public_outputs = {
|
||||
"youtube_url": None,
|
||||
"brand_code": "NOMAD-0042",
|
||||
"gdrive_files": None,
|
||||
"dropbox_path": None,
|
||||
"artist": "A",
|
||||
"title": "T",
|
||||
}
|
||||
|
||||
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)), \
|
||||
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mock_mirror:
|
||||
mock_brand_svc = MagicMock()
|
||||
mock_bcs.return_value = mock_brand_svc
|
||||
|
||||
await service._delete_public_outputs("test-123", public_outputs)
|
||||
|
||||
# No public YouTube/Dropbox/GDrive present → all deletions "succeed" →
|
||||
# the public number is recycled and the mirror is cleaned.
|
||||
mock_mirror.assert_called_once_with("NOMAD-0042")
|
||||
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_public_outputs_skips_recycle_on_incomplete_cleanup(self):
|
||||
"""If a public deletion fails, the number is NOT recycled (avoids a future
|
||||
duplicate against lingering public files)."""
|
||||
mock_job_manager = MagicMock()
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
|
||||
public_outputs = {
|
||||
"youtube_url": None,
|
||||
"brand_code": "NOMAD-0042",
|
||||
"gdrive_files": {"mp4": "id1"},
|
||||
"dropbox_path": None,
|
||||
"artist": "A",
|
||||
"title": "T",
|
||||
}
|
||||
|
||||
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_gd, \
|
||||
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters"), \
|
||||
patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
|
||||
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
|
||||
gd = MagicMock()
|
||||
gd.is_configured = True
|
||||
gd.delete_files.side_effect = RuntimeError("gdrive boom")
|
||||
mock_gd.return_value = gd
|
||||
mock_brand_svc = MagicMock()
|
||||
mock_bcs.return_value = mock_brand_svc
|
||||
|
||||
await service._delete_public_outputs("test-123", public_outputs)
|
||||
|
||||
mock_brand_svc.recycle_brand_code.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clears_distribution_state_keys(self):
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
"""Unit tests for the encoding-worker deploy decision logic.
|
||||
|
||||
The module lives under infrastructure/ (not an importable package), so we load
|
||||
it by path. Covers the two things the CI workflow can't test itself: which VMs
|
||||
to try as a fresh green target, and how to promote a validated green to serving.
|
||||
"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
_MODULE_PATH = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ "infrastructure" / "encoding-worker" / "deploy_promote.py"
|
||||
)
|
||||
_spec = importlib.util.spec_from_file_location("deploy_promote", _MODULE_PATH)
|
||||
deploy_promote = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(deploy_promote)
|
||||
|
||||
select_green_candidates = deploy_promote.select_green_candidates
|
||||
promote_plan = deploy_promote.promote_plan
|
||||
|
||||
|
||||
FALLBACKS = [
|
||||
{"vm": "encoding-worker-fallback-a", "zone": "us-central1-a", "ip": "34.55.231.54"},
|
||||
{"vm": "encoding-worker-fallback-b", "zone": "us-central1-b", "ip": "35.193.127.24"},
|
||||
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "35.226.119.227"},
|
||||
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "35.254.152.14"},
|
||||
]
|
||||
|
||||
|
||||
def _config(**over):
|
||||
base = {
|
||||
"primary_vm": "encoding-worker-b", "primary_ip": "34.10.189.118",
|
||||
"primary_version": "0.192.9",
|
||||
"secondary_vm": "encoding-worker-a", "secondary_ip": "34.57.78.246",
|
||||
"active_override_vm": "encoding-worker-fallback-n2f",
|
||||
"active_override_ip": "35.254.152.14", "active_override_zone": "us-central1-f",
|
||||
}
|
||||
base.update(over)
|
||||
return base
|
||||
|
||||
|
||||
class TestSelectGreenCandidates:
|
||||
def test_secondary_first_then_n2_before_c4d_excluding_override(self):
|
||||
# LEGACY secret shape (no machine_type). The shared ranking infers n2 from
|
||||
# the n2c/n2f names (rank 70) but CANNOT infer the bare c4d fallbacks a/b
|
||||
# (no family token) → they get UNKNOWN_RANK and sort last. Net order here
|
||||
# matches the pre-refactor "secondary, then n2, then c4d" result. Once the
|
||||
# secret carries machine_type (post-rollout), a/b rank as c4d — see
|
||||
# TestSelectGreenRankingSharedWithRuntime.
|
||||
cands = select_green_candidates(_config(), FALLBACKS)
|
||||
vms = [c["vm"] for c in cands]
|
||||
# c4d secondary leads; current override (n2f) excluded; n2c (n2) before c4d fallbacks.
|
||||
assert vms[0] == "encoding-worker-a"
|
||||
assert cands[0]["kind"] == "secondary"
|
||||
assert "encoding-worker-fallback-n2f" not in vms # the serving override is excluded
|
||||
assert vms[1] == "encoding-worker-fallback-n2c" # remaining n2 preferred
|
||||
assert vms[1:] == [
|
||||
"encoding-worker-fallback-n2c",
|
||||
"encoding-worker-fallback-a",
|
||||
"encoding-worker-fallback-b",
|
||||
]
|
||||
assert all(c["kind"] == "fallback" for c in cands[1:])
|
||||
|
||||
def test_candidate_carries_zone_and_ip(self):
|
||||
cands = select_green_candidates(_config(), FALLBACKS)
|
||||
n2c = next(c for c in cands if c["vm"] == "encoding-worker-fallback-n2c")
|
||||
assert n2c["zone"] == "us-central1-c"
|
||||
assert n2c["ip"] == "35.226.119.227"
|
||||
|
||||
def test_no_secondary_still_lists_fallbacks(self):
|
||||
cands = select_green_candidates(_config(secondary_vm=None), FALLBACKS)
|
||||
assert all(c["kind"] == "fallback" for c in cands)
|
||||
assert cands[0]["vm"] == "encoding-worker-fallback-n2c"
|
||||
|
||||
def test_malformed_fallback_entries_are_dropped(self):
|
||||
fbs = [
|
||||
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "35.226.119.227"},
|
||||
{"vm": "encoding-worker-fallback-broken", "ip": "1.2.3.4"}, # no zone
|
||||
{"zone": "us-central1-a", "ip": "5.6.7.8"}, # no vm
|
||||
{"vm": "encoding-worker-fallback-noip", "zone": "us-central1-b"}, # no ip
|
||||
]
|
||||
cands = select_green_candidates(_config(active_override_vm=None), fbs)
|
||||
vms = [c["vm"] for c in cands]
|
||||
assert vms.count("encoding-worker-fallback-n2c") == 1
|
||||
assert "encoding-worker-fallback-broken" not in vms
|
||||
assert "encoding-worker-fallback-noip" not in vms
|
||||
assert None not in vms # the entry with no "vm" is dropped, not emitted as vm=None
|
||||
|
||||
def test_no_override_keeps_all_fallbacks(self):
|
||||
cands = select_green_candidates(_config(active_override_vm=None), FALLBACKS)
|
||||
fb_vms = [c["vm"] for c in cands if c["kind"] == "fallback"]
|
||||
# n2 fallbacks first (either order among the two n2s is fine — assert as a set head)
|
||||
assert set(fb_vms[:2]) == {"encoding-worker-fallback-n2c", "encoding-worker-fallback-n2f"}
|
||||
assert set(fb_vms) == {f["vm"] for f in FALLBACKS}
|
||||
|
||||
|
||||
class TestPromotePlanFallbackBranch:
|
||||
def test_fallback_green_becomes_override_and_drains_old(self):
|
||||
green = {"vm": "encoding-worker-fallback-n2c", "ip": "35.226.119.227",
|
||||
"zone": "us-central1-c", "kind": "fallback"}
|
||||
plan = promote_plan(green, _config(), now="NOW", version="0.194.1")
|
||||
u = plan["firestore_updates"]
|
||||
assert u["active_override_vm"] == "encoding-worker-fallback-n2c"
|
||||
assert u["active_override_ip"] == "35.226.119.227"
|
||||
assert u["active_override_zone"] == "us-central1-c"
|
||||
assert u["active_override_version"] == "0.194.1"
|
||||
assert u["deploy_in_progress"] is False
|
||||
# primary/secondary untouched (c4d resumes when capacity returns)
|
||||
assert "primary_vm" not in u and "secondary_vm" not in u
|
||||
# old override (n2f) drained + stopped
|
||||
assert plan["drain_and_stop"] == [
|
||||
{"vm": "encoding-worker-fallback-n2f", "ip": "35.254.152.14", "zone": "us-central1-f"}
|
||||
]
|
||||
|
||||
def test_no_drain_when_no_previous_override(self):
|
||||
green = {"vm": "encoding-worker-fallback-n2c", "ip": "35.226.119.227",
|
||||
"zone": "us-central1-c", "kind": "fallback"}
|
||||
plan = promote_plan(green, _config(active_override_vm=None), now="NOW", version="0.194.1")
|
||||
assert plan["drain_and_stop"] == []
|
||||
|
||||
def test_no_self_drain_when_green_is_current_override(self):
|
||||
# Degenerate (shouldn't happen since candidates exclude the override), but
|
||||
# must never drain-stop the worker we just promoted.
|
||||
green = {"vm": "encoding-worker-fallback-n2f", "ip": "35.254.152.14",
|
||||
"zone": "us-central1-f", "kind": "fallback"}
|
||||
plan = promote_plan(green, _config(), now="NOW", version="0.194.1")
|
||||
assert plan["drain_and_stop"] == []
|
||||
|
||||
|
||||
class TestPromotePlanSecondaryBranch:
|
||||
def test_secondary_green_swaps_and_clears_stale_override(self):
|
||||
green = {"vm": "encoding-worker-a", "ip": "34.57.78.246",
|
||||
"zone": "us-central1-c", "kind": "secondary"}
|
||||
plan = promote_plan(green, _config(), now="NOW", version="0.194.1")
|
||||
u = plan["firestore_updates"]
|
||||
# green -> primary, old primary -> secondary
|
||||
assert u["primary_vm"] == "encoding-worker-a"
|
||||
assert u["primary_version"] == "0.194.1"
|
||||
assert u["secondary_vm"] == "encoding-worker-b"
|
||||
assert u["secondary_version"] == "0.192.9"
|
||||
# stale override cleared so active_url follows the fresh primary
|
||||
assert u["active_override_vm"] is None
|
||||
assert u["active_override_version"] is None
|
||||
assert u["deploy_in_progress"] is False
|
||||
# both the old primary and the old override get drained + stopped
|
||||
drained = {d["vm"] for d in plan["drain_and_stop"]}
|
||||
assert drained == {"encoding-worker-b", "encoding-worker-fallback-n2f"}
|
||||
|
||||
def test_secondary_never_drains_the_promoted_green(self):
|
||||
# Pathological config where a stale override (or primary) names the green
|
||||
# VM — the plan must never tell the workflow to stop what it just promoted.
|
||||
green = {"vm": "encoding-worker-a", "ip": "34.57.78.246",
|
||||
"zone": "us-central1-c", "kind": "secondary"}
|
||||
cfg = _config(active_override_vm="encoding-worker-a",
|
||||
active_override_ip="34.57.78.246",
|
||||
active_override_zone="us-central1-c")
|
||||
plan = promote_plan(green, cfg, now="NOW", version="0.194.2")
|
||||
assert all(d["vm"] != "encoding-worker-a" for d in plan["drain_and_stop"])
|
||||
# The override is still cleared in config even though we don't stop that VM.
|
||||
assert plan["firestore_updates"]["active_override_vm"] is None
|
||||
|
||||
def test_secondary_swap_without_override(self):
|
||||
green = {"vm": "encoding-worker-a", "ip": "34.57.78.246",
|
||||
"zone": "us-central1-c", "kind": "secondary"}
|
||||
plan = promote_plan(green, _config(active_override_vm=None), now="NOW", version="0.194.1")
|
||||
u = plan["firestore_updates"]
|
||||
assert "active_override_vm" not in u # nothing to clear
|
||||
assert [d["vm"] for d in plan["drain_and_stop"]] == ["encoding-worker-b"]
|
||||
|
||||
|
||||
class TestSelectGreenRankingSharedWithRuntime:
|
||||
"""Green selection now ranks via the shared preference (machine_type + cooldown)."""
|
||||
|
||||
# 6-type pool with explicit machine_type (mirrors the post-rollout secret).
|
||||
POOL = [
|
||||
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.1",
|
||||
"machine_type": "c4-highcpu-32"},
|
||||
{"vm": "encoding-worker-fallback-n4db", "zone": "us-central1-b", "ip": "10.0.0.2",
|
||||
"machine_type": "n4d-highcpu-32"},
|
||||
{"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "10.0.0.3",
|
||||
"machine_type": "c2d-highcpu-32"},
|
||||
{"vm": "encoding-worker-fallback-n2da", "zone": "us-central1-a", "ip": "10.0.0.4",
|
||||
"machine_type": "n2d-highcpu-32"},
|
||||
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "10.0.0.5",
|
||||
"machine_type": "n2-highcpu-32"},
|
||||
]
|
||||
|
||||
def test_secondary_c4d_leads_then_fastest_fallbacks(self):
|
||||
cfg = _config(active_override_vm=None)
|
||||
vms = [c["vm"] for c in select_green_candidates(cfg, self.POOL)]
|
||||
# c4d secondary (rank 10) first, then c4 > n4d > c2d > n2d > n2.
|
||||
assert vms == [
|
||||
"encoding-worker-a", # secondary, c4d
|
||||
"encoding-worker-fallback-c4a", # c4
|
||||
"encoding-worker-fallback-n4db", # n4d
|
||||
"encoding-worker-fallback-c2df", # c2d
|
||||
"encoding-worker-fallback-n2da", # n2d
|
||||
"encoding-worker-fallback-n2c", # n2
|
||||
]
|
||||
|
||||
def test_c4d_stockout_demotes_secondary_below_deep_pool(self):
|
||||
# c4d@us-central1-c (the secondary's zone) recently stocked out.
|
||||
from datetime import datetime, timezone
|
||||
cfg = _config(
|
||||
active_override_vm=None,
|
||||
capacity_state={"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()},
|
||||
)
|
||||
cands = select_green_candidates(cfg, self.POOL)
|
||||
vms = [c["vm"] for c in cands]
|
||||
# The c4d secondary is demoted to the back; a fast fallback (c4) now leads.
|
||||
assert vms[0] == "encoding-worker-fallback-c4a"
|
||||
assert vms[-1] == "encoding-worker-a" # demoted secondary re-probed last
|
||||
# kind survives the reordering so promote_plan still treats it correctly.
|
||||
assert cands[-1]["kind"] == "secondary"
|
||||
|
||||
def test_machine_type_carried_through(self):
|
||||
cands = select_green_candidates(_config(active_override_vm=None), self.POOL)
|
||||
c4 = next(c for c in cands if c["vm"] == "encoding-worker-fallback-c4a")
|
||||
assert c4["machine_type"] == "c4-highcpu-32"
|
||||
@@ -313,37 +313,6 @@ class TestGCEEncodingBackend:
|
||||
assert output.success is False
|
||||
assert "GCE worker error" in output.error_message
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_reraises_lost_job_error(self, mock_get_service):
|
||||
"""A lost-job error (worker restart) must propagate, NOT become success=False.
|
||||
|
||||
The orchestrator's resubmit wrapper only fires on the typed exception; if
|
||||
the backend flattened it into success=False the render would just fail
|
||||
instead of being retried."""
|
||||
from backend.services.encoding_errors import EncodingJobLostError
|
||||
|
||||
mock_service = MagicMock()
|
||||
mock_service.encode_videos = AsyncMock(
|
||||
side_effect=EncodingJobLostError("worker lost the job", job_id="test-job")
|
||||
)
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
backend = GCEEncodingBackend()
|
||||
input_config = EncodingInput(
|
||||
title_video_path="/input/title.mov",
|
||||
karaoke_video_path="/input/karaoke.mov",
|
||||
instrumental_audio_path="/input/audio.flac",
|
||||
options={
|
||||
"job_id": "test-job",
|
||||
"input_gcs_path": "gs://bucket/input/",
|
||||
"output_gcs_path": "gs://bucket/output/",
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(EncodingJobLostError):
|
||||
await backend.encode(input_config)
|
||||
|
||||
@patch.object(GCEEncodingBackend, "_get_service")
|
||||
@pytest.mark.asyncio
|
||||
async def test_encode_handles_list_result(self, mock_get_service):
|
||||
|
||||
@@ -16,9 +16,7 @@ from backend.services.encoding_service import (
|
||||
INITIAL_BACKOFF_SECONDS,
|
||||
MAX_BACKOFF_SECONDS,
|
||||
MAX_CONSECUTIVE_POLL_FAILURES,
|
||||
run_with_lost_job_resubmit,
|
||||
)
|
||||
from backend.services.encoding_errors import EncodingJobLostError, EncodingJobNotFoundError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -668,193 +666,6 @@ class TestWaitForCompletionPollTolerance:
|
||||
assert call_count == 6 # 2 fail + 1 success + 2 fail + 1 success
|
||||
|
||||
|
||||
class TestWaitForCompletionLostJob:
|
||||
"""A worker restart (OOM/deploy) that wipes an in-flight job must surface a
|
||||
distinct, recoverable signal instead of the generic poll-failure timeout."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_404_after_job_seen_raises_lost_error(self, encoding_service):
|
||||
"""Once we've seen the job run, a later 404 = the worker lost it → resubmit."""
|
||||
call_count = 0
|
||||
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 1:
|
||||
return {"status": "running", "progress": 30}
|
||||
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(EncodingJobLostError):
|
||||
await encoding_service.wait_for_completion("j1")
|
||||
|
||||
# Should bail on the FIRST 404, not burn the full poll tolerance.
|
||||
assert call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_404_before_job_seen_is_tolerated(self, encoding_service):
|
||||
"""A 404 before the job is ever seen is a submit/poll race, not a lost job —
|
||||
keep the transient tolerance (avoids false resubmits)."""
|
||||
async def always_404(job_id, worker_url=None):
|
||||
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=always_404), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
# Falls through to the generic tolerance, NOT EncodingJobLostError.
|
||||
with pytest.raises(RuntimeError, match="consecutive poll failures"):
|
||||
await encoding_service.wait_for_completion("j1")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restart_failure_code_raises_lost_error(self, encoding_service):
|
||||
"""A terminal failure carrying the restart marker is recoverable → lost error."""
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
return {
|
||||
"status": "failed",
|
||||
"error": "Encoding worker restarted mid-job",
|
||||
"restart_failure_code": "encoding_worker_restart",
|
||||
}
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(EncodingJobLostError):
|
||||
await encoding_service.wait_for_completion("j1")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_plain_failure_still_raises_runtimeerror(self, encoding_service):
|
||||
"""A normal (non-restart) failure stays a hard RuntimeError, not a resubmit."""
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
return {"status": "failed", "error": "ffmpeg exploded"}
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.return_value = 0
|
||||
with pytest.raises(RuntimeError, match="ffmpeg exploded"):
|
||||
await encoding_service.wait_for_completion("j1")
|
||||
# And it must not be the recoverable subtype.
|
||||
try:
|
||||
await encoding_service.wait_for_completion("j1")
|
||||
except EncodingJobLostError: # pragma: no cover
|
||||
pytest.fail("plain failure should not be EncodingJobLostError")
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pending_does_not_count_toward_run_timeout(self, encoding_service):
|
||||
"""Time spent queued (pending) is bounded by queue_timeout, not the per-run
|
||||
timeout — a burst can wait in the serialized heavy queue and still succeed."""
|
||||
statuses = [
|
||||
{"status": "pending", "progress": 0, "queue_position": 3},
|
||||
{"status": "pending", "progress": 0, "queue_position": 2},
|
||||
{"status": "pending", "progress": 0, "queue_position": 1},
|
||||
{"status": "running", "progress": 10},
|
||||
{"status": "complete", "output_files": ["a.mp4"]},
|
||||
]
|
||||
idx = 0
|
||||
|
||||
async def mock_get_status(job_id, worker_url=None):
|
||||
nonlocal idx
|
||||
s = statuses[idx]
|
||||
idx += 1
|
||||
return s
|
||||
|
||||
# start_time read, then one read per loop iteration. Job is pending until
|
||||
# t=300 (>> timeout=50) then runs and completes at t=310 (10s of run time).
|
||||
seq = [0, 0, 100, 200, 300, 310]
|
||||
|
||||
def fake_time():
|
||||
return seq.pop(0) if len(seq) > 1 else seq[0]
|
||||
|
||||
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
|
||||
patch("asyncio.sleep", new_callable=AsyncMock), \
|
||||
patch("asyncio.get_event_loop") as mock_loop:
|
||||
mock_loop.return_value.time.side_effect = fake_time
|
||||
result = await encoding_service.wait_for_completion(
|
||||
"j1", timeout=50, queue_timeout=1000
|
||||
)
|
||||
|
||||
assert result["status"] == "complete"
|
||||
|
||||
|
||||
class TestPreviewQueueTimeout:
|
||||
"""A queued preview must not wait the long default queue_timeout — an
|
||||
interactive user is waiting, so total wait is capped at the short timeout."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preview_caps_queue_timeout_to_timeout(self, encoding_service):
|
||||
submit = AsyncMock(return_value={"status": "accepted", "job_id": "p1"})
|
||||
wait = AsyncMock(return_value={"status": "complete"})
|
||||
with patch.object(encoding_service, "submit_preview_encoding_job", submit), \
|
||||
patch.object(encoding_service, "wait_for_completion", wait):
|
||||
await encoding_service.encode_preview_video(
|
||||
job_id="p1",
|
||||
ass_gcs_path="gs://b/x.ass",
|
||||
audio_gcs_path="gs://b/a.flac",
|
||||
output_gcs_path="gs://b/out.mp4",
|
||||
timeout=90.0,
|
||||
)
|
||||
_, kwargs = wait.call_args
|
||||
assert kwargs["timeout"] == 90.0
|
||||
assert kwargs["queue_timeout"] == 90.0
|
||||
|
||||
|
||||
class TestRunWithLostJobResubmit:
|
||||
"""The bounded resubmit wrapper used by the render + encode workers."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resubmits_with_fresh_id_then_succeeds(self):
|
||||
seen_ids = []
|
||||
|
||||
async def op(job_id):
|
||||
seen_ids.append(job_id)
|
||||
if len(seen_ids) == 1:
|
||||
raise EncodingJobLostError("lost", job_id=job_id)
|
||||
return {"status": "complete"}
|
||||
|
||||
result = await run_with_lost_job_resubmit(op, "base123", max_resubmits=2)
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert seen_ids[0] == "base123"
|
||||
assert seen_ids[1].startswith("base123_retry_")
|
||||
assert len(seen_ids) == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gives_up_after_max_resubmits(self):
|
||||
attempts = []
|
||||
|
||||
async def op(job_id):
|
||||
attempts.append(job_id)
|
||||
raise EncodingJobLostError("lost", job_id=job_id)
|
||||
|
||||
with pytest.raises(EncodingJobLostError):
|
||||
await run_with_lost_job_resubmit(op, "base", max_resubmits=2)
|
||||
|
||||
# 1 initial + 2 resubmits = 3 attempts.
|
||||
assert len(attempts) == 3
|
||||
assert attempts[0] == "base"
|
||||
assert all(a.startswith("base_retry_") for a in attempts[1:])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_other_errors_are_not_retried(self):
|
||||
attempts = []
|
||||
|
||||
async def op(job_id):
|
||||
attempts.append(job_id)
|
||||
raise RuntimeError("some other failure")
|
||||
|
||||
with pytest.raises(RuntimeError, match="some other failure"):
|
||||
await run_with_lost_job_resubmit(op, "base", max_resubmits=2)
|
||||
|
||||
assert len(attempts) == 1 # not retried
|
||||
|
||||
|
||||
class TestDynamicURLResolution:
|
||||
"""Tests that EncodingService reads URL from Firestore, not static config."""
|
||||
|
||||
@@ -1066,88 +877,3 @@ class TestWorkerUrlPinning:
|
||||
|
||||
assert result["status"] == "complete"
|
||||
assert result["output_files"] == ["4k.mp4"]
|
||||
|
||||
|
||||
class TestBuildWorkerCandidates:
|
||||
"""_build_worker_candidates ranks primary + fallbacks via the shared preference."""
|
||||
|
||||
def _config(self, capacity_state=None):
|
||||
cfg = MagicMock()
|
||||
cfg.primary_vm = "encoding-worker-a"
|
||||
cfg.primary_ip = "10.0.0.1"
|
||||
cfg.primary_machine_type = None # → defaults to c4d
|
||||
cfg.capacity_state = capacity_state or {}
|
||||
return cfg
|
||||
|
||||
def _service_with_fallbacks(self, encoding_service, fallbacks_json, capacity_state=None):
|
||||
mgr = MagicMock()
|
||||
mgr._zone = "us-central1-c"
|
||||
mgr.get_config.return_value = self._config(capacity_state)
|
||||
encoding_service._worker_manager = mgr
|
||||
encoding_service.settings.encoding_worker_fallback_vms = fallbacks_json
|
||||
return encoding_service
|
||||
|
||||
def test_primary_first_and_flagged(self, encoding_service):
|
||||
svc = self._service_with_fallbacks(encoding_service, None)
|
||||
cands = svc._build_worker_candidates()
|
||||
assert cands[0].vm_name == "encoding-worker-a"
|
||||
assert cands[0].is_primary is True
|
||||
assert cands[0].machine_type == "c4d-highcpu-32"
|
||||
|
||||
def test_fallbacks_ranked_fastest_first(self, encoding_service):
|
||||
import json
|
||||
fallbacks = json.dumps([
|
||||
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "10.0.0.5",
|
||||
"machine_type": "n2-highcpu-32"},
|
||||
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
|
||||
"machine_type": "c4-highcpu-32"},
|
||||
])
|
||||
svc = self._service_with_fallbacks(encoding_service, fallbacks)
|
||||
order = [c.vm_name for c in svc._build_worker_candidates()]
|
||||
# c4d primary, then c4 (faster), then n2.
|
||||
assert order == ["encoding-worker-a", "encoding-worker-fallback-c4a",
|
||||
"encoding-worker-fallback-n2f"]
|
||||
|
||||
def test_stocked_out_primary_demoted(self, encoding_service):
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
fallbacks = json.dumps([
|
||||
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
|
||||
"machine_type": "c4-highcpu-32"},
|
||||
])
|
||||
# c4d@us-central1-c stocked out "now" → demoted below c4.
|
||||
cap = {"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()}
|
||||
svc = self._service_with_fallbacks(encoding_service, fallbacks, capacity_state=cap)
|
||||
cands = svc._build_worker_candidates()
|
||||
order = [c.vm_name for c in cands]
|
||||
assert order == ["encoding-worker-fallback-c4a", "encoding-worker-a"]
|
||||
# is_primary still correctly attached to the demoted c4d.
|
||||
primary = [c for c in cands if c.is_primary][0]
|
||||
assert primary.vm_name == "encoding-worker-a"
|
||||
|
||||
def test_legacy_fallback_without_machine_type_inferred(self, encoding_service):
|
||||
import json
|
||||
fallbacks = json.dumps([
|
||||
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "10.0.0.7"},
|
||||
])
|
||||
svc = self._service_with_fallbacks(encoding_service, fallbacks)
|
||||
cands = svc._build_worker_candidates()
|
||||
n2 = [c for c in cands if "n2c" in c.vm_name][0]
|
||||
assert n2.machine_type is None # not fabricated on the object…
|
||||
# …but inference placed it after the c4d primary.
|
||||
assert [c.vm_name for c in cands] == ["encoding-worker-a", "encoding-worker-fallback-n2c"]
|
||||
|
||||
def test_no_worker_manager_returns_empty(self, encoding_service):
|
||||
encoding_service._worker_manager = None
|
||||
assert encoding_service._build_worker_candidates() == []
|
||||
|
||||
def test_non_list_fallback_json_degrades_to_primary_only(self, encoding_service):
|
||||
# A JSON scalar (e.g. "null") parses fine but must not blow up iteration.
|
||||
svc = self._service_with_fallbacks(encoding_service, "null")
|
||||
cands = svc._build_worker_candidates()
|
||||
assert [c.vm_name for c in cands] == ["encoding-worker-a"]
|
||||
|
||||
def test_dict_fallback_json_degrades_to_primary_only(self, encoding_service):
|
||||
svc = self._service_with_fallbacks(encoding_service, '{"vm": "x"}')
|
||||
cands = svc._build_worker_candidates()
|
||||
assert [c.vm_name for c in cands] == ["encoding-worker-a"]
|
||||
@@ -934,141 +934,3 @@ class TestWaitForWorkerReady:
|
||||
)
|
||||
|
||||
assert call_count["n"] == 3
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# capacity_state (availability awareness) + is_primary override routing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestCapacityStateFeedback:
|
||||
"""ensure_any_running records/clears per-(type,zone) stockout state."""
|
||||
|
||||
def test_records_stockout_on_capacity_error(self, manager, mock_db, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
# Primary c4d hits capacity; fallback n2 succeeds.
|
||||
mock_compute.start.side_effect = [_capacity_op(), _ok_op()]
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
|
||||
ip="10.0.0.2", machine_type="n2-highcpu-32"),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
manager.ensure_any_running(candidates)
|
||||
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
# A merge-set recorded the c4d stockout under its type@zone key.
|
||||
set_calls = [c for c in doc_ref.set.call_args_list
|
||||
if "capacity_state" in (c.args[0] if c.args else {})]
|
||||
recorded = {}
|
||||
for c in set_calls:
|
||||
recorded.update(c.args[0]["capacity_state"])
|
||||
assert recorded.get("c4d-highcpu-32@us-central1-c") == "2026-05-05T09:00:00+00:00"
|
||||
|
||||
def test_clears_stockout_for_type_on_clean_start(self, manager, mock_db, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
mock_compute.start.return_value = _ok_op()
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
manager.ensure_any_running(candidates)
|
||||
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
cleared = {}
|
||||
for c in doc_ref.set.call_args_list:
|
||||
payload = c.args[0] if c.args else {}
|
||||
if "capacity_state" in payload:
|
||||
cleared.update(payload["capacity_state"])
|
||||
assert cleared.get("c4d-highcpu-32@us-central1-c") is None
|
||||
|
||||
def test_stockout_write_failure_does_not_break_start(self, manager, mock_db, mock_compute):
|
||||
"""A Firestore error while recording a stockout must not abort failover."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
mock_compute.start.side_effect = [_capacity_op(), _ok_op()]
|
||||
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
doc_ref.set.side_effect = RuntimeError("firestore down")
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
|
||||
ip="10.0.0.2", machine_type="n2-highcpu-32"),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_any_running(candidates)
|
||||
|
||||
assert result["vm_name"] == "encoding-worker-fallback-n2f"
|
||||
assert result["fell_back"] is True
|
||||
|
||||
def test_is_primary_flag_routes_override_regardless_of_position(self, manager, mock_db, mock_compute):
|
||||
"""A fallback ranked FIRST (is_primary=False) must still set active_override.
|
||||
|
||||
When the preference logic demotes a stocked-out primary, the fallback can be
|
||||
candidate index 0 — the override must key off is_primary, not position.
|
||||
"""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
mock_compute.start.return_value = _ok_op()
|
||||
|
||||
# Fallback is first (primary demoted), primary flagged but ranked second.
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-c2df", zone="us-central1-f",
|
||||
ip="10.0.0.9", machine_type="c2d-highcpu-32", is_primary=False),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
|
||||
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_any_running(candidates)
|
||||
|
||||
assert result["vm_name"] == "encoding-worker-fallback-c2df"
|
||||
assert result["fell_back"] is True
|
||||
doc_ref = mock_db.collection.return_value.document.return_value
|
||||
override_calls = [c for c in doc_ref.update.call_args_list
|
||||
if "active_override_vm" in c.args[0]]
|
||||
assert override_calls, "Fallback at index 0 must still set the override"
|
||||
assert override_calls[0].args[0]["active_override_vm"] == "encoding-worker-fallback-c2df"
|
||||
|
||||
def test_legacy_candidates_without_flag_use_position(self, manager, mock_db, mock_compute):
|
||||
"""No is_primary flag anywhere → first candidate is treated as primary (legacy)."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
mock_compute.start.return_value = _ok_op()
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-blue", zone="us-central1-c", ip="10.0.0.1"),
|
||||
EncodingWorkerCandidate(vm_name="encoding-worker-fb-a", zone="us-central1-a", ip="10.0.0.2"),
|
||||
]
|
||||
|
||||
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_any_running(candidates)
|
||||
|
||||
assert result["fell_back"] is False
|
||||
assert result["vm_name"] == "encoding-worker-blue"
|
||||
@@ -1,172 +0,0 @@
|
||||
"""Unit tests for the shared encoding-worker candidate preference logic.
|
||||
|
||||
This pure module drives BOTH runtime selection and deploy green selection, so its
|
||||
ordering guarantees (fastest-first, cooldown demotion, machine_type inference) are
|
||||
the contract both call-sites rely on.
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from backend.services.encoding_worker_preference import (
|
||||
COOLDOWN_SECONDS,
|
||||
SPEED_RANK,
|
||||
UNKNOWN_RANK,
|
||||
cooldown_key,
|
||||
infer_machine_type,
|
||||
ordered_candidates,
|
||||
)
|
||||
|
||||
NOW = datetime(2026, 8, 15, 19, 0, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _c(vm, zone, machine_type=None, **extra):
|
||||
d = {"vm": vm, "zone": zone, "ip": f"10.0.0.{hash(vm) % 250 + 1}"}
|
||||
if machine_type is not None:
|
||||
d["machine_type"] = machine_type
|
||||
d.update(extra)
|
||||
return d
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# machine_type inference
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_explicit_machine_type_wins():
|
||||
assert infer_machine_type(_c("whatever", "z", "c2d-highcpu-32")) == "c2d-highcpu-32"
|
||||
|
||||
|
||||
def test_infer_from_vm_name_specific_before_generic():
|
||||
# "n2d"/"c4d" must not be shadowed by "n2"/"c4".
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-n2da", "z")) == "n2d-highcpu-32"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-n2f", "z")) == "n2-highcpu-32"
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-c4x", "z")) == "c4-highcpu-32"
|
||||
|
||||
|
||||
def test_infer_unknown_returns_none():
|
||||
# Bare a/b c4d fallbacks (no family token) can't be inferred from the name.
|
||||
assert infer_machine_type(_c("encoding-worker-fallback-a", "z")) is None
|
||||
|
||||
|
||||
def test_runtime_dict_shape_uses_vm_name_key():
|
||||
assert infer_machine_type({"vm_name": "x-n2d-y", "zone": "z"}) == "n2d-highcpu-32"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# fastest-first ordering
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_orders_fastest_first():
|
||||
pool = [
|
||||
_c("n2", "us-central1-c", "n2-highcpu-32"),
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
]
|
||||
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
|
||||
assert got == ["c4d", "c4", "c2d", "n2"]
|
||||
|
||||
|
||||
def test_unknown_type_sorts_last_but_kept():
|
||||
pool = [
|
||||
_c("mystery", "z"), # no machine_type, unknown name
|
||||
_c("c4d", "z", "c4d-highcpu-32"),
|
||||
]
|
||||
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
|
||||
assert got == ["c4d", "mystery"]
|
||||
assert SPEED_RANK["c4d-highcpu-32"] < UNKNOWN_RANK
|
||||
|
||||
|
||||
def test_stable_within_equal_rank_preserves_zone_spread():
|
||||
# Two n2 in different zones keep input order (caller's secondary preference).
|
||||
pool = [
|
||||
_c("n2f", "us-central1-f", "n2-highcpu-32"),
|
||||
_c("n2c", "us-central1-c", "n2-highcpu-32"),
|
||||
]
|
||||
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
|
||||
assert got == ["n2f", "n2c"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# cooldown / availability awareness
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_recent_stockout_demotes_type_to_back():
|
||||
pool = [
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-32"),
|
||||
]
|
||||
# c4d stocked out 1 minute ago → demoted behind the still-healthy types.
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": (NOW - timedelta(minutes=1)).isoformat()}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["c4", "n2", "c4d"]
|
||||
|
||||
|
||||
def test_cooldown_expires_and_snaps_back_to_fastest():
|
||||
pool = [
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
]
|
||||
# Stockout older than COOLDOWN → c4d is hot again and returns to the top.
|
||||
old = (NOW - timedelta(seconds=COOLDOWN_SECONDS + 60)).isoformat()
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": old}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["c4d", "c4"]
|
||||
|
||||
|
||||
def test_two_types_stocked_out_still_serves_from_deep_pool():
|
||||
# Both newest-gen types (c4d, c4) exhausted; deep pools keep serving in order.
|
||||
pool = [
|
||||
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("c4", "us-central1-a", "c4-highcpu-32"),
|
||||
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
|
||||
_c("n2d", "us-central1-a", "n2d-highcpu-32"),
|
||||
]
|
||||
recent = (NOW - timedelta(minutes=2)).isoformat()
|
||||
capacity_state = {
|
||||
"c4d-highcpu-32@us-central1-c": recent,
|
||||
"c4-highcpu-32@us-central1-a": recent,
|
||||
}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
# Hot deep pools first (fastest-first among them), then the two cold types.
|
||||
assert got == ["c2d", "n2d", "c4d", "c4"]
|
||||
|
||||
|
||||
def test_type_only_capacity_key_demotes_all_zones():
|
||||
pool = [
|
||||
_c("c4d-c", "us-central1-c", "c4d-highcpu-32"),
|
||||
_c("n2", "us-central1-c", "n2-highcpu-32"),
|
||||
]
|
||||
capacity_state = {"c4d-highcpu-32": (NOW - timedelta(minutes=1)).isoformat()}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["n2", "c4d-c"]
|
||||
|
||||
|
||||
def test_empty_capacity_state_is_pure_speed_order():
|
||||
pool = [_c("n2", "z", "n2-highcpu-32"), _c("c4d", "z", "c4d-highcpu-32")]
|
||||
assert [c["vm"] for c in ordered_candidates(pool, {}, now=NOW)] == ["c4d", "n2"]
|
||||
assert [c["vm"] for c in ordered_candidates(pool, None, now=NOW)] == ["c4d", "n2"]
|
||||
|
||||
|
||||
def test_naive_timestamp_tolerated():
|
||||
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
|
||||
naive = (NOW - timedelta(minutes=1)).replace(tzinfo=None).isoformat()
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": naive}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["n2", "c4d"]
|
||||
|
||||
|
||||
def test_malformed_timestamp_ignored():
|
||||
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
|
||||
capacity_state = {"c4d-highcpu-32@us-central1-c": "not-a-date"}
|
||||
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
|
||||
assert got == ["c4d", "n2"] # unparseable → not in cooldown
|
||||
|
||||
|
||||
def test_empty_pool():
|
||||
assert ordered_candidates([], now=NOW) == []
|
||||
|
||||
|
||||
def test_cooldown_key_shape():
|
||||
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-32")) == "c4d-highcpu-32@us-central1-c"
|
||||
assert cooldown_key(_c("x", None, "n2-highcpu-32")) == "n2-highcpu-32"
|
||||
assert cooldown_key(_c("no-token", "z")) is None
|
||||
@@ -1,102 +0,0 @@
|
||||
"""
|
||||
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)
|
||||
@@ -1,215 +0,0 @@
|
||||
"""
|
||||
Tests for the encoding worker's two-lane execution model (gce_encoding/main.py).
|
||||
|
||||
The worker serializes heavy jobs (renders/encodes) into a single lane so it can
|
||||
never OOM from running multiple 4K ffmpeg encodes at once (incident 2026-08-15:
|
||||
3 concurrent encodes OOM-killed the 32 GB fallback worker). Light jobs (previews,
|
||||
wheel installs) run on their own lane. `/status` also exposes a queue position so
|
||||
the client can wait through a deep queue.
|
||||
|
||||
Importing main.py constructs a storage.Client() at module load, so we patch it.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def worker():
|
||||
"""Import the GCE worker module with GCS creds mocked out.
|
||||
|
||||
Clear ENCODING_HEAVY_CONCURRENCY during import so the default-behavior
|
||||
assertions hold regardless of the CI environment.
|
||||
"""
|
||||
with patch.dict(os.environ, {}, clear=False):
|
||||
os.environ.pop("ENCODING_HEAVY_CONCURRENCY", None)
|
||||
with patch("google.cloud.storage.Client", return_value=MagicMock()):
|
||||
sys.modules.pop("backend.services.gce_encoding.main", None)
|
||||
import backend.services.gce_encoding.main as m
|
||||
yield m
|
||||
sys.modules.pop("backend.services.gce_encoding.main", None)
|
||||
|
||||
|
||||
class TestHeavyLaneSerialization:
|
||||
def test_heavy_concurrency_defaults_to_one(self, worker):
|
||||
# One heavy ffmpeg at a time → OOM-proof on any machine type.
|
||||
assert worker.HEAVY_CONCURRENCY == 1
|
||||
assert worker.heavy_executor._max_workers == 1
|
||||
|
||||
def test_heavy_and_light_are_separate_lanes(self, worker):
|
||||
# Previews / wheel installs must not queue behind a multi-minute encode.
|
||||
assert worker.heavy_executor is not worker.light_executor
|
||||
assert worker.light_executor._max_workers >= 2
|
||||
|
||||
|
||||
class TestHeavyConcurrencyParsing:
|
||||
@pytest.mark.parametrize("val,expected", [
|
||||
("1", 1), ("2", 2), ("4", 4), # valid
|
||||
("0", 1), ("-3", 1), # too low → clamp up to 1
|
||||
("9", 4), # too high → clamp down to 4
|
||||
("abc", 1), ("", 1), # malformed → default 1
|
||||
])
|
||||
def test_clamped_to_sane_range(self, worker, val, expected):
|
||||
with patch.dict("os.environ", {"ENCODING_HEAVY_CONCURRENCY": val}):
|
||||
assert worker._heavy_concurrency() == expected
|
||||
|
||||
def test_missing_env_defaults_to_one(self, worker):
|
||||
import os
|
||||
with patch.dict(os.environ, {}, clear=False):
|
||||
os.environ.pop("ENCODING_HEAVY_CONCURRENCY", None)
|
||||
assert worker._heavy_concurrency() == 1
|
||||
|
||||
|
||||
class TestHeavyQueuePosition:
|
||||
def _reset_jobs(self, worker, entries):
|
||||
worker.jobs.clear()
|
||||
for job_id, kind, status in entries:
|
||||
worker.jobs[job_id] = {
|
||||
"job_id": job_id,
|
||||
"status": status,
|
||||
"progress": 0,
|
||||
"kind": kind,
|
||||
}
|
||||
|
||||
def test_orders_heavy_jobs_ignoring_previews_and_terminal(self, worker):
|
||||
# Insertion order == submission order (dict is ordered).
|
||||
self._reset_jobs(worker, [
|
||||
("e0done", "encode", "complete"), # terminal — not counted, position None
|
||||
("e1", "encode", "running"), # front of the lane
|
||||
("e2", "render", "pending"), # one heavy job (e1) ahead
|
||||
("p1", "preview", "running"), # light lane — never counted
|
||||
("e3", "encode", "pending"), # e1 + e2 ahead (preview + terminal excluded)
|
||||
])
|
||||
assert worker._heavy_queue_position("e0done") is None
|
||||
assert worker._heavy_queue_position("e1") == 0
|
||||
assert worker._heavy_queue_position("e2") == 1
|
||||
assert worker._heavy_queue_position("p1") is None
|
||||
assert worker._heavy_queue_position("e3") == 2
|
||||
|
||||
def test_preview_has_no_queue_position(self, worker):
|
||||
self._reset_jobs(worker, [("p1", "preview", "running")])
|
||||
assert worker._heavy_queue_position("p1") is None
|
||||
|
||||
def test_unknown_job_is_none(self, worker):
|
||||
worker.jobs.clear()
|
||||
assert worker._heavy_queue_position("nope") is None
|
||||
|
||||
|
||||
class TestJobStatusModel:
|
||||
def test_new_fields_present_and_optional(self, worker):
|
||||
# Old-shaped payloads still validate (fields default to None)...
|
||||
s = worker.JobStatus(job_id="j", status="running", progress=10)
|
||||
assert s.restart_failure_code is None
|
||||
assert s.queue_position is None
|
||||
# ...and the new fields round-trip.
|
||||
s2 = worker.JobStatus(
|
||||
job_id="j", status="failed", progress=0,
|
||||
restart_failure_code="encoding_worker_restart", queue_position=3,
|
||||
)
|
||||
assert s2.restart_failure_code == "encoding_worker_restart"
|
||||
assert s2.queue_position == 3
|
||||
|
||||
def test_extra_keys_like_kind_are_ignored(self, worker):
|
||||
# get_job_status spreads the whole job dict (which now carries "kind").
|
||||
s = worker.JobStatus(
|
||||
**{"job_id": "j", "status": "pending", "progress": 0, "kind": "encode"},
|
||||
queue_position=worker._heavy_queue_position("missing"),
|
||||
)
|
||||
assert s.status == "pending"
|
||||
|
||||
|
||||
_LATEST_WHEEL_URI = (
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.194.0-py3-none-any.whl"
|
||||
)
|
||||
|
||||
|
||||
def _fake_subprocess(counter):
|
||||
"""subprocess.run stub that dispatches by command and counts cp/pip calls."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
def _run(cmd, **kwargs):
|
||||
head = cmd[:2]
|
||||
if head == ["gsutil", "ls"]:
|
||||
return SimpleNamespace(returncode=0, stdout=_LATEST_WHEEL_URI + "\n", stderr="")
|
||||
if head == ["gsutil", "cp"]:
|
||||
counter["cp"] += 1
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
if "pip" in cmd:
|
||||
counter["pip"] += 1
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||
|
||||
return _run
|
||||
|
||||
|
||||
class TestEnsureLatestWheelConcurrency:
|
||||
"""ensure_latest_wheel must be idempotent + race-free: it runs on the light
|
||||
lane (>1 thread) at the start of every job, so concurrent calls used to
|
||||
clobber the shared /tmp wheel path and venv (incident 2026-08-15, 374dec26)."""
|
||||
|
||||
def test_fast_path_when_already_verified_this_process(self, worker):
|
||||
worker._verified_wheel_version = "0.194.0"
|
||||
counter = {"cp": 0, "pip": 0}
|
||||
with patch.object(worker.subprocess, "run", _fake_subprocess(counter)), \
|
||||
patch.object(worker, "verify_wheel_imports", return_value=True) as vwi:
|
||||
assert worker.ensure_latest_wheel() is True
|
||||
assert counter == {"cp": 0, "pip": 0} # no download, no install
|
||||
vwi.assert_not_called() # no reverify either
|
||||
|
||||
def test_installed_version_verifies_without_reinstall(self, worker):
|
||||
worker._verified_wheel_version = None
|
||||
counter = {"cp": 0, "pip": 0}
|
||||
with patch.object(worker.subprocess, "run", _fake_subprocess(counter)), \
|
||||
patch.object(worker, "_installed_karaoke_gen_version", return_value="0.194.0"), \
|
||||
patch.object(worker, "verify_wheel_imports", return_value=True):
|
||||
assert worker.ensure_latest_wheel() is True
|
||||
# Right version already present → verify only, no cp/pip.
|
||||
assert counter == {"cp": 0, "pip": 0}
|
||||
assert worker._verified_wheel_version == "0.194.0"
|
||||
|
||||
def test_installs_when_version_differs(self, worker):
|
||||
worker._verified_wheel_version = None
|
||||
counter = {"cp": 0, "pip": 0}
|
||||
with patch.object(worker.subprocess, "run", _fake_subprocess(counter)), \
|
||||
patch.object(worker, "_installed_karaoke_gen_version", return_value="0.193.0"), \
|
||||
patch.object(worker, "verify_wheel_imports", return_value=True):
|
||||
assert worker.ensure_latest_wheel() is True
|
||||
assert counter["cp"] == 1 and counter["pip"] >= 1
|
||||
assert worker._verified_wheel_version == "0.194.0"
|
||||
|
||||
def test_concurrent_calls_install_at_most_once(self, worker):
|
||||
"""The lock + version cache guarantee only ONE thread installs even when
|
||||
several race in on a fresh boot; the rest hit the verified fast path."""
|
||||
import threading
|
||||
import time
|
||||
|
||||
worker._verified_wheel_version = None
|
||||
counter = {"cp": 0, "pip": 0}
|
||||
base = _fake_subprocess(counter)
|
||||
|
||||
def slow_run(cmd, **kwargs):
|
||||
if cmd[:2] == ["gsutil", "cp"]:
|
||||
time.sleep(0.2) # widen the race window
|
||||
return base(cmd, **kwargs)
|
||||
|
||||
results = []
|
||||
barrier = threading.Barrier(3)
|
||||
|
||||
def call():
|
||||
barrier.wait()
|
||||
results.append(worker.ensure_latest_wheel())
|
||||
|
||||
with patch.object(worker.subprocess, "run", slow_run), \
|
||||
patch.object(worker, "_installed_karaoke_gen_version", return_value="0.193.0"), \
|
||||
patch.object(worker, "verify_wheel_imports", return_value=True):
|
||||
threads = [threading.Thread(target=call) for _ in range(3)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert results == [True, True, True]
|
||||
assert counter["cp"] == 1 # exactly one download despite 3 concurrent callers
|
||||
assert counter["pip"] == 1 # and exactly one install (no concurrent venv writes)
|
||||
@@ -555,181 +555,3 @@ class TestScreenVideoStaging:
|
||||
|
||||
assert (outputs / "Artist - Title (Title).mov").is_file()
|
||||
assert not (outputs / "Artist - Title (End).mov").exists()
|
||||
|
||||
|
||||
class TestEnsureLatestWheelVerification:
|
||||
"""Test ensure_latest_wheel() install-retry + import-verification behavior.
|
||||
|
||||
Regression: a freshly-provisioned worker installs the wheel with --no-deps
|
||||
at boot and relies on ensure_latest_wheel() to install the full dependency
|
||||
tree at the first job. A transient/partial install could leave the env
|
||||
importable-but-broken (`pip` exits 0 while `tenacity` is still missing),
|
||||
and the return value was ignored, so the job proceeded and died with
|
||||
"No module named 'tenacity'" deep inside render_video.
|
||||
|
||||
Fix: verify the render/encode import chain (via subprocess) and only return
|
||||
True when it imports; retry a failed/partial install; callers fail fast.
|
||||
"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_wheel_cache(self, monkeypatch):
|
||||
"""ensure_latest_wheel caches the verified version in a module global and
|
||||
can fast-path when the installed version already matches. Reset the cache
|
||||
and pin the "installed" version to None around each test so these
|
||||
download/install-flow tests run deterministically regardless of the test
|
||||
venv's real karaoke-gen version."""
|
||||
from backend.services.gce_encoding import main
|
||||
main._verified_wheel_version = None
|
||||
monkeypatch.setattr(main, "_installed_karaoke_gen_version", lambda: None)
|
||||
yield
|
||||
main._verified_wheel_version = None
|
||||
|
||||
# A couple of versioned wheels plus the (filtered-out) current wheel, as
|
||||
# `gsutil ls` would emit them.
|
||||
DEFAULT_LS = (
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.5-py3-none-any.whl\n"
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.6-py3-none-any.whl\n"
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl\n"
|
||||
)
|
||||
|
||||
def _completed(self, returncode=0, stdout="", stderr=""):
|
||||
import subprocess
|
||||
return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)
|
||||
|
||||
def _side_effect(self, ls_stdout=None, ls_rc=0, cp_rc=0, install_rc=0, verify_results=None):
|
||||
"""Build a subprocess.run side_effect keyed on the command.
|
||||
|
||||
Models the download flow (gsutil ls -> gsutil cp of a single wheel),
|
||||
the pip install, and the import-verification subprocess.
|
||||
|
||||
verify_results: list of booleans consumed in order, one per verify call
|
||||
(True -> returncode 0). Lets a test model "install succeeded but imports
|
||||
fail, then a retry fixes them".
|
||||
"""
|
||||
import sys
|
||||
ls = self.DEFAULT_LS if ls_stdout is None else ls_stdout
|
||||
verify_iter = iter(verify_results or [])
|
||||
|
||||
def side_effect(cmd, *args, **kwargs):
|
||||
if cmd and cmd[0] == "gsutil" and cmd[1] == "ls":
|
||||
return self._completed(returncode=ls_rc, stdout=ls)
|
||||
if cmd and cmd[0] == "gsutil" and cmd[1] == "cp":
|
||||
return self._completed(returncode=cp_rc)
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-m":
|
||||
# pip install ...
|
||||
return self._completed(returncode=install_rc)
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-c":
|
||||
# import verification subprocess
|
||||
ok = next(verify_iter, False)
|
||||
return self._completed(
|
||||
returncode=0 if ok else 1,
|
||||
stderr="" if ok else "ModuleNotFoundError: No module named 'tenacity'",
|
||||
)
|
||||
return self._completed(returncode=0)
|
||||
|
||||
return side_effect
|
||||
|
||||
def test_downloads_only_latest_single_wheel(self, monkeypatch):
|
||||
"""Must `gsutil cp` exactly one wheel (the latest version), not the whole dir."""
|
||||
from backend.services.gce_encoding import main
|
||||
|
||||
cp_targets = []
|
||||
base = self._side_effect(verify_results=[True])
|
||||
|
||||
def spy(cmd, *args, **kwargs):
|
||||
if cmd and cmd[0] == "gsutil" and cmd[1] == "cp":
|
||||
cp_targets.append(cmd[2])
|
||||
return base(cmd, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(main.subprocess, "run", spy)
|
||||
|
||||
assert main.ensure_latest_wheel() is True
|
||||
assert cp_targets == [
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.6-py3-none-any.whl"
|
||||
]
|
||||
|
||||
def test_returns_true_when_install_and_imports_succeed(self, monkeypatch):
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(verify_results=[True]))
|
||||
assert main.ensure_latest_wheel() is True
|
||||
|
||||
def test_returns_false_when_pip_ok_but_imports_broken(self, monkeypatch):
|
||||
"""The core regression: pip exits 0 but a dependency is missing."""
|
||||
from backend.services.gce_encoding import main
|
||||
# install always "succeeds", verification always fails -> not ready.
|
||||
monkeypatch.setattr(main.subprocess, "run",
|
||||
self._side_effect(install_rc=0, verify_results=[False, False, False]))
|
||||
assert main.ensure_latest_wheel() is False
|
||||
|
||||
def test_retries_and_succeeds_after_partial_install(self, monkeypatch):
|
||||
"""First attempt leaves deps missing; a retry completes them."""
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(verify_results=[False, True]))
|
||||
assert main.ensure_latest_wheel() is True
|
||||
|
||||
def test_returns_false_when_no_wheel_found(self, monkeypatch):
|
||||
"""Only the current wheel exists (filtered out) -> no versioned wheel."""
|
||||
from backend.services.gce_encoding import main
|
||||
only_current = "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl\n"
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(ls_stdout=only_current))
|
||||
assert main.ensure_latest_wheel() is False
|
||||
|
||||
def test_returns_false_when_download_fails(self, monkeypatch):
|
||||
"""A failed single-wheel copy is reported, not silently installed."""
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(cp_rc=1))
|
||||
assert main.ensure_latest_wheel() is False
|
||||
|
||||
def test_install_timeout_then_success(self, monkeypatch):
|
||||
"""A timed-out first install must not abort the whole routine."""
|
||||
import sys
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
|
||||
state = {"install_calls": 0}
|
||||
base = self._side_effect()
|
||||
|
||||
def side_effect(cmd, *args, **kwargs):
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-m":
|
||||
state["install_calls"] += 1
|
||||
if state["install_calls"] == 1:
|
||||
raise subprocess.TimeoutExpired(cmd, main.WHEEL_INSTALL_TIMEOUT)
|
||||
return self._completed(returncode=0)
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-c":
|
||||
# Imports fail after the timed-out first install, succeed after retry.
|
||||
return self._completed(returncode=0 if state["install_calls"] >= 2 else 1,
|
||||
stderr="ModuleNotFoundError")
|
||||
return base(cmd, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(main.subprocess, "run", side_effect)
|
||||
assert main.ensure_latest_wheel() is True
|
||||
|
||||
|
||||
class TestVerifyWheelImports:
|
||||
"""Test the verify_wheel_imports() helper in isolation."""
|
||||
|
||||
def test_true_on_clean_import(self, monkeypatch):
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run",
|
||||
lambda *a, **k: subprocess.CompletedProcess([], 0, "", ""))
|
||||
assert main.verify_wheel_imports() is True
|
||||
|
||||
def test_false_on_import_error(self, monkeypatch):
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(
|
||||
main.subprocess, "run",
|
||||
lambda *a, **k: subprocess.CompletedProcess(
|
||||
[], 1, "", "ModuleNotFoundError: No module named 'tenacity'"))
|
||||
assert main.verify_wheel_imports() is False
|
||||
|
||||
def test_false_on_timeout(self, monkeypatch):
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
|
||||
def _timeout(*a, **k):
|
||||
raise subprocess.TimeoutExpired(["python", "-c"], 180)
|
||||
|
||||
monkeypatch.setattr(main.subprocess, "run", _timeout)
|
||||
assert main.verify_wheel_imports() is False
|
||||
@@ -171,7 +171,7 @@ class TestLocalEncodingServiceEncodingMethods:
|
||||
|
||||
@patch.object(LocalEncodingService, "_execute_command_with_fallback")
|
||||
def test_convert_mov_to_mp4(self, mock_execute):
|
||||
"""Test MOV to MP4 conversion produces a standard, portable "With Vocals" mp4."""
|
||||
"""Test MOV to MP4 conversion."""
|
||||
mock_execute.return_value = True
|
||||
|
||||
service = LocalEncodingService()
|
||||
@@ -182,19 +182,6 @@ class TestLocalEncodingServiceEncodingMethods:
|
||||
|
||||
assert result is True
|
||||
mock_execute.assert_called_once()
|
||||
gpu_command, cpu_command = mock_execute.call_args[0][0], mock_execute.call_args[0][1]
|
||||
# The CPU (software) command is what runs on prod encoding workers (no NVENC).
|
||||
# It must normalize 4:4:4 -> 4:2:0 for playback compatibility, use a fast preset
|
||||
# (this is the longest finalization stage), and emit portable AAC (not FLAC-in-mp4).
|
||||
assert "-pix_fmt yuv420p" in cpu_command
|
||||
assert "-preset veryfast" in cpu_command
|
||||
assert "-c:a aac" in cpu_command
|
||||
assert "-b:a 320k" in cpu_command
|
||||
assert "-c:a copy" not in cpu_command # regression guard: no FLAC-in-mp4
|
||||
# GPU path also forces 4:2:0 (h264_nvenc can preserve yuv444p) and emits AAC.
|
||||
assert "-pix_fmt yuv420p" in gpu_command
|
||||
assert "-c:a aac" in gpu_command
|
||||
assert "-b:a 320k" in gpu_command
|
||||
|
||||
@patch.object(LocalEncodingService, "_execute_command_with_fallback")
|
||||
def test_encode_lossless_mp4_without_end(self, mock_execute):
|
||||
|
||||
@@ -266,37 +266,6 @@ 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."""
|
||||
|
||||
@@ -1788,179 +1757,6 @@ 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:
|
||||
"""
|
||||
|
||||
@@ -1132,103 +1132,3 @@ class TestGetPreviewVideoRedirect:
|
||||
self._call(mock_storage)
|
||||
assert exc_info.value.status_code == 404
|
||||
mock_storage.generate_signed_url.assert_not_called()
|
||||
|
||||
|
||||
class TestGetVocalsAudio:
|
||||
"""The vocals waveform endpoint proxies the full vocal stem for the timeline.
|
||||
|
||||
Two behaviours: (1) select the fullest vocal mix (vocals_clean) — real jobs
|
||||
never store a plain 'vocals' key, they store vocals_clean / lead_vocals /
|
||||
backing_vocals. (2) Return the bytes directly (not a 302 to GCS): the
|
||||
waveform fetch()es + decodeAudioData()s the audio, and a cross-origin
|
||||
redirect makes the browser send `Origin: null` which the bucket CORS rejects,
|
||||
so the waveform never loads.
|
||||
"""
|
||||
|
||||
def _call(self, stems, audio_complete=True):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _stream_audio
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
job.file_urls = {"stems": stems}
|
||||
job.state_data = {"audio_complete": audio_complete}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
transcoding = MagicMock()
|
||||
transcoding.get_review_audio_bytes_async = AsyncMock(
|
||||
return_value=(b"OggS-fake-vocals-bytes", "audio/ogg")
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=transcoding,
|
||||
):
|
||||
resp = asyncio.run(
|
||||
_stream_audio(job_id="j", stem="vocals")
|
||||
)
|
||||
return resp, transcoding
|
||||
|
||||
def test_proxies_bytes_not_redirect(self):
|
||||
from starlette.responses import RedirectResponse, Response
|
||||
|
||||
resp, _ = self._call({"vocals_clean": "jobs/j/stems/vocals_clean.flac"})
|
||||
|
||||
# Must serve the bytes from the API (CORS-friendly), never 302 to GCS.
|
||||
assert not isinstance(resp, RedirectResponse)
|
||||
assert isinstance(resp, Response)
|
||||
assert resp.status_code == 200
|
||||
assert resp.media_type == "audio/ogg"
|
||||
assert resp.body == b"OggS-fake-vocals-bytes"
|
||||
|
||||
def test_selects_vocals_clean_when_no_plain_vocals_key(self):
|
||||
# The shape produced by real cloud jobs (no plain "vocals").
|
||||
_, transcoding = self._call(
|
||||
{
|
||||
"instrumental_clean": "jobs/j/stems/instrumental_clean.flac",
|
||||
"vocals_clean": "jobs/j/stems/vocals_clean.flac",
|
||||
"lead_vocals": "jobs/j/stems/lead_vocals.flac",
|
||||
"backing_vocals": "jobs/j/stems/backing_vocals.flac",
|
||||
}
|
||||
)
|
||||
# Must pick the full vocal mix (vocals_clean), not lead_vocals or KeyError.
|
||||
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/vocals_clean.flac"
|
||||
|
||||
def test_prefers_plain_vocals_then_falls_back_to_lead(self):
|
||||
# 2-stem split exposes a plain "vocals" — preferred.
|
||||
_, transcoding = self._call({"vocals": "jobs/j/stems/vocals.flac"})
|
||||
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/vocals.flac"
|
||||
|
||||
# Only lead_vocals available — last-resort fallback.
|
||||
_, transcoding = self._call({"lead_vocals": "jobs/j/stems/lead_vocals.flac"})
|
||||
assert transcoding.get_review_audio_bytes_async.call_args[0][0] == "jobs/j/stems/lead_vocals.flac"
|
||||
|
||||
def test_404_when_no_vocal_stem_present(self):
|
||||
"""audio_complete=True + no vocal stem = the stem will never exist -> 404."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._call({"instrumental_clean": "jobs/j/stems/instrumental_clean.flac"})
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_202_when_separation_still_in_progress(self):
|
||||
"""Users can open lyrics review before audio separation finishes (it's
|
||||
decoupled from the critical path), so a missing vocal stem while
|
||||
audio_complete=False means "not yet" — return 202 so the frontend polls
|
||||
instead of permanently hiding the waveform on a terminal 404."""
|
||||
resp, transcoding = self._call({}, audio_complete=False)
|
||||
|
||||
assert resp.status_code == 202
|
||||
assert resp.headers.get("Retry-After") == "15"
|
||||
transcoding.get_review_audio_bytes_async.assert_not_called()
|
||||
|
||||
def test_404_when_separation_skipped_and_no_vocal_stem(self):
|
||||
"""Existing-instrumental jobs set audio_complete=True without ever
|
||||
producing vocal stems — must 404 (terminal), not 202 (retry forever)."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._call({}, audio_complete=True)
|
||||
assert exc_info.value.status_code == 404
|
||||
@@ -206,34 +206,9 @@ class TestStorageServiceDownload:
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
service.download_file("missing/file.flac", "/local/path")
|
||||
|
||||
|
||||
assert "File not found" in str(exc_info.value)
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_download_file_missing_reraises_notfound(self, mock_settings, mock_client_class):
|
||||
"""A 404 from GCS re-raises NotFound (so callers can map it to HTTP 404)
|
||||
and is logged at warning, not error, to avoid tripping the error-monitor."""
|
||||
from google.cloud.exceptions import NotFound
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
|
||||
mock_blob = Mock()
|
||||
mock_blob.download_to_filename.side_effect = NotFound("No such object")
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client = Mock()
|
||||
mock_client.bucket.return_value = mock_bucket
|
||||
mock_client_class.return_value = mock_client
|
||||
|
||||
service = StorageService()
|
||||
with patch("backend.services.storage_service.logger") as mock_logger:
|
||||
with pytest.raises(NotFound):
|
||||
service.download_file("jobs/abc/finals/lossy_4k_mp4.mp4", "/local/path")
|
||||
mock_logger.error.assert_not_called()
|
||||
mock_logger.warning.assert_called_once()
|
||||
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_download_json(self, mock_settings, mock_client_class):
|
||||
|
||||
@@ -51,12 +51,6 @@ 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
|
||||
|
||||
|
||||
@@ -140,7 +134,6 @@ 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), \
|
||||
@@ -162,46 +155,3 @@ 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"
|
||||
@@ -11,28 +11,6 @@ from backend.models.user import VerifyMagicLinkResponse, UserPublic
|
||||
from backend.services.auth_service import AuthResult, AuthService, UserType
|
||||
|
||||
|
||||
def _sent_fields(call_args):
|
||||
"""Extract the sent email's fields regardless of positional/keyword call style.
|
||||
|
||||
Sends now flow through EmailService._log_and_send, which invokes the provider
|
||||
with keyword args; older direct calls used positionals. Read both.
|
||||
"""
|
||||
args, kwargs = call_args.args, call_args.kwargs
|
||||
|
||||
def pick(name, idx):
|
||||
if name in kwargs:
|
||||
return kwargs[name]
|
||||
return args[idx] if len(args) > idx else None
|
||||
|
||||
return {
|
||||
"to_email": pick("to_email", 0),
|
||||
"subject": pick("subject", 1),
|
||||
"html_content": pick("html_content", 2),
|
||||
"text_content": pick("text_content", 3),
|
||||
"from_email_override": kwargs.get("from_email_override"),
|
||||
}
|
||||
|
||||
|
||||
class TestTenantConfigGetFrontendUrl:
|
||||
"""Tests for TenantConfig.get_frontend_url()."""
|
||||
|
||||
@@ -69,10 +47,10 @@ class TestSendMagicLinkTenantParams:
|
||||
"""Without tenant params, email uses default Nomad Karaoke branding."""
|
||||
email_service.send_magic_link("user@test.com", "abc123")
|
||||
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
subject = f["subject"]
|
||||
html_content = f["html_content"]
|
||||
text_content = f["text_content"]
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert subject == "Sign in to Nomad Karaoke"
|
||||
assert "Nomad Karaoke" in html_content
|
||||
@@ -88,9 +66,9 @@ class TestSendMagicLinkTenantParams:
|
||||
tenant_frontend_url="https://vocalstar.nomadkaraoke.com",
|
||||
)
|
||||
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
html_content = f["html_content"]
|
||||
text_content = f["text_content"]
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in html_content
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=abc123" in text_content
|
||||
@@ -105,10 +83,10 @@ class TestSendMagicLinkTenantParams:
|
||||
tenant_name="Vocal Star",
|
||||
)
|
||||
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
subject = f["subject"]
|
||||
html_content = f["html_content"]
|
||||
text_content = f["text_content"]
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
text_content = call_args[0][3]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "Vocal Star" in html_content
|
||||
@@ -122,7 +100,8 @@ class TestSendMagicLinkTenantParams:
|
||||
tenant_name='<script>alert("xss")</script>',
|
||||
)
|
||||
|
||||
html_content = _sent_fields(email_service.provider.send_email.call_args)["html_content"]
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
html_content = call_args[0][2]
|
||||
|
||||
# Should be escaped in HTML
|
||||
assert "<script>" not in html_content
|
||||
@@ -140,14 +119,14 @@ class TestSendMagicLinkTenantParams:
|
||||
|
||||
assert result is True
|
||||
|
||||
f = _sent_fields(email_service.provider.send_email.call_args)
|
||||
subject = f["subject"]
|
||||
html_content = f["html_content"]
|
||||
call_args = email_service.provider.send_email.call_args
|
||||
subject = call_args[0][1]
|
||||
html_content = call_args[0][2]
|
||||
|
||||
assert subject == "Sign in to Vocal Star"
|
||||
assert "https://vocalstar.nomadkaraoke.com/en/auth/verify?token=token123" in html_content
|
||||
# Check sender email override was passed through
|
||||
assert f["from_email_override"] == "vocalstar@nomadkaraoke.com"
|
||||
assert call_args[1]["from_email_override"] == "vocalstar@nomadkaraoke.com"
|
||||
|
||||
|
||||
class TestVerifyMagicLinkResponseTenantSubdomain:
|
||||
|
||||
@@ -21,7 +21,6 @@ from backend.workers.video_worker_orchestrator import (
|
||||
VideoWorkerOrchestrator,
|
||||
create_orchestrator_config_from_job,
|
||||
)
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
|
||||
class TestOrchestratorConfig:
|
||||
@@ -2133,52 +2132,3 @@ class TestOriginalVocalsGuideEmit:
|
||||
|
||||
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
|
||||
assert await orch._resolve_intro_seconds() == 8.0
|
||||
|
||||
|
||||
class TestRedistributeModeProgress:
|
||||
"""redistribute_mode must not attempt job status transitions.
|
||||
|
||||
Regression for the public->private data-loss bug: redistributing an already
|
||||
`complete` job drove `_update_progress(PACKAGING)`, which raised
|
||||
InvalidStateTransitionError (`complete -> packaging`) and aborted the
|
||||
redistribution after the public outputs had already been deleted.
|
||||
"""
|
||||
|
||||
def _config(self, redistribute_mode):
|
||||
return OrchestratorConfig(
|
||||
job_id="job-1",
|
||||
artist="A",
|
||||
title="T",
|
||||
title_video_path="",
|
||||
karaoke_video_path="",
|
||||
instrumental_audio_path="",
|
||||
redistribute_mode=redistribute_mode,
|
||||
)
|
||||
|
||||
def test_redistribute_mode_skips_status_transition(self):
|
||||
jm = MagicMock()
|
||||
orch = VideoWorkerOrchestrator(
|
||||
config=self._config(redistribute_mode=True),
|
||||
job_manager=jm,
|
||||
storage=MagicMock(),
|
||||
job_logger=MagicMock(),
|
||||
)
|
||||
|
||||
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
|
||||
|
||||
jm.transition_to_state.assert_not_called()
|
||||
jm.update_job.assert_called_once_with("job-1", {"progress": 90})
|
||||
|
||||
def test_normal_mode_drives_status_transition(self):
|
||||
jm = MagicMock()
|
||||
orch = VideoWorkerOrchestrator(
|
||||
config=self._config(redistribute_mode=False),
|
||||
job_manager=jm,
|
||||
storage=MagicMock(),
|
||||
job_logger=MagicMock(),
|
||||
)
|
||||
|
||||
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
|
||||
|
||||
jm.transition_to_state.assert_called_once()
|
||||
jm.update_job.assert_not_called()
|
||||
@@ -816,46 +816,20 @@ 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 loudly (no local yt-dlp fallback)."""
|
||||
"""A URL job with no GCS file must fail (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:
|
||||
# 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
|
||||
)
|
||||
result = await download_audio(
|
||||
"test123",
|
||||
temp_dir,
|
||||
mock_storage,
|
||||
mock_job_with_url,
|
||||
job_manager_instance=mock_job_manager
|
||||
)
|
||||
|
||||
# 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,
|
||||
)
|
||||
# Refuses to download locally → returns None, never touches storage
|
||||
assert result is None
|
||||
mock_storage.download_file.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -176,25 +176,3 @@ 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()
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"authError": "Authentication error: no user identity available",
|
||||
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
|
||||
"notFound": "Job not found",
|
||||
"fileNoLongerAvailable": "File no longer available",
|
||||
"noPermissionAccess": "You don't have permission to access this job",
|
||||
"noPermissionEdit": "You don't have permission to edit this job",
|
||||
"noPermissionDelete": "You don't have permission to delete this job",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection غير صالح. يجب أن يكون واحدًا من: {valid_selections}",
|
||||
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
|
||||
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
|
||||
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}",
|
||||
"fileNoLongerAvailable": "الملف لم يعد متاحاً"
|
||||
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "المهمة غير موجودة",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection no vàlid. Ha de ser un de: {valid_selections}",
|
||||
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
|
||||
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
|
||||
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}",
|
||||
"fileNoLongerAvailable": "El fitxer ja no està disponible"
|
||||
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tasca no trobada",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Neplatné instrumental_selection. Musí být jedno z: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
|
||||
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}",
|
||||
"fileNoLongerAvailable": "Soubor již není dostupný"
|
||||
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha nebyla nalezena",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Skal være en af: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
|
||||
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig"
|
||||
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet blev ikke fundet",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
|
||||
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}",
|
||||
"fileNoLongerAvailable": "Datei nicht mehr verfügbar"
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Μη έγκυρο instrumental_selection. Πρέπει να είναι ένα από τα: {valid_selections}",
|
||||
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
|
||||
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
|
||||
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}",
|
||||
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο"
|
||||
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Η εργασία δεν βρέθηκε",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"authError": "Authentication error: no user identity available",
|
||||
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
|
||||
"notFound": "Job not found",
|
||||
"fileNoLongerAvailable": "File no longer available",
|
||||
"noPermissionAccess": "You don't have permission to access this job",
|
||||
"noPermissionEdit": "You don't have permission to edit this job",
|
||||
"noPermissionDelete": "You don't have permission to delete this job",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
|
||||
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}",
|
||||
"fileNoLongerAvailable": "El archivo ya no está disponible"
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Virheellinen instrumental_selection. Täytyy olla jokin näistä: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
|
||||
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
|
||||
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}",
|
||||
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla"
|
||||
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Työtä ei löytynyt",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection invalide. Doit être l'un de : {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
|
||||
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
|
||||
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}",
|
||||
"fileNoLongerAvailable": "Le fichier n'est plus disponible"
|
||||
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tâche introuvable",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "בחירת instrumental_selection לא חוקית. חייב להיות אחד מ: {valid_selections}",
|
||||
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
|
||||
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
|
||||
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}",
|
||||
"fileNoLongerAvailable": "הקובץ אינו זמין יותר"
|
||||
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "המשימה לא נמצאה",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "अमान्य instrumental_selection। इनमें से एक होना चाहिए: {valid_selections}",
|
||||
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
|
||||
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
|
||||
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}",
|
||||
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है"
|
||||
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "जॉब नहीं मिली",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Nevažeći instrumental_selection. Mora biti jedno od: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
|
||||
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
|
||||
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}",
|
||||
"fileNoLongerAvailable": "Datoteka više nije dostupna"
|
||||
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Zadatak nije pronađen",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Érvénytelen instrumental_selection. A következők egyike kell legyen: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
|
||||
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
|
||||
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}",
|
||||
"fileNoLongerAvailable": "A fájl már nem elérhető"
|
||||
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "A feladat nem található",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection tidak valid. Harus salah satu dari: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
|
||||
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
|
||||
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}",
|
||||
"fileNoLongerAvailable": "File sudah tidak tersedia"
|
||||
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugas tidak ditemukan",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection non valido. Deve essere uno tra: {valid_selections}",
|
||||
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
|
||||
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
|
||||
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}",
|
||||
"fileNoLongerAvailable": "File non più disponibile"
|
||||
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Lavoro non trovato",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "無効な instrumental_selection です。次のいずれかである必要があります: {valid_selections}",
|
||||
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
|
||||
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
|
||||
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}",
|
||||
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました"
|
||||
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ジョブが見つかりません",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "잘못된 instrumental_selection입니다. 다음 중 하나여야 합니다: {valid_selections}",
|
||||
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
|
||||
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
|
||||
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}",
|
||||
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다"
|
||||
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "작업을 찾을 수 없습니다",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection tidak sah. Mesti salah satu daripada: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
|
||||
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
|
||||
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}",
|
||||
"fileNoLongerAvailable": "Fail tidak lagi tersedia"
|
||||
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugasan tidak dijumpai",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Må være en av: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering startet.",
|
||||
"instrumentalSelectionError": "Feil ved valg av instrumental for jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig"
|
||||
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobben ble ikke funnet",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Ongeldige instrumental_selection. Moet een van de volgende zijn: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental geselecteerd. Videogeneratie is gestart.",
|
||||
"instrumentalSelectionError": "Fout bij het selecteren van instrumental voor taak {job_id}: {error}",
|
||||
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}",
|
||||
"fileNoLongerAvailable": "Bestand niet meer beschikbaar"
|
||||
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Taak niet gevonden",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Nieprawidłowe instrumental_selection. Musi to być jedno z: {valid_selections}",
|
||||
"instrumentalSelected": "Wybrano podkład. Rozpoczęto generowanie wideo.",
|
||||
"instrumentalSelectionError": "Błąd podczas wybierania podkładu dla zadania {job_id}: {error}",
|
||||
"downloadUrlsError": "Błąd podczas pobierania linków: {error}",
|
||||
"fileNoLongerAvailable": "Plik nie jest już dostępny"
|
||||
"downloadUrlsError": "Błąd podczas pobierania linków: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Nie znaleziono zadania",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection inválido. Deve ser um de: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selecionado. Geração de vídeo iniciada.",
|
||||
"instrumentalSelectionError": "Erro ao selecionar instrumental para o job {job_id}: {error}",
|
||||
"downloadUrlsError": "Erro ao obter URLs de download: {error}",
|
||||
"fileNoLongerAvailable": "O arquivo não está mais disponível"
|
||||
"downloadUrlsError": "Erro ao obter URLs de download: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job não encontrado",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection invalid. Trebuie să fie unul dintre: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selectat. A început generarea videoclipului.",
|
||||
"instrumentalSelectionError": "Eroare la selectarea instrumentalului pentru jobul {job_id}: {error}",
|
||||
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}",
|
||||
"fileNoLongerAvailable": "Fișierul nu mai este disponibil"
|
||||
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobul nu a fost găsit",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Недопустимый instrumental_selection. Должно быть одно из: {valid_selections}",
|
||||
"instrumentalSelected": "Инструментал выбран. Началась генерация видео.",
|
||||
"instrumentalSelectionError": "Ошибка при выборе инструментала для задачи {job_id}: {error}",
|
||||
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}",
|
||||
"fileNoLongerAvailable": "Файл больше недоступен"
|
||||
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Задача не найдена",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Neplatný výber inštrumentálu. Musí byť jeden z: {valid_selections}",
|
||||
"instrumentalSelected": "Inštrumentál bol vybraný. Začalo sa generovanie videa.",
|
||||
"instrumentalSelectionError": "Chyba pri výbere inštrumentálu pre úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}",
|
||||
"fileNoLongerAvailable": "Súbor už nie je dostupný"
|
||||
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha sa nenašla",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Ogiltigt instrumental_selection. Måste vara en av: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental vald. Videogenereringen har startat.",
|
||||
"instrumentalSelectionError": "Fel vid val av instrumental för jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}",
|
||||
"fileNoLongerAvailable": "Filen är inte längre tillgänglig"
|
||||
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet hittades inte",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection ไม่ถูกต้อง ต้องเป็นหนึ่งใน: {valid_selections}",
|
||||
"instrumentalSelected": "เลือกดนตรีบรรเลงแล้ว กำลังเริ่มสร้างวิดีโอ",
|
||||
"instrumentalSelectionError": "เกิดข้อผิดพลาดในการเลือกดนตรีบรรเลงสำหรับงาน {job_id}: {error}",
|
||||
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}",
|
||||
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว"
|
||||
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ไม่พบงาน",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Mali ang instrumental_selection. Dapat isa sa: {valid_selections}",
|
||||
"instrumentalSelected": "Napili na ang instrumental. Nagsimula na ang paggawa ng video.",
|
||||
"instrumentalSelectionError": "Error sa pagpili ng instrumental para sa job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}",
|
||||
"fileNoLongerAvailable": "Hindi na available ang file"
|
||||
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Hindi nahanap ang job",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Geçersiz instrumental_selection. Şunlardan biri olmalıdır: {valid_selections}",
|
||||
"instrumentalSelected": "Enstrümantal seçildi. Video oluşturma başladı.",
|
||||
"instrumentalSelectionError": "{job_id} işi için enstrümantal seçme hatası: {error}",
|
||||
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}",
|
||||
"fileNoLongerAvailable": "Dosya artık mevcut değil"
|
||||
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "İş bulunamadı",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "Недійсний instrumental_selection. Має бути одним із: {valid_selections}",
|
||||
"instrumentalSelected": "Інструментал вибрано. Розпочато генерацію відео.",
|
||||
"instrumentalSelectionError": "Помилка вибору інструменталу для завдання {job_id}: {error}",
|
||||
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}",
|
||||
"fileNoLongerAvailable": "Файл більше недоступний"
|
||||
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Завдання не знайдено",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection không hợp lệ. Phải là một trong: {valid_selections}",
|
||||
"instrumentalSelected": "Đã chọn nhạc nền. Đã bắt đầu tạo video.",
|
||||
"instrumentalSelectionError": "Lỗi khi chọn nhạc nền cho công việc {job_id}: {error}",
|
||||
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}",
|
||||
"fileNoLongerAvailable": "Tệp không còn khả dụng"
|
||||
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Không tìm thấy công việc",
|
||||
|
||||
@@ -47,8 +47,7 @@
|
||||
"invalidInstrumentalSelection": "无效的 instrumental_selection。必须是以下之一:{valid_selections}",
|
||||
"instrumentalSelected": "已选择伴奏。已开始生成视频。",
|
||||
"instrumentalSelectionError": "为任务 {job_id} 选择伴奏时出错:{error}",
|
||||
"downloadUrlsError": "获取下载 URL 时出错:{error}",
|
||||
"fileNoLongerAvailable": "文件已不可用"
|
||||
"downloadUrlsError": "获取下载 URL 时出错:{error}"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "未找到任务",
|
||||
|
||||
@@ -24,7 +24,6 @@ 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
|
||||
@@ -214,9 +213,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")
|
||||
@@ -364,16 +363,6 @@ 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)
|
||||
@@ -407,7 +396,7 @@ async def download_audio(
|
||||
storage: StorageService,
|
||||
job,
|
||||
job_manager_instance: JobManager = None
|
||||
) -> str:
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Fetch the job's audio file from GCS to a local temp directory.
|
||||
|
||||
@@ -425,14 +414,9 @@ 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 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.
|
||||
Path to downloaded audio file, or None if failed
|
||||
"""
|
||||
try:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
@@ -480,22 +464,14 @@ async def download_audio(
|
||||
"fetched via the flacfetch service before processing; refusing to "
|
||||
"download locally."
|
||||
)
|
||||
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."
|
||||
)
|
||||
return None
|
||||
|
||||
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
|
||||
raise DownloadError(
|
||||
"No input audio source found for this job (no GCS path and no file_urls)."
|
||||
)
|
||||
|
||||
except DownloadError:
|
||||
raise
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
|
||||
raise DownloadError(f"Failed to download audio from storage: {e}") from e
|
||||
return None
|
||||
|
||||
|
||||
async def upload_separation_results(
|
||||
|
||||
@@ -31,7 +31,6 @@ 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
|
||||
@@ -303,9 +302,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))
|
||||
|
||||
@@ -553,17 +552,6 @@ 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)
|
||||
@@ -599,14 +587,13 @@ async def download_audio(
|
||||
job,
|
||||
job_manager: JobManager,
|
||||
max_wait_seconds: int = 300
|
||||
) -> str:
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Download audio file from GCS to local temp directory.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
temp_dir: Temporary directory for download
|
||||
@@ -614,14 +601,9 @@ 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 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").
|
||||
Path to downloaded audio file, or None if failed
|
||||
"""
|
||||
import time
|
||||
|
||||
@@ -654,30 +636,20 @@ 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")
|
||||
raise DownloadError(
|
||||
"Audio worker failed before lyrics could run; cannot "
|
||||
"proceed without the downloaded/separated audio."
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
# 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)")
|
||||
raise DownloadError(
|
||||
f"Timed out after {max_wait_seconds}s waiting for the audio worker "
|
||||
"to download the input audio."
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
logger.error(f"Job {job_id}: No input_media_gcs_path found and no URL")
|
||||
raise DownloadError(
|
||||
"No input audio available (no input_media_gcs_path and no URL)."
|
||||
)
|
||||
|
||||
except DownloadError:
|
||||
raise
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
|
||||
raise DownloadError(f"Failed to download audio for lyrics: {e}") from e
|
||||
return None
|
||||
|
||||
|
||||
async def upload_lyrics_results(
|
||||
|
||||
Loaded 100 of 3829 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user