mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-02 18:08:07 +09:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53f02bfcc2 |
No files matched your search
@@ -1,58 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Nomad Karaoke pre-commit hook (karaoke-gen variant)
|
||||
# 1. Gitleaks secret scan (fail fast)
|
||||
# 2. i18n auto-translation when en.json changes
|
||||
# Enable: git config core.hooksPath .githooks
|
||||
set -eu
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Gitleaks secret scan
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if command -v gitleaks >/dev/null 2>&1; then
|
||||
if ! gitleaks protect --staged --redact --no-banner; then
|
||||
printf '\n\033[31m✗ gitleaks detected a potential secret in staged changes.\033[0m\n' >&2
|
||||
printf ' • If real: remove it, rotate the credential, then re-commit.\n' >&2
|
||||
printf ' • If false positive: add an allowlist entry to .gitleaks.toml.\n' >&2
|
||||
printf ' • Emergency override (not recommended): git commit --no-verify\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
printf '\033[33mwarn:\033[0m gitleaks not installed — skipping secret scan\n' >&2
|
||||
printf ' install: brew install gitleaks\n' >&2
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. i18n auto-translation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
STAGED_EN=$(git diff --cached --name-only --diff-filter=ACM | grep -E '(messages|translations)/en\.json$' || true)
|
||||
|
||||
if [ -z "$STAGED_EN" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "i18n: English translations changed — running translation pipeline..."
|
||||
|
||||
for en_file in $STAGED_EN; do
|
||||
dir=$(dirname "$en_file")
|
||||
|
||||
if [[ "$dir" == frontend/messages ]]; then
|
||||
script="frontend/scripts/translate.py"
|
||||
elif [[ "$dir" == backend/translations ]]; then
|
||||
script="frontend/scripts/translate.py"
|
||||
else
|
||||
echo " Warning: Unknown messages dir $dir, skipping"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo " Translating $dir..."
|
||||
if python "$script" --messages-dir "$dir" --target all --skip-review 2>&1 | tail -5; then
|
||||
git add "$dir"/*.json
|
||||
echo " Done: $dir"
|
||||
else
|
||||
echo " Warning: Translation failed for $dir (GCP auth may be missing). CI will catch this."
|
||||
fi
|
||||
done
|
||||
|
||||
echo "i18n: Translation complete."
|
||||
@@ -1,298 +0,0 @@
|
||||
name: Build GHA Runner Images
|
||||
|
||||
# Produces the custom GCE images used by the ephemeral GitHub Actions runner
|
||||
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu,
|
||||
# gha-runner-gpu-windows.
|
||||
#
|
||||
# Flow per variant:
|
||||
# 1. Create a temporary build VM from the variant's base image with the
|
||||
# variant's provisioning script as its startup script:
|
||||
# - Linux variants: debian-12 + runner-image-provision.sh (startup-script)
|
||||
# - gpu-windows: windows-2022 + runner-image-provision.ps1
|
||||
# (windows-startup-script-ps1)
|
||||
# 2. Poll the serial console for the READY/FAILED marker (survives reboots).
|
||||
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
|
||||
# image family with name gha-runner-<variant>-<timestamp>.
|
||||
# 4. Delete the build VM (boot disk auto-deletes).
|
||||
# 5. Deprecate older images in the family, keeping the newest 3 ACTIVE.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variants:
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
|
||||
required: false
|
||||
default: 'all'
|
||||
skip_prune:
|
||||
description: 'Skip deprecation of old images (debugging)'
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
schedule:
|
||||
# Monthly on the 1st at 02:00 UTC
|
||||
- cron: '0 2 1 * *'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
GCP_PROJECT: nomadkaraoke
|
||||
BUILD_REGION: us-central1
|
||||
BUILD_ZONE: us-central1-a
|
||||
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
|
||||
KEEP_IMAGES_PER_FAMILY: 3
|
||||
|
||||
jobs:
|
||||
resolve-matrix:
|
||||
name: Resolve variant matrix
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
variants: ${{ steps.resolve.outputs.variants }}
|
||||
steps:
|
||||
- id: resolve
|
||||
run: |
|
||||
requested='${{ github.event.inputs.variants || 'all' }}'
|
||||
if [[ "$requested" == "all" || -z "$requested" ]]; then
|
||||
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
|
||||
echo "variants=$json" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.variant }} image
|
||||
needs: resolve-matrix
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
variant: ${{ fromJSON(needs.resolve-matrix.outputs.variants) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Set up Cloud SDK
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
with:
|
||||
project_id: ${{ env.GCP_PROJECT }}
|
||||
|
||||
- name: Resolve build parameters
|
||||
id: params
|
||||
run: |
|
||||
variant='${{ matrix.variant }}'
|
||||
ts="$(date -u +%Y%m%d-%H%M%S)"
|
||||
name="gha-runner-${variant}-${ts}"
|
||||
family="gha-runner-${variant}"
|
||||
vm="gha-image-build-${variant}-${ts}"
|
||||
|
||||
# Per-variant base image + startup-script metadata key: Windows
|
||||
# VMs only execute scripts under windows-startup-script-ps1.
|
||||
image_flag="--image=${{ env.BASE_IMAGE }}"
|
||||
metadata_file="startup-script=infrastructure/scripts/runner-image-provision.sh"
|
||||
|
||||
case "$variant" in
|
||||
general|build)
|
||||
machine="n2-standard-8"
|
||||
disk_size="50"
|
||||
accel=""
|
||||
;;
|
||||
gpu)
|
||||
# Build with a T4 attached so DKMS module is built and validated
|
||||
# against the kernel that ships in the image.
|
||||
machine="n1-standard-4"
|
||||
disk_size="200"
|
||||
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
|
||||
;;
|
||||
gpu-windows)
|
||||
# T4 attached so the GRID driver install can validate WDDM mode
|
||||
# (required for DirectML). Keep disk in sync with the
|
||||
# gpu-windows FamilySpec in runner_manager/ephemeral.py.
|
||||
machine="n1-standard-4"
|
||||
disk_size="100"
|
||||
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
|
||||
image_flag="--image-family=windows-2022 --image-project=windows-cloud"
|
||||
metadata_file="windows-startup-script-ps1=infrastructure/scripts/runner-image-provision.ps1"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown variant: $variant" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
{
|
||||
echo "name=$name"
|
||||
echo "family=$family"
|
||||
echo "vm=$vm"
|
||||
echo "machine=$machine"
|
||||
echo "disk_size=$disk_size"
|
||||
echo "accel=$accel"
|
||||
echo "image_flag=$image_flag"
|
||||
echo "metadata_file=$metadata_file"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create build VM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gcloud compute instances create '${{ steps.params.outputs.vm }}' \
|
||||
--project='${{ env.GCP_PROJECT }}' \
|
||||
--zone='${{ env.BUILD_ZONE }}' \
|
||||
--machine-type='${{ steps.params.outputs.machine }}' \
|
||||
${{ steps.params.outputs.image_flag }} \
|
||||
--boot-disk-size='${{ steps.params.outputs.disk_size }}GB' \
|
||||
--boot-disk-type=pd-balanced \
|
||||
--boot-disk-auto-delete \
|
||||
--service-account="${{ secrets.GCP_SERVICE_ACCOUNT }}" \
|
||||
--scopes=https://www.googleapis.com/auth/cloud-platform \
|
||||
--metadata=enable-oslogin=TRUE,image-variant='${{ matrix.variant }}' \
|
||||
--metadata-from-file='${{ steps.params.outputs.metadata_file }}' \
|
||||
--labels=purpose=gha-runner-image-builder,variant='${{ matrix.variant }}' \
|
||||
${{ steps.params.outputs.accel }}
|
||||
|
||||
- name: Wait for provisioning to complete
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
# Read the serial console — NOT SSH — to detect completion.
|
||||
#
|
||||
# The provisioner script tees its full output to /dev/ttyS0 (the GCE
|
||||
# serial console). `gcloud compute instances get-serial-port-output`
|
||||
# returns the full console buffer with zero SSH/IAP dependency. This
|
||||
# makes the wait robust against the IAP tunnel issues that previously
|
||||
# caused both false-positive readiness and false-negative timeouts.
|
||||
#
|
||||
# The script writes one of two distinctive marker lines:
|
||||
# "### runner-image: READY: ..." — successful completion
|
||||
# "### runner-image-provision FAILED ..." — fatal error (with line+rc)
|
||||
#
|
||||
# We also stream live progress to the GHA log so the operator can
|
||||
# see what's happening without leaving the run page.
|
||||
deadline=$(( $(date +%s) + 75 * 60 ))
|
||||
last_size=0
|
||||
attempt=0
|
||||
while (( $(date +%s) < deadline )); do
|
||||
attempt=$((attempt+1))
|
||||
console=$(gcloud compute instances get-serial-port-output "$VM" \
|
||||
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null || true)
|
||||
cur_size=${#console}
|
||||
# Stream new provisioner lines (filter syslog noise).
|
||||
if (( cur_size > last_size )); then
|
||||
echo "$console" | tail -c +$((last_size+1)) \
|
||||
| grep -E "runner-image|### |Attempt " || true
|
||||
last_size=$cur_size
|
||||
fi
|
||||
# Success marker
|
||||
if echo "$console" | grep -qE 'runner-image: READY:'; then
|
||||
echo
|
||||
echo "### Image ready (attempt $attempt)"
|
||||
echo "$console" | grep -E 'runner-image: READY:' | tail -1
|
||||
exit 0
|
||||
fi
|
||||
# Failure marker
|
||||
if echo "$console" | grep -qE 'runner-image-provision FAILED'; then
|
||||
echo
|
||||
echo "### Provisioner reported FAILURE — failure block + 40 lines of preceding context:" >&2
|
||||
# -B 40: include 40 lines BEFORE the marker (where the actual
|
||||
# error output of the failing command lives — python tracebacks,
|
||||
# apt errors, curl messages, etc).
|
||||
# -A 5: include the variant/line/cmd metadata lines after the marker.
|
||||
echo "$console" | grep -B 40 -A 5 'runner-image-provision FAILED' \
|
||||
| tail -80 >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 30
|
||||
done
|
||||
echo
|
||||
echo "### Timed out waiting for READY marker after 75 minutes" >&2
|
||||
echo "### Last serial console output (tail):" >&2
|
||||
gcloud compute instances get-serial-port-output "$VM" \
|
||||
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null \
|
||||
| grep -E "runner-image|### " | tail -50 >&2 || true
|
||||
exit 1
|
||||
|
||||
- name: Stop build VM
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gcloud compute instances stop "$VM" --zone="$ZONE" --project="$PROJECT" --quiet
|
||||
# Belt-and-suspenders wait for TERMINATED.
|
||||
for _ in $(seq 1 60); do
|
||||
status=$(gcloud compute instances describe "$VM" --zone="$ZONE" --project="$PROJECT" --format='value(status)')
|
||||
[[ "$status" == "TERMINATED" ]] && break
|
||||
sleep 5
|
||||
done
|
||||
|
||||
- name: Create image
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
IMAGE: ${{ steps.params.outputs.name }}
|
||||
FAMILY: ${{ steps.params.outputs.family }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# The "Create build VM" step doesn't pass --device-name or
|
||||
# --boot-disk-name, so GCE auto-names the boot disk after the
|
||||
# instance. We rely on that here instead of extracting the name
|
||||
# via a format expression — the previous
|
||||
# `disks[0].source.scope(disks).segment(1)` selector silently
|
||||
# returned empty and gcloud rejected the call with
|
||||
# "You cannot specify [--source-disk-zone] unless you are
|
||||
# specifying [--source-disk]".
|
||||
DISK="$VM"
|
||||
echo "Creating image $IMAGE in family $FAMILY from disk $DISK in $ZONE..."
|
||||
gcloud compute images create "$IMAGE" \
|
||||
--project="$PROJECT" \
|
||||
--source-disk="$DISK" \
|
||||
--source-disk-zone="$ZONE" \
|
||||
--family="$FAMILY" \
|
||||
--description="GHA ephemeral runner image (${{ matrix.variant }}) built ${{ github.run_id }}" \
|
||||
--labels=purpose=gha-ephemeral-runner,variant=${{ matrix.variant }},built-by=gha
|
||||
echo "Created $IMAGE in family $FAMILY"
|
||||
|
||||
- name: Delete build VM
|
||||
if: always()
|
||||
env:
|
||||
VM: ${{ steps.params.outputs.vm }}
|
||||
ZONE: ${{ env.BUILD_ZONE }}
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
run: |
|
||||
gcloud compute instances delete "$VM" --zone="$ZONE" --project="$PROJECT" --quiet || true
|
||||
|
||||
- name: Deprecate old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
|
||||
if: ${{ github.event.inputs.skip_prune != 'true' }}
|
||||
env:
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
FAMILY: ${{ steps.params.outputs.family }}
|
||||
KEEP: ${{ env.KEEP_IMAGES_PER_FAMILY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# List ACTIVE images in this family, newest first, skip the top $KEEP.
|
||||
to_deprecate=$(gcloud compute images list \
|
||||
--project="$PROJECT" \
|
||||
--filter="family=$FAMILY AND status=READY AND -deprecated.state:*" \
|
||||
--sort-by='~creationTimestamp' \
|
||||
--format='value(name)' | tail -n +$((KEEP+1)))
|
||||
if [[ -z "$to_deprecate" ]]; then
|
||||
echo "Nothing to deprecate."
|
||||
exit 0
|
||||
fi
|
||||
for img in $to_deprecate; do
|
||||
echo "Deprecating $img"
|
||||
gcloud compute images deprecate "$img" \
|
||||
--project="$PROJECT" \
|
||||
--state=DEPRECATED \
|
||||
--replacement="projects/$PROJECT/global/images/family/$FAMILY"
|
||||
done
|
||||
+96
-411
@@ -90,26 +90,6 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: npm run lint
|
||||
|
||||
translation-check:
|
||||
name: "Translation Validation"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Validate frontend translations (key parity)
|
||||
run: |
|
||||
python frontend/scripts/validate-translations.py --messages-dir frontend/messages --keys-only || echo "::warning::Frontend translation validation failed — run translate.py to fix"
|
||||
|
||||
- name: Validate backend translations (key parity)
|
||||
run: python frontend/scripts/validate-translations.py --messages-dir backend/translations --keys-only
|
||||
|
||||
frontend-unit-tests:
|
||||
name: "Frontend - Unit Tests"
|
||||
runs-on: ubuntu-latest
|
||||
@@ -268,7 +248,7 @@ jobs:
|
||||
- name: Refresh E2E session token
|
||||
id: refresh_token
|
||||
run: |
|
||||
RESPONSE=$(curl -sf --connect-timeout 5 --max-time 30 -X POST \
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
@@ -515,34 +495,8 @@ 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
|
||||
run: poetry build
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
@@ -603,15 +557,6 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
- name: Cache spaCy model
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/spacy
|
||||
key: spacy-en_core_web_sm-${{ runner.os }}
|
||||
|
||||
- name: Install spaCy language models
|
||||
run: poetry run python -m spacy download en_core_web_sm
|
||||
|
||||
- name: Run all backend unit tests
|
||||
env:
|
||||
GOOGLE_CLOUD_PROJECT: test-project
|
||||
@@ -678,17 +623,7 @@ jobs:
|
||||
java-version: "21"
|
||||
|
||||
- name: Install Firestore emulator
|
||||
run: |
|
||||
# Ensure Google Cloud SDK apt source is present (ephemeral runner images
|
||||
# may not ship it pre-installed). Idempotent.
|
||||
if ! grep -rq "packages.cloud.google.com" /etc/apt/sources.list.d/ 2>/dev/null; then
|
||||
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | \
|
||||
sudo tee /etc/apt/sources.list.d/google-cloud-sdk.list
|
||||
curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | \
|
||||
sudo gpg --dearmor --yes -o /usr/share/keyrings/cloud.google.gpg
|
||||
fi
|
||||
sudo apt-get update -y
|
||||
sudo apt-get install -y google-cloud-cli-firestore-emulator
|
||||
run: sudo apt-get install -y google-cloud-cli-firestore-emulator
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
@@ -759,7 +694,7 @@ jobs:
|
||||
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
|
||||
# frontend-e2e-happy-path is required ONLY when 'e2e-happy-path' label is present
|
||||
# frontend-e2e-full is optional (requires 'e2e' label) so not enforced here
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path, translation-check]
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
@@ -783,14 +718,6 @@ jobs:
|
||||
fi
|
||||
done
|
||||
|
||||
# Translation check: warn but don't block (pre-existing placeholder issues)
|
||||
translation_result="${{ needs.translation-check.result }}"
|
||||
if [[ "$translation_result" == "failure" ]]; then
|
||||
echo "⚠️ Translation validation failed — run translate.py to fix"
|
||||
elif [[ "$translation_result" == "success" ]]; then
|
||||
echo "✅ Translation validation passed"
|
||||
fi
|
||||
|
||||
# E2E Happy Path: enforced when 'e2e-happy-path' label is on the PR
|
||||
e2e_result="${{ needs.frontend-e2e-happy-path.result }}"
|
||||
has_label="${{ contains(github.event.pull_request.labels.*.name, 'e2e-happy-path') }}"
|
||||
@@ -856,36 +783,8 @@ 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
|
||||
# dead weight and pushed the project over PyPI's 10 GB storage cap.
|
||||
# pip always installs from the wheel; nothing builds karaoke-gen from
|
||||
# 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
|
||||
run: poetry build
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -979,6 +878,7 @@ jobs:
|
||||
prerelease: false
|
||||
files: |
|
||||
dist/*.whl
|
||||
dist/*.tar.gz
|
||||
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (Cloudflare Pages)"
|
||||
@@ -1234,15 +1134,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,165 +1172,35 @@ 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"
|
||||
|
||||
echo "Waiting for service at $HEALTH_URL..."
|
||||
for i in $(seq 1 18); do
|
||||
RESPONSE=$(curl -sf --connect-timeout 3 --max-time 5 "$HEALTH_URL" 2>/dev/null || echo "")
|
||||
RESPONSE=$(curl -sf "$HEALTH_URL" 2>/dev/null || echo "")
|
||||
if [ -n "$RESPONSE" ]; then
|
||||
WHEEL_VERSION=$(echo "$RESPONSE" | jq -r '.wheel_version // empty')
|
||||
echo "Health: version=$WHEEL_VERSION"
|
||||
@@ -1458,7 +1223,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)
|
||||
|
||||
@@ -1471,8 +1236,7 @@ jobs:
|
||||
"${DEPLOY_TEST_PATH}/test-audio.flac"
|
||||
|
||||
echo "Submitting test encode to $SECONDARY_IP..."
|
||||
HTTP_CODE=$(curl -s --connect-timeout 5 --max-time 30 \
|
||||
-o /tmp/encode-response.json -w '%{http_code}' \
|
||||
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
|
||||
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
|
||||
-H "X-API-Key: $API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
@@ -1501,7 +1265,7 @@ jobs:
|
||||
|
||||
for i in $(seq 1 12); do
|
||||
sleep 5
|
||||
JOB_STATUS=$(curl -s --connect-timeout 3 --max-time 10 \
|
||||
JOB_STATUS=$(curl -s \
|
||||
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
|
||||
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
|
||||
echo "Encode status: $JOB_STATUS (attempt $i/12)"
|
||||
@@ -1522,35 +1286,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 +1305,77 @@ 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 }}"
|
||||
API_KEY=$(gcloud secrets versions access latest \
|
||||
--secret=encoding-worker-api-key --project=nomadkaraoke)
|
||||
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
|
||||
if [ "$ACTIVE_JOBS" -gt 0 ]; then
|
||||
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
|
||||
DRAIN_TIMEOUT=600
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
|
||||
sleep 15
|
||||
ELAPSED=$((ELAPSED + 15))
|
||||
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
|
||||
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
|
||||
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
|
||||
if [ "$ACTIVE_JOBS" -eq 0 ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
echo "Stopping old primary: $OLD_PRIMARY"
|
||||
gcloud compute instances stop "$OLD_PRIMARY" \
|
||||
--zone=us-central1-c --project=nomadkaraoke || true
|
||||
|
||||
- name: Configure Docker for Artifact Registry
|
||||
run: |
|
||||
@@ -1885,13 +1584,7 @@ jobs:
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
# EDGE-SECURITY: the `edge-origin-secret` Secret Manager secret is
|
||||
# referenced in --set-secrets below (created 2026-07-20; has a value).
|
||||
# EDGE_AUTH_MODE=enforce (in --set-env-vars) means the backend rejects
|
||||
# requests to public routes that lack the Cloudflare-injected X-Edge-Auth
|
||||
# header — i.e. direct-to-origin traffic bypassing the edge (health/root
|
||||
# exempt). Cutover done 2026-07-20; validated via prod E2E with 0 blocked
|
||||
# legit callers. To disable, set EDGE_AUTH_MODE=off here and redeploy.
|
||||
|
||||
- name: Deploy to Cloud Run
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
@@ -1917,8 +1610,8 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
run: |
|
||||
@@ -1935,14 +1628,6 @@ jobs:
|
||||
--quiet
|
||||
|
||||
# Lyrics transcription job (CPU, us-central1)
|
||||
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
|
||||
# ("Invalid secret path ... in annotation") because this job's existing
|
||||
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
|
||||
# re-validates and rejects. Proactive auto-correct env/secret
|
||||
# (AUTO_CORRECT_PROACTIVE_ENABLED + ANTHROPIC_API_KEY) must be wired by a
|
||||
# method that handles the alias format (see proactive-autocorrect plan
|
||||
# doc); until then the proactive flag stays unset and the worker's
|
||||
# _run_proactive_auto_correct() returns early (no-op).
|
||||
gcloud run jobs update lyrics-transcription-job \
|
||||
--image "$IMAGE" \
|
||||
--region us-central1 \
|
||||
@@ -1973,7 +1658,7 @@ jobs:
|
||||
sleep 15
|
||||
|
||||
# Basic health check
|
||||
curl -f --connect-timeout 5 --max-time 30 "$SERVICE_URL/api/health" || exit 1
|
||||
curl -f "$SERVICE_URL/api/health" || exit 1
|
||||
echo "✅ Service is healthy"
|
||||
|
||||
# Version verification with retries (Cloud Run may take time to route to new revision)
|
||||
@@ -1981,7 +1666,7 @@ jobs:
|
||||
RETRY_DELAY=10
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Checking deployed version (attempt $i/$MAX_RETRIES)..."
|
||||
DEPLOYED_VERSION=$(curl -sf --connect-timeout 5 --max-time 30 "$SERVICE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
DEPLOYED_VERSION=$(curl -sf "$SERVICE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
|
||||
if [ "$DEPLOYED_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Version verified: $DEPLOYED_VERSION"
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
name: DR backup freshness monitor
|
||||
|
||||
# Off-platform monitor: runs in GitHub (not GCP) so it survives a full GCP
|
||||
# compromise. If the nightly backup pipeline dies silently, this catches it.
|
||||
#
|
||||
# Required secrets:
|
||||
# AWS_BACKUP_READONLY_ACCESS_KEY_ID
|
||||
# AWS_BACKUP_READONLY_SECRET_ACCESS_KEY
|
||||
# DR_MONITOR_DISCORD_WEBHOOK
|
||||
#
|
||||
# Setup: see docs/DISASTER-RECOVERY.md § "Backup freshness monitor".
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Daily at 14:00 UTC (~9h after the 1am ET backup window).
|
||||
- cron: "0 14 * * *"
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-freshness:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_BACKUP_READONLY_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_BACKUP_READONLY_SECRET_ACCESS_KEY }}
|
||||
AWS_DEFAULT_REGION: us-east-1
|
||||
BUCKET: nomadkaraoke-backup
|
||||
DISCORD_WEBHOOK: ${{ secrets.DR_MONITOR_DISCORD_WEBHOOK }}
|
||||
|
||||
steps:
|
||||
- name: Verify required secrets are set
|
||||
run: |
|
||||
missing=0
|
||||
for var in AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY DISCORD_WEBHOOK; do
|
||||
if [ -z "${!var}" ]; then
|
||||
echo "::error::Required secret $var is empty"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
[ "$missing" = "0" ] || exit 1
|
||||
|
||||
- name: Install boto3
|
||||
run: pip install --quiet boto3
|
||||
|
||||
- name: Check freshness of each tracked prefix
|
||||
id: check
|
||||
shell: bash
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
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.
|
||||
# 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
|
||||
# sees the S3 (off-site) copy, so their limits must allow a full week
|
||||
# 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"),
|
||||
]
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
stale, ok = [], []
|
||||
|
||||
# Paginated scan — JMESPath --query on `aws s3api list-objects-v2`
|
||||
# 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:
|
||||
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"]
|
||||
|
||||
if latest is None:
|
||||
stale.append(f"{label}: NO OBJECTS in s3://{BUCKET}/{prefix}")
|
||||
continue
|
||||
age = (now - latest).total_seconds()
|
||||
age_h = int(age // 3600)
|
||||
line = f"{label}: {age_h}h old (limit {max_hours}h) — last {latest.isoformat()}"
|
||||
(stale if age > max_hours * 3600 else ok).append(line)
|
||||
|
||||
summary = ["## DR backup freshness", ""]
|
||||
if stale:
|
||||
summary.append("### Stale")
|
||||
summary.extend(f"- {s}" for s in stale)
|
||||
summary.append("")
|
||||
summary.append("### Fresh")
|
||||
summary.extend(f"- {o}" for o in ok)
|
||||
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f:
|
||||
f.write("\n".join(summary) + "\n")
|
||||
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
|
||||
f.write(f"ok_count={len(ok)}\n")
|
||||
f.write(f"stale_count={len(stale)}\n")
|
||||
if stale:
|
||||
f.write("STALE_LIST<<EOF\n")
|
||||
f.write("\n".join(stale) + "\n")
|
||||
f.write("EOF\n")
|
||||
|
||||
for o in ok:
|
||||
print("OK:", o)
|
||||
if stale:
|
||||
for s in stale:
|
||||
print("STALE:", s, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
- name: Alert Discord on stale backup
|
||||
if: failure() && steps.check.outputs.stale_count != ''
|
||||
env:
|
||||
STALE: ${{ steps.check.outputs.STALE_LIST }}
|
||||
run: |
|
||||
payload=$(jq -n \
|
||||
--arg title "🚨 DR backup is stale" \
|
||||
--arg desc "$STALE" \
|
||||
--arg url "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" \
|
||||
'{
|
||||
embeds: [{
|
||||
title: $title,
|
||||
description: $desc,
|
||||
color: 15158332,
|
||||
fields: [{name: "Workflow run", value: $url}]
|
||||
}]
|
||||
}')
|
||||
curl -fsS -X POST -H "Content-Type: application/json" \
|
||||
-d "$payload" "$DISCORD_WEBHOOK"
|
||||
|
||||
- name: Alert Discord on workflow failure (catch-all)
|
||||
if: failure() && steps.check.outputs.stale_count == ''
|
||||
run: |
|
||||
payload=$(jq -n \
|
||||
--arg title "⚠️ DR freshness monitor failed to run" \
|
||||
--arg desc "Could not list S3 backup bucket — credentials, network, or bucket policy may be broken." \
|
||||
--arg url "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" \
|
||||
'{
|
||||
embeds: [{
|
||||
title: $title,
|
||||
description: $desc,
|
||||
color: 15844367,
|
||||
fields: [{name: "Workflow run", value: $url}]
|
||||
}]
|
||||
}')
|
||||
curl -fsS -X POST -H "Content-Type: application/json" \
|
||||
-d "$payload" "$DISCORD_WEBHOOK"
|
||||
@@ -1,345 +0,0 @@
|
||||
name: E2E Daily Test (Payment + Happy Path)
|
||||
|
||||
# Full production E2E: buy credits via real Stripe, then use them for karaoke generation.
|
||||
# Replaces the previous e2e-happy-path.yml with an additional payment stage.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * *'
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
debug_mode:
|
||||
description: 'Enable debug mode (slower, more screenshots)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
browser:
|
||||
description: 'Browser to test with'
|
||||
required: false
|
||||
default: 'chromium'
|
||||
type: choice
|
||||
options:
|
||||
- chromium
|
||||
- firefox
|
||||
- webkit
|
||||
skip_payment:
|
||||
description: 'Skip Stage 1 (payment) — use admin-granted credits for happy path only'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
use_test_token:
|
||||
description: 'Skip signup entirely — use E2E_TEST_TOKEN (for quick iterations)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# =========================================================================
|
||||
# Stage 1: Purchase credits via real Stripe Checkout
|
||||
# =========================================================================
|
||||
e2e-credit-purchase:
|
||||
name: "Stage 1: Credit Purchase"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
|
||||
|
||||
outputs:
|
||||
session_token: ${{ steps.extract_token.outputs.token }}
|
||||
result: ${{ steps.test_result.outputs.result }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run Credit Purchase Test
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
|
||||
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
|
||||
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
|
||||
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
|
||||
echo "Time: $(date)"
|
||||
npx playwright test credit-purchase-real.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=600000 \
|
||||
2>&1 | tee test-output-payment.log
|
||||
# Capture Playwright's real exit code, not tee's (0) — the
|
||||
# authoritative pass/fail signal. See Stage 2 for rationale.
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
run: |
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Extract session token
|
||||
id: extract_token
|
||||
if: steps.test_result.outputs.result == 'success'
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if [ -f test-results/e2e-session-token.txt ]; then
|
||||
TOKEN=$(cat test-results/e2e-session-token.txt)
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
echo "Session token extracted for Stage 2"
|
||||
else
|
||||
echo "No session token file found"
|
||||
echo "token=" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-payment-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/test-output-payment.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Stage 2: Happy Path (uses credit from Stage 1)
|
||||
# =========================================================================
|
||||
e2e-happy-path:
|
||||
name: "Stage 2: Happy Path"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
needs: e2e-credit-purchase
|
||||
if: |
|
||||
always() && (
|
||||
needs.e2e-credit-purchase.result == 'success' ||
|
||||
github.event.inputs.skip_payment == 'true' ||
|
||||
github.event.inputs.use_test_token == 'true'
|
||||
)
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: github.event.inputs.use_test_token == 'true'
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Test
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 2: Happy Path ==="
|
||||
echo "Time: $(date)"
|
||||
TOKEN_SOURCE="none"
|
||||
if [ -n "${{ steps.refresh_token.outputs.token }}" ]; then
|
||||
TOKEN_SOURCE="use_test_token (impersonation)"
|
||||
elif [ -n "${{ needs.e2e-credit-purchase.outputs.session_token }}" ]; then
|
||||
TOKEN_SOURCE="Stage 1 (credit purchase)"
|
||||
fi
|
||||
echo "Token source: $TOKEN_SOURCE"
|
||||
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-happy-path.log
|
||||
# Capture Playwright's real exit code, not tee's (0). This is the
|
||||
# authoritative pass/fail signal — grepping the log for "failed" is
|
||||
# fragile because benign retry warnings (e.g. "goto attempt 1/3
|
||||
# failed") contain that substring and produce false alarms.
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
run: |
|
||||
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output-happy-path.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload video recordings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-videos-${{ github.run_number }}
|
||||
path: frontend/test-results/**/*.webm
|
||||
retention-days: 30
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Create summary
|
||||
if: always()
|
||||
run: |
|
||||
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
|
||||
STAGE2="${{ steps.test_result.outputs.result || 'unknown' }}"
|
||||
echo "## E2E Daily Test Results" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage | Result |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage 1: Credit Purchase | ${STAGE1} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage 2: Happy Path | ${STAGE2} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 2: Happy Path\", \"description\": \"Karaoke generation flow is broken.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Final: Send notifications
|
||||
# =========================================================================
|
||||
notify:
|
||||
name: "Notify"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [e2e-credit-purchase, e2e-happy-path]
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
- name: Discord notification (success)
|
||||
if: needs.e2e-happy-path.result == 'success'
|
||||
run: |
|
||||
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"✅ E2E Daily Test PASSED\", \"description\": \"Payment: ${STAGE1} | Happy Path: success\n\n**Run:** #${{ github.run_number }}\", \"color\": 3066993}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Send email notification
|
||||
if: github.event_name == 'schedule'
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.postmarkapp.com
|
||||
server_port: 587
|
||||
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
E2E Daily Test Results
|
||||
======================
|
||||
|
||||
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
|
||||
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
|
||||
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
|
||||
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -0,0 +1,196 @@
|
||||
name: E2E Happy Path Test
|
||||
|
||||
# Comprehensive end-to-end test that validates the full karaoke generation journey
|
||||
# using ONLY browser interactions (no API shortcuts)
|
||||
#
|
||||
# See docs/E2E-HAPPY-PATH-TEST-SPEC.md for full requirements
|
||||
|
||||
on:
|
||||
# Daily run at 6 AM UTC
|
||||
schedule:
|
||||
- cron: '0 6 * * *'
|
||||
|
||||
# Manual trigger with optional parameters
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
debug_mode:
|
||||
description: 'Enable debug mode (slower, more screenshots)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
browser:
|
||||
description: 'Browser to test with'
|
||||
required: false
|
||||
default: 'chromium'
|
||||
type: choice
|
||||
options:
|
||||
- chromium
|
||||
- firefox
|
||||
- webkit
|
||||
use_test_token:
|
||||
description: 'Skip signup and use E2E_TEST_TOKEN (for iterations)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
e2e-happy-path:
|
||||
name: "Full Happy Path (Real User)"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90 # 1.5 hours max (test itself is 60 min)
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: |
|
||||
BROWSER=${{ inputs.browser || 'chromium' }}
|
||||
npx playwright install --with-deps $BROWSER
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
# testmail.app is used for E2E testing but gets flagged as disposable
|
||||
# by external APIs. Ensure it's in the allowlist before the test runs.
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: failed to allowlist domain (may already exist)"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run E2E Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "Starting E2E Happy Path Test"
|
||||
echo "Browser: ${{ inputs.browser || 'chromium' }}"
|
||||
echo "Debug mode: ${{ inputs.debug_mode || 'false' }}"
|
||||
echo "Use test token: ${{ inputs.use_test_token || 'false' }}"
|
||||
echo "Time: $(date)"
|
||||
echo ""
|
||||
|
||||
# Run the real user happy path test
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output.log
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "passed" test-output.log && ! grep -q "failed" test-output.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
echo "Test PASSED"
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
echo "Test FAILED - see artifacts for details"
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload video recordings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-videos-${{ github.run_number }}
|
||||
path: frontend/test-results/**/*.webm
|
||||
retention-days: 30
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Create summary
|
||||
if: always()
|
||||
run: |
|
||||
echo "## E2E Happy Path Test Results" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Result | ${{ steps.test_result.outputs.result || 'unknown' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
if [ -f frontend/test-output.log ]; then
|
||||
echo "### Test Output (last 100 lines)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
tail -100 frontend/test-output.log >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
- name: Send email notification
|
||||
if: always() && github.event_name == 'schedule'
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.sendgrid.net
|
||||
server_port: 587
|
||||
username: apikey
|
||||
password: ${{ secrets.SENDGRID_API_KEY }}
|
||||
subject: "E2E Happy Path Test ${{ steps.test_result.outputs.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
E2E Happy Path Test Results
|
||||
===========================
|
||||
|
||||
Status: ${{ steps.test_result.outputs.result == 'success' && 'PASSED ✅' || 'FAILED ❌' }}
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
Time: ${{ github.event.repository.updated_at }}
|
||||
|
||||
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
|
||||
This is an automated notification from the daily E2E happy path test.
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
@@ -1,132 +0,0 @@
|
||||
name: E2E Daily Test (Tenant Portals)
|
||||
|
||||
# Full production E2E per white-label tenant: submit a job with the tenant's own
|
||||
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
|
||||
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
|
||||
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
|
||||
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
|
||||
# top-of-hour scheduler herd.
|
||||
- cron: '7 0 * * *'
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # for Workload Identity Federation
|
||||
|
||||
jobs:
|
||||
e2e-tenant:
|
||||
name: "Tenant E2E: ${{ matrix.tenant }}"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
|
||||
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
|
||||
max-parallel: 1
|
||||
matrix:
|
||||
tenant: [vocalstar, singa]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Authenticate to GCP
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Fetch test audio (private GCS)
|
||||
run: bash scripts/e2e/fetch_test_audio.sh frontend/e2e/fixtures
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted (rate limit)
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run tenant E2E (frontend journey)
|
||||
id: run_test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
TENANT_ID: ${{ matrix.tenant }}
|
||||
TENANT_PORTAL_URL: https://${{ matrix.tenant }}.nomadkaraoke.com
|
||||
run: |
|
||||
echo "=== Tenant E2E (frontend): ${{ matrix.tenant }} ==="
|
||||
npx playwright test tenant-happy-path.spec.ts \
|
||||
--config=playwright.production.config.ts --project=chromium \
|
||||
--reporter=list --timeout=2400000 2>&1 | tee e2e-output.log
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/e2e-output.log
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
retention-days: 14
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
|
||||
run: |
|
||||
if [ -n "$DISCORD_WEBHOOK" ]; then
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
|
||||
"$DISCORD_WEBHOOK" || true
|
||||
fi
|
||||
|
||||
- name: Fail the job if the test failed
|
||||
if: ${{ steps.run_test.outputs.exit_code != '0' }}
|
||||
run: exit 1
|
||||
|
||||
notify-email:
|
||||
name: "Email summary"
|
||||
runs-on: ubuntu-latest
|
||||
needs: e2e-tenant
|
||||
if: ${{ always() && github.event_name == 'schedule' }}
|
||||
steps:
|
||||
- name: Send email notification
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.postmarkapp.com
|
||||
server_port: 587
|
||||
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
|
||||
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
Tenant E2E Daily Test (Vocal Star + Singa)
|
||||
Result: ${{ needs.e2e-tenant.result }}
|
||||
Run: #${{ github.run_number }}
|
||||
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -1,10 +0,0 @@
|
||||
name: Security
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
gitleaks:
|
||||
uses: nomadkaraoke/.github/.github/workflows/gitleaks.yml@main
|
||||
@@ -13,9 +13,6 @@ tests/outputs
|
||||
/input
|
||||
/output/
|
||||
|
||||
# Local karaoke-gen CLI test output dirs (created during manual validation)
|
||||
/test-output-*/
|
||||
|
||||
# Cloud Infra
|
||||
.emulator-logs
|
||||
|
||||
@@ -28,9 +25,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
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
# Nomad Karaoke shared gitleaks config.
|
||||
# Extends the default ruleset with one custom rule for Discord webhooks
|
||||
# and an allowlist covering known false-positive paths.
|
||||
|
||||
title = "Nomad Karaoke"
|
||||
|
||||
[extend]
|
||||
useDefault = true
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Custom rules
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
[[rules]]
|
||||
id = "discord-webhook-url"
|
||||
description = "Discord webhook URL (token embedded in URL)"
|
||||
regex = '''https://(?:discord|discordapp)\.com/api/webhooks/\d{17,20}/[A-Za-z0-9_-]{60,}'''
|
||||
tags = ["discord", "webhook", "secret"]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Global allowlist
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
[allowlist]
|
||||
description = "Paths and patterns that are known false positives"
|
||||
|
||||
paths = [
|
||||
'''(?i)\.(jpg|jpeg|png|gif|bmp|svg|webp|pdf|ico|mp3|mp4|wav|flac|m4a)$''',
|
||||
'''(^|/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Podfile\.lock|Cargo\.lock|go\.sum|composer\.lock|Gemfile\.lock|uv\.lock)$''',
|
||||
'''(^|/)node_modules/''',
|
||||
'''(^|/)vendor/''',
|
||||
'''(^|/)wp-content/''',
|
||||
'''(^|/)\.dart_tool/''',
|
||||
'''(^|/)\.venv/''',
|
||||
'''(^|/)\.next/''',
|
||||
'''(^|/)build/''',
|
||||
'''(^|/)dist/''',
|
||||
'''(^|/)\.flutter-plugins''',
|
||||
'''(^|/)test[-_]?fixtures?/''',
|
||||
'''(^|/)tests?/.*conftest\.py$''',
|
||||
'''(^|/)tests?/.*test_[^/]+\.py$''',
|
||||
'''(^|/)tests?/.*_test\.py$''',
|
||||
'''(^|/).*\.(test|spec)\.(js|mjs|cjs|ts|tsx|jsx)$''',
|
||||
'''(^|/).*\.test\.local\.(js|mjs|cjs|ts|tsx|jsx|py)$''',
|
||||
'''(^|/).*\.local\.(js|mjs|cjs|ts|tsx|jsx|py)$''',
|
||||
]
|
||||
|
||||
regexes = [
|
||||
# Explicit placeholder patterns
|
||||
'''YOUR_[A-Z_]{2,}''',
|
||||
'''EXAMPLE_[A-Z_]{2,}''',
|
||||
'''PLACEHOLDER_[A-Z_]{2,}''',
|
||||
'''CHANGE[_-]?ME''',
|
||||
'''<[A-Z_]{2,}>''',
|
||||
'''\$\{[A-Z_]{2,}\}''',
|
||||
|
||||
# Firebase / GCP client API keys — public by design (identify the project,
|
||||
# access is gated by Firebase Security Rules).
|
||||
'''AIzaSy[A-Za-z0-9_-]{33}''',
|
||||
]
|
||||
@@ -96,26 +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)
|
||||
|
||||
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
|
||||
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
|
||||
- Components use `useTranslations('namespace')` from next-intl
|
||||
- Pages are under `frontend/app/[locale]/` — locale-aware routing (customer-facing: `/`, `/app/*`, `/order/*`, `/auth/*`, `/payment/*`, `/r/*`)
|
||||
- Non-locale routes at those same paths (e.g. `frontend/app/app/jobs/[[...slug]]/page.tsx`) are `<LocaleRedirect />` shims that redirect into `[locale]` — they are NOT English-only surfaces
|
||||
- The `/app/jobs/#/{id}/review`, `/instrumental`, and `/audio-edit` review UIs are fully multilingual (components under `components/lyrics-review/`, `components/instrumental-review/`, `components/audio-editor/` use `useTranslations` heavily)
|
||||
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
|
||||
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
|
||||
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
|
||||
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
|
||||
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
|
||||
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
|
||||
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
|
||||
|
||||
## API Authentication (for Agents)
|
||||
|
||||
@@ -149,18 +129,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"
|
||||
```
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Makefile for karaoke-gen project
|
||||
# Run `make help` to see available commands
|
||||
|
||||
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop eval-custom-lyrics
|
||||
.PHONY: help install install-backend install-frontend build-frontend dev-install test test-unit test-backend test-e2e test-frontend test-all lint clean emulators-start emulators-stop
|
||||
|
||||
# Per-stage timeout in seconds (default: 10 minutes)
|
||||
# Prevents hangs from stale dev servers, broken emulators, etc.
|
||||
@@ -133,7 +133,3 @@ clean:
|
||||
rm -rf htmlcov/ .coverage coverage.xml 2>/dev/null || true
|
||||
@echo "Cleaned up temporary files"
|
||||
|
||||
.PHONY: eval-custom-lyrics
|
||||
eval-custom-lyrics:
|
||||
cd backend && poetry run python -m backend.eval.custom_lyrics.run
|
||||
|
||||
@@ -23,7 +23,6 @@ RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
curl \
|
||||
xz-utils \
|
||||
chromium \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install comprehensive font support for international lyrics and symbols
|
||||
|
||||
+31
-119
@@ -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", [])
|
||||
@@ -967,27 +948,6 @@ async def update_job(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Reassigning a job to an email with no account would orphan it (the user
|
||||
# couldn't log in to see it, and impersonation would 404) — so normalize the
|
||||
# email and auto-create the account if needed.
|
||||
user_created_email = None
|
||||
if isinstance(updates.get("user_email"), str):
|
||||
normalized_email = updates["user_email"].strip().lower()
|
||||
if not normalized_email or "@" not in normalized_email:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="user_email must be a valid email address"
|
||||
)
|
||||
updates["user_email"] = normalized_email
|
||||
user_service = get_user_service()
|
||||
if not user_service.get_user(normalized_email):
|
||||
user_service.get_or_create_user(normalized_email)
|
||||
user_created_email = normalized_email
|
||||
logger.info(
|
||||
f"Admin {admin_email} reassigned job {job_id} to {normalized_email} — "
|
||||
f"no account existed, created one"
|
||||
)
|
||||
|
||||
# Check if we're toggling is_private from False to True on a completed job
|
||||
# If so, auto-delete existing outputs (YouTube, Dropbox, GDrive)
|
||||
toggling_to_private = (
|
||||
@@ -1037,8 +997,6 @@ async def update_job(
|
||||
)
|
||||
|
||||
message = f"Successfully updated {len(updates)} field(s)"
|
||||
if user_created_email:
|
||||
message += f". Created new user account for {user_created_email}."
|
||||
if auto_deleted:
|
||||
message += ". Existing outputs were auto-deleted (job set to private)."
|
||||
|
||||
@@ -1245,7 +1203,7 @@ async def reset_job(
|
||||
job_manager.update_job(job_id, updates)
|
||||
|
||||
# Clear the state data keys and error state using direct Firestore update
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion, Increment
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
job_ref = user_service.db.collection("jobs").document(job_id)
|
||||
|
||||
@@ -1261,14 +1219,6 @@ async def reset_job(
|
||||
clear_updates["error_message"] = DELETE_FIELD
|
||||
clear_updates["error_details"] = DELETE_FIELD
|
||||
|
||||
# Advance the supersession fence: a reset is a "stop what you're doing" event.
|
||||
# Any render/video worker still in flight (e.g. the operator hit "Review"
|
||||
# mid-render) will observe the bumped generation and discard its stale result
|
||||
# instead of overwriting fresh outputs or failing this reset. See
|
||||
# backend/workers/supersede.py. Atomic with the clears above so an in-flight
|
||||
# worker can never observe a half-applied reset.
|
||||
clear_updates["state_data.worker_generation"] = Increment(1)
|
||||
|
||||
# Add timeline event
|
||||
clear_updates["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
@@ -1759,12 +1709,6 @@ async def delete_job_outputs(
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too (prefix-keyed
|
||||
# by brand_code, covers renames). Non-fatal, Nomad-only, no-op otherwise.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
|
||||
# Clean up GCS finals folder - prevents stale files from being picked up during re-encoding
|
||||
try:
|
||||
from backend.services.storage_service import StorageService
|
||||
@@ -2105,7 +2049,6 @@ REGENERATE_SCREENS_ALLOWED_STATES = {
|
||||
"complete",
|
||||
"failed",
|
||||
"awaiting_review",
|
||||
"in_review", # User opened the review UI but hasn't submitted yet
|
||||
"awaiting_instrumental_selection",
|
||||
"instrumental_selected",
|
||||
"prep_complete",
|
||||
@@ -2188,7 +2131,7 @@ async def regenerate_screens(
|
||||
]
|
||||
for path in screen_paths:
|
||||
try:
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
storage.delete_file(path)
|
||||
except Exception:
|
||||
pass # File may not exist
|
||||
screens_deleted = True
|
||||
@@ -2343,16 +2286,16 @@ async def restart_job(
|
||||
for screen_file in ["title.mov", "title.jpg", "title.png", "end.mov", "end.jpg", "end.png"]:
|
||||
try:
|
||||
path = f"jobs/{job_id}/screens/{screen_file}"
|
||||
if storage.delete_file(path, ignore_missing=True):
|
||||
deleted_paths.append(path)
|
||||
storage.delete_file(path)
|
||||
deleted_paths.append(path)
|
||||
except Exception:
|
||||
pass
|
||||
# Delete final outputs
|
||||
for output_file in ["final_4k.mp4", "final_720p.mp4", "with_vocals.mkv", "preview.mp4"]:
|
||||
try:
|
||||
path = f"jobs/{job_id}/output/{output_file}"
|
||||
if storage.delete_file(path, ignore_missing=True):
|
||||
deleted_paths.append(path)
|
||||
storage.delete_file(path)
|
||||
deleted_paths.append(path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -3019,37 +2962,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,
|
||||
|
||||
@@ -52,10 +52,8 @@ from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.services.tracing import add_span_attribute
|
||||
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__)
|
||||
|
||||
@@ -230,57 +228,6 @@ class AudioSelectRequest(BaseModel):
|
||||
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
|
||||
display_artist: Optional[str] = Field(None, description="Override display artist name")
|
||||
display_title: Optional[str] = Field(None, description="Override display title")
|
||||
# Anti-mismatch guard: client may send the expected credit total it observed.
|
||||
# If the server's computed target_total differs, we return 409 so the UI can refresh.
|
||||
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):
|
||||
@@ -628,55 +575,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 +704,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 +881,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 +1007,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 +1124,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,
|
||||
@@ -1574,62 +1174,6 @@ async def select_audio_source(
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results cached for this job")
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Duration-based pricing: charge the DELTA before triggering any download.
|
||||
# -------------------------------------------------------------------------
|
||||
# The selected result may carry a duration field (seconds as int).
|
||||
selected_result = search_results[body.selection_index] if 0 <= body.selection_index < len(search_results) else {}
|
||||
duration = selected_result.get('duration') # int seconds, or None
|
||||
|
||||
# Hard ceiling: reject inputs over 60 minutes immediately (before any state change).
|
||||
if duration is not None and is_blocked(duration):
|
||||
raise HTTPException(status_code=422, detail="Inputs over 60 minutes aren't supported")
|
||||
|
||||
# Idempotency guard: if a previous /select call already applied the delta charge,
|
||||
# skip re-charging entirely. This makes double-click / rapid-retry safe.
|
||||
# Residual race: two *truly simultaneous* requests can both read the flag as False
|
||||
# and both charge before either writes it True. The atomic status transition in
|
||||
# _validate_and_prepare_selection() causes the second request to fail with 400,
|
||||
# so the window is tiny; any rare double-charge is recoverable via support refund.
|
||||
select_charge_applied = bool((job.state_data or {}).get('select_charge_applied', False))
|
||||
|
||||
# Compute how many credits this job should total after selecting this result.
|
||||
# If duration is unknown, keep target_total == credits_charged so owed = 0.
|
||||
credits_charged = int((job.state_data or {}).get('credits_charged', 1))
|
||||
target_total = duration_to_credits(duration) if duration is not None else credits_charged
|
||||
owed = max(0, target_total - credits_charged)
|
||||
|
||||
# Anti-mismatch guard: if the client sent an expected total, verify it still matches.
|
||||
if body.acknowledged_credits is not None and body.acknowledged_credits != target_total:
|
||||
raise HTTPException(status_code=409, detail="Credit figure changed; please refresh")
|
||||
|
||||
# Deduct the owed delta (or just persist duration metadata if owed == 0).
|
||||
user_email = job.user_email
|
||||
if not select_charge_applied:
|
||||
if owed > 0:
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=500, detail="Job has no associated user email")
|
||||
ok, _, _ = get_user_service().deduct_credits(
|
||||
user_email,
|
||||
job_id,
|
||||
amount=owed,
|
||||
reason="job_creation",
|
||||
count_as_job_creation=False, # job was already counted at create_job()
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=402, detail="Insufficient credits")
|
||||
|
||||
# Persist updated credit total, duration estimate, and idempotency flag.
|
||||
state_update: dict = {
|
||||
"state_data.credits_charged": target_total,
|
||||
"state_data.select_charge_applied": True,
|
||||
}
|
||||
if duration is not None:
|
||||
state_update["state_data.duration_estimate_seconds"] = duration
|
||||
state_update["state_data.duration_estimate_source"] = "search_metadata"
|
||||
job_manager.update_job(job_id, state_update)
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
|
||||
selection_info = _validate_and_prepare_selection(
|
||||
job_id=job_id,
|
||||
|
||||
@@ -1,478 +0,0 @@
|
||||
"""Bulk Mode API routes.
|
||||
|
||||
Lets a user submit up to 100 karaoke jobs at once, by text (artist/title rows)
|
||||
or by album (MusicBrainz release lookup). Album tracklists and text rows are
|
||||
enriched with KaraokeNerds community-version availability so the user can skip
|
||||
tracks that already exist.
|
||||
|
||||
Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
|
||||
(added in later phases).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Literal, Optional
|
||||
|
||||
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__)
|
||||
|
||||
router = APIRouter(prefix="/bulk", tags=["bulk"])
|
||||
|
||||
MAX_BULK_SONGS = 100
|
||||
|
||||
|
||||
# --- Models -----------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkArtist(BaseModel):
|
||||
mbid: Optional[str] = None
|
||||
name: str
|
||||
disambiguation: str = ""
|
||||
type: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
|
||||
|
||||
class BulkAlbum(BaseModel):
|
||||
release_group_mbid: str
|
||||
title: str
|
||||
primary_type: Optional[str] = None
|
||||
secondary_types: list[str] = []
|
||||
first_release_date: str = ""
|
||||
is_studio: bool = True
|
||||
|
||||
|
||||
class BulkEdition(BaseModel):
|
||||
release_mbid: str
|
||||
title: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
date: str = ""
|
||||
country: Optional[str] = None
|
||||
track_count: int = 0
|
||||
|
||||
|
||||
class BulkEditionVariant(BaseModel):
|
||||
"""A distinct tracklist variant (country pressings collapsed by track count)."""
|
||||
|
||||
representative_release_mbid: str
|
||||
label: Literal["Original", "Reissue"] = "Original"
|
||||
track_count: int = 0
|
||||
year: str = ""
|
||||
pressing_count: int = 0
|
||||
delta_vs_original: int = 0
|
||||
|
||||
|
||||
class CommunityVersion(BaseModel):
|
||||
"""An existing community karaoke version the user can preview on YouTube."""
|
||||
|
||||
brand: str
|
||||
url: str
|
||||
|
||||
|
||||
class BulkTrack(BaseModel):
|
||||
position: Optional[int] = None
|
||||
title: str
|
||||
recording_mbid: Optional[str] = None
|
||||
length_ms: Optional[int] = None
|
||||
is_extra: bool = False
|
||||
extra_reason: str = ""
|
||||
# Availability (filled from KaraokeNerds); available=True => already exists
|
||||
available: bool = False
|
||||
brands: list[str] = []
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
class BulkTracklistResponse(BaseModel):
|
||||
release_mbid: Optional[str] = None
|
||||
canonical_release_mbid: Optional[str] = None
|
||||
selected_variant_mbid: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
date: str = ""
|
||||
tracks: list[BulkTrack] = []
|
||||
editions: list[BulkEdition] = []
|
||||
variants: list[BulkEditionVariant] = []
|
||||
|
||||
|
||||
class AvailabilityItem(BaseModel):
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class AvailabilityRequest(BaseModel):
|
||||
tracks: list[AvailabilityItem]
|
||||
|
||||
|
||||
class AvailabilityResult(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
available: bool
|
||||
brands: list[str] = []
|
||||
brand_count: int = 0
|
||||
versions: list[CommunityVersion] = []
|
||||
|
||||
|
||||
class AvailabilityResponse(BaseModel):
|
||||
results: list[AvailabilityResult]
|
||||
|
||||
|
||||
# --- Album lookup routes ----------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/album/artists", response_model=list[BulkArtist])
|
||||
async def album_artists(
|
||||
request: Request,
|
||||
q: str = Query(..., min_length=2, description="Artist name search"),
|
||||
limit: int = Query(8, ge=1, le=25),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Search MusicBrainz for artists (album-mode step 1)."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
|
||||
try:
|
||||
results = await get_musicbrainz_service().search_artists(q, limit=limit)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz artist search failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Artist lookup is temporarily unavailable")
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/album/albums", response_model=list[BulkAlbum])
|
||||
async def album_albums(
|
||||
request: Request,
|
||||
artist_mbid: str = Query(..., min_length=1),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""List an artist's albums (release-groups) for the album picker."""
|
||||
from backend.services.musicbrainz_service import get_musicbrainz_service
|
||||
|
||||
try:
|
||||
return await get_musicbrainz_service().get_albums(artist_mbid)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz album list failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Album lookup is temporarily unavailable")
|
||||
|
||||
|
||||
@router.get("/album/tracklist", response_model=BulkTracklistResponse)
|
||||
async def album_tracklist(
|
||||
request: Request,
|
||||
artist: str = Query(..., min_length=1, description="Artist name for availability checks"),
|
||||
release_group_mbid: Optional[str] = Query(None),
|
||||
release_mbid: Optional[str] = Query(None, description="Specific edition to load"),
|
||||
locale: Optional[str] = Query(None, description="UI locale → biases representative-pressing choice"),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Resolve an album's canonical tracklist (or a specific edition) and enrich
|
||||
each track with KaraokeNerds community-version availability.
|
||||
|
||||
Response shape note: ``variants`` is only populated on the ``release_group_mbid``
|
||||
path (the initial album load). When loading a specific edition via
|
||||
``release_mbid`` it is intentionally ``[]`` — the client already holds the
|
||||
variant list from the initial load and only needs the chosen edition's tracks.
|
||||
"""
|
||||
from backend.services.musicbrainz_service import (
|
||||
get_musicbrainz_service,
|
||||
country_prefs_for_locale,
|
||||
)
|
||||
from backend.services.karaokenerds_service import check_community_versions_batch
|
||||
|
||||
if not release_group_mbid and not release_mbid:
|
||||
raise HTTPException(status_code=422, detail="release_group_mbid or release_mbid required")
|
||||
|
||||
mb = get_musicbrainz_service()
|
||||
try:
|
||||
if release_mbid:
|
||||
# Loading a specific variant — variants already known to the client.
|
||||
tracklist = await mb.get_release_tracklist(release_mbid)
|
||||
tracklist.setdefault("editions", [])
|
||||
tracklist.setdefault("canonical_release_mbid", release_mbid)
|
||||
tracklist.setdefault("variants", [])
|
||||
tracklist.setdefault("selected_variant_mbid", release_mbid)
|
||||
else:
|
||||
tracklist = await mb.get_album_tracklist(
|
||||
release_group_mbid, preferred_countries=country_prefs_for_locale(locale)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("MusicBrainz tracklist failed: %r", e, exc_info=True)
|
||||
raise HTTPException(status_code=502, detail="Tracklist lookup is temporarily unavailable")
|
||||
|
||||
tracks = tracklist.get("tracks", [])
|
||||
# Availability enrichment — never fatal.
|
||||
try:
|
||||
avail = await check_community_versions_batch(
|
||||
[{"artist": artist, "title": t["title"]} for t in tracks]
|
||||
)
|
||||
for t, a in zip(tracks, avail):
|
||||
t["available"] = a["available"]
|
||||
t["brands"] = a["brands"]
|
||||
t["versions"] = a.get("versions", [])
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Availability enrichment failed (non-fatal): %s", e)
|
||||
|
||||
return BulkTracklistResponse(
|
||||
release_mbid=tracklist.get("release_mbid"),
|
||||
canonical_release_mbid=tracklist.get("canonical_release_mbid"),
|
||||
selected_variant_mbid=tracklist.get("selected_variant_mbid"),
|
||||
title=tracklist.get("title"),
|
||||
date=tracklist.get("date", ""),
|
||||
tracks=[BulkTrack(**t) for t in tracks],
|
||||
editions=[BulkEdition(**e) for e in tracklist.get("editions", [])],
|
||||
variants=[BulkEditionVariant(**v) for v in tracklist.get("variants", [])],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/availability", response_model=AvailabilityResponse)
|
||||
async def bulk_availability(
|
||||
request: Request,
|
||||
body: AvailabilityRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Batch KaraokeNerds availability check for text-mode rows."""
|
||||
from backend.services.karaokenerds_service import check_community_versions_batch
|
||||
|
||||
if len(body.tracks) > MAX_BULK_SONGS:
|
||||
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} tracks per request")
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": t.artist, "title": t.title} for t in body.tracks]
|
||||
)
|
||||
return AvailabilityResponse(results=[AvailabilityResult(**r) for r in results])
|
||||
|
||||
|
||||
# --- Submission -------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkSong(BaseModel):
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
display_artist: Optional[str] = None
|
||||
display_title: Optional[str] = None
|
||||
|
||||
|
||||
class BulkSettings(BaseModel):
|
||||
auto_select_if_lossless: bool = True
|
||||
is_private: bool = False
|
||||
skip_audio_edit: bool = True
|
||||
skip_customization: bool = True
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
songs: list[BulkSong]
|
||||
settings: BulkSettings = Field(default_factory=BulkSettings)
|
||||
|
||||
|
||||
class BulkSubmitResponse(BaseModel):
|
||||
batch_id: str
|
||||
job_ids: list[str]
|
||||
total: int
|
||||
|
||||
|
||||
@router.post("/submit", response_model=BulkSubmitResponse)
|
||||
async def bulk_submit(
|
||||
request: Request,
|
||||
body: BulkSubmitRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Create one job per song, gate on credits upfront, and dispatch the batch
|
||||
search worker. Jobs start parked (auto_download=False) and the worker either
|
||||
auto-selects a confident lossless match or leaves them awaiting selection."""
|
||||
from backend.config import get_settings
|
||||
from backend.exceptions import InsufficientCreditsError
|
||||
from backend.models.job import JobCreate
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
n = len(body.songs)
|
||||
if n == 0:
|
||||
raise HTTPException(status_code=422, detail="At least one song is required")
|
||||
if n > MAX_BULK_SONGS:
|
||||
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} songs per batch")
|
||||
|
||||
user_email = auth_result.user_email
|
||||
is_admin = bool(auth_result.is_admin)
|
||||
|
||||
# Upfront credit gate (1 credit/song minimum). Admins bypass.
|
||||
if not is_admin and user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
available = get_user_service().check_credits(user_email)
|
||||
if available < n:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"error": "insufficient_credits",
|
||||
"message": "You don't have enough credits for this batch.",
|
||||
"credits_available": available,
|
||||
"credits_required": n,
|
||||
},
|
||||
)
|
||||
|
||||
settings = get_settings()
|
||||
theme_service = get_theme_service()
|
||||
theme_id = theme_service.get_default_theme_id()
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
|
||||
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
bulk_settings = body.settings.model_dump()
|
||||
job_manager = JobManager()
|
||||
job_ids: list[str] = []
|
||||
|
||||
for song in body.songs:
|
||||
display_artist = (song.display_artist or song.artist).strip()
|
||||
display_title = (song.display_title or song.title).strip()
|
||||
request_metadata = {
|
||||
"created_from": "bulk",
|
||||
"batch_id": batch_id,
|
||||
"user_email": user_email,
|
||||
}
|
||||
job_create = JobCreate(
|
||||
artist=display_artist,
|
||||
title=display_title,
|
||||
theme_id=theme_id,
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
user_email=user_email,
|
||||
audio_search_artist=song.artist.strip(),
|
||||
audio_search_title=song.title.strip(),
|
||||
auto_download=False,
|
||||
is_private=body.settings.is_private,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
discord_webhook_url=settings.default_discord_webhook_url,
|
||||
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)
|
||||
except InsufficientCreditsError:
|
||||
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
|
||||
# already-created jobs are valid and will proceed.
|
||||
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
|
||||
break
|
||||
|
||||
job_manager.update_job(
|
||||
job.job_id,
|
||||
{
|
||||
"state_data.batch_id": batch_id,
|
||||
"state_data.bulk_settings": bulk_settings,
|
||||
"state_data.bulk_pending_search": True,
|
||||
},
|
||||
)
|
||||
job_ids.append(job.job_id)
|
||||
|
||||
if not job_ids:
|
||||
raise HTTPException(status_code=402, detail="No jobs could be created")
|
||||
|
||||
# Dispatch the batch search worker. Retry once on transient failure. If it
|
||||
# still fails the jobs exist (and are charged) but won't process, so surface
|
||||
# an explicit error with the batch_id — and tell the user NOT to resubmit
|
||||
# (that would create+charge a second batch); the batch can be re-dispatched.
|
||||
worker_service = get_worker_service()
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
|
||||
if not triggered:
|
||||
logger.critical(
|
||||
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
|
||||
batch_id, len(job_ids),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail={
|
||||
"error": "dispatch_failed",
|
||||
"message": "Your batch was created but processing couldn't start. "
|
||||
"Please don't resubmit — contact support with this batch ID and we'll start it.",
|
||||
"batch_id": batch_id,
|
||||
"job_ids": job_ids,
|
||||
},
|
||||
)
|
||||
logger.info("[batch:%s] created %d jobs, dispatched bulk-search worker", batch_id, len(job_ids))
|
||||
|
||||
return BulkSubmitResponse(batch_id=batch_id, job_ids=job_ids, total=len(job_ids))
|
||||
|
||||
|
||||
# --- Progress ---------------------------------------------------------------
|
||||
|
||||
|
||||
class BulkJobStatus(BaseModel):
|
||||
job_id: str
|
||||
artist: str
|
||||
title: str
|
||||
status: str
|
||||
auto_selected: bool = False
|
||||
|
||||
|
||||
class BulkBatchResponse(BaseModel):
|
||||
batch_id: str
|
||||
total: int
|
||||
counts: dict
|
||||
jobs: list[BulkJobStatus]
|
||||
|
||||
|
||||
# Status -> progress bucket for the batch summary.
|
||||
_AWAITING = "awaiting_audio_selection"
|
||||
_TERMINAL_OK = "complete"
|
||||
_TERMINAL_FAIL = "failed"
|
||||
_SEARCHING = {"pending", "searching_audio"}
|
||||
|
||||
|
||||
def _bucket(status: str, pending_search: bool) -> str:
|
||||
if pending_search or status in _SEARCHING:
|
||||
return "searching"
|
||||
if status == _AWAITING:
|
||||
return "awaiting_selection"
|
||||
if status == _TERMINAL_OK:
|
||||
return "complete"
|
||||
if status == _TERMINAL_FAIL:
|
||||
return "failed"
|
||||
return "processing"
|
||||
|
||||
|
||||
@router.get("/{batch_id}", response_model=BulkBatchResponse)
|
||||
async def bulk_batch(
|
||||
request: Request,
|
||||
batch_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Progress summary for a batch: counts by bucket + per-job status."""
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
job_manager = JobManager()
|
||||
jobs = job_manager.list_jobs_by_batch_id(batch_id)
|
||||
|
||||
if not bool(auth_result.is_admin):
|
||||
email = (auth_result.user_email or "").lower()
|
||||
jobs = [j for j in jobs if (j.user_email or "").lower() == email]
|
||||
|
||||
if not jobs:
|
||||
raise HTTPException(status_code=404, detail="Batch not found")
|
||||
|
||||
counts = {"searching": 0, "awaiting_selection": 0, "processing": 0, "complete": 0, "failed": 0}
|
||||
job_statuses: list[BulkJobStatus] = []
|
||||
for j in jobs:
|
||||
status = j.status.value if hasattr(j.status, "value") else str(j.status)
|
||||
sd = j.state_data or {}
|
||||
bucket = _bucket(status, bool(sd.get("bulk_pending_search")))
|
||||
counts[bucket] += 1
|
||||
job_statuses.append(
|
||||
BulkJobStatus(
|
||||
job_id=j.job_id,
|
||||
artist=j.audio_search_artist or j.artist or "",
|
||||
title=j.audio_search_title or j.title or "",
|
||||
status=status,
|
||||
auto_selected=bool(sd.get("bulk_auto_selected")),
|
||||
)
|
||||
)
|
||||
|
||||
return BulkBatchResponse(
|
||||
batch_id=batch_id, total=len(jobs), counts=counts, jobs=job_statuses
|
||||
)
|
||||
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Literal, Optional
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -103,38 +103,6 @@ class CommunityCheckResponse(BaseModel):
|
||||
best_youtube_url: Optional[str] = None
|
||||
|
||||
|
||||
class MatchJudgeRequest(BaseModel):
|
||||
"""Request body for the artist/title match judge."""
|
||||
artist: str = Field(..., min_length=1)
|
||||
title: str = Field(..., min_length=1)
|
||||
# The audio search's confidence tier (1=strong..3=weak), so the judge can
|
||||
# tell whether weak results hint at a typo. Optional.
|
||||
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
|
||||
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
|
||||
# parallel with the audio search; "full" = complete pipeline once the tier is
|
||||
# known. Defaults to "full" so a single legacy call still works.
|
||||
stage: Literal["fast", "full"] = "full"
|
||||
|
||||
|
||||
class MatchJudgeAlternative(BaseModel):
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
class MatchJudgeResponse(BaseModel):
|
||||
"""Verdict on a typed artist/title — formatting + match acceptance."""
|
||||
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
|
||||
confident: bool
|
||||
canonical_artist: str
|
||||
canonical_title: str
|
||||
alternatives: list[MatchJudgeAlternative] = []
|
||||
engine: str # "deterministic" | "catalog" | "ai"
|
||||
reason: str = ""
|
||||
# Set by a "fast" pass that couldn't decide — the client should follow up with
|
||||
# a "full" call once the audio tier is known.
|
||||
needs_ai: bool = False
|
||||
|
||||
|
||||
# --- Routes ---
|
||||
|
||||
|
||||
@@ -193,31 +161,3 @@ async def check_community_versions(
|
||||
from backend.services.karaokenerds_service import check_community_versions
|
||||
result = await check_community_versions(body.artist, body.title)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/match-judge", response_model=MatchJudgeResponse)
|
||||
async def match_judge(
|
||||
request: Request,
|
||||
body: MatchJudgeRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Judge a typed artist/title: decide official formatting + whether it matches a
|
||||
real song. Deterministic + catalog layers run first; a light AI model fires
|
||||
only when those aren't confident. Never blocks the submission flow — failures
|
||||
degrade to a "none" verdict.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
|
||||
|
||||
from backend.services.match_judge.service import judge_match
|
||||
verdict = await judge_match(
|
||||
body.artist, body.title,
|
||||
audio_tier=body.audio_confidence_tier,
|
||||
stage=body.stage,
|
||||
)
|
||||
logger.info(
|
||||
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
|
||||
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
|
||||
)
|
||||
return verdict.to_dict()
|
||||
@@ -1,108 +0,0 @@
|
||||
"""POST /api/client-errors — ingest frontend crash reports.
|
||||
|
||||
Unauthenticated (logged-out users' crashes still matter). Deduped and alerted
|
||||
via the existing error-monitor pipeline — see
|
||||
``backend/services/error_monitor``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from backend.services.error_monitor.firestore_adapter import ErrorPatternsAdapter
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
FrontendErrorReport,
|
||||
RateLimiter,
|
||||
build_pattern_data,
|
||||
is_bot_user_agent,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/client-errors", tags=["client-errors"])
|
||||
|
||||
_limiter = RateLimiter(max_per_minute=60)
|
||||
_adapter_singleton: ErrorPatternsAdapter | None = None
|
||||
|
||||
|
||||
def _get_adapter() -> ErrorPatternsAdapter:
|
||||
global _adapter_singleton
|
||||
if _adapter_singleton is None:
|
||||
_adapter_singleton = ErrorPatternsAdapter()
|
||||
return _adapter_singleton
|
||||
|
||||
|
||||
class ClientErrorPayload(BaseModel):
|
||||
message: str = Field(..., min_length=1, max_length=4000)
|
||||
stack: Optional[str] = Field(None, max_length=1_000_000)
|
||||
url: str = Field("", max_length=2048)
|
||||
user_agent: str = Field("", max_length=1024)
|
||||
release: str = Field("", max_length=64)
|
||||
user_email: Optional[str] = Field(None, max_length=320)
|
||||
viewport: Optional[dict] = None
|
||||
locale: str = Field("en", max_length=10)
|
||||
source: str = Field("unknown", max_length=64)
|
||||
# optional free-form extra for debugging. Capped server-side.
|
||||
extra: Optional[dict] = None
|
||||
|
||||
@field_validator("message", "url", "user_agent", "locale", "source")
|
||||
@classmethod
|
||||
def strip(cls, v: str) -> str:
|
||||
return (v or "").strip()
|
||||
|
||||
|
||||
class ClientErrorResponse(BaseModel):
|
||||
pattern_id: str
|
||||
is_new: bool
|
||||
|
||||
|
||||
@router.post("", response_model=ClientErrorResponse, status_code=202)
|
||||
def report_client_error(payload: ClientErrorPayload, request: Request) -> ClientErrorResponse:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many reports")
|
||||
|
||||
# Crawler/bot crashes are pure alert noise (bots run headless Chrome and trip
|
||||
# DOM errors no real user hits). Accept the report so the client doesn't retry,
|
||||
# but don't persist/alert on it.
|
||||
if is_bot_user_agent(payload.user_agent):
|
||||
# Log the bot UA (not sensitive) + sanitized URL (query/token stripped)
|
||||
# for visibility into what's being dropped, without persisting/alerting.
|
||||
logger.info(
|
||||
"frontend_crash_ignored_bot ua=%r url=%s source=%s",
|
||||
payload.user_agent[:120],
|
||||
sanitize_url(payload.url),
|
||||
payload.source,
|
||||
)
|
||||
return ClientErrorResponse(pattern_id="bot-ignored", is_new=False)
|
||||
|
||||
report = FrontendErrorReport(
|
||||
message=payload.message,
|
||||
stack=payload.stack,
|
||||
url=payload.url,
|
||||
user_agent=payload.user_agent,
|
||||
release=payload.release,
|
||||
user_email=payload.user_email,
|
||||
viewport=payload.viewport,
|
||||
locale=payload.locale,
|
||||
extra=payload.extra,
|
||||
)
|
||||
pattern_data = build_pattern_data(report)
|
||||
|
||||
try:
|
||||
result = _get_adapter().upsert_pattern(pattern_data)
|
||||
except Exception: # pragma: no cover - Firestore transient errors
|
||||
logger.exception("Failed to upsert frontend error pattern")
|
||||
raise HTTPException(status_code=503, detail="storage unavailable")
|
||||
|
||||
logger.info(
|
||||
"frontend_crash_reported pattern_id=%s is_new=%s source=%s",
|
||||
result.pattern_id,
|
||||
result.is_new,
|
||||
payload.source,
|
||||
)
|
||||
return ClientErrorResponse(pattern_id=result.pattern_id, is_new=result.is_new)
|
||||
@@ -2,23 +2,14 @@
|
||||
Encoding worker lifecycle endpoints.
|
||||
|
||||
Provides warmup and heartbeat endpoints for the blue-green
|
||||
encoding worker VMs. Called by the lyrics-review frontend to ensure the
|
||||
primary VM is running before the reviewer previews a render.
|
||||
|
||||
Auth: these are gated on ``require_review_auth`` (review access to a specific
|
||||
job), NOT ``require_admin``. The callers are ordinary customers on the
|
||||
lyrics-review page — gating on admin makes every non-admin caller 403, which
|
||||
silently defeats the JIT pre-warm. Scoping to the job being reviewed keeps the
|
||||
abuse posture identical to the rest of the review surface: you can only warm
|
||||
the shared encoding VM if you already have review access to a real job.
|
||||
encoding worker VMs. Called by the frontend to ensure the
|
||||
primary VM is running before encoding requests.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Tuple
|
||||
from fastapi import APIRouter, Depends
|
||||
from backend.api.dependencies import require_review_auth
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -44,50 +35,28 @@ def get_worker_manager():
|
||||
return _manager
|
||||
|
||||
|
||||
@router.post("/warmup/{job_id}")
|
||||
@router.post("/warmup")
|
||||
async def warmup_encoding_worker(
|
||||
job_id: str,
|
||||
_auth: Tuple[str, str] = Depends(require_review_auth),
|
||||
_admin=Depends(require_admin),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Start the primary encoding worker VM if it's stopped.
|
||||
|
||||
Called on lyrics-review page load so the VM is warm by the time the
|
||||
reviewer previews a render. ``job_id`` scopes auth to the job under review.
|
||||
"""
|
||||
"""Start the primary encoding worker VM if it's stopped."""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.info(f"Started encoding worker VM: {result['vm_name']}")
|
||||
return result
|
||||
except EncodingWorkerStartError as e:
|
||||
# The primary VM couldn't start (capacity exhaustion or a transient
|
||||
# 503 SERVICE_UNAVAILABLE from the GCE backend). This is NOT fatal:
|
||||
# the encoding flow's own warmup (ensure_any_running) falls back to
|
||||
# the alternate-zone workers, so the job still completes. Log at
|
||||
# WARNING so it doesn't trip the production error monitor and page us
|
||||
# for self-healing capacity events.
|
||||
logger.warning(
|
||||
f"Primary encoding worker warmup failed ({e}); "
|
||||
f"encoding will fall back to an alternate-zone worker"
|
||||
)
|
||||
return {"started": False, "error": str(e)}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to warm up encoding worker: {e}")
|
||||
return {"started": False, "error": str(e)}
|
||||
|
||||
|
||||
@router.post("/heartbeat/{job_id}")
|
||||
@router.post("/heartbeat")
|
||||
async def heartbeat_encoding_worker(
|
||||
job_id: str,
|
||||
_auth: Tuple[str, str] = Depends(require_review_auth),
|
||||
_admin=Depends(require_admin),
|
||||
manager=Depends(get_worker_manager),
|
||||
):
|
||||
"""Update activity timestamp to prevent idle shutdown.
|
||||
|
||||
Called periodically while the reviewer works. ``job_id`` scopes auth to the
|
||||
job under review.
|
||||
"""
|
||||
"""Update activity timestamp to prevent idle shutdown."""
|
||||
try:
|
||||
manager.update_activity()
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -10,11 +10,12 @@ Supports two upload flows:
|
||||
- Client uploads files directly to GCS using signed URLs (no size limit)
|
||||
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import os
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
|
||||
@@ -44,7 +45,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__)
|
||||
|
||||
@@ -57,19 +58,6 @@ def _is_youtube_url(url: str) -> bool:
|
||||
router = APIRouter(tags=["jobs"])
|
||||
|
||||
|
||||
def _select_mixed_audio_files(files):
|
||||
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
|
||||
|
||||
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
|
||||
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
|
||||
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
|
||||
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
|
||||
the instrumental — so transcription would run on the backing track instead of the
|
||||
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
|
||||
"""
|
||||
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
@@ -80,20 +68,12 @@ def _apply_tenant_overrides(
|
||||
"""
|
||||
Apply tenant-specific overrides to distribution settings and job options.
|
||||
|
||||
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
|
||||
distribution settings, so tenant outputs never inherit the global consumer defaults
|
||||
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
|
||||
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
|
||||
tenant job would land in the shared consumer Dropbox folder and upload to the global
|
||||
Google Drive, regardless of the tenant's own config.
|
||||
|
||||
For tenant jobs:
|
||||
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
|
||||
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
|
||||
otherwise disables that channel entirely (no global-default leak)
|
||||
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
|
||||
(only when not already set in the request body / dist)
|
||||
- Forces is_private = True
|
||||
- Applies locked_theme as effective theme
|
||||
- Disables YouTube upload (tenants never publish to YouTube)
|
||||
- Disables YouTube upload
|
||||
|
||||
Returns:
|
||||
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
|
||||
@@ -102,12 +82,14 @@ def _apply_tenant_overrides(
|
||||
return dist, effective_theme_id, is_private, enable_youtube_upload
|
||||
|
||||
defaults = tenant_config.defaults
|
||||
features = tenant_config.features
|
||||
|
||||
# Authoritative distribution routing (overrides any global defaults in `dist`).
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
|
||||
# Overlay tenant distribution defaults (request-level values take precedence)
|
||||
if defaults.brand_prefix and not dist.brand_prefix:
|
||||
dist.brand_prefix = defaults.brand_prefix
|
||||
if defaults.dropbox_path and not dist.dropbox_path:
|
||||
dist.dropbox_path = defaults.dropbox_path
|
||||
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
|
||||
dist.gdrive_folder_id = defaults.gdrive_folder_id
|
||||
|
||||
# Force private for all tenant jobs
|
||||
is_private = True
|
||||
@@ -356,6 +338,16 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
|
||||
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
|
||||
|
||||
|
||||
async def _trigger_audio_worker_only(job_id: str) -> None:
|
||||
"""
|
||||
Trigger only the audio worker.
|
||||
|
||||
Used for URL jobs where audio needs to be downloaded first.
|
||||
The audio worker will trigger the lyrics worker after download completes.
|
||||
"""
|
||||
await worker_service.trigger_audio_worker(job_id)
|
||||
|
||||
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
@@ -685,8 +677,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 +1261,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
|
||||
@@ -1405,14 +1393,12 @@ async def mark_uploads_complete(
|
||||
|
||||
# List files with this prefix to find the actual uploaded file
|
||||
files = storage_service.list_files(prefix)
|
||||
if file_type == 'audio':
|
||||
files = _select_mixed_audio_files(files)
|
||||
if not files:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
|
||||
)
|
||||
|
||||
|
||||
# Use the first (and should be only) file found
|
||||
gcs_path = files[0]
|
||||
|
||||
@@ -1585,140 +1571,11 @@ def _validate_url(url: Optional[str]) -> bool:
|
||||
for supported in supported_domains:
|
||||
if domain == supported or domain.endswith('.' + supported):
|
||||
return True
|
||||
|
||||
|
||||
# For other URLs, let yt-dlp try (it supports many more sites)
|
||||
return True
|
||||
|
||||
|
||||
# Streaming services whose catalogue is DRM-protected and therefore cannot be
|
||||
# downloaded by yt-dlp / flacfetch. Submitting one of these only creates a job
|
||||
# that fails deep in the download stage with a cryptic "Unsupported URL" error
|
||||
# (and lets the user trigger a futile retry), so we reject them at submission
|
||||
# time with a clear, actionable message. Maps host -> friendly platform name;
|
||||
# matching is suffix-based, so e.g. "spotify.com" also covers open./play.
|
||||
_UNSUPPORTED_DRM_HOSTS = {
|
||||
'music.apple.com': 'Apple Music',
|
||||
'itunes.apple.com': 'Apple Music',
|
||||
'spotify.com': 'Spotify',
|
||||
'tidal.com': 'Tidal',
|
||||
'deezer.com': 'Deezer',
|
||||
'pandora.com': 'Pandora',
|
||||
}
|
||||
|
||||
# Third-party tools that can download audio from a DRM platform, which the user
|
||||
# can then upload to us. Listed where we know of working options; platforms
|
||||
# without an entry fall back to a web-search link for "<platform> downloader".
|
||||
_DRM_DOWNLOADER_SUGGESTIONS = {
|
||||
'Apple Music': ['https://am-dl.pages.dev', 'https://aplmate.com'],
|
||||
'Spotify': ['https://spotdown.org', 'https://spotmate.online'],
|
||||
}
|
||||
|
||||
|
||||
def _drm_unsupported_detail(locale: str, platform: str) -> str:
|
||||
"""
|
||||
Build the user-facing 400 message for a rejected DRM streaming URL.
|
||||
|
||||
Platforms with known downloader tools get a "download from {tools}, then
|
||||
upload" message linking each tool; everything else gets a "search the web
|
||||
for a '<platform> downloader'" message linking a Google search. Either way
|
||||
the goal is to guide the user to obtain the audio and upload it themselves.
|
||||
"""
|
||||
downloaders = _DRM_DOWNLOADER_SUGGESTIONS.get(platform)
|
||||
if downloaders:
|
||||
# Join with commas (locale-neutral) rather than an English "or"; the
|
||||
# message wording frames them as options and LinkifiedText makes each
|
||||
# URL clickable in the frontend.
|
||||
return t(
|
||||
locale, "audioSearch.drmUrlUnsupportedWithLink",
|
||||
platform=platform, downloader=", ".join(downloaders),
|
||||
)
|
||||
|
||||
from urllib.parse import quote_plus
|
||||
search_url = "https://www.google.com/search?q=" + quote_plus(f"{platform} downloader")
|
||||
return t(
|
||||
locale, "audioSearch.drmUrlUnsupportedSearch",
|
||||
platform=platform, searchUrl=search_url,
|
||||
)
|
||||
|
||||
|
||||
def _unsupported_url_platform(url: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
Return a friendly platform name if the URL belongs to a known DRM-protected
|
||||
streaming service that cannot be downloaded, else None.
|
||||
|
||||
These links (Apple Music, Spotify, Tidal, Amazon Music, Deezer, Pandora) are
|
||||
rejected at submission time instead of being allowed to create a job that
|
||||
always fails deep in the download stage. Note: YouTube Music
|
||||
(music.youtube.com) is downloadable and is deliberately NOT included.
|
||||
"""
|
||||
if not url or not isinstance(url, str):
|
||||
return None
|
||||
|
||||
from urllib.parse import urlparse
|
||||
try:
|
||||
# .hostname is already lowercased and strips userinfo, port, and IPv6
|
||||
# brackets, so it's safer than parsing .netloc by hand.
|
||||
domain = (urlparse(url).hostname or "").lower()
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
if not domain:
|
||||
return None
|
||||
# Normalise leading www.
|
||||
if domain.startswith('www.'):
|
||||
domain = domain[4:]
|
||||
|
||||
for host, platform in _UNSUPPORTED_DRM_HOSTS.items():
|
||||
if domain == host or domain.endswith('.' + host):
|
||||
return platform
|
||||
|
||||
# Amazon Music spans many country domains (music.amazon.com, .co.uk, .co.jp,
|
||||
# .fr, .de, ...), so match the music.amazon.* prefix generically.
|
||||
if domain == 'music.amazon' or domain.startswith('music.amazon.'):
|
||||
return 'Amazon Music'
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class ValidateUrlRequest(BaseModel):
|
||||
"""Request to pre-validate a URL before submitting a job."""
|
||||
url: str = Field(..., description="The URL the user intends to submit")
|
||||
|
||||
|
||||
class ValidateUrlResponse(BaseModel):
|
||||
"""Whether a URL can be used for a job, with a friendly reason if not."""
|
||||
supported: bool
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
|
||||
async def validate_job_url(
|
||||
request: Request,
|
||||
body: ValidateUrlRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
) -> ValidateUrlResponse:
|
||||
"""
|
||||
Lightweight pre-flight check for a job URL, used by the guided submission
|
||||
flow so unsupported links are caught at the "Use this URL" step instead of
|
||||
only at final submit. Mirrors the URL validation in create_job_from_url.
|
||||
"""
|
||||
locale = get_locale_from_request(request)
|
||||
|
||||
platform = _unsupported_url_platform(body.url)
|
||||
if platform:
|
||||
return ValidateUrlResponse(
|
||||
supported=False, detail=_drm_unsupported_detail(locale, platform)
|
||||
)
|
||||
|
||||
if not _validate_url(body.url):
|
||||
return ValidateUrlResponse(
|
||||
supported=False,
|
||||
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL.",
|
||||
)
|
||||
|
||||
return ValidateUrlResponse(supported=True)
|
||||
|
||||
|
||||
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
|
||||
async def create_job_from_url(
|
||||
request: Request,
|
||||
@@ -1752,17 +1609,6 @@ async def create_job_from_url(
|
||||
)
|
||||
|
||||
try:
|
||||
# Reject DRM-protected streaming links upfront (Apple Music, Spotify,
|
||||
# Tidal, etc.). These can never be downloaded, so creating a job would
|
||||
# only fail deep in the pipeline with a cryptic error and tempt the user
|
||||
# into a futile retry storm.
|
||||
unsupported_platform = _unsupported_url_platform(body.url)
|
||||
if unsupported_platform:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=_drm_unsupported_detail(locale, unsupported_platform),
|
||||
)
|
||||
|
||||
# Validate URL
|
||||
if not _validate_url(body.url):
|
||||
raise HTTPException(
|
||||
@@ -1789,13 +1635,6 @@ async def create_job_from_url(
|
||||
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 — "
|
||||
"YouTube is asking our server to verify it's not a bot. "
|
||||
"Please try again in a few minutes, or use Audio Search to find this song "
|
||||
"from another source."
|
||||
)
|
||||
elif availability.get("is_age_restricted"):
|
||||
detail = "This YouTube video is age-restricted and cannot be downloaded."
|
||||
else:
|
||||
@@ -1901,8 +1740,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
|
||||
@@ -1940,47 +1777,55 @@ async def create_job_from_url(
|
||||
if title:
|
||||
logger.info(f" Title: {title}")
|
||||
|
||||
# Download audio NOW via the flacfetch service for ALL URLs (YouTube and
|
||||
# any other yt-dlp-supported site, e.g. Facebook/SoundCloud/TikTok).
|
||||
# flacfetch is the sole downloader — no yt-dlp ever runs on Cloud Run.
|
||||
# Downloading up front (before the GPU worker starts) also keeps the GPU
|
||||
# idle until the audio is in GCS.
|
||||
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
|
||||
try:
|
||||
download_service = get_youtube_download_service()
|
||||
audio_gcs_path = await download_service.download(
|
||||
url=body.url,
|
||||
# For YouTube URLs, download audio NOW using YouTubeDownloadService
|
||||
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
|
||||
if _is_youtube_url(body.url):
|
||||
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
|
||||
try:
|
||||
youtube_service = get_youtube_download_service()
|
||||
audio_gcs_path = await youtube_service.download(
|
||||
url=body.url,
|
||||
job_id=job_id,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
# Update job with the downloaded audio path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
10, # progress
|
||||
"Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
except YouTubeDownloadError as e:
|
||||
logger.error(f"YouTube download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
|
||||
)
|
||||
else:
|
||||
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
|
||||
# The audio worker will download the URL and trigger lyrics worker after
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
# Update job with the downloaded audio path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': os.path.basename(audio_gcs_path),
|
||||
})
|
||||
|
||||
logger.info(f"Audio downloaded to GCS: {audio_gcs_path}")
|
||||
|
||||
# Use centralized start_job_processing which handles:
|
||||
# 1. Validates job exists and has input_media_gcs_path
|
||||
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
|
||||
# 3. Triggers audio + lyrics workers in parallel
|
||||
background_tasks.add_task(
|
||||
job_manager.start_job_processing,
|
||||
job_id,
|
||||
10, # progress
|
||||
"Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
except YouTubeDownloadError as e:
|
||||
logger.error(f"URL download failed: {e}")
|
||||
job_manager.fail_job(job_id, f"Download failed: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message="Starting audio download from URL"
|
||||
)
|
||||
background_tasks.add_task(_trigger_audio_worker_only, job_id)
|
||||
|
||||
return CreateJobFromUrlResponse(
|
||||
status="success",
|
||||
@@ -2208,8 +2053,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}")
|
||||
|
||||
+35
-445
@@ -20,7 +20,6 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.workers.audio_worker import process_audio_separation
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
from backend.workers.lyrics_worker import process_lyrics_transcription
|
||||
from backend.workers.screens_worker import generate_screens
|
||||
from backend.workers.video_worker import generate_video
|
||||
@@ -228,48 +227,6 @@ async def trigger_lyrics_worker(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/auto-correct", response_model=WorkerResponse)
|
||||
async def trigger_auto_correct_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Proactively pre-generate + cache AI auto-correct suggestions for a job.
|
||||
|
||||
Called by the lyrics worker once transcription + references are ready, so
|
||||
the suggestions are cached before the reviewer opens the lyrics UI. Runs
|
||||
HERE (the API service) because the service has the working Anthropic key /
|
||||
compare-models config; the lyrics job does not.
|
||||
|
||||
Best-effort and runs synchronously within the request (the caller awaits
|
||||
with its own timeout): the work never fails the karaoke job, and the
|
||||
response just reports what happened. Gated by AUTO_CORRECT_PROACTIVE_ENABLED.
|
||||
"""
|
||||
job_id = request.job_id
|
||||
|
||||
# Extract trace context from incoming request (propagated via the trigger).
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
logger.info(f"[job:{job_id}] WORKER_TRIGGER worker=auto-correct")
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("worker", "auto-correct")
|
||||
|
||||
# process_proactive_auto_correct already swallows its own errors; the extra
|
||||
# guard keeps the endpoint itself best-effort no matter what.
|
||||
try:
|
||||
result = await process_proactive_auto_correct(job_id)
|
||||
add_span_event("auto_correct_proactive", {"result": result.get("status", "unknown")})
|
||||
return WorkerResponse(
|
||||
status=result.get("status", "unknown"),
|
||||
job_id=job_id,
|
||||
message=f"Proactive auto-correct: {result.get('status', 'unknown')}",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 — best-effort, never fail the caller
|
||||
logger.warning(f"[job:{job_id}] auto-correct endpoint error (non-fatal): {e}")
|
||||
add_span_event("auto_correct_proactive", {"result": "error"})
|
||||
return WorkerResponse(status="error", job_id=job_id, message=f"error: {e}")
|
||||
|
||||
|
||||
@router.post("/workers/screens", response_model=WorkerResponse)
|
||||
async def trigger_screens_worker(
|
||||
request: WorkerRequest,
|
||||
@@ -405,9 +362,8 @@ async def check_idle_reminder(
|
||||
"""
|
||||
Check if a job needs an idle reminder email.
|
||||
|
||||
This endpoint is called by a Cloud Tasks scheduled task after a job enters
|
||||
a blocking state (AWAITING_REVIEW, AWAITING_AUDIO_EDIT, AWAITING_DURATION_CONFIRM,
|
||||
or the legacy AWAITING_INSTRUMENTAL_SELECTION).
|
||||
This endpoint is called by a Cloud Tasks scheduled task 5 minutes after
|
||||
a job enters AWAITING_REVIEW state.
|
||||
|
||||
If the job is still in the blocking state and no reminder has been sent yet,
|
||||
sends a reminder email to the user.
|
||||
@@ -434,11 +390,7 @@ async def check_idle_reminder(
|
||||
|
||||
# Check if job is still in a blocking state
|
||||
# Note: AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs only
|
||||
blocking_states = [
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
|
||||
JobStatus.AWAITING_DURATION_CONFIRM,
|
||||
]
|
||||
blocking_states = [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]
|
||||
if job.status not in [s.value for s in blocking_states]:
|
||||
logger.info(f"[job:{job_id}] Job no longer in blocking state ({job.status}), skipping reminder")
|
||||
add_span_event("not_blocking", {"current_status": job.status})
|
||||
@@ -472,32 +424,23 @@ async def check_idle_reminder(
|
||||
# Determine action type
|
||||
action_type = state_data.get('blocking_action_type')
|
||||
if not action_type:
|
||||
if job.status == JobStatus.AWAITING_REVIEW.value:
|
||||
action_type = "lyrics"
|
||||
elif job.status == JobStatus.AWAITING_DURATION_CONFIRM.value:
|
||||
action_type = "duration_confirm"
|
||||
else:
|
||||
action_type = "instrumental"
|
||||
action_type = "lyrics" if job.status == JobStatus.AWAITING_REVIEW.value else "instrumental"
|
||||
|
||||
# Send the reminder email
|
||||
try:
|
||||
notification_service = get_job_notification_service()
|
||||
|
||||
if action_type == "duration_confirm":
|
||||
# Duration-confirm has its own dedicated reminder method
|
||||
success = await notification_service.send_duration_confirm_reminder(job)
|
||||
else:
|
||||
success = await notification_service.send_action_reminder_email(
|
||||
job_id=job.job_id,
|
||||
user_email=job.user_email,
|
||||
action_type=action_type,
|
||||
user_name=None, # Could fetch from user service if needed
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
audio_hash=job.audio_hash,
|
||||
review_token=job.review_token,
|
||||
instrumental_token=job.instrumental_token,
|
||||
)
|
||||
success = await notification_service.send_action_reminder_email(
|
||||
job_id=job.job_id,
|
||||
user_email=job.user_email,
|
||||
action_type=action_type,
|
||||
user_name=None, # Could fetch from user service if needed
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
audio_hash=job.audio_hash,
|
||||
review_token=job.review_token,
|
||||
instrumental_token=job.instrumental_token,
|
||||
)
|
||||
|
||||
if success:
|
||||
# Mark reminder as sent (prevents duplicate sends)
|
||||
@@ -633,417 +576,64 @@ async def trigger_gdrive_validation_endpoint(
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@router.post("/retry-pending-render-jobs")
|
||||
async def retry_pending_render_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
|
||||
|
||||
Called every 5 minutes by Cloud Scheduler. When the GCE encoding worker
|
||||
can't be started because the zone is exhausted, the render worker parks
|
||||
the job in this state instead of failing it. This endpoint re-attempts
|
||||
the render — when GCE has capacity, the start succeeds and the job
|
||||
completes normally.
|
||||
|
||||
Strategy:
|
||||
- Process up to MAX_PER_TICK jobs (the GCE worker is single-tenant per
|
||||
render, so spinning up many in parallel just collides on the same VM)
|
||||
- Pick the oldest first (longest waiter gets fairness)
|
||||
- Time out jobs that have been waiting longer than MAX_WAIT_SECONDS;
|
||||
transition them to FAILED with a clear permanent-failure message
|
||||
- For each remaining job: clear error state, reset to REVIEW_COMPLETE,
|
||||
kick off the render worker again
|
||||
"""
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
# Long enough to ride out a sustained capacity outage but short enough
|
||||
# that an op gets paged about it before the user sees a "still pending"
|
||||
# job >24h old.
|
||||
MAX_WAIT_SECONDS = 24 * 60 * 60 # 24h
|
||||
MAX_PER_TICK = 1 # one render at a time on the GCE worker
|
||||
|
||||
extract_trace_context(dict(http_request.headers))
|
||||
add_span_attribute("operation", "retry_pending_render_jobs")
|
||||
logger.info("RETRY_PENDING_RENDER_JOBS starting")
|
||||
|
||||
job_manager = JobManager()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
# Filter by status only — sorting by updated_at server-side would require
|
||||
# a composite Firestore index that we don't have. The pending-capacity
|
||||
# population is small (handful of jobs at most), so streaming and
|
||||
# sorting in Python is cheap and avoids the index ceremony.
|
||||
pending_query = (
|
||||
jobs_ref
|
||||
.where(filter=FieldFilter("status", "==", JobStatus.RENDER_PENDING_CAPACITY.value))
|
||||
.limit(50) # cap defensively in case the queue ever grows
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
timed_out = []
|
||||
retried = []
|
||||
skipped = 0
|
||||
|
||||
# Materialize and sort by first_seen_at (oldest waiter first). Falls back
|
||||
# to updated_at, then doc id, when meta is missing.
|
||||
pending_docs = list(pending_query.stream())
|
||||
|
||||
def _sort_key(doc):
|
||||
data = doc.to_dict() or {}
|
||||
meta = (data.get("state_data") or {}).get("render_pending_capacity") or {}
|
||||
first_seen = meta.get("first_seen_at") or ""
|
||||
updated = data.get("updated_at")
|
||||
# Firestore returns a datetime; isoformat sorts correctly within the same TZ.
|
||||
updated_str = updated.isoformat() if hasattr(updated, "isoformat") else str(updated or "")
|
||||
return (first_seen, updated_str, doc.id)
|
||||
|
||||
pending_docs.sort(key=_sort_key)
|
||||
|
||||
for doc in pending_docs:
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
sd = job_data.get("state_data") or {}
|
||||
pending_meta = sd.get("render_pending_capacity") or {}
|
||||
first_seen = pending_meta.get("first_seen_at")
|
||||
|
||||
# Permanent-failure timeout
|
||||
if first_seen:
|
||||
try:
|
||||
first_seen_dt = datetime.fromisoformat(first_seen)
|
||||
age = now - first_seen_dt
|
||||
except (ValueError, TypeError):
|
||||
age = timedelta(0)
|
||||
if age.total_seconds() > MAX_WAIT_SECONDS:
|
||||
permanent_msg = (
|
||||
"Encoding capacity remained unavailable after "
|
||||
f"{int(age.total_seconds() // 3600)}h of automatic retries. "
|
||||
"Please retry manually or contact support."
|
||||
)
|
||||
logger.error(
|
||||
f"[job:{job_id}] Capacity wait exceeded {MAX_WAIT_SECONDS}s — failing permanently"
|
||||
)
|
||||
job_manager.fail_job(job_id, permanent_msg, error_details={
|
||||
"stage": "render_video",
|
||||
"permanent_capacity_timeout": True,
|
||||
"first_seen_at": first_seen,
|
||||
"attempts": pending_meta.get("attempt_count", 0),
|
||||
})
|
||||
timed_out.append(job_id)
|
||||
continue
|
||||
|
||||
if len(retried) >= MAX_PER_TICK:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Clear error state and reset render progress for idempotency.
|
||||
# render_pending_capacity meta is preserved so the next failure (if any)
|
||||
# increments the existing attempt counter.
|
||||
job_manager.update_job(job_id, {
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
})
|
||||
job_manager.update_state_data(job_id, "render_progress", {"stage": "pending"})
|
||||
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.REVIEW_COMPLETE,
|
||||
progress=70,
|
||||
message="Auto-retrying video render — encoding capacity check",
|
||||
raise_on_invalid=False,
|
||||
):
|
||||
logger.warning(f"[job:{job_id}] Could not transition to REVIEW_COMPLETE for retry")
|
||||
continue
|
||||
|
||||
try:
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
retried.append(job_id)
|
||||
logger.info(f"[job:{job_id}] Auto-retry triggered")
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Failed to trigger render worker: {e}")
|
||||
# Job remains in REVIEW_COMPLETE — next tick will pick it up if it
|
||||
# falls back to RENDER_PENDING_CAPACITY again.
|
||||
|
||||
add_span_event("retry_complete", {
|
||||
"retried": len(retried),
|
||||
"timed_out": len(timed_out),
|
||||
"skipped": skipped,
|
||||
})
|
||||
logger.info(
|
||||
f"RETRY_PENDING_RENDER_JOBS complete: retried={len(retried)} "
|
||||
f"timed_out={len(timed_out)} skipped={skipped}"
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"retried_jobs": retried,
|
||||
"retried_count": len(retried),
|
||||
"timed_out_jobs": timed_out,
|
||||
"timed_out_count": len(timed_out),
|
||||
"skipped_for_next_tick": skipped,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/recover-stuck-jobs")
|
||||
async def recover_stuck_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Detect and recover jobs stuck in a processing status.
|
||||
Detect and recover jobs stuck in downloading_audio status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
- DOWNLOADING_AUDIO stuck >10 min:
|
||||
* torrent sources (RED/OPS) → park into DOWNLOAD_PENDING_RETRY and keep
|
||||
auto-retrying for up to 24h (handles rare tracks with intermittent
|
||||
seeders and transient tracker outages gracefully).
|
||||
* other sources → fail so the user can retry.
|
||||
- DOWNLOAD_PENDING_RETRY → re-trigger the download; permanently fail after 24h.
|
||||
- RENDERING_VIDEO stuck with no progress (worker died mid-render) →
|
||||
re-park into RENDER_PENDING_CAPACITY so the existing
|
||||
retry-pending-render-jobs cron resumes it automatically. Closes the orphan
|
||||
gap where a hard-killed render worker leaves the job frozen at
|
||||
"rendering_video" forever with no error and no Retry button.
|
||||
Finds jobs stuck in DOWNLOADING_AUDIO for >10 minutes and fails them
|
||||
so they can be retried.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
extract_trace_context(dict(http_request.headers))
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
logger.info("RECOVER_STUCK_JOBS starting")
|
||||
add_span_attribute("operation", "recover_stuck_jobs")
|
||||
|
||||
job_manager = JobManager()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
# Query jobs in downloading_audio status
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
|
||||
recovered = [] # download jobs failed for user retry
|
||||
download_parked = [] # transient torrent downloads parked for auto-retry
|
||||
download_retried = [] # parked downloads re-triggered this tick
|
||||
download_timed_out = [] # parked downloads that exceeded the 24h ceiling
|
||||
reparked = [] # render jobs re-parked for auto-retry
|
||||
|
||||
# --- Stuck audio downloads: park torrents for auto-retry, else fail ---
|
||||
stuck_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING_AUDIO.value)
|
||||
filter=FieldFilter("status", "==", "downloading_audio")
|
||||
).stream()
|
||||
|
||||
recovered = []
|
||||
for doc in stuck_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
# Use the health service to check if actually stuck
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if not any("downloading_audio_stuck" in i for i in check_job_consistency(job)):
|
||||
continue
|
||||
if _is_retryable_torrent_source(job):
|
||||
logger.warning(f"[job:{job_id}] Parking stuck torrent download for auto-retry")
|
||||
if _park_download_for_retry(job_manager, job_id, "download stalled (>10 min)"):
|
||||
download_parked.append(job_id)
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download (non-torrent)")
|
||||
|
||||
issues = check_job_consistency(job)
|
||||
stuck_issues = [i for i in issues if "downloading_audio_stuck" in i]
|
||||
|
||||
if stuck_issues:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download: {stuck_issues[0]}")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
"Audio download timed out (stuck >10 minutes). Use retry to re-attempt."
|
||||
)
|
||||
recovered.append(job_id)
|
||||
|
||||
# --- Parked downloads: re-trigger, or permanently fail after 24h ---
|
||||
retried_this_tick = 0
|
||||
pending_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOAD_PENDING_RETRY.value)
|
||||
).limit(100).stream()
|
||||
for doc in pending_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
meta = (job.state_data or {}).get("download_retry", {}) or {}
|
||||
first_seen = meta.get("first_seen_at")
|
||||
if _download_retry_expired(first_seen):
|
||||
hours = int(DOWNLOAD_RETRY_MAX_SECONDS // 3600)
|
||||
logger.error(f"[job:{job_id}] Download retries exhausted after {hours}h — failing")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Couldn't find a working source for this track after {hours}h of "
|
||||
"automatic retries. It may be too rare to source right now — please "
|
||||
"try a different version or contact support.",
|
||||
error_details={"stage": "audio_download", "permanent_download_timeout": True},
|
||||
)
|
||||
download_timed_out.append(job_id)
|
||||
continue
|
||||
if retried_this_tick >= DOWNLOAD_RETRIES_PER_TICK:
|
||||
continue
|
||||
# Count the dispatch ATTEMPT against the per-tick cap before awaiting, so
|
||||
# a failing audio-worker (helper returns False after an external dispatch)
|
||||
# can't fan out to every queried job in one tick.
|
||||
retried_this_tick += 1
|
||||
if await _retrigger_parked_download(job_manager, worker_service, job_id):
|
||||
download_retried.append(job_id)
|
||||
|
||||
# --- Orphaned renders: re-park for automatic retry ---
|
||||
render_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.RENDERING_VIDEO.value)
|
||||
).stream()
|
||||
for doc in render_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if any("rendering_video_stuck" in i for i in check_job_consistency(job)):
|
||||
logger.warning(f"[job:{job_id}] Re-parking orphaned render for auto-retry")
|
||||
if _repark_stalled_render(job_manager, job_id):
|
||||
reparked.append(job_id)
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
"download_parked_count": len(download_parked),
|
||||
"download_retried_count": len(download_retried),
|
||||
"download_timed_out_count": len(download_timed_out),
|
||||
"reparked_count": len(reparked),
|
||||
})
|
||||
logger.info(f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} jobs")
|
||||
add_span_event("recovery_complete", {"recovered_count": len(recovered)})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"recovered_jobs": recovered,
|
||||
"recovered_count": len(recovered),
|
||||
"download_parked_jobs": download_parked,
|
||||
"download_retried_jobs": download_retried,
|
||||
"download_timed_out_jobs": download_timed_out,
|
||||
"reparked_render_jobs": reparked,
|
||||
"reparked_render_count": len(reparked),
|
||||
}
|
||||
|
||||
|
||||
# Torrent sources whose downloads are worth auto-retrying over a long window —
|
||||
# they fail transiently when a rare release has few/intermittent seeders or the
|
||||
# private tracker is briefly unreachable. Non-torrent sources (YouTube/Spotify/
|
||||
# URL) fail deterministically, so they are not auto-retried here.
|
||||
RETRYABLE_TORRENT_SOURCES = frozenset({"RED", "OPS"})
|
||||
DOWNLOAD_RETRY_MAX_SECONDS = 24 * 60 * 60 # keep retrying a transient download for 24h
|
||||
DOWNLOAD_RETRIES_PER_TICK = 10 # cap re-triggers per 5-min tick
|
||||
|
||||
|
||||
def _is_retryable_torrent_source(job) -> bool:
|
||||
"""True if the job's audio came from a torrent tracker (RED/OPS)."""
|
||||
return (getattr(job, "source_name", "") or "").upper() in RETRYABLE_TORRENT_SOURCES
|
||||
|
||||
|
||||
def _download_retry_expired(first_seen_at: Optional[str]) -> bool:
|
||||
"""True if the first parked failure is older than the 24h retry ceiling."""
|
||||
if not first_seen_at:
|
||||
return False
|
||||
from datetime import datetime, UTC
|
||||
try:
|
||||
age = datetime.now(UTC) - datetime.fromisoformat(first_seen_at)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return age.total_seconds() > DOWNLOAD_RETRY_MAX_SECONDS
|
||||
|
||||
|
||||
def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str) -> bool:
|
||||
"""Park a transient torrent-download failure into DOWNLOAD_PENDING_RETRY.
|
||||
|
||||
The recover-stuck cron re-triggers parked downloads on later ticks (up to
|
||||
24h) instead of dead-ending the job at FAILED after ~1h.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
job = job_manager.get_job(job_id)
|
||||
existing = (job.state_data or {}).get("download_retry", {}) if job else {}
|
||||
meta = {
|
||||
"first_seen_at": existing.get("first_seen_at") or now,
|
||||
"last_attempt_at": now,
|
||||
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
|
||||
"last_reason": str(reason)[:300],
|
||||
}
|
||||
job_manager.update_state_data(job_id, "download_retry", meta)
|
||||
# Clear any Cloud Run auto-retry marker so the UI reflects the parked state.
|
||||
job_manager.update_state_data(job_id, "cloud_run_retry_pending", None)
|
||||
return bool(job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOAD_PENDING_RETRY,
|
||||
progress=12,
|
||||
message=(
|
||||
"Still finding a good source for this track — it may be rare, or a "
|
||||
"source is temporarily offline. We'll keep trying automatically for up "
|
||||
"to 24 hours; no action needed."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
))
|
||||
|
||||
|
||||
async def _retrigger_parked_download(job_manager: JobManager, worker_service, job_id: str) -> bool:
|
||||
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job."""
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
job_manager.update_job(job_id, {"error_message": None, "error_details": None})
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=12,
|
||||
message="Retrying audio download — checking sources again",
|
||||
raise_on_invalid=False,
|
||||
):
|
||||
logger.warning(f"[job:{job_id}] Could not transition parked download for retry")
|
||||
return False
|
||||
try:
|
||||
await worker_service.trigger_audio_download_worker(job_id)
|
||||
logger.info(f"[job:{job_id}] Parked download re-triggered")
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"[job:{job_id}] Failed to re-trigger parked download: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _repark_stalled_render(job_manager: JobManager, job_id: str) -> bool:
|
||||
"""Re-park a render orphaned at RENDERING_VIDEO into RENDER_PENDING_CAPACITY.
|
||||
|
||||
Mirrors render_video_worker._park_job_for_capacity_retry but for a mid-render
|
||||
stall (no EncodingWorkerStartError to carry). The existing
|
||||
retry-pending-render-jobs cron then resets it to REVIEW_COMPLETE and
|
||||
re-triggers the render, with the same 24h permanent-failure ceiling.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
job = job_manager.get_job(job_id)
|
||||
existing = (job.state_data or {}).get("render_pending_capacity", {}) if job else {}
|
||||
pending_meta = {
|
||||
"first_seen_at": existing.get("first_seen_at") or now,
|
||||
"last_attempt_at": now,
|
||||
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
|
||||
"last_code": "render_stalled",
|
||||
"last_zone": existing.get("last_zone", ""),
|
||||
"last_vm": existing.get("last_vm", ""),
|
||||
}
|
||||
job_manager.update_state_data(job_id, "render_pending_capacity", pending_meta)
|
||||
return bool(job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDER_PENDING_CAPACITY,
|
||||
progress=70,
|
||||
message=(
|
||||
"The render was interrupted (a worker was recycled). Your job will "
|
||||
"retry automatically — no action needed."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
))
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
|
||||
+28
-415
@@ -17,8 +17,7 @@ from pathlib import Path
|
||||
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 datetime import datetime
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
@@ -39,16 +38,13 @@ 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
|
||||
from backend.services.firestore_service import FirestoreService, log_to_job
|
||||
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.youtube_download_service import get_youtube_download_service
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from pydantic import BaseModel, Field, HttpUrl, validator
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -124,32 +120,6 @@ async def create_job(
|
||||
)
|
||||
logger.info(f"Applying default theme: {effective_theme_id}")
|
||||
|
||||
# Duration-based pricing: derive credit cost from known audio duration.
|
||||
# Reject inputs that are too long before any job is created.
|
||||
duration_seconds = request.duration_seconds
|
||||
if duration_seconds is not None and is_blocked(duration_seconds):
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="Inputs over 60 minutes aren't supported"
|
||||
)
|
||||
credits = duration_to_credits(duration_seconds) if duration_seconds is not None else 1
|
||||
|
||||
# Anti-mismatch guard: if the client told us how many credits it expects,
|
||||
# reject early if the server's computation disagrees (avoids surprise charges).
|
||||
if request.acknowledged_credits is not None and request.acknowledged_credits != credits:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Credit figure changed; please refresh"
|
||||
)
|
||||
|
||||
# Build initial state_data with duration estimate for observability.
|
||||
initial_state_data: Dict[str, Any] = {}
|
||||
if duration_seconds is not None:
|
||||
initial_state_data["duration_estimate_seconds"] = duration_seconds
|
||||
initial_state_data["duration_estimate_source"] = "youtube_metadata"
|
||||
else:
|
||||
initial_state_data["duration_estimate_source"] = "unknown"
|
||||
|
||||
# Create job with all preferences
|
||||
job_create = JobCreate(
|
||||
url=str(request.url),
|
||||
@@ -163,19 +133,13 @@ async def create_job(
|
||||
webhook_url=request.webhook_url,
|
||||
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)
|
||||
|
||||
# Persist duration estimate fields and creation_ip in a single Firestore write.
|
||||
update_payload = {
|
||||
f"state_data.{k}": v for k, v in initial_state_data.items()
|
||||
}
|
||||
# Store client IP on job for anti-abuse correlation
|
||||
creation_ip = get_client_ip(http_request)
|
||||
if creation_ip:
|
||||
update_payload["creation_ip"] = creation_ip
|
||||
FirestoreService().update_job(job.job_id, update_payload)
|
||||
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
|
||||
|
||||
# Trace attributes for observability
|
||||
add_span_attribute("job_id", job.job_id)
|
||||
@@ -196,7 +160,7 @@ async def create_job(
|
||||
job_id=job.job_id,
|
||||
message=t(locale, "jobs.created")
|
||||
)
|
||||
except (InsufficientCreditsError, HTTPException):
|
||||
except InsufficientCreditsError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating job: {e}", exc_info=True)
|
||||
@@ -398,11 +362,6 @@ async def edit_completed_track(
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
# Also remove the Nomad 720p master from the GCS fast-sync mirror
|
||||
# (prefix-keyed by brand_code, so it covers renames). Non-fatal,
|
||||
# Nomad-brand only, no-op otherwise.
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
else:
|
||||
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
except Exception as e:
|
||||
@@ -577,58 +536,11 @@ _SUMMARY_STATE_DATA_KEYS = {
|
||||
'audio_progress', 'lyrics_progress',
|
||||
'audio_complete', 'lyrics_complete',
|
||||
'backing_vocals_analysis', 'visibility_change_in_progress',
|
||||
'render_pending_capacity',
|
||||
'cloud_run_retry_pending',
|
||||
'credits_charged',
|
||||
'pending_additional_credits',
|
||||
'duration_actual_seconds',
|
||||
'duration_confirm_reason',
|
||||
'batch_id',
|
||||
'bulk_auto_selected',
|
||||
}
|
||||
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
|
||||
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
|
||||
|
||||
|
||||
def _is_auto_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
|
||||
"""Return True if a Cloud Run Job auto-retry is currently expected.
|
||||
|
||||
The audio-download worker records `state_data.cloud_run_retry_pending`
|
||||
with an `expires_at` when it fails and another task attempt is coming.
|
||||
The /retry endpoint uses this to refuse starting a parallel execution,
|
||||
and the UI uses the projected field to show a "Retrying automatically..."
|
||||
indicator instead of a Retry button.
|
||||
"""
|
||||
pending = (state_data or {}).get('cloud_run_retry_pending')
|
||||
if not isinstance(pending, dict):
|
||||
return False
|
||||
expires_at_str = pending.get('expires_at')
|
||||
if not expires_at_str:
|
||||
return False
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(str(expires_at_str).replace('Z', '+00:00'))
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
return expires_at > datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _has_title_screen(file_urls: Dict[str, Any]) -> bool:
|
||||
"""Return True if a title screen image (jpg or png) was generated.
|
||||
|
||||
Used by the /retry endpoint to decide whether to resume from the render
|
||||
stage or rewind further. The actual screen URLs live under format-specific
|
||||
keys (`title_jpg`, `title_png`) rather than a bare `title` key, so a
|
||||
naive `screens.get('title')` check produced false-negatives and forced
|
||||
completed-review jobs back to AWAITING_REVIEW.
|
||||
"""
|
||||
screens = file_urls.get('screens') or {}
|
||||
if not isinstance(screens, dict):
|
||||
return False
|
||||
return any(k == 'title' or k.startswith('title_') for k in screens)
|
||||
|
||||
|
||||
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Strip state_data down to dashboard-required keys."""
|
||||
sd = data.get('state_data')
|
||||
@@ -1083,32 +995,17 @@ async def submit_corrections(
|
||||
)
|
||||
|
||||
try:
|
||||
# Persist ONLY a lightweight summary of the corrections to Firestore —
|
||||
# never the full segment arrays. The complete corrections JSON
|
||||
# (corrected_segments, original_segments, resized_segments, etc.) can be
|
||||
# several MB for long songs (e.g. a 30+ minute mashup with hundreds of
|
||||
# segments) and would blow past Firestore's 1MB per-document hard limit,
|
||||
# failing the save with a 400. (An earlier fix stripped only
|
||||
# reference_lyrics, but the segment arrays are the real bulk.) The full
|
||||
# data is preserved in the GCS upload below (corrections_updated.json),
|
||||
# which the render worker reads. The only in-Firestore consumer is the
|
||||
# complete-review 0-segment guard, which just needs the segment count.
|
||||
corrected_segments = submission.corrections.get('corrected_segments')
|
||||
corrected_lyrics_summary = {
|
||||
'corrected_segment_count': (
|
||||
len(corrected_segments) if isinstance(corrected_segments, list) else 0
|
||||
),
|
||||
# Strip reference_lyrics from Firestore save to avoid exceeding 1MB document
|
||||
# limit. reference_lyrics can be very large (e.g. Genius fetching non-lyrics
|
||||
# content like screenplays). The full data is preserved in the GCS upload below.
|
||||
corrections_for_firestore = {
|
||||
k: v for k, v in submission.corrections.items()
|
||||
if k != 'reference_lyrics'
|
||||
}
|
||||
job_manager.update_state_data(job_id, 'corrected_lyrics', corrected_lyrics_summary)
|
||||
job_manager.update_state_data(job_id, 'corrected_lyrics', corrections_for_firestore)
|
||||
if submission.user_notes:
|
||||
job_manager.update_state_data(job_id, 'review_notes', submission.user_notes)
|
||||
|
||||
# Persist is_duet when explicitly provided; don't overwrite a previously-set flag
|
||||
# when the field is absent from the request (None means "not specified").
|
||||
if submission.is_duet is not None:
|
||||
job_manager.update_state_data(job_id, 'is_duet', submission.is_duet)
|
||||
logger.info(f"Job {job_id}: Stored is_duet flag via /corrections: {submission.is_duet}")
|
||||
|
||||
|
||||
# Transition to IN_REVIEW if not already
|
||||
if job.status == JobStatus.AWAITING_REVIEW:
|
||||
job_manager.transition_to_state(
|
||||
@@ -1116,27 +1013,15 @@ async def submit_corrections(
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User is reviewing lyrics"
|
||||
)
|
||||
|
||||
|
||||
# Save updated corrections to GCS for the render worker
|
||||
from backend.services.storage_service import StorageService
|
||||
storage = StorageService()
|
||||
|
||||
# Safety net: never persist word timings that fall outside their segment.
|
||||
# Frontend should already prevent this; this guarantees clean stored data
|
||||
# (the render worker reads corrections_updated.json verbatim).
|
||||
from backend.services.timing_sanitizer import sanitize_corrections
|
||||
sanitized, clamp_count = sanitize_corrections(submission.corrections)
|
||||
if clamp_count:
|
||||
logger.warning(
|
||||
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
|
||||
f"in submitted corrections before persisting"
|
||||
)
|
||||
submission.corrections = sanitized
|
||||
|
||||
|
||||
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
storage.upload_json(corrections_gcs_path, submission.corrections)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
|
||||
|
||||
|
||||
logger.info(f"Job {job_id}: Corrections saved (review in progress)")
|
||||
|
||||
return {
|
||||
@@ -1467,15 +1352,10 @@ async def complete_review(
|
||||
lyrics_metadata = state_data.get('lyrics_metadata')
|
||||
if lyrics_metadata is not None:
|
||||
segment_count = lyrics_metadata.get('segment_count', 0)
|
||||
corrected_lyrics = state_data.get('corrected_lyrics') or {}
|
||||
# corrected_lyrics now stores a lightweight summary
|
||||
# ({'corrected_segment_count': N}). Fall back to the legacy shape (full
|
||||
# dict with a corrected_segments list) for jobs saved before that change.
|
||||
corrected_segment_count = corrected_lyrics.get('corrected_segment_count')
|
||||
if corrected_segment_count is None:
|
||||
corrected_segment_count = len(corrected_lyrics.get('corrected_segments') or [])
|
||||
corrected_lyrics = state_data.get('corrected_lyrics', {})
|
||||
corrected_segments = corrected_lyrics.get('corrected_segments', [])
|
||||
|
||||
if segment_count == 0 and corrected_segment_count == 0:
|
||||
if segment_count == 0 and len(corrected_segments) == 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t(locale, "jobs.noLyricsDetected")
|
||||
@@ -1484,13 +1364,6 @@ async def complete_review(
|
||||
try:
|
||||
# Store instrumental selection if provided (combined review flow)
|
||||
instrumental_selection = body.instrumental_selection if body else None
|
||||
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
|
||||
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
|
||||
# render uses the provided instrumental instead of a separated stem that was never
|
||||
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
|
||||
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
instrumental_selection = 'custom'
|
||||
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
|
||||
if instrumental_selection:
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
|
||||
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
|
||||
@@ -1648,17 +1521,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 +1594,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 +1629,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}")
|
||||
|
||||
@@ -1853,15 +1701,6 @@ async def retry_job(
|
||||
detail=t(locale, "jobs.notCompleted", status=job.status)
|
||||
)
|
||||
|
||||
# Refuse if a Cloud Run Job auto-retry is already coming for this job.
|
||||
# Otherwise the manual retry races with the automatic one and produces
|
||||
# duplicate downloads and downstream worker triggers (see job 8a9c74ff).
|
||||
if _is_auto_retry_pending(job.state_data):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="An automatic retry is already in progress. Please wait a few minutes."
|
||||
)
|
||||
|
||||
try:
|
||||
# Determine retry point based on what's already complete
|
||||
error_details = job.error_details or {}
|
||||
@@ -1913,7 +1752,7 @@ async def retry_job(
|
||||
# Review completion is proven by instrumental_selection in state_data
|
||||
# (set only when user submits the review endpoint)
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
_has_title_screen(file_urls) and
|
||||
file_urls.get('screens', {}).get('title') and
|
||||
state_data.get('instrumental_selection')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
|
||||
@@ -1950,7 +1789,7 @@ async def retry_job(
|
||||
# If we have corrections and screens but review was NOT completed,
|
||||
# return to awaiting_review so the user can review lyrics
|
||||
elif (file_urls.get('lyrics', {}).get('corrections') and
|
||||
_has_title_screen(file_urls)):
|
||||
file_urls.get('screens', {}).get('title')):
|
||||
|
||||
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
|
||||
|
||||
@@ -2014,18 +1853,9 @@ async def retry_job(
|
||||
"retry_stage": "screens_generation"
|
||||
}
|
||||
|
||||
# If the input audio is already in GCS (an uploaded file, or a URL whose
|
||||
# download succeeded), restart from beginning — the audio/lyrics workers
|
||||
# re-fetch it from GCS.
|
||||
#
|
||||
# A URL job whose download never succeeded has only `job.url` and NO
|
||||
# audio in GCS, so it must NOT take this branch: triggering the workers
|
||||
# would just fail with "Failed to download audio file" and Cloud Run
|
||||
# would retry them repeatedly (see job 7f36304a — an Apple Music link).
|
||||
# Such jobs fall through to the "resubmit" refusal below, since there is
|
||||
# no worker that re-downloads a generic URL.
|
||||
elif job.input_media_gcs_path:
|
||||
logger.info(f"Job {job_id}: Has input audio in GCS, restarting from beginning")
|
||||
# If we have input audio (uploaded or from URL), restart from beginning
|
||||
elif job.input_media_gcs_path or job.url:
|
||||
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
|
||||
|
||||
# Clear error state and any partial progress
|
||||
job_manager.update_job(job_id, {
|
||||
@@ -2314,14 +2144,6 @@ async def cleanup_distribution(
|
||||
"status": "skipped",
|
||||
"reason": "no files found to delete",
|
||||
}
|
||||
|
||||
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too, so a
|
||||
# re-finalise (incl. artist/title rename) doesn't leave the old cut on
|
||||
# kjbox. Prefix-keyed by brand_code (covers renames); the subsequent
|
||||
# re-run's push re-adds the new master. Non-fatal, Nomad-only.
|
||||
if brand_code:
|
||||
from backend.services.nomad_master_mirror import cleanup_nomad_masters
|
||||
cleanup_nomad_masters(brand_code)
|
||||
else:
|
||||
results["gdrive"] = {
|
||||
"status": "failed",
|
||||
@@ -2492,21 +2314,11 @@ async def create_job_from_search(
|
||||
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
|
||||
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
|
||||
|
||||
# Determine display values.
|
||||
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
|
||||
# body.title carry whatever is currently in the wizard's artist/title fields,
|
||||
# which reflect a "Use official formatting" correction the user may have applied
|
||||
# after searching. The displayed job name must honour that correction, so prefer
|
||||
# the request body over the stored query. An explicit display override wins above all.
|
||||
# Determine display values
|
||||
session_artist = session.get('artist', body.artist)
|
||||
session_title = session.get('title', body.title)
|
||||
# body.artist/body.title are required but unvalidated for whitespace, so strip
|
||||
# them and fall back to the stored query if blank (display_* is pre-stripped to
|
||||
# None by its validator). This keeps a stray " " from becoming the job name.
|
||||
body_artist = (body.artist or "").strip()
|
||||
body_title = (body.title or "").strip()
|
||||
effective_display_artist = body.display_artist or body_artist or session_artist
|
||||
effective_display_title = body.display_title or body_title or session_title
|
||||
effective_display_artist = body.display_artist or session_artist
|
||||
effective_display_title = body.display_title or session_title
|
||||
|
||||
tenant_id = session.get('tenant_id') or ""
|
||||
|
||||
@@ -2542,7 +2354,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
|
||||
@@ -2680,201 +2491,3 @@ async def change_visibility(
|
||||
except Exception as e:
|
||||
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Duration Confirmation Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class ConfirmDurationRequest(BaseModel):
|
||||
"""Request body for POST /jobs/{job_id}/confirm-duration."""
|
||||
acknowledged_credits: int
|
||||
|
||||
|
||||
# Keep a set of background tasks alive to prevent GC (mirrors complete_review pattern)
|
||||
_duration_confirm_tasks: set = set()
|
||||
|
||||
|
||||
@router.post("/{job_id}/confirm-duration")
|
||||
async def confirm_duration(
|
||||
job_id: str,
|
||||
body: ConfirmDurationRequest,
|
||||
http_request: Request,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Confirm duration-based credit charge and resume job processing.
|
||||
|
||||
Called when a job is paused in AWAITING_DURATION_CONFIRM state.
|
||||
|
||||
The only pause reason currently used is ``reconcile``: the actual measured
|
||||
duration costs more than was already charged; ``state_data.pending_additional_credits``
|
||||
holds the delta owed. This applies to URL, upload, and audio-search jobs alike.
|
||||
|
||||
The caller must pass ``acknowledged_credits`` equal to the total credit cost
|
||||
the user has agreed to pay. If the figure has changed (race condition) a 409
|
||||
is returned so the frontend can refresh and re-show the dialog.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
# 1. Load job — 404 if not found or not owned by this user.
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
if not _check_job_ownership(job, auth_result):
|
||||
# Return 404 (not 403) to avoid leaking job existence to non-owners.
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# 2. Status guard.
|
||||
if job.status != JobStatus.AWAITING_DURATION_CONFIRM:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"Job is not awaiting duration confirmation (status: {job.status})",
|
||||
)
|
||||
|
||||
# 3. Compute owed credits and expected total.
|
||||
#
|
||||
# - credits_charged: total already deducted from the user's account
|
||||
# - pending_additional_credits: exactly how many MORE credits are owed to clear the pause
|
||||
#
|
||||
# The reconcile engine is responsible for computing and storing pending_additional_credits.
|
||||
# confirm_duration never needs to call duration_to_credits.
|
||||
state_data = job.state_data or {}
|
||||
reason = state_data.get("duration_confirm_reason", "reconcile")
|
||||
credits_charged = int(state_data.get("credits_charged", 0))
|
||||
owed = int(state_data.get("pending_additional_credits", 0))
|
||||
expected_total = credits_charged + owed
|
||||
|
||||
# 4. Acknowledged-credits mismatch guard (figure may have changed; client refreshes).
|
||||
if body.acknowledged_credits != expected_total:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=(
|
||||
f"acknowledged_credits ({body.acknowledged_credits}) does not match "
|
||||
f"expected total ({expected_total}). Please refresh and confirm again."
|
||||
),
|
||||
)
|
||||
|
||||
# 5. Deduct credits if any are owed.
|
||||
if owed > 0:
|
||||
user_email = job.user_email
|
||||
if not user_email:
|
||||
raise HTTPException(status_code=500, detail="Job has no associated user email")
|
||||
|
||||
user_svc = get_user_service()
|
||||
success, _remaining, _msg = user_svc.deduct_credits(
|
||||
user_email,
|
||||
job_id,
|
||||
amount=owed,
|
||||
reason="duration_confirm",
|
||||
count_as_job_creation=False, # job was already counted at create_job()
|
||||
)
|
||||
if not success:
|
||||
raise InsufficientCreditsError(
|
||||
message=f"Insufficient credits to confirm processing ({owed} credit(s) required).",
|
||||
credits_available=_remaining,
|
||||
credits_required=owed,
|
||||
)
|
||||
|
||||
# Update credits_charged in state_data to reflect the new total.
|
||||
job_manager.update_job(
|
||||
job_id,
|
||||
{
|
||||
"state_data.credits_charged": credits_charged + owed,
|
||||
"state_data.duration_confirmed": True,
|
||||
"state_data.pending_additional_credits": 0,
|
||||
},
|
||||
)
|
||||
else:
|
||||
# owed == 0: nothing to charge, just mark confirmed.
|
||||
job_manager.update_job(
|
||||
job_id,
|
||||
{
|
||||
"state_data.duration_confirmed": True,
|
||||
"state_data.pending_additional_credits": 0,
|
||||
},
|
||||
)
|
||||
|
||||
# 6. Transition job OUT of AWAITING_DURATION_CONFIRM before triggering workers.
|
||||
#
|
||||
# This is the idempotency guard: if a duplicate confirm POST arrives (e.g. a
|
||||
# double-click) the status guard at step 2 will now 409 immediately, preventing
|
||||
# a second pair of worker launches. We transition to SEPARATING_STAGE1 —
|
||||
# the normal next state for both the audio and lyrics parallel tracks — which is
|
||||
# a valid transition from AWAITING_DURATION_CONFIRM per STATE_TRANSITIONS.
|
||||
# The audio and lyrics workers update their own track states from here on, the
|
||||
# same as the normal convergence path.
|
||||
job_manager.transition_to_state(
|
||||
job_id,
|
||||
new_status=JobStatus.SEPARATING_STAGE1,
|
||||
progress=20,
|
||||
message="Cost confirmed, processing",
|
||||
)
|
||||
|
||||
# 7. Resume processing: trigger both parallel workers in background.
|
||||
# Use asyncio.create_task (mirrors complete_review in review.py) so the HTTP
|
||||
# response returns immediately without waiting for Cloud Run job submission.
|
||||
ws = get_worker_service()
|
||||
|
||||
async def _trigger_workers_after_confirm():
|
||||
try:
|
||||
await asyncio.gather(
|
||||
ws.trigger_audio_worker(job_id),
|
||||
ws.trigger_lyrics_worker(job_id),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"Job {job_id}: Failed to trigger workers after duration confirm: {exc}")
|
||||
|
||||
task = asyncio.create_task(_trigger_workers_after_confirm())
|
||||
_duration_confirm_tasks.add(task)
|
||||
task.add_done_callback(_duration_confirm_tasks.discard)
|
||||
|
||||
logger.info(
|
||||
f"Job {job_id}: duration confirmed (reason={reason}, owed={owed}); workers triggered"
|
||||
)
|
||||
|
||||
# 8. Return the updated job.
|
||||
updated_job = job_manager.get_job(job_id)
|
||||
if updated_job is None:
|
||||
# Should not happen, but be safe.
|
||||
return {"job_id": job_id, "status": "confirmed"}
|
||||
return updated_job
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# POST /jobs/estimate — URL duration probe
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class EstimateRequest(BaseModel):
|
||||
url: HttpUrl
|
||||
|
||||
|
||||
@router.post("/estimate")
|
||||
async def estimate_duration(
|
||||
body: EstimateRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Probe a URL to estimate its duration and compute the credit cost,
|
||||
WITHOUT creating a job or downloading any audio.
|
||||
|
||||
Returns duration_seconds (or None if unknown), source, credits, and
|
||||
whether the duration exceeds the supported ceiling (blocked).
|
||||
"""
|
||||
info = await get_youtube_download_service().check_availability(str(body.url))
|
||||
seconds = (info or {}).get("duration")
|
||||
if seconds is None:
|
||||
return {
|
||||
"duration_seconds": None,
|
||||
"source": "unknown",
|
||||
"credits": 1,
|
||||
"blocked": False,
|
||||
}
|
||||
return {
|
||||
"duration_seconds": seconds,
|
||||
"source": "youtube_metadata",
|
||||
"credits": duration_to_credits(seconds),
|
||||
"blocked": is_blocked(seconds),
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
"""POST /api/parse-karaoke-titles — batch karaoke-filename → artist/title.
|
||||
|
||||
Internal admin endpoint used by kjbox to canonicalise downloaded-file names.
|
||||
Reuses the Vertex Gemini parser; never blocks the caller (kjbox degrades to a
|
||||
deterministic guess when this is unavailable).
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.parse_titles import parse_titles
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["parse-titles"])
|
||||
|
||||
|
||||
class ParseItem(BaseModel):
|
||||
id: str
|
||||
filename: str
|
||||
channel: Optional[str] = None
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
class ParseRequest(BaseModel):
|
||||
items: list[ParseItem]
|
||||
|
||||
|
||||
class ParseResult(BaseModel):
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
confidence: float
|
||||
|
||||
|
||||
class ParseResponse(BaseModel):
|
||||
results: list[ParseResult]
|
||||
|
||||
|
||||
@router.post("/parse-karaoke-titles", response_model=ParseResponse)
|
||||
async def parse_karaoke_titles(
|
||||
body: ParseRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
items = [i.model_dump() for i in body.items]
|
||||
results = await parse_titles(items)
|
||||
logger.info("parse-karaoke-titles: %d items", len(items))
|
||||
return {"results": results}
|
||||
@@ -11,8 +11,6 @@ import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.models.referral import (
|
||||
@@ -20,7 +18,6 @@ from backend.models.referral import (
|
||||
UpdateReferralLinkRequest,
|
||||
ReferralInterstitialResponse,
|
||||
)
|
||||
from backend.services.flyer_service import get_flyer_service, FlyerError
|
||||
from backend.services.referral_service import get_referral_service
|
||||
|
||||
|
||||
@@ -29,22 +26,17 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/referrals", tags=["referrals"])
|
||||
|
||||
|
||||
class GenerateFlyerRequest(BaseModel):
|
||||
theme: str = Field(..., pattern="^(light|dark)$")
|
||||
qr_data_url: str = Field(..., max_length=500_000)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Public endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
|
||||
async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
async def get_referral_interstitial(code: str):
|
||||
"""
|
||||
Public endpoint: get interstitial data for a referral link.
|
||||
|
||||
Increments click count unless no_track=true. Returns valid=False if code not found.
|
||||
Increments click count. Returns valid=False if code not found.
|
||||
"""
|
||||
service = get_referral_service()
|
||||
link = service.get_link_by_code(code)
|
||||
@@ -52,12 +44,11 @@ async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
if not link:
|
||||
return ReferralInterstitialResponse(valid=False)
|
||||
|
||||
# Track the click (skip when fetching for display purposes)
|
||||
if not no_track:
|
||||
try:
|
||||
service.increment_clicks(code)
|
||||
except Exception:
|
||||
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
|
||||
# Track the click
|
||||
try:
|
||||
service.increment_clicks(code)
|
||||
except Exception:
|
||||
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
|
||||
|
||||
return ReferralInterstitialResponse(
|
||||
valid=True,
|
||||
@@ -127,105 +118,6 @@ async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
return {"account_id": account_id, "onboarding_url": onboarding_url}
|
||||
|
||||
|
||||
@router.post("/me/connect/dashboard-link")
|
||||
async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
"""Get a login link to the Stripe Express dashboard for managing payout settings."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
if not user or not user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
|
||||
|
||||
service = get_referral_service()
|
||||
url = service.create_connect_login_link(user.stripe_connect_account_id)
|
||||
if not url:
|
||||
raise HTTPException(status_code=500, detail="Failed to create dashboard link")
|
||||
|
||||
return {"url": url}
|
||||
|
||||
|
||||
@router.post("/me/connect/update-link")
|
||||
async def get_connect_update_link(auth=Depends(require_auth)):
|
||||
"""Get a link to update Stripe Connect account info (re-onboarding)."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
if not user or not user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
|
||||
|
||||
service = get_referral_service()
|
||||
url = service.create_connect_update_link(user.stripe_connect_account_id)
|
||||
if not url:
|
||||
raise HTTPException(status_code=500, detail="Failed to create update link")
|
||||
|
||||
return {"url": url}
|
||||
|
||||
|
||||
class VanityRequest(BaseModel):
|
||||
desired_code: str = Field(..., min_length=2, max_length=30, pattern="^[a-z0-9-]+$")
|
||||
|
||||
|
||||
@router.post("/me/vanity-request")
|
||||
async def request_vanity_url(
|
||||
request: VanityRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Request a custom vanity referral URL. Sends email to admin for review."""
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
# Check if code is already taken
|
||||
existing = service.get_link_by_code(request.desired_code)
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="That code is already taken. Please try another.")
|
||||
|
||||
email_service = get_email_service()
|
||||
email_service.provider.send_email(
|
||||
to_email="andrew@nomadkaraoke.com",
|
||||
subject=f"Vanity referral URL request: {request.desired_code}",
|
||||
html_content=f"""
|
||||
<h2>Vanity Referral URL Request</h2>
|
||||
<p><strong>User:</strong> {auth.user_email}</p>
|
||||
<p><strong>Current code:</strong> {link.code}</p>
|
||||
<p><strong>Desired vanity code:</strong> {request.desired_code}</p>
|
||||
<p>To approve, create the vanity link in the <a href="https://gen.nomadkaraoke.com/admin/referrals">admin dashboard</a>.</p>
|
||||
""",
|
||||
text_content=f"Vanity URL request from {auth.user_email}: {request.desired_code} (current: {link.code})",
|
||||
)
|
||||
|
||||
logger.info("Vanity URL request from %s: %s", auth.user_email, request.desired_code)
|
||||
return {"ok": True, "message": "Request sent"}
|
||||
|
||||
|
||||
@router.post("/me/flyer")
|
||||
async def generate_flyer(
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Generate a personalized referral flyer PDF."""
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="nomad-karaoke-referral-flyer.pdf"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Admin endpoints
|
||||
# ============================================================================
|
||||
@@ -339,36 +231,3 @@ async def update_link(
|
||||
raise HTTPException(status_code=404, detail=message)
|
||||
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
|
||||
@router.post("/admin/links/{code}/flyer")
|
||||
async def admin_generate_flyer(
|
||||
code: str,
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: generate a personalized referral flyer PDF for any code."""
|
||||
service = get_referral_service()
|
||||
link = service.get_link_by_code(code)
|
||||
|
||||
if not link:
|
||||
raise HTTPException(status_code=404, detail=f"Referral link '{code}' not found")
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="nomad-karaoke-flyer-{link.code}.pdf"',
|
||||
},
|
||||
)
|
||||
+39
-498
@@ -19,10 +19,11 @@ 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 import APIRouter, HTTPException, Request, Depends
|
||||
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.models.review_session import ReviewSession, ReviewSessionSummary
|
||||
@@ -36,156 +37,11 @@ from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
|
||||
from pydantic import BaseModel as _PydBaseModel
|
||||
from backend.services.custom_lyrics_service import (
|
||||
CustomLyricsService,
|
||||
CustomLyricsServiceError,
|
||||
get_custom_lyrics_service,
|
||||
)
|
||||
from backend.services.auto_correct import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
|
||||
class LineMetadataResponse(_PydBaseModel):
|
||||
line_index: int
|
||||
target_text: str
|
||||
candidate_text: str
|
||||
target_syllables: list[int]
|
||||
candidate_syllables: list[int]
|
||||
min_delta: int
|
||||
passes: bool
|
||||
severity: str # "ok" | "minor" | "major"
|
||||
time_budget_seconds: float
|
||||
|
||||
|
||||
class CustomLyricsResponse(_PydBaseModel):
|
||||
lines: list[str]
|
||||
line_metadata: list[LineMetadataResponse]
|
||||
iterations_used: int
|
||||
stop_reason: str # "success" | "plateau" | "max_iters_reached" | "line_count_mismatch" | "verbatim_skip"
|
||||
settings_applied: dict
|
||||
new_segment_timing: Optional[list[tuple[float, float]]] = None
|
||||
line_count_mismatch: bool
|
||||
warnings: list[str]
|
||||
model: str
|
||||
|
||||
|
||||
class AutoCorrectRequest(_PydBaseModel):
|
||||
segments: list[dict] # client's current working corrected_segments
|
||||
reference_lyrics: dict # client's reference sources (incl. user-added)
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
settings: Optional[dict] = None # AutoCorrectSettings knobs
|
||||
|
||||
|
||||
class AutoCorrectSuggestionResponse(_PydBaseModel):
|
||||
id: str
|
||||
op: str # "replace" | "delete" | "insert_after"
|
||||
word_ids: list[str]
|
||||
segment_ids: list[str]
|
||||
original_text: str
|
||||
new_text: str
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
models: list[str]
|
||||
consensus: int
|
||||
total_models: int
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
class AutoCorrectResponse(_PydBaseModel):
|
||||
suggestions: list[AutoCorrectSuggestionResponse]
|
||||
model: str
|
||||
elapsed_seconds: float
|
||||
settings_applied: dict
|
||||
warnings: list[str]
|
||||
cached: bool = False
|
||||
|
||||
|
||||
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_custom_lyrics_service()
|
||||
|
||||
|
||||
def _get_auto_correct_service_dep() -> AutoCorrectService:
|
||||
"""FastAPI dependency wrapper around the singleton accessor."""
|
||||
return get_auto_correct_service()
|
||||
|
||||
|
||||
async def _load_target_segments_for_custom_lyrics(
|
||||
job_id: str,
|
||||
target_lines: list[str],
|
||||
) -> list[dict]:
|
||||
"""Load segments with timing for the custom-lyrics endpoint.
|
||||
|
||||
Tries to fetch corrections.json from GCS for accurate per-segment timing
|
||||
(start_time, end_time). Falls back to synthesized timing (2s per line)
|
||||
if corrections.json is unavailable or has a mismatched line count.
|
||||
|
||||
Returns a list of dicts with at least start_time, end_time, text, words keys.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
return _synthesized_segments(target_lines)
|
||||
|
||||
# Try corrections_updated first (latest review session edits), then corrections (original)
|
||||
corrections_path = (
|
||||
job.file_urls.get("lyrics", {}).get("corrections_updated")
|
||||
or f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
)
|
||||
if not (corrections_path and storage.file_exists(corrections_path)):
|
||||
corrections_path = (
|
||||
job.file_urls.get("lyrics", {}).get("corrections")
|
||||
or f"jobs/{job_id}/lyrics/corrections.json"
|
||||
)
|
||||
|
||||
try:
|
||||
if corrections_path and storage.file_exists(corrections_path):
|
||||
data = storage.download_json(corrections_path)
|
||||
segments = data.get("corrected_segments") or data.get("segments") or []
|
||||
if len(segments) == len(target_lines):
|
||||
return segments
|
||||
logger.warning(
|
||||
f"Job {job_id}: corrections.json has {len(segments)} segments but "
|
||||
f"{len(target_lines)} target_lines provided; using synthesized timing"
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 - degrade gracefully
|
||||
logger.warning(
|
||||
f"Job {job_id}: could not load segments from {corrections_path}: {e}; "
|
||||
f"using synthesized timing"
|
||||
)
|
||||
|
||||
return _synthesized_segments(target_lines)
|
||||
|
||||
|
||||
def _synthesized_segments(target_lines: list[str]) -> list[dict]:
|
||||
"""Fallback when real timing is unavailable: 2s per line."""
|
||||
return [
|
||||
{
|
||||
"id": f"synth-{i}",
|
||||
"start_time": float(i * 2.0),
|
||||
"end_time": float((i + 1) * 2.0),
|
||||
"text": line,
|
||||
"words": [],
|
||||
}
|
||||
for i, line in enumerate(target_lines)
|
||||
]
|
||||
|
||||
|
||||
# LyricsTranscriber imports for preview generation
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.output.timing_validation import LyricsTimingError
|
||||
|
||||
# Import from the unified style loader
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
@@ -372,15 +228,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 +248,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 +263,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)
|
||||
@@ -518,23 +327,10 @@ async def complete_review(
|
||||
detail=t("en", "review.invalidInstrumentalSelection", valid_selections=valid_selections)
|
||||
)
|
||||
|
||||
# === is_duet flag (optional) — latch-up-only ===
|
||||
# InstrumentalSelector may send is_duet=False on the complete call when
|
||||
# correctionData.is_duet is undefined (the flag doesn't round-trip through
|
||||
# the /corrections response on the cloud path). Never downgrade True→False:
|
||||
# if a prior submit_corrections already persisted True, honor that.
|
||||
is_duet_raw = updated_data.get("is_duet", None)
|
||||
if is_duet_raw is not None and not isinstance(is_duet_raw, bool):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t("en", "review.invalidIsDuetFlag"),
|
||||
)
|
||||
|
||||
try:
|
||||
# Remove instrumental_selection and is_duet from updated_data before saving corrections
|
||||
# (they're stored separately in state_data)
|
||||
excluded_fields = {"instrumental_selection", "is_duet"}
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k not in excluded_fields}
|
||||
# Remove instrumental_selection from updated_data before saving to corrections
|
||||
# (it's stored separately in state_data)
|
||||
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
|
||||
|
||||
# Only write corrections_updated.json if there's actual correction data.
|
||||
# Writing an empty dict causes KeyError downstream when render workers
|
||||
@@ -552,24 +348,6 @@ async def complete_review(
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
|
||||
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
|
||||
|
||||
# Store duet flag so render worker knows to use multi-singer styles.
|
||||
# Latch-up-only: True overwrites; False is ignored if a prior submit
|
||||
# already persisted True.
|
||||
if is_duet_raw is True:
|
||||
job_manager.update_state_data(job_id, 'is_duet', True)
|
||||
logger.info(f"Job {job_id}: Stored is_duet flag: True (from complete)")
|
||||
elif is_duet_raw is False:
|
||||
job = job_manager.get_job(job_id)
|
||||
prior = bool(job.state_data.get('is_duet', False)) if job else False
|
||||
if prior:
|
||||
logger.info(
|
||||
f"Job {job_id}: Ignoring is_duet=False on complete — already True from prior submit"
|
||||
)
|
||||
else:
|
||||
job_manager.update_state_data(job_id, 'is_duet', False)
|
||||
logger.info(f"Job {job_id}: Stored is_duet flag: False")
|
||||
# else is_duet_raw is None: leave existing state_data value untouched
|
||||
|
||||
# Clear worker progress keys to ensure workers will run fresh (not skip due to idempotency)
|
||||
# This handles cases where a job is re-reviewed after completion or where state was inconsistent.
|
||||
# The idempotency check in workers looks at {worker}_progress.stage == 'complete' to skip,
|
||||
@@ -610,196 +388,6 @@ async def complete_review(
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.reviewCompletedError", error=str(e)))
|
||||
|
||||
|
||||
@router.post("/{job_id}/custom-lyrics/generate", response_model=CustomLyricsResponse)
|
||||
async def generate_custom_lyrics(
|
||||
job_id: str,
|
||||
existing_lines: str = Form(..., description="JSON-encoded array of segment lines"),
|
||||
custom_text: Optional[str] = Form(None),
|
||||
notes: Optional[str] = Form(None),
|
||||
artist: Optional[str] = Form(None),
|
||||
title: Optional[str] = Form(None),
|
||||
settings_json: Optional[str] = Form(None, description="JSON-encoded GenerationSettings"),
|
||||
file: Optional[UploadFile] = File(None),
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
service: CustomLyricsService = Depends(_get_custom_lyrics_service_dep),
|
||||
) -> CustomLyricsResponse:
|
||||
"""Generate syllable-aware custom lyrics for a job using Gemini 3.1 Pro.
|
||||
|
||||
Stateless: returns generated lines + per-line metadata for the frontend
|
||||
to render in an annotated preview. Persistence happens via the existing
|
||||
/complete path after the user reviews and saves.
|
||||
"""
|
||||
from backend.services.custom_lyrics.settings import (
|
||||
GenerationSettings,
|
||||
settings_from_dict,
|
||||
)
|
||||
|
||||
# Parse existing_lines JSON
|
||||
try:
|
||||
parsed_lines = json.loads(existing_lines)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"existing_lines is not valid JSON: {exc}"
|
||||
) from exc
|
||||
if not isinstance(parsed_lines, list) or not all(
|
||||
isinstance(x, str) for x in parsed_lines
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="existing_lines must be a JSON array of strings",
|
||||
)
|
||||
if not parsed_lines:
|
||||
raise HTTPException(status_code=400, detail="existing_lines is empty")
|
||||
|
||||
# Parse settings (default to GenerationSettings() if missing)
|
||||
if settings_json:
|
||||
try:
|
||||
settings_dict = json.loads(settings_json)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"settings_json is not valid JSON: {exc}"
|
||||
) from exc
|
||||
try:
|
||||
settings = settings_from_dict(settings_dict)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
|
||||
else:
|
||||
settings = GenerationSettings()
|
||||
|
||||
# Read file body
|
||||
file_bytes: Optional[bytes] = None
|
||||
file_mime: Optional[str] = None
|
||||
file_name: Optional[str] = None
|
||||
if file is not None:
|
||||
file_bytes = await file.read()
|
||||
file_mime = file.content_type
|
||||
file_name = file.filename
|
||||
|
||||
if not custom_text and not file_bytes:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="must provide either custom_text or a file upload",
|
||||
)
|
||||
|
||||
# Load segments for timing context
|
||||
target_segments = await _load_target_segments_for_custom_lyrics(job_id, parsed_lines)
|
||||
|
||||
try:
|
||||
result = service.generate(
|
||||
job_id=job_id,
|
||||
target_lines=parsed_lines,
|
||||
target_segments=target_segments,
|
||||
artist=artist,
|
||||
title=title,
|
||||
custom_text=custom_text,
|
||||
file_bytes=file_bytes,
|
||||
file_mime=file_mime,
|
||||
file_name=file_name,
|
||||
notes=notes,
|
||||
settings=settings,
|
||||
)
|
||||
except CustomLyricsServiceError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
|
||||
return CustomLyricsResponse(
|
||||
lines=result.lines,
|
||||
line_metadata=[
|
||||
LineMetadataResponse(
|
||||
line_index=v.line_index,
|
||||
target_text=v.target_text,
|
||||
candidate_text=v.candidate_text,
|
||||
target_syllables=v.target_syllables,
|
||||
candidate_syllables=v.candidate_syllables,
|
||||
min_delta=v.min_delta,
|
||||
passes=v.passes,
|
||||
severity=v.severity.value,
|
||||
time_budget_seconds=v.time_budget_seconds,
|
||||
)
|
||||
for v in result.line_metadata
|
||||
],
|
||||
iterations_used=result.iterations_used,
|
||||
stop_reason=result.stop_reason.value,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
new_segment_timing=result.new_segment_timing,
|
||||
line_count_mismatch=result.line_count_mismatch,
|
||||
warnings=result.warnings,
|
||||
model=result.model,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/auto-correct", response_model=AutoCorrectResponse)
|
||||
async def auto_correct_suggestions(
|
||||
job_id: str,
|
||||
body: AutoCorrectRequest,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth),
|
||||
service: AutoCorrectService = Depends(_get_auto_correct_service_dep),
|
||||
) -> AutoCorrectResponse:
|
||||
"""Generate AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless and strictly opt-in: one whole-song LLM call comparing the
|
||||
client's current working transcription against the reference lyrics.
|
||||
Returns word-id-keyed suggestions; nothing is applied server-side —
|
||||
the reviewer accepts or rejects each suggestion individually and
|
||||
persistence happens via the existing corrections/complete paths.
|
||||
"""
|
||||
from backend.services.auto_correct.settings import settings_from_dict
|
||||
|
||||
try:
|
||||
settings = settings_from_dict(body.settings or {})
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
|
||||
|
||||
with job_log_context(job_id), create_span("auto_correct_suggestions"):
|
||||
add_span_attribute("job_id", job_id)
|
||||
add_span_attribute("segment_count", len(body.segments))
|
||||
logger.info(
|
||||
"auto-correct requested job=%s segments=%d sources=%d",
|
||||
job_id, len(body.segments), len(body.reference_lyrics),
|
||||
)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
service.suggest,
|
||||
job_id=job_id,
|
||||
segments=body.segments,
|
||||
reference_lyrics=body.reference_lyrics,
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
settings=settings,
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
|
||||
logger.info(
|
||||
"auto-correct completed job=%s suggestions=%d model=%s elapsed=%.1fs",
|
||||
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
|
||||
)
|
||||
|
||||
return AutoCorrectResponse(
|
||||
suggestions=[
|
||||
AutoCorrectSuggestionResponse(
|
||||
id=s.id,
|
||||
op=s.op,
|
||||
word_ids=s.word_ids,
|
||||
segment_ids=s.segment_ids,
|
||||
original_text=s.original_text,
|
||||
new_text=s.new_text,
|
||||
reason=s.reason,
|
||||
category=s.category,
|
||||
confidence=s.confidence,
|
||||
models=s.models,
|
||||
consensus=s.consensus,
|
||||
total_models=s.total_models,
|
||||
conflict_group=s.conflict_group,
|
||||
)
|
||||
for s in result.suggestions
|
||||
],
|
||||
model=result.model,
|
||||
elapsed_seconds=result.elapsed_seconds,
|
||||
settings_applied=result.settings_applied.to_dict(),
|
||||
warnings=result.warnings,
|
||||
cached=result.cached,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(
|
||||
job_id: str,
|
||||
@@ -898,29 +486,16 @@ async def add_lyrics(
|
||||
updated_result.metadata['audio_hash'] = audio_hash
|
||||
updated_result.metadata['artist'] = job.artist
|
||||
updated_result.metadata['title'] = job.title
|
||||
|
||||
# The relevance filter may silently drop the new source during the
|
||||
# correction rerun. Surface that as a "rejected" outcome (without
|
||||
# persisting the no-op rerun) so the frontend can offer force-add.
|
||||
source_kept = source in (updated_result.reference_lyrics or {})
|
||||
if not source_kept:
|
||||
rejection = (updated_result.metadata.get("rejected_sources") or {}).get(source) or {}
|
||||
logger.info(
|
||||
f"Job {job_id}: Lyrics source '{source}' rejected by relevance filter "
|
||||
f"({rejection.get('matched_words')}/{rejection.get('total_words')} words matched)"
|
||||
)
|
||||
span.set_attribute("rejected", True)
|
||||
return {"status": "rejected", "rejection": rejection, "data": updated_result.to_dict()}
|
||||
|
||||
|
||||
# Upload updated corrections back to GCS
|
||||
with create_span("upload-corrections") as upload_span:
|
||||
updated_data = updated_result.to_dict()
|
||||
storage.upload_json(corrections_gcs, updated_data)
|
||||
upload_span.set_attribute("gcs_path", corrections_gcs)
|
||||
|
||||
|
||||
logger.info(f"Job {job_id}: Successfully added lyrics source '{source}'")
|
||||
span.set_attribute("success", True)
|
||||
|
||||
|
||||
return {"status": "success", "data": updated_data}
|
||||
|
||||
except ValueError as e:
|
||||
@@ -1115,17 +690,7 @@ async def generate_preview_video(
|
||||
|
||||
# Check if user wants theme background image (slower) or black background (faster, default)
|
||||
use_background_image = updated_data.get("use_background_image", False)
|
||||
|
||||
# === is_duet flag (optional, defaults to False) ===
|
||||
is_duet_raw = updated_data.get("is_duet", False)
|
||||
if not isinstance(is_duet_raw, bool):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t("en", "review.invalidIsDuetFlag"),
|
||||
)
|
||||
is_duet = is_duet_raw
|
||||
|
||||
logger.info(f"Job {job_id}: Generating preview video (GCE: {use_gce_preview}, background image: {use_background_image}, is_duet: {is_duet})")
|
||||
logger.info(f"Job {job_id}: Generating preview video (GCE: {use_gce_preview}, background image: {use_background_image})")
|
||||
|
||||
# Use tracing and job_log_context for full observability
|
||||
with create_span("generate-preview-video", {"job_id": job_id, "use_gce": use_gce_preview}) as span:
|
||||
@@ -1173,7 +738,6 @@ async def generate_preview_video(
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
video_resolution="360p",
|
||||
is_duet=is_duet,
|
||||
)
|
||||
|
||||
# 6. Generate preview (ASS-only if using GCE, or full video if local)
|
||||
@@ -1287,13 +851,6 @@ async def generate_preview_video(
|
||||
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
|
||||
except LyricsTimingError as timing_err:
|
||||
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
|
||||
# user-fixable input problem, not a server fault. Return 422 with an
|
||||
# actionable message instead of a cryptic 500.
|
||||
logger.warning(f"Job {job_id}: Preview blocked — lyrics not synchronized: {timing_err}")
|
||||
span.set_attribute("error", "lyrics_not_synchronized")
|
||||
raise HTTPException(status_code=422, detail=str(timing_err)) from timing_err
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Failed to generate preview video: {e}", exc_info=True)
|
||||
span.set_attribute("error", str(e))
|
||||
@@ -1309,19 +866,9 @@ async def get_preview_video(
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Serve the generated preview video via a signed GCS URL redirect.
|
||||
|
||||
We redirect to a signed URL rather than proxying the bytes through Cloud
|
||||
Run because Cloud Run caps response bodies at 32 MiB. Long songs (e.g. a
|
||||
30+ minute mashup) produce a 360p preview larger than that, which the proxy
|
||||
path truncated mid-stream — the response started as 206 but the client
|
||||
received a 500, so the browser reported "no supported format". The signed
|
||||
URL lets the browser fetch the mp4 directly from GCS (with byte-range
|
||||
support intact), bypassing the limit entirely. Mirrors the audio-review
|
||||
endpoint above.
|
||||
"""
|
||||
"""Stream the generated preview video."""
|
||||
storage = StorageService()
|
||||
|
||||
|
||||
# Check in-memory cache first
|
||||
preview_gcs_path = None
|
||||
if job_id in _preview_videos and preview_hash in _preview_videos[job_id]:
|
||||
@@ -1331,14 +878,30 @@ async def get_preview_video(
|
||||
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
|
||||
if not storage.file_exists(preview_gcs_path):
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
|
||||
|
||||
|
||||
try:
|
||||
signed_url = storage.generate_signed_url(preview_gcs_path, expiration_minutes=120)
|
||||
logger.info(f"Job {job_id}: Redirecting to signed URL for preview video {preview_hash}")
|
||||
return RedirectResponse(url=signed_url, status_code=302)
|
||||
|
||||
# Download to temp file and stream
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
storage.download_file(preview_gcs_path, tmp_path)
|
||||
|
||||
logger.info(f"Job {job_id}: Streaming preview video {preview_hash}")
|
||||
|
||||
return FileResponse(
|
||||
tmp_path,
|
||||
media_type="video/mp4",
|
||||
filename=f"preview_{preview_hash}.mp4",
|
||||
headers={
|
||||
"Accept-Ranges": "bytes",
|
||||
"Content-Disposition": "inline",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
background=BackgroundTask(os.unlink, tmp_path),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error serving preview video: {e}", exc_info=True)
|
||||
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
|
||||
|
||||
|
||||
@@ -2001,8 +1564,7 @@ async def apply_audio_edit(
|
||||
"""
|
||||
Apply an edit operation to the input audio.
|
||||
|
||||
Supported operations: trim_start, trim_end, cut, mute, fade_in, fade_out,
|
||||
join_start, join_end.
|
||||
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
|
||||
Returns updated waveform data and playback URL.
|
||||
"""
|
||||
import uuid
|
||||
@@ -2016,7 +1578,7 @@ async def apply_audio_edit(
|
||||
if not operation:
|
||||
raise HTTPException(status_code=400, detail="Missing 'operation' field")
|
||||
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "fade_in", "fade_out", "join_start", "join_end"}
|
||||
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
|
||||
if operation not in valid_operations:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
|
||||
|
||||
@@ -2361,27 +1923,6 @@ async def submit_audio_edit(
|
||||
message="Audio edit complete, starting processing"
|
||||
)
|
||||
|
||||
# Reconcile credit charge against the (possibly-edited) audio before triggering workers.
|
||||
# reconcile_and_maybe_pause probes job.input_media_gcs_path — which was just updated above
|
||||
# to point to the edited audio (jobs/{job_id}/input/edited.flac) if edits were applied.
|
||||
if await reconcile_and_maybe_pause(job_id):
|
||||
# Job paused (AWAITING_DURATION_CONFIRM) or cancelled — do not start processing.
|
||||
# Reload to distinguish the two outcomes so the caller can surface the right message.
|
||||
reloaded = job_manager.get_job(job_id)
|
||||
if reloaded and reloaded.status in (JobStatus.CANCELLED, JobStatus.FAILED):
|
||||
return {
|
||||
"status": "cancelled",
|
||||
"message": "Audio edit saved. Job was cancelled — audio exceeds the supported limit.",
|
||||
"job_id": job_id,
|
||||
"edits_applied": len(edit_stack),
|
||||
}
|
||||
return {
|
||||
"status": "paused",
|
||||
"message": "Audio edit saved. Additional credits are required to continue processing.",
|
||||
"job_id": job_id,
|
||||
"edits_applied": len(edit_stack),
|
||||
}
|
||||
|
||||
# Trigger parallel workers in background so the HTTP response returns immediately.
|
||||
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
|
||||
# waiting synchronously causes the browser request to time out.
|
||||
|
||||
+59
-426
@@ -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,
|
||||
@@ -44,12 +43,8 @@ from backend.models.user import (
|
||||
SendMagicLinkRequest,
|
||||
SendMagicLinkResponse,
|
||||
VerifyMagicLinkResponse,
|
||||
ResendFromTokenRequest,
|
||||
ResendFromTokenResponse,
|
||||
AddCreditsRequest,
|
||||
AddCreditsResponse,
|
||||
AdminCreateUserRequest,
|
||||
AdminCreateUserResponse,
|
||||
UserListResponse,
|
||||
UserFeedback,
|
||||
UserFeedbackRequest,
|
||||
@@ -222,7 +217,7 @@ async def send_magic_link(
|
||||
Send a magic link email for passwordless authentication.
|
||||
|
||||
The user will receive an email with a link that logs them in.
|
||||
Links expire after 24 hours and can only be used once.
|
||||
Links expire after 15 minutes and can only be used once.
|
||||
|
||||
For white-label tenants, validates email domain against tenant config.
|
||||
"""
|
||||
@@ -440,22 +435,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
|
||||
|
||||
@@ -496,178 +479,6 @@ async def verify_magic_link(
|
||||
)
|
||||
|
||||
|
||||
class MagicLinkStatusResponse(BaseModel):
|
||||
status: str # "valid" | "used" | "expired" | "invalid"
|
||||
|
||||
|
||||
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
|
||||
async def magic_link_status(
|
||||
token: str,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Read-only status of a magic link — does NOT consume it.
|
||||
|
||||
The verify page calls this on load so it can show the correct UI upfront:
|
||||
the "Complete Sign-In" gate for a valid link, or an "already used / expired"
|
||||
message for a dead one — without making the user click only to then fail.
|
||||
|
||||
This endpoint is intentionally non-mutating so that an email link-scanner
|
||||
which renders the verify page (and triggers this read) cannot burn a still-
|
||||
valid token before the real user clicks. Token consumption happens only in
|
||||
the separate GET /auth/verify, which requires an explicit user click.
|
||||
"""
|
||||
if not token or not token.strip():
|
||||
return MagicLinkStatusResponse(status="invalid")
|
||||
return MagicLinkStatusResponse(status=user_service.get_magic_link_status(token))
|
||||
|
||||
|
||||
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
|
||||
async def resend_magic_link_from_token(
|
||||
request: ResendFromTokenRequest,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
email_service: EmailService = Depends(get_email_service),
|
||||
):
|
||||
"""
|
||||
Resend a magic link to the email associated with a previously-issued token.
|
||||
|
||||
Used by the verify failure UI to give users a one-click recovery when their
|
||||
sign-in link has expired or already been used. The original token is a 32-byte
|
||||
cryptographic secret — only the email recipient could possess it — so resending
|
||||
to the email recorded in the token doc adds no new attack surface.
|
||||
|
||||
Behaviour:
|
||||
- Token doc found → mint a fresh magic link, send it, return masked email.
|
||||
- Token doc missing → return status="no_token" so the UI can fall back to
|
||||
the standard sign-in form.
|
||||
"""
|
||||
from backend.services.user_service import MAGIC_LINKS_COLLECTION
|
||||
from backend.middleware.tenant import get_tenant_from_request, get_tenant_config_from_request
|
||||
|
||||
locale = get_locale_from_request(http_request)
|
||||
token = (request.token or "").strip()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(status_code=422, detail=t(locale, "users.invalidToken"))
|
||||
|
||||
magic_link_doc = user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
|
||||
if not magic_link_doc.exists:
|
||||
return ResendFromTokenResponse(
|
||||
status="no_token",
|
||||
masked_email=None,
|
||||
message=t(locale, "users.resendNoToken"),
|
||||
)
|
||||
|
||||
magic_link_data = magic_link_doc.to_dict() or {}
|
||||
email = (magic_link_data.get("email") or "").lower()
|
||||
if not email:
|
||||
return ResendFromTokenResponse(
|
||||
status="no_token",
|
||||
masked_email=None,
|
||||
message=t(locale, "users.resendNoToken"),
|
||||
)
|
||||
|
||||
if not email_service.is_configured():
|
||||
logger.error("Email service not configured - cannot resend magic links")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=t(locale, "users.emailServiceNotConfigured"),
|
||||
)
|
||||
|
||||
# Per-token cooldown: ignore repeat clicks of the resend button (or
|
||||
# email-scanner pre-fetches) within a short window. We still report
|
||||
# "sent" so the UI doesn't degrade — the user already got an email.
|
||||
RESEND_COOLDOWN_SECONDS = 60
|
||||
last_resend_at = magic_link_data.get("last_resend_at")
|
||||
if last_resend_at is not None:
|
||||
last_resend_dt = last_resend_at
|
||||
if isinstance(last_resend_at, str):
|
||||
try:
|
||||
last_resend_dt = datetime.fromisoformat(last_resend_at.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
last_resend_dt = None
|
||||
if last_resend_dt is not None:
|
||||
now = datetime.utcnow()
|
||||
if last_resend_dt.tzinfo is not None:
|
||||
from datetime import timezone as _tz
|
||||
now = now.replace(tzinfo=_tz.utc)
|
||||
elapsed = (now - last_resend_dt).total_seconds()
|
||||
if 0 <= elapsed < RESEND_COOLDOWN_SECONDS:
|
||||
logger.info(
|
||||
f"Resend cooldown active for {_mask_email(email)} ({elapsed:.0f}s elapsed)"
|
||||
)
|
||||
return ResendFromTokenResponse(
|
||||
status="sent",
|
||||
masked_email=_mask_email(email),
|
||||
message=t(locale, "users.magicLinkSent"),
|
||||
)
|
||||
|
||||
ip_address = get_client_ip(http_request)
|
||||
user_agent = http_request.headers.get("user-agent")
|
||||
|
||||
# Carry forward tenant context: prefer the original token's tenant so the
|
||||
# resent link goes to the same portal the user originally signed up on.
|
||||
original_tenant_id = magic_link_data.get("tenant_id")
|
||||
request_tenant_id = get_tenant_from_request(http_request)
|
||||
request_tenant_config = get_tenant_config_from_request(http_request)
|
||||
tenant_id = original_tenant_id or request_tenant_id
|
||||
|
||||
tenant_config = request_tenant_config
|
||||
if original_tenant_id and original_tenant_id != request_tenant_id:
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
tenant_config = get_tenant_service().get_tenant_config(original_tenant_id)
|
||||
|
||||
referral_code = magic_link_data.get("referral_code")
|
||||
device_fingerprint = magic_link_data.get("device_fingerprint")
|
||||
|
||||
new_link = user_service.create_magic_link(
|
||||
email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
|
||||
sender_email = None
|
||||
tenant_frontend_url = None
|
||||
tenant_name = None
|
||||
if tenant_config:
|
||||
sender_email = tenant_config.get_sender_email()
|
||||
tenant_frontend_url = tenant_config.get_frontend_url()
|
||||
tenant_name = tenant_config.name
|
||||
|
||||
sent = email_service.send_magic_link(
|
||||
email,
|
||||
new_link.token,
|
||||
sender_email=sender_email,
|
||||
tenant_frontend_url=tenant_frontend_url,
|
||||
tenant_name=tenant_name,
|
||||
locale=locale,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to resend magic link email to {_mask_email(email)}")
|
||||
|
||||
# Stamp the original token so the cooldown applies to subsequent clicks.
|
||||
try:
|
||||
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
"last_resend_at": datetime.utcnow(),
|
||||
})
|
||||
except Exception:
|
||||
logger.exception("Failed to stamp last_resend_at on magic link doc")
|
||||
|
||||
logger.info(f"Resent magic link to {_mask_email(email)} from expired/used token")
|
||||
|
||||
return ResendFromTokenResponse(
|
||||
status="sent",
|
||||
masked_email=_mask_email(email),
|
||||
message=t(locale, "users.magicLinkSent"),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/auth/logout", response_model=LogoutResponse)
|
||||
async def logout(
|
||||
request: Request,
|
||||
@@ -815,7 +626,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),
|
||||
):
|
||||
"""
|
||||
@@ -840,7 +650,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:
|
||||
@@ -861,72 +670,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,
|
||||
@@ -975,10 +718,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()
|
||||
@@ -1024,8 +763,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)
|
||||
@@ -1066,48 +803,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
|
||||
@@ -1230,59 +925,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")
|
||||
@@ -1776,10 +1478,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
|
||||
@@ -1944,7 +1642,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
|
||||
@@ -1981,8 +1678,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,
|
||||
@@ -2003,68 +1698,6 @@ async def get_user_detail(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/users", response_model=AdminCreateUserResponse, status_code=201)
|
||||
async def admin_create_user(
|
||||
request: AdminCreateUserRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Create a user account directly (admin only).
|
||||
|
||||
Use this to set up an account for someone who has never logged in, so you can
|
||||
grant them credits, submit jobs on their behalf, or impersonate them. The user
|
||||
can later log in normally via magic link with the same email.
|
||||
|
||||
Users created this way with initial credits do NOT receive the automatic
|
||||
welcome credit on first login (welcome_credits_granted is set to prevent
|
||||
double-granting).
|
||||
"""
|
||||
admin_id = auth_data.user_email or "admin:unknown"
|
||||
email = request.email.strip().lower()
|
||||
|
||||
if request.initial_credits < 0 or request.initial_credits > 1000:
|
||||
raise HTTPException(status_code=400, detail="initial_credits must be between 0 and 1000")
|
||||
|
||||
if user_service.get_user(email):
|
||||
raise HTTPException(status_code=409, detail=f"User {email} already exists")
|
||||
|
||||
user = user_service.get_or_create_user(email)
|
||||
|
||||
extra_updates = {}
|
||||
if request.display_name and request.display_name.strip():
|
||||
extra_updates["display_name"] = request.display_name.strip()
|
||||
|
||||
if request.initial_credits > 0:
|
||||
success, new_balance, message = user_service.add_credits(
|
||||
email=email,
|
||||
amount=request.initial_credits,
|
||||
reason=request.credit_reason,
|
||||
admin_email=admin_id,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(status_code=500, detail=f"User created but adding credits failed: {message}")
|
||||
user.credits = new_balance
|
||||
# Admin-granted starter credits replace the automatic welcome credit
|
||||
extra_updates["welcome_credits_granted"] = True
|
||||
|
||||
if extra_updates:
|
||||
user_service.update_user(email, **extra_updates)
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_id} created user {_mask_email(email)} "
|
||||
f"(initial_credits={request.initial_credits})"
|
||||
)
|
||||
|
||||
return AdminCreateUserResponse(
|
||||
status="success",
|
||||
email=email,
|
||||
credits=user.credits,
|
||||
message=f"Created user {email}"
|
||||
+ (f" with {request.initial_credits} credit(s)" if request.initial_credits > 0 else ""),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/credits", response_model=AddCreditsResponse)
|
||||
async def add_credits_to_user(
|
||||
request: AddCreditsRequest,
|
||||
|
||||
+1
-133
@@ -20,17 +20,6 @@ class Settings(BaseSettings):
|
||||
gcs_temp_bucket: str = os.getenv("GCS_TEMP_BUCKET", "karaoke-gen-temp")
|
||||
gcs_output_bucket: str = os.getenv("GCS_OUTPUT_BUCKET", "karaoke-gen-outputs")
|
||||
firestore_collection: str = os.getenv("FIRESTORE_COLLECTION", "jobs")
|
||||
|
||||
# Nomad master fast-sync: push freshly-published Nomad 720p masters straight to the
|
||||
# Divebar GCS mirror so kjbox (which mirrors that folder every 5 min) picks them up
|
||||
# within minutes instead of waiting for the nightly Drive->GCS VM. Nomad-brand only.
|
||||
divebar_files_bucket: str = os.getenv("DIVEBAR_FILES_BUCKET", "nomadkaraoke-divebar-files")
|
||||
nomad_master_gcs_prefix: str = os.getenv("NOMAD_MASTER_GCS_PREFIX", "files/Nomad Karaoke/MP4-720p")
|
||||
nomad_master_fast_sync_enabled: bool = os.getenv("NOMAD_MASTER_FAST_SYNC_ENABLED", "true").lower() == "true"
|
||||
# Original-vocals guide: a padded isolated-vocals file (silence[intro] + vocals) pushed to
|
||||
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
|
||||
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
|
||||
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
@@ -72,78 +61,12 @@ class Settings(BaseSettings):
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
|
||||
# Lyrics transcription outer (safety-net) timeout, scaled by audio duration.
|
||||
# Long inputs (e.g. 30+ minute mashups) legitimately take longer to transcribe,
|
||||
# so the timeout = clamp(floor, duration * per_audio_second, cap). The cap must
|
||||
# stay under the Cloud Run Job task timeout so we surface a clean RuntimeError
|
||||
# before the platform hard-kills the task. The lyrics-transcription-job sets the
|
||||
# task timeout to 3000s and overrides this cap to 2700s via env; the 1700s
|
||||
# default here is the safe value if that env is ever unset (under an 1800s task).
|
||||
transcription_timeout_floor_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_FLOOR_SECONDS", "1200"))
|
||||
transcription_timeout_cap_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_CAP_SECONDS", "1700"))
|
||||
transcription_timeout_per_audio_second: float = float(os.getenv("TRANSCRIPTION_TIMEOUT_PER_AUDIO_SECOND", "1.0"))
|
||||
|
||||
# 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")
|
||||
|
||||
# Custom Lyrics (LLM-powered) — used by the Custom Lyrics mode in the
|
||||
# Edit All Lyrics modal. Stateless service: takes operator-provided
|
||||
# custom-lyrics text/file and returns transformed lyric lines.
|
||||
custom_lyrics_model: str = os.getenv("CUSTOM_LYRICS_MODEL", "gemini-3.1-pro-preview")
|
||||
custom_lyrics_max_file_mb: int = int(os.getenv("CUSTOM_LYRICS_MAX_FILE_MB", "5"))
|
||||
custom_lyrics_max_input_lines: int = int(os.getenv("CUSTOM_LYRICS_MAX_INPUT_LINES", "500"))
|
||||
custom_lyrics_max_iterations: int = int(os.getenv("CUSTOM_LYRICS_MAX_ITERATIONS", "4"))
|
||||
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
|
||||
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
|
||||
|
||||
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
|
||||
# review UI. Stateless: one whole-song LLM call returning word-level
|
||||
# suggestions the reviewer accepts/rejects individually.
|
||||
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
|
||||
# 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.
|
||||
auto_correct_proactive_enabled: bool = os.getenv(
|
||||
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
|
||||
).lower() in ("true", "1", "yes")
|
||||
|
||||
# Match judge — artist/title formatting + match-acceptance for the job
|
||||
# submission flow. Deterministic + catalog layers always run; the light AI
|
||||
# layer (Vertex Gemini Flash) fires only when those aren't confident.
|
||||
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
|
||||
"true", "1", "yes",
|
||||
)
|
||||
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
|
||||
# Bounds the AI call so a hung model never strands the submission UI. Kept
|
||||
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
|
||||
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
|
||||
# call still runs off the critical path and degrades to "none" on timeout.
|
||||
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
|
||||
|
||||
# Batch karaoke-filename parser (kjbox download-naming). Reuses the Vertex
|
||||
# Gemini stack. Larger timeout than match_judge because it batches ~200 items.
|
||||
parse_titles_enabled: bool = os.getenv("PARSE_TITLES_ENABLED", "true").lower() in (
|
||||
"1", "true", "yes",
|
||||
)
|
||||
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.5-flash")
|
||||
parse_titles_timeout_ms: int = int(os.getenv("PARSE_TITLES_TIMEOUT_MS", "20000"))
|
||||
parse_titles_max_items: int = int(os.getenv("PARSE_TITLES_MAX_ITEMS", "200"))
|
||||
# Items per Gemini call: large client batches are split into concurrent
|
||||
# chunks of this size so one call never outgrows parse_titles_timeout_ms
|
||||
# (a 100-item single call did, blanking the whole batch).
|
||||
parse_titles_chunk_size: int = int(os.getenv("PARSE_TITLES_CHUNK_SIZE", "10"))
|
||||
|
||||
# Cloud Tasks (for scalable worker coordination)
|
||||
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
|
||||
# When disabled (default), workers are triggered via direct HTTP (for development)
|
||||
@@ -164,13 +87,6 @@ class Settings(BaseSettings):
|
||||
encoding_worker_url: Optional[str] = os.getenv("ENCODING_WORKER_URL") # e.g., http://136.119.50.148:8080
|
||||
encoding_worker_api_key: Optional[str] = os.getenv("ENCODING_WORKER_API_KEY")
|
||||
|
||||
# Optional capacity-fallback VMs in alternate zones. JSON list of objects:
|
||||
# '[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"34.x.x.x"}]'
|
||||
# Empty by default. After `pulumi up` provisions the fallback VMs (Phase 3
|
||||
# of the capacity-resilience plan), populate this var with their public
|
||||
# IPs to enable multi-zone failover when us-central1-c is exhausted.
|
||||
encoding_worker_fallback_vms: Optional[str] = os.getenv("ENCODING_WORKER_FALLBACK_VMS")
|
||||
|
||||
# GCE Preview Encoding (for faster preview video generation)
|
||||
# When enabled, preview video encoding during lyrics review is offloaded to the GCE worker.
|
||||
# This reduces preview generation time from 60+ seconds to ~15-20 seconds.
|
||||
@@ -309,51 +225,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)."
|
||||
)
|
||||
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -1,81 +0,0 @@
|
||||
"""One-shot script to populate the year-5-stars fixture from a real production job.
|
||||
|
||||
Run once:
|
||||
poetry run python -m backend.eval.custom_lyrics._bootstrap_year5
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
|
||||
JOB_ID = "2cb49a45"
|
||||
FIXTURE_DIR = Path(__file__).parent / "fixtures" / "year-5-stars-shake-it-off"
|
||||
CLIENT_INPUT_SRC = Path("/Users/andrew/Projects/nomadkaraoke/year-5-stars-client-custom-lyrics.txt")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
FIXTURE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
fs = firestore.Client(project="nomadkaraoke")
|
||||
job_doc = fs.collection("jobs").document(JOB_ID).get()
|
||||
if not job_doc.exists:
|
||||
raise SystemExit(f"Job {JOB_ID} not found")
|
||||
job = job_doc.to_dict()
|
||||
|
||||
# Corrected lyrics are stored inline in state_data (not in GCS for this job)
|
||||
corrected = (
|
||||
job.get("state_data", {}).get("corrected_lyrics")
|
||||
or job.get("corrected_lyrics")
|
||||
or {}
|
||||
)
|
||||
if not corrected:
|
||||
# Fallback: try GCS path if present
|
||||
corrected_path = job.get("corrected_json_gcs_path") or job.get("lyrics", {}).get("corrected_path")
|
||||
if corrected_path:
|
||||
from google.cloud import storage # noqa: PLC0415
|
||||
storage_client = storage.Client(project="nomadkaraoke")
|
||||
bucket_name, *blob_parts = corrected_path.replace("gs://", "").split("/", 1)
|
||||
blob = storage_client.bucket(bucket_name).blob(blob_parts[0])
|
||||
corrected = json.loads(blob.download_as_bytes())
|
||||
else:
|
||||
raise SystemExit(f"Job {JOB_ID} has no corrected lyrics (checked state_data and GCS path fields)")
|
||||
|
||||
segments = corrected.get("corrected_segments") or corrected.get("segments") or []
|
||||
if not segments:
|
||||
raise SystemExit("No segments found in corrected.json")
|
||||
|
||||
(FIXTURE_DIR / "original_segments.json").write_text(json.dumps(segments, indent=2))
|
||||
(FIXTURE_DIR / "original_lyrics.txt").write_text(
|
||||
"\n".join(seg.get("text", "").strip() for seg in segments) + "\n"
|
||||
)
|
||||
|
||||
if CLIENT_INPUT_SRC.exists():
|
||||
shutil.copy(CLIENT_INPUT_SRC, FIXTURE_DIR / "client_input.txt")
|
||||
else:
|
||||
print(f"WARNING: {CLIENT_INPUT_SRC} not found; populate client_input.txt manually")
|
||||
|
||||
metadata = {
|
||||
"id": "year-5-stars-shake-it-off",
|
||||
"artist": job.get("artist") or "Taylor Swift",
|
||||
"title": job.get("title") or "Shake It Off",
|
||||
"source_job_id": JOB_ID,
|
||||
"difficulty": "hard",
|
||||
"input_style": "long substantive lines, name-heavy, mismatched syllable budget",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": True, "allow_omit": True, "fixed_line_count": True, "strictness": "balanced"},
|
||||
{"name": "verbatim", "allow_reword": True, "allow_omit": True, "fixed_line_count": True, "strictness": "verbatim"},
|
||||
{"name": "strict", "allow_reword": True, "allow_omit": True, "fixed_line_count": True, "strictness": "strict"},
|
||||
],
|
||||
}
|
||||
(FIXTURE_DIR / "metadata.json").write_text(json.dumps(metadata, indent=2))
|
||||
|
||||
print(f"Fixture populated at {FIXTURE_DIR}")
|
||||
print(f" - {len(segments)} segments")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,64 +0,0 @@
|
||||
"""Disk-backed cache for LLM responses, keyed by (system, user, model, settings)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
class LlmCallCache:
|
||||
def __init__(self, cache_dir: Path, replay_only: bool = False) -> None:
|
||||
self.cache_dir = cache_dir
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.replay_only = replay_only
|
||||
|
||||
def _key(
|
||||
self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
*,
|
||||
model: str,
|
||||
settings_dict: dict[str, Any],
|
||||
) -> str:
|
||||
h = hashlib.sha256()
|
||||
h.update(system_prompt.encode())
|
||||
h.update(b"\x00")
|
||||
h.update(user_prompt.encode())
|
||||
h.update(b"\x00")
|
||||
h.update(model.encode())
|
||||
h.update(b"\x00")
|
||||
h.update(json.dumps(settings_dict, sort_keys=True).encode())
|
||||
return h.hexdigest()
|
||||
|
||||
def _path(self, key: str) -> Path:
|
||||
return self.cache_dir / f"{key}.json"
|
||||
|
||||
def get(
|
||||
self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
*,
|
||||
model: str,
|
||||
settings_dict: dict[str, Any],
|
||||
) -> Optional[list[str]]:
|
||||
path = self._path(self._key(system_prompt, user_prompt, model=model, settings_dict=settings_dict))
|
||||
if not path.exists():
|
||||
if self.replay_only:
|
||||
raise RuntimeError(f"cache miss in replay-only mode: {path.name}")
|
||||
return None
|
||||
return json.loads(path.read_text())["lines"]
|
||||
|
||||
def set(
|
||||
self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
*,
|
||||
model: str,
|
||||
settings_dict: dict[str, Any],
|
||||
response_lines: list[str],
|
||||
) -> None:
|
||||
if self.replay_only:
|
||||
return
|
||||
path = self._path(self._key(system_prompt, user_prompt, model=model, settings_dict=settings_dict))
|
||||
path.write_text(json.dumps({"lines": response_lines}, indent=2))
|
||||
@@ -1,2 +0,0 @@
|
||||
*
|
||||
!.gitignore
|
||||
@@ -1 +0,0 @@
|
||||
We're singing this for Alex's birthday! Can you change the lyrics so it says Alex's name instead of "he"? Like "For she's a jolly good fellow" or however it makes sense with Alex. Just make it clear it's for Alex. It's a birthday celebration for our friend Alex.
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"id": "jolly-good-fellow-name-replace",
|
||||
"artist": "Traditional",
|
||||
"title": "For He's a Jolly Good Fellow",
|
||||
"difficulty": "easy",
|
||||
"input_style": "explicit name replacement instruction",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "balanced"},
|
||||
{"name": "strict", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "strict"}
|
||||
]
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
For he's a jolly good fellow
|
||||
For he's a jolly good fellow
|
||||
For he's a jolly good fellow
|
||||
Which nobody can deny
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": "seg-00",
|
||||
"start_time": 0.0,
|
||||
"end_time": 2.5,
|
||||
"text": "For he's a jolly good fellow",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-01",
|
||||
"start_time": 2.5,
|
||||
"end_time": 5.0,
|
||||
"text": "For he's a jolly good fellow",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-02",
|
||||
"start_time": 5.0,
|
||||
"end_time": 7.5,
|
||||
"text": "For he's a jolly good fellow",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-03",
|
||||
"start_time": 7.5,
|
||||
"end_time": 10.0,
|
||||
"text": "Which nobody can deny",
|
||||
"words": []
|
||||
}
|
||||
]
|
||||
@@ -1 +0,0 @@
|
||||
We need this song to be about Mike and Sarah's wedding. Mike is a software engineer who loves climbing mountains, hiking on Saturdays with his border collie Max, and brewing his own beer in the basement. Sarah is a pediatric nurse with three sisters — Jenny, Tara, and Rachel — and she runs marathons every fall in the city park near her apartment. They met five years ago at a friend's birthday party in Brooklyn and bought their first house together last summer in Queens. Make the song celebrate their journey together. Highlight Max the dog if you can, and mention the marathons and the brewing.
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"id": "row-row-line-surplus",
|
||||
"artist": "Traditional",
|
||||
"title": "Row, Row, Row Your Boat",
|
||||
"difficulty": "medium",
|
||||
"input_style": "client input far exceeds song's structural capacity (line surplus)",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "balanced"},
|
||||
{"name": "strict", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "strict"}
|
||||
]
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
Row, row, row your boat,
|
||||
Gently down the stream,
|
||||
Merrily, merrily, merrily, merrily,
|
||||
Life is but a dream.
|
||||
@@ -1,30 +0,0 @@
|
||||
[
|
||||
{
|
||||
"text": "Row, row, row your boat,",
|
||||
"start_time": 0.0,
|
||||
"end_time": 1.5,
|
||||
"id": "rr-0",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"text": "Gently down the stream,",
|
||||
"start_time": 1.5,
|
||||
"end_time": 3.0,
|
||||
"id": "rr-1",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"text": "Merrily, merrily, merrily, merrily,",
|
||||
"start_time": 3.0,
|
||||
"end_time": 4.5,
|
||||
"id": "rr-2",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"text": "Life is but a dream.",
|
||||
"start_time": 4.5,
|
||||
"end_time": 6.0,
|
||||
"id": "rr-3",
|
||||
"words": []
|
||||
}
|
||||
]
|
||||
@@ -1 +0,0 @@
|
||||
Hi! Can you change the word "star" to "Sam" throughout the song? Every time "star" appears, I want it to say "Sam" instead. It's for my son Sam's birthday party. Thanks!
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"id": "twinkle-name-swap",
|
||||
"artist": "Traditional",
|
||||
"title": "Twinkle Twinkle Little Star",
|
||||
"difficulty": "easy",
|
||||
"input_style": "simple word substitution, well-defined target",
|
||||
"settings_to_test": [
|
||||
{"name": "default", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "balanced"},
|
||||
{"name": "strict", "allow_reword": true, "allow_omit": true, "fixed_line_count": true, "strictness": "strict"}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
Twinkle, twinkle, little star
|
||||
How I wonder what you are
|
||||
Up above the world so high
|
||||
Like a diamond in the sky
|
||||
Twinkle, twinkle, little star
|
||||
How I wonder what you are
|
||||
@@ -1,44 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": "seg-00",
|
||||
"start_time": 0.0,
|
||||
"end_time": 2.0,
|
||||
"text": "Twinkle, twinkle, little star",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-01",
|
||||
"start_time": 2.0,
|
||||
"end_time": 4.0,
|
||||
"text": "How I wonder what you are",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-02",
|
||||
"start_time": 4.0,
|
||||
"end_time": 6.0,
|
||||
"text": "Up above the world so high",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-03",
|
||||
"start_time": 6.0,
|
||||
"end_time": 8.0,
|
||||
"text": "Like a diamond in the sky",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-04",
|
||||
"start_time": 8.0,
|
||||
"end_time": 10.0,
|
||||
"text": "Twinkle, twinkle, little star",
|
||||
"words": []
|
||||
},
|
||||
{
|
||||
"id": "seg-05",
|
||||
"start_time": 10.0,
|
||||
"end_time": 12.0,
|
||||
"text": "How I wonder what you are",
|
||||
"words": []
|
||||
}
|
||||
]
|
||||
@@ -1,68 +0,0 @@
|
||||
We walk in the room, yeah we own this place
|
||||
Anna hits the floor, watch her lead the way
|
||||
Grace brings the rhythm, dancing every day
|
||||
Oona on guitar, getting in the groove
|
||||
Savannah steps forward, watch her make her move
|
||||
Eirini singing, Frankie right there
|
||||
Voices together, filling the air
|
||||
Step aside now, nobody stands a chance
|
||||
|
||||
|
||||
Mr Moulton jokes, we try not to laugh
|
||||
But we’re ready now, we’ve done the graft
|
||||
|
||||
|
||||
We’re gonna win, win, win, hear the crowd go loud
|
||||
Singing all together, yeah we’re making you proud
|
||||
Clap your hands, feel the beat, come and take a glance
|
||||
We’re Year 5 strong, nobody stands a chance
|
||||
Oh oh, here we go
|
||||
Oh oh, steal the show
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
|
||||
|
||||
Mr Bunney listening, nodding to the beat
|
||||
Mr Woodward watching, tapping his feet
|
||||
We’ll impress him with every note we play
|
||||
Best performance of the whole school day
|
||||
Mrs Woodbridge smiling, watching from the side
|
||||
Thinking “Year 6 will be full of pride”
|
||||
We’re stepping up, this is our dance
|
||||
Better step back, nobody stands a chance
|
||||
|
||||
|
||||
If we feel nervous, we just smile
|
||||
We’ve been ready for a while
|
||||
|
||||
|
||||
We’re gonna win, win, win, hear the crowd go loud
|
||||
Singing all together, yeah we’re making you proud
|
||||
Clap your hands, feel the beat, come and take a glance
|
||||
We’re Year 5 strong, nobody stands a chance
|
||||
Oh oh, here we go
|
||||
Oh oh, steal the show
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
|
||||
|
||||
Savannah solo
|
||||
I step to the front, now it’s my time
|
||||
Hear my voice, watch me shine
|
||||
All eyes on me, feel that vibe
|
||||
This is my moment, I come alive
|
||||
|
||||
Strum it strong, feel the sound
|
||||
Let the music spin around
|
||||
Keep the rhythm, don’t slow down
|
||||
Now we bring it back around
|
||||
|
||||
|
||||
We’re gonna win, win, win, loud and clear
|
||||
Best group performance of the year
|
||||
Sing it out, give it all, take a chance
|
||||
We’re Year 5 stars, nobody stands a chance
|
||||
Oh oh, this is it
|
||||
Oh oh, we won’t quit
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"id": "year-5-stars-shake-it-off",
|
||||
"artist": "Taylor Swift",
|
||||
"title": "Year 5 Stars",
|
||||
"source_job_id": "2cb49a45",
|
||||
"difficulty": "hard",
|
||||
"input_style": "long substantive lines, name-heavy, mismatched syllable budget",
|
||||
"settings_to_test": [
|
||||
{
|
||||
"name": "default",
|
||||
"allow_reword": true,
|
||||
"allow_omit": true,
|
||||
"fixed_line_count": true,
|
||||
"strictness": "balanced"
|
||||
},
|
||||
{
|
||||
"name": "verbatim",
|
||||
"allow_reword": true,
|
||||
"allow_omit": true,
|
||||
"fixed_line_count": true,
|
||||
"strictness": "verbatim"
|
||||
},
|
||||
{
|
||||
"name": "strict",
|
||||
"allow_reword": true,
|
||||
"allow_omit": true,
|
||||
"fixed_line_count": true,
|
||||
"strictness": "strict"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
We walk in the room
|
||||
Yeah we own this place
|
||||
Anna hits the floor, mm- mm
|
||||
Watch her lead the way, mm- mm
|
||||
Grace brings the rhythm
|
||||
Dancing every day
|
||||
Oona on guitar, mm- mm
|
||||
Getting in the groove, mm- mm
|
||||
Eirini singing, Frankie right there
|
||||
Voices together, filling the air
|
||||
Nobody stands a chance
|
||||
'Cause the players gonna play, play, play, play, play
|
||||
And the haters gonna hate, hate, hate, hate, hate
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Heartbreakers gonna break, break, break, break, break
|
||||
And the fakers gonna fake, fake, fake, fake, fake
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Mr Moulton jokes
|
||||
We try not to laugh
|
||||
But we’re ready now, mm- mm
|
||||
We’ve done the graft, mm- mm
|
||||
We’re gonna win (hear the crowd go loud)
|
||||
Singing all together (yeah we’re making you proud)
|
||||
Clap your hands, feel the beat, mm- mm
|
||||
Come and take a glance, mm- mm
|
||||
We’re Year 5 strong
|
||||
Here we go, steal the show
|
||||
Watch us now, take our stance
|
||||
Nobody stands a chance
|
||||
'Cause the players gonna play, play, play, play, play
|
||||
And the haters gonna hate, hate, hate, hate, hate
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Heartbreakers gonna break, break, break, break, break
|
||||
And the fakers gonna fake, fake, fake, fake, fake
|
||||
Baby, I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
Hey, hey, hey
|
||||
Just think, while you've been gettin' down and out about the liars
|
||||
And the dirty, dirty cheats of the world
|
||||
You could've been gettin' down to this sick beat
|
||||
My ex- man brought his new girlfriend
|
||||
She's like, "Oh my God"
|
||||
But I'm just gonna shake
|
||||
And to the fella over there with the hella good hair
|
||||
Won't you come on over, baby? We can shake, shake, shake
|
||||
Yeah, oh
|
||||
'Cause the players gonna play, play, play, play, play
|
||||
And the haters gonna hate, hate, hate, hate, hate
|
||||
I'm just gonna shake, shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Heartbreakers gonna break, break, break, break, break
|
||||
And the fakers gonna fake, fake, fake, fake
|
||||
I'm just gonna shake, shake, shake, shake
|
||||
I shake it off, I shake it off
|
||||
Shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
Shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
(You got to)
|
||||
I- I- I shake it off, I shake it off
|
||||
I- I- I shake it off, I shake it off
|
||||
-4153
File diff suppressed because it is too large.
Load diff
@@ -1,109 +0,0 @@
|
||||
"""Markdown report generation for eval runs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from backend.eval.custom_lyrics.runner import FixtureRunResult
|
||||
from backend.eval.custom_lyrics.scorer import aggregate_corpus
|
||||
|
||||
|
||||
def write_run_reports(
|
||||
results: list[FixtureRunResult],
|
||||
out_dir: Path,
|
||||
baseline: Optional[dict] = None,
|
||||
) -> None:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "per_fixture").mkdir(exist_ok=True)
|
||||
|
||||
summary_lines = ["# Custom Lyrics Eval Run", ""]
|
||||
summary_lines.append(f"_Generated: {datetime.now(timezone.utc).isoformat()}_")
|
||||
summary_lines.append("")
|
||||
summary_lines.append("## Per-fixture summary")
|
||||
summary_lines.append("")
|
||||
summary_lines.append("| Fixture | Settings | pass@±2 | Δ | mean_Δ | iters | stop |")
|
||||
summary_lines.append("|---------|----------|---------|---|--------|-------|------|")
|
||||
for r in results:
|
||||
s = r.score
|
||||
delta_str = ""
|
||||
if baseline:
|
||||
prev = baseline.get(r.fixture_id, {}).get(r.settings_name, {})
|
||||
if "pct_pass_at_2" in prev:
|
||||
d = s.pct_pass_at_2 - prev["pct_pass_at_2"]
|
||||
delta_str = f"{d:+.2f}"
|
||||
summary_lines.append(
|
||||
f"| {r.fixture_id} | {r.settings_name} | {s.pct_pass_at_2:.2f} | "
|
||||
f"{delta_str} | {s.mean_delta:.2f} | {s.iterations_used} | {s.stop_reason} |"
|
||||
)
|
||||
|
||||
summary_lines.append("")
|
||||
corpus = aggregate_corpus([r.score for r in results])
|
||||
summary_lines.append("## Corpus aggregate")
|
||||
summary_lines.append("")
|
||||
summary_lines.append(f"- Macro pass@±2: {corpus.get('macro_pct_pass_at_2', 0):.2f}")
|
||||
summary_lines.append(f"- Macro pass@±1: {corpus.get('macro_pct_pass_at_1', 0):.2f}")
|
||||
summary_lines.append(f"- Macro pass@±0: {corpus.get('macro_pct_pass_at_0', 0):.2f}")
|
||||
summary_lines.append(f"- Total Gemini calls: {corpus.get('total_gemini_calls', 0)}")
|
||||
|
||||
(out_dir / "summary.md").write_text("\n".join(summary_lines))
|
||||
|
||||
for r in results:
|
||||
per_dir = out_dir / "per_fixture" / f"{r.fixture_id}__{r.settings_name}"
|
||||
per_dir.mkdir(parents=True, exist_ok=True)
|
||||
(per_dir / "output.json").write_text(json.dumps({
|
||||
"fixture_id": r.fixture_id,
|
||||
"settings_name": r.settings_name,
|
||||
"score": r.score.__dict__,
|
||||
"lines": r.output_lines,
|
||||
"line_metadata": r.line_metadata,
|
||||
}, indent=2))
|
||||
_write_per_fixture_md(per_dir, r)
|
||||
|
||||
|
||||
def _write_per_fixture_md(out_dir: Path, r: FixtureRunResult) -> None:
|
||||
lines = [
|
||||
f"# {r.fixture_id} — {r.settings_name}",
|
||||
"",
|
||||
f"Stop reason: **{r.score.stop_reason}** after {r.score.iterations_used} iterations.",
|
||||
f"Pass@±2: **{r.score.pct_pass_at_2:.0%}** ({sum(1 for v in r.line_metadata if v['min_delta']<=2)}/{r.score.line_count})",
|
||||
"",
|
||||
"| # | Original target | Candidate | Δ | Severity |",
|
||||
"|---|------------------|-----------|---|----------|",
|
||||
]
|
||||
for v in r.line_metadata:
|
||||
lines.append(
|
||||
f"| {v['line_index']+1} | {_escape(v['target_text'])} | "
|
||||
f"{_escape(v['candidate_text'])} | {v['min_delta']} | {v['severity']} |"
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"## Your rating",
|
||||
"",
|
||||
"Add your qualitative notes here:",
|
||||
"- [ ] Singable end-to-end",
|
||||
"- [ ] Names placed naturally",
|
||||
"- [ ] Stress patterns reasonable",
|
||||
"- Notes:",
|
||||
"",
|
||||
]
|
||||
(out_dir / "output.md").write_text("\n".join(lines))
|
||||
|
||||
|
||||
def _escape(s: str) -> str:
|
||||
return s.replace("|", "\\|").replace("\n", " ")
|
||||
|
||||
|
||||
def write_baseline(results: list[FixtureRunResult], path: Path) -> None:
|
||||
out: dict = {}
|
||||
for r in results:
|
||||
bucket = out.setdefault(r.fixture_id, {})
|
||||
bucket[r.settings_name] = {
|
||||
"pct_pass_at_2": r.score.pct_pass_at_2,
|
||||
"pct_pass_at_0": r.score.pct_pass_at_0,
|
||||
"mean_delta": r.score.mean_delta,
|
||||
"iterations_used": r.score.iterations_used,
|
||||
"captured_at": datetime.now(timezone.utc).date().isoformat(),
|
||||
}
|
||||
path.write_text(json.dumps(out, indent=2))
|
||||
@@ -1,2 +0,0 @@
|
||||
*
|
||||
!.gitignore
|
||||
@@ -1,86 +0,0 @@
|
||||
"""CLI: python -m backend.eval.custom_lyrics.run"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from backend.eval.custom_lyrics.cache import LlmCallCache
|
||||
from backend.eval.custom_lyrics.report import write_baseline, write_run_reports
|
||||
from backend.eval.custom_lyrics.runner import run_fixture
|
||||
from backend.services.custom_lyrics.service import CustomLyricsService
|
||||
|
||||
EVAL_ROOT = Path(__file__).parent
|
||||
FIXTURES_DIR = EVAL_ROOT / "fixtures"
|
||||
RESULTS_DIR = EVAL_ROOT / "results"
|
||||
CACHE_DIR = EVAL_ROOT / "cache"
|
||||
BASELINE_PATH = EVAL_ROOT / "baseline.json"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--fixtures", default="all", help="fixture id, or comma-separated, or 'all'")
|
||||
parser.add_argument("--settings", default=None, help="settings name from metadata.settings_to_test")
|
||||
parser.add_argument("--no-cache", action="store_true")
|
||||
parser.add_argument("--replay-only", action="store_true")
|
||||
parser.add_argument("--save-as-baseline", default=None,
|
||||
help="path to write baseline JSON (e.g., baseline-post.json)")
|
||||
args = parser.parse_args()
|
||||
|
||||
cache = LlmCallCache(
|
||||
CACHE_DIR,
|
||||
replay_only=args.replay_only,
|
||||
) if not args.no_cache else _NullCache()
|
||||
|
||||
fixture_dirs = _select_fixtures(args.fixtures)
|
||||
service = CustomLyricsService()
|
||||
|
||||
results = []
|
||||
for fdir in fixture_dirs:
|
||||
meta = json.loads((fdir / "metadata.json").read_text())
|
||||
candidate_settings = meta.get("settings_to_test", [{
|
||||
"name": "default",
|
||||
"allow_reword": True,
|
||||
"allow_omit": True,
|
||||
"fixed_line_count": True,
|
||||
"strictness": "balanced",
|
||||
}])
|
||||
for s in candidate_settings:
|
||||
if args.settings and s["name"] != args.settings:
|
||||
continue
|
||||
settings_dict = {k: v for k, v in s.items() if k != "name"}
|
||||
print(f"Running {fdir.name} / {s['name']}...", file=sys.stderr)
|
||||
results.append(run_fixture(
|
||||
fdir, s["name"], settings_dict,
|
||||
cache=cache, service=service,
|
||||
))
|
||||
|
||||
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H%M")
|
||||
out_dir = RESULTS_DIR / ts
|
||||
baseline = json.loads(BASELINE_PATH.read_text()) if BASELINE_PATH.exists() else None
|
||||
write_run_reports(results, out_dir, baseline=baseline)
|
||||
|
||||
if args.save_as_baseline:
|
||||
write_baseline(results, EVAL_ROOT / args.save_as_baseline)
|
||||
print(f"Baseline saved to {args.save_as_baseline}", file=sys.stderr)
|
||||
|
||||
print(f"\nReport: {out_dir / 'summary.md'}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
def _select_fixtures(spec: str) -> list[Path]:
|
||||
if spec == "all":
|
||||
return sorted(p for p in FIXTURES_DIR.iterdir() if p.is_dir() and (p / "metadata.json").exists())
|
||||
ids = [s.strip() for s in spec.split(",")]
|
||||
return [FIXTURES_DIR / i for i in ids]
|
||||
|
||||
|
||||
class _NullCache:
|
||||
def get(self, *args, **kwargs): return None
|
||||
def set(self, *args, **kwargs): pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,112 +0,0 @@
|
||||
"""Eval runner: load fixture → call service (cached) → score → return result."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from backend.eval.custom_lyrics.cache import LlmCallCache
|
||||
from backend.eval.custom_lyrics.scorer import FixtureScore, aggregate_fixture
|
||||
from backend.services.custom_lyrics.service import CustomLyricsService
|
||||
from backend.services.custom_lyrics.settings import (
|
||||
GenerationSettings,
|
||||
settings_from_dict,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FixtureRunResult:
|
||||
fixture_id: str
|
||||
settings_name: str
|
||||
score: FixtureScore
|
||||
output_lines: list[str]
|
||||
line_metadata: list[dict[str, Any]]
|
||||
fixture_dir: Path
|
||||
|
||||
|
||||
def load_fixture(fixture_dir: Path) -> dict:
|
||||
metadata = json.loads((fixture_dir / "metadata.json").read_text())
|
||||
metadata["original_lyrics"] = (fixture_dir / "original_lyrics.txt").read_text().strip().splitlines()
|
||||
metadata["original_segments"] = json.loads((fixture_dir / "original_segments.json").read_text())
|
||||
metadata["client_input"] = (fixture_dir / "client_input.txt").read_text()
|
||||
notes_path = fixture_dir / "notes.txt"
|
||||
metadata["notes"] = notes_path.read_text() if notes_path.exists() else None
|
||||
return metadata
|
||||
|
||||
|
||||
def run_fixture(
|
||||
fixture_dir: Path,
|
||||
settings_name: str,
|
||||
settings_dict: dict[str, Any],
|
||||
*,
|
||||
cache: LlmCallCache,
|
||||
service: CustomLyricsService,
|
||||
) -> FixtureRunResult:
|
||||
fixture = load_fixture(fixture_dir)
|
||||
settings = settings_from_dict(settings_dict)
|
||||
gemini_call_count = 0
|
||||
|
||||
real_call = service._call_gemini
|
||||
|
||||
def cached_call(*, system_prompt: str, user_prompt: str, pdf_bytes, settings: GenerationSettings):
|
||||
nonlocal gemini_call_count
|
||||
cached = cache.get(
|
||||
system_prompt, user_prompt,
|
||||
model=service.settings.custom_lyrics_model,
|
||||
settings_dict=settings.to_dict(),
|
||||
)
|
||||
if cached is not None:
|
||||
return cached
|
||||
gemini_call_count += 1
|
||||
result = real_call(
|
||||
system_prompt=system_prompt, user_prompt=user_prompt,
|
||||
pdf_bytes=pdf_bytes, settings=settings,
|
||||
)
|
||||
cache.set(
|
||||
system_prompt, user_prompt,
|
||||
model=service.settings.custom_lyrics_model,
|
||||
settings_dict=settings.to_dict(),
|
||||
response_lines=result,
|
||||
)
|
||||
return result
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=cached_call):
|
||||
result = service.generate(
|
||||
job_id=fixture["id"],
|
||||
target_lines=fixture["original_lyrics"],
|
||||
target_segments=fixture["original_segments"],
|
||||
artist=fixture.get("artist"),
|
||||
title=fixture.get("title"),
|
||||
custom_text=fixture["client_input"],
|
||||
file_bytes=None, file_mime=None, file_name=None,
|
||||
notes=fixture.get("notes"),
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
score = aggregate_fixture(
|
||||
fixture_id=fixture["id"],
|
||||
settings_name=settings_name,
|
||||
metadata=result.line_metadata,
|
||||
iterations_used=result.iterations_used,
|
||||
stop_reason=result.stop_reason.value,
|
||||
duration_ms=result.duration_ms,
|
||||
gemini_calls=gemini_call_count,
|
||||
line_count_match=not result.line_count_mismatch,
|
||||
)
|
||||
|
||||
return FixtureRunResult(
|
||||
fixture_id=fixture["id"],
|
||||
settings_name=settings_name,
|
||||
score=score,
|
||||
output_lines=result.lines,
|
||||
line_metadata=[{
|
||||
"line_index": v.line_index,
|
||||
"target_text": v.target_text,
|
||||
"candidate_text": v.candidate_text,
|
||||
"min_delta": v.min_delta,
|
||||
"severity": v.severity.value,
|
||||
} for v in result.line_metadata],
|
||||
fixture_dir=fixture_dir,
|
||||
)
|
||||
@@ -1,113 +0,0 @@
|
||||
"""Pure scoring functions for custom-lyrics eval."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
from backend.services.custom_lyrics.validator import LineValidation
|
||||
|
||||
|
||||
@dataclass
|
||||
class PerLineScore:
|
||||
line_index: int
|
||||
min_delta: int
|
||||
pass_at_0: bool
|
||||
pass_at_1: bool
|
||||
pass_at_2: bool
|
||||
pass_at_4: bool
|
||||
severity: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class FixtureScore:
|
||||
fixture_id: str
|
||||
settings_name: str
|
||||
line_count: int
|
||||
pct_pass_at_2: float
|
||||
pct_pass_at_1: float
|
||||
pct_pass_at_0: float
|
||||
pct_pass_at_4: float
|
||||
mean_delta: float
|
||||
median_delta: float
|
||||
max_delta: int
|
||||
iterations_used: int
|
||||
stop_reason: str
|
||||
duration_ms: int
|
||||
gemini_calls: int
|
||||
line_count_match: bool
|
||||
severity_breakdown: dict[str, int]
|
||||
|
||||
|
||||
def score_per_line(val: LineValidation) -> PerLineScore:
|
||||
return PerLineScore(
|
||||
line_index=val.line_index,
|
||||
min_delta=val.min_delta,
|
||||
pass_at_0=val.min_delta <= 0,
|
||||
pass_at_1=val.min_delta <= 1,
|
||||
pass_at_2=val.min_delta <= 2,
|
||||
pass_at_4=val.min_delta <= 4,
|
||||
severity=val.severity.value,
|
||||
)
|
||||
|
||||
|
||||
def aggregate_fixture(
|
||||
*,
|
||||
fixture_id: str,
|
||||
settings_name: str,
|
||||
metadata: list[LineValidation],
|
||||
iterations_used: int,
|
||||
stop_reason: str,
|
||||
duration_ms: int,
|
||||
gemini_calls: int,
|
||||
line_count_match: bool,
|
||||
) -> FixtureScore:
|
||||
n = len(metadata)
|
||||
if n == 0:
|
||||
return FixtureScore(
|
||||
fixture_id=fixture_id, settings_name=settings_name,
|
||||
line_count=0,
|
||||
pct_pass_at_2=0, pct_pass_at_1=0, pct_pass_at_0=0, pct_pass_at_4=0,
|
||||
mean_delta=0, median_delta=0, max_delta=0,
|
||||
iterations_used=iterations_used, stop_reason=stop_reason,
|
||||
duration_ms=duration_ms, gemini_calls=gemini_calls,
|
||||
line_count_match=line_count_match,
|
||||
severity_breakdown={"ok": 0, "minor": 0, "major": 0},
|
||||
)
|
||||
deltas = sorted(v.min_delta for v in metadata)
|
||||
severity_breakdown = {"ok": 0, "minor": 0, "major": 0}
|
||||
for v in metadata:
|
||||
severity_breakdown[v.severity.value] += 1
|
||||
return FixtureScore(
|
||||
fixture_id=fixture_id,
|
||||
settings_name=settings_name,
|
||||
line_count=n,
|
||||
pct_pass_at_2=sum(1 for d in deltas if d <= 2) / n,
|
||||
pct_pass_at_1=sum(1 for d in deltas if d <= 1) / n,
|
||||
pct_pass_at_0=sum(1 for d in deltas if d <= 0) / n,
|
||||
pct_pass_at_4=sum(1 for d in deltas if d <= 4) / n,
|
||||
mean_delta=sum(deltas) / n,
|
||||
median_delta=deltas[n // 2],
|
||||
max_delta=deltas[-1],
|
||||
iterations_used=iterations_used,
|
||||
stop_reason=stop_reason,
|
||||
duration_ms=duration_ms,
|
||||
gemini_calls=gemini_calls,
|
||||
line_count_match=line_count_match,
|
||||
severity_breakdown=severity_breakdown,
|
||||
)
|
||||
|
||||
|
||||
def aggregate_corpus(per_fixture: Iterable[FixtureScore]) -> dict:
|
||||
"""Macro-averaged corpus aggregate."""
|
||||
fixtures = list(per_fixture)
|
||||
if not fixtures:
|
||||
return {}
|
||||
return {
|
||||
"fixture_count": len(fixtures),
|
||||
"macro_pct_pass_at_2": sum(f.pct_pass_at_2 for f in fixtures) / len(fixtures),
|
||||
"macro_pct_pass_at_1": sum(f.pct_pass_at_1 for f in fixtures) / len(fixtures),
|
||||
"macro_pct_pass_at_0": sum(f.pct_pass_at_0 for f in fixtures) / len(fixtures),
|
||||
"macro_pct_pass_at_4": sum(f.pct_pass_at_4 for f in fixtures) / len(fixtures),
|
||||
"macro_mean_delta": sum(f.mean_delta for f in fixtures) / len(fixtures),
|
||||
"total_gemini_calls": sum(f.gemini_calls for f in fixtures),
|
||||
}
|
||||
Whitespace-only changes.
@@ -1,38 +0,0 @@
|
||||
"""Tests for the LLM-call disk cache."""
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from backend.eval.custom_lyrics.cache import LlmCallCache
|
||||
|
||||
|
||||
def test_miss_returns_none() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp))
|
||||
assert c.get("system", "user", model="m1", settings_dict={"x": 1}) is None
|
||||
|
||||
|
||||
def test_set_then_get_hits() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp))
|
||||
c.set("system", "user", model="m1", settings_dict={"x": 1}, response_lines=["a", "b"])
|
||||
assert c.get("system", "user", model="m1", settings_dict={"x": 1}) == ["a", "b"]
|
||||
|
||||
|
||||
def test_different_settings_different_keys() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp))
|
||||
c.set("system", "user", model="m1", settings_dict={"x": 1}, response_lines=["a"])
|
||||
assert c.get("system", "user", model="m1", settings_dict={"x": 2}) is None
|
||||
|
||||
|
||||
def test_replay_only_raises_on_miss() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
c = LlmCallCache(Path(tmp), replay_only=True)
|
||||
try:
|
||||
c.get("system", "user", model="m1", settings_dict={"x": 1})
|
||||
except RuntimeError as e:
|
||||
assert "cache miss" in str(e).lower()
|
||||
else:
|
||||
raise AssertionError("expected RuntimeError")
|
||||
@@ -1,66 +0,0 @@
|
||||
"""Tests for eval scorer."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.eval.custom_lyrics.scorer import (
|
||||
PerLineScore,
|
||||
FixtureScore,
|
||||
score_per_line,
|
||||
aggregate_fixture,
|
||||
)
|
||||
from backend.services.custom_lyrics.validator import LineValidation, Severity
|
||||
|
||||
|
||||
def _line_val(idx: int, target: list[int], cand: list[int], passes: bool, severity: Severity, delta: int) -> LineValidation:
|
||||
return LineValidation(
|
||||
line_index=idx,
|
||||
target_text=f"t{idx}",
|
||||
candidate_text=f"c{idx}",
|
||||
target_syllables=target,
|
||||
candidate_syllables=cand,
|
||||
min_delta=delta,
|
||||
passes=passes,
|
||||
severity=severity,
|
||||
time_budget_seconds=1.0,
|
||||
)
|
||||
|
||||
|
||||
def test_score_per_line_pass_fail_thresholds() -> None:
|
||||
val = _line_val(0, [5, 5, 5, 5], [6, 6, 6, 6], passes=False, severity=Severity.MINOR, delta=1)
|
||||
s = score_per_line(val)
|
||||
assert s.pass_at_0 is False
|
||||
assert s.pass_at_1 is True
|
||||
assert s.pass_at_2 is True
|
||||
assert s.pass_at_4 is True
|
||||
assert s.min_delta == 1
|
||||
|
||||
|
||||
def test_score_per_line_major_violation() -> None:
|
||||
val = _line_val(0, [5, 5, 5, 5], [12, 12, 12, 12], passes=False, severity=Severity.MAJOR, delta=7)
|
||||
s = score_per_line(val)
|
||||
assert s.pass_at_0 is False
|
||||
assert s.pass_at_4 is False
|
||||
assert s.severity == "major"
|
||||
|
||||
|
||||
def test_aggregate_fixture_basic() -> None:
|
||||
metadata = [
|
||||
_line_val(0, [5]*4, [5]*4, passes=True, severity=Severity.OK, delta=0),
|
||||
_line_val(1, [5]*4, [6]*4, passes=False, severity=Severity.MINOR, delta=1),
|
||||
_line_val(2, [5]*4, [9]*4, passes=False, severity=Severity.MAJOR, delta=4),
|
||||
]
|
||||
fixture = aggregate_fixture(
|
||||
fixture_id="x",
|
||||
settings_name="default",
|
||||
metadata=metadata,
|
||||
iterations_used=2,
|
||||
stop_reason="max_iters_reached",
|
||||
duration_ms=1500,
|
||||
gemini_calls=3,
|
||||
line_count_match=True,
|
||||
)
|
||||
assert fixture.pct_pass_at_2 == pytest.approx(2 / 3)
|
||||
assert fixture.pct_pass_at_0 == pytest.approx(1 / 3)
|
||||
assert fixture.mean_delta == pytest.approx((0 + 1 + 4) / 3)
|
||||
assert fixture.max_delta == 4
|
||||
@@ -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:
|
||||
|
||||
+5
-42
@@ -1,16 +1,13 @@
|
||||
"""
|
||||
FastAPI application entry point for karaoke generation backend.
|
||||
|
||||
(Trivial comment touch to trigger backend CI on ephemeral runners after
|
||||
the 2026-05-17 dispatcher e2 fix; safe to remove on next backend edit.)
|
||||
"""
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings, validate_production_config
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
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
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -18,7 +15,6 @@ from backend.services.nltk_preloader import preload_all_nltk_resources
|
||||
from backend.services.langfuse_preloader import preload_langfuse_handler
|
||||
from backend.middleware.audit_logging import AuditLoggingMiddleware
|
||||
from backend.middleware.tenant import TenantMiddleware
|
||||
from backend.middleware.edge_auth import EdgeAuthMiddleware
|
||||
from backend.workers.registry import worker_registry
|
||||
|
||||
|
||||
@@ -77,11 +73,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
|
||||
|
||||
@@ -112,37 +103,18 @@ async def lifespan(app: FastAPI):
|
||||
yield
|
||||
|
||||
# Shutdown - wait for any active workers to complete before terminating
|
||||
# This prevents Cloud Run from killing workers mid-processing.
|
||||
#
|
||||
# Cloud Run gen2 default termination grace period is 600s. We wait up to
|
||||
# 480s, leaving ~120s for the cleanup pass below to write Firestore state
|
||||
# before SIGKILL. Without that headroom, render jobs that miss the wait
|
||||
# would sit in `rendering_video` forever waiting for an operator.
|
||||
# This prevents Cloud Run from killing workers mid-processing
|
||||
logger.info("Shutdown requested, checking for active workers...")
|
||||
if worker_registry.has_active_workers():
|
||||
active = worker_registry.get_active_workers()
|
||||
logger.info(f"Active workers found: {active}")
|
||||
logger.info("Waiting for workers to complete (timeout: 480s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=480)
|
||||
logger.info("Waiting for workers to complete (timeout: 600s)...")
|
||||
completed = await worker_registry.wait_for_completion(timeout=600) # 10 min max
|
||||
if not completed:
|
||||
logger.error(
|
||||
"Shutdown timeout - some workers may not have completed cleanly. "
|
||||
f"Remaining workers: {worker_registry.get_active_workers()}"
|
||||
)
|
||||
|
||||
# Park any still-active render jobs so the auto-retry scheduler can
|
||||
# recover them. Safe to call unconditionally — it's a no-op if nothing
|
||||
# render-related is in flight.
|
||||
try:
|
||||
from backend.workers.render_video_worker import park_active_render_jobs_for_shutdown
|
||||
parked = park_active_render_jobs_for_shutdown()
|
||||
if parked:
|
||||
logger.warning(
|
||||
f"Parked {parked} in-flight render job(s) for auto-retry "
|
||||
f"due to shutdown"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(f"Render-job shutdown park failed: {exc!r}")
|
||||
else:
|
||||
logger.info("No active workers, proceeding with shutdown")
|
||||
|
||||
@@ -176,12 +148,6 @@ app.add_middleware(AuditLoggingMiddleware)
|
||||
# Add tenant detection middleware (extracts tenant from subdomain/headers)
|
||||
app.add_middleware(TenantMiddleware)
|
||||
|
||||
# Edge origin lock (added last = outermost, runs first). Rejects direct-to-origin
|
||||
# requests that bypassed the Cloudflare edge, before tenant/audit middleware do
|
||||
# any work. No-op unless EDGE_AUTH_MODE is warn/enforce. See
|
||||
# backend/middleware/edge_auth.py.
|
||||
app.add_middleware(EdgeAuthMiddleware)
|
||||
|
||||
# Include routers
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(jobs.router, prefix="/api")
|
||||
@@ -199,9 +165,6 @@ app.include_router(admin.router, prefix="/api") # Admin dashboard and managemen
|
||||
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
|
||||
app.include_router(push.router, prefix="/api") # Push notification subscription management
|
||||
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
|
||||
app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename parser
|
||||
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
|
||||
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
"""
|
||||
Edge origin-lock middleware.
|
||||
|
||||
Cloudflare fronts ``api.nomadkaraoke.com`` (WAF + rate limiting). To stop
|
||||
attackers from bypassing the edge by hitting the Cloud Run origin directly
|
||||
(``*.run.app`` / ``ghs.googlehosted.com``), Cloudflare injects a shared-secret
|
||||
header (``X-Edge-Auth``) on every proxied request via a Transform Rule. This
|
||||
middleware rejects public requests that lack the correct header.
|
||||
|
||||
A Cloud Run *domain mapping* can't use ``ingress=internal-and-cloud-load-balancing``
|
||||
(that needs a load balancer), so this app-layer check is how we lock the origin.
|
||||
|
||||
Modes (env ``EDGE_AUTH_MODE``, default ``off``):
|
||||
off - passthrough, no checks (deploy-dormant; behaviour unchanged).
|
||||
warn - log requests missing/failing the header, but ALLOW them. Use to
|
||||
confirm nothing legit is missing the header before enforcing.
|
||||
enforce - reject requests missing/failing the header with 403.
|
||||
|
||||
Secret: env ``EDGE_ORIGIN_SECRET`` (same value Cloudflare injects). If enforce
|
||||
mode is set but the secret is unconfigured, the middleware FAILS CLOSED (503) —
|
||||
a security control must not silently allow direct-origin traffic. (Low risk:
|
||||
Cloud Run won't start a revision whose secret ref is missing, and enforce is
|
||||
only enabled after staging confirms the secret.) In warn mode it still allows.
|
||||
|
||||
Exemptions (always allowed, even in enforce mode):
|
||||
* Health / root endpoints and Cloud Run probes, which hit the origin
|
||||
directly (not via Cloudflare) and legitimately lack the header.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Header Cloudflare injects (must match CloudflareConfig.ORIGIN_AUTH_HEADER in
|
||||
# infrastructure/modules/edge_security.py).
|
||||
EDGE_AUTH_HEADER = "X-Edge-Auth"
|
||||
|
||||
# Paths always allowed without the edge header. These are non-sensitive and are
|
||||
# probed directly on the origin by Cloud Run startup/liveness checks and GCP
|
||||
# uptime monitoring, which don't traverse Cloudflare.
|
||||
_EXEMPT_EXACT = {"/", "/api/health", "/api/health/"}
|
||||
_EXEMPT_PREFIXES = ("/api/health/",)
|
||||
|
||||
_VALID_MODES = {"off", "warn", "enforce"}
|
||||
|
||||
|
||||
def _mode() -> str:
|
||||
mode = os.environ.get("EDGE_AUTH_MODE", "off").lower().strip()
|
||||
return mode if mode in _VALID_MODES else "off"
|
||||
|
||||
|
||||
def _is_exempt(path: str) -> bool:
|
||||
if path in _EXEMPT_EXACT:
|
||||
return True
|
||||
return any(path.startswith(p) for p in _EXEMPT_PREFIXES)
|
||||
|
||||
|
||||
class EdgeAuthMiddleware(BaseHTTPMiddleware):
|
||||
"""Reject origin requests that didn't come through the Cloudflare edge."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
mode = _mode()
|
||||
if mode == "off":
|
||||
return await call_next(request)
|
||||
|
||||
if _is_exempt(request.url.path):
|
||||
return await call_next(request)
|
||||
|
||||
secret = os.environ.get("EDGE_ORIGIN_SECRET", "")
|
||||
if not secret:
|
||||
# Misconfiguration: enforce is requested but no secret is wired up.
|
||||
# In enforce mode, fail CLOSED (503) — a security control must not
|
||||
# silently allow direct-origin traffic when it can't do its job.
|
||||
# This is low-risk operationally: Cloud Run won't even start a
|
||||
# revision whose --set-secrets ref is missing, and enforce is only
|
||||
# turned on after staging confirms the secret. In warn mode we still
|
||||
# allow (observational only).
|
||||
logger.error(
|
||||
"EDGE_AUTH_MODE=%s but EDGE_ORIGIN_SECRET is unset.", mode,
|
||||
)
|
||||
if mode == "enforce":
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"detail": "Origin authentication unavailable"},
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
provided = request.headers.get(EDGE_AUTH_HEADER, "")
|
||||
# Constant-time comparison to avoid leaking the secret via timing.
|
||||
ok = bool(provided) and hmac.compare_digest(provided, secret)
|
||||
|
||||
if ok:
|
||||
return await call_next(request)
|
||||
|
||||
client = request.client.host if request.client else "?"
|
||||
if mode == "warn":
|
||||
logger.warning(
|
||||
"edge-auth: request missing/invalid %s header (warn mode, "
|
||||
"allowing). path=%s ip=%s",
|
||||
EDGE_AUTH_HEADER, request.url.path, client,
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
# enforce
|
||||
logger.warning(
|
||||
"edge-auth: blocked direct-to-origin request. path=%s ip=%s",
|
||||
request.url.path, client,
|
||||
)
|
||||
return JSONResponse(status_code=403, content={"detail": "Forbidden"})
|
||||
@@ -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
|
||||
|
||||
+6
-55
@@ -37,7 +37,6 @@ class JobStatus(str, Enum):
|
||||
SEARCHING_AUDIO = "searching_audio" # Searching for audio sources via flacfetch
|
||||
AWAITING_AUDIO_SELECTION = "awaiting_audio_selection" # ⚠️ WAITING FOR USER - select audio source
|
||||
DOWNLOADING_AUDIO = "downloading_audio" # Downloading selected audio from source
|
||||
DOWNLOAD_PENDING_RETRY = "download_pending_retry" # Download hit a transient issue (few/no seeders, tracker blip); auto-retrying for up to 24h
|
||||
|
||||
DOWNLOADING = "downloading" # Downloading from URL or processing upload
|
||||
|
||||
@@ -46,9 +45,6 @@ class JobStatus(str, Enum):
|
||||
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
|
||||
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
|
||||
|
||||
# Optional: duration cost confirmation (BLOCKING) - confirm credits before heavy processing
|
||||
AWAITING_DURATION_CONFIRM = "awaiting_duration_confirm" # ⚠️ WAITING FOR USER - confirm duration-based cost
|
||||
|
||||
# Stage 2a: Audio separation (parallel track 1)
|
||||
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
|
||||
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
|
||||
@@ -72,7 +68,6 @@ class JobStatus(str, Enum):
|
||||
|
||||
# Stage 5.5: Render video with corrected lyrics (post-review)
|
||||
RENDERING_VIDEO = "rendering_video" # Using OutputGenerator to create with_vocals.mkv
|
||||
RENDER_PENDING_CAPACITY = "render_pending_capacity" # Waiting for GCE encoding capacity (auto-retry)
|
||||
|
||||
# Stage 6: Instrumental already selected (during combined review)
|
||||
# Note: AWAITING_INSTRUMENTAL_SELECTION kept for DB compatibility with historical jobs only
|
||||
@@ -111,27 +106,16 @@ STATE_TRANSITIONS = {
|
||||
# Audio search flow (for artist+title search mode)
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.DOWNLOAD_PENDING_RETRY, JobStatus.FAILED],
|
||||
# DOWNLOAD_PENDING_RETRY = parked when a torrent download hits a transient
|
||||
# issue (few/no seeders, tracker outage); auto-retried by the recover-stuck
|
||||
# cron for up to 24h before failing permanently.
|
||||
JobStatus.DOWNLOAD_PENDING_RETRY: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
|
||||
|
||||
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
|
||||
# Can also enter optional audio edit phase if requires_audio_edit flag is set
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
|
||||
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
|
||||
|
||||
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
|
||||
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
|
||||
|
||||
# Duration cost confirmation (BLOCKING) - user confirms before heavy processing begins
|
||||
JobStatus.AWAITING_DURATION_CONFIRM: [
|
||||
JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING,
|
||||
JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT,
|
||||
JobStatus.FAILED, JobStatus.CANCELLED,
|
||||
],
|
||||
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
|
||||
|
||||
# Audio separation flow
|
||||
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
|
||||
@@ -151,27 +135,10 @@ STATE_TRANSITIONS = {
|
||||
# AWAITING_REVIEW can go directly to REVIEW_COMPLETE (quick review) or to IN_REVIEW (editing)
|
||||
JobStatus.AWAITING_REVIEW: [JobStatus.IN_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.IN_REVIEW: [JobStatus.REVIEW_COMPLETE, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
|
||||
JobStatus.REVIEW_COMPLETE: [
|
||||
JobStatus.RENDERING_VIDEO,
|
||||
JobStatus.PREP_COMPLETE, # for prep-only jobs
|
||||
JobStatus.RENDER_PENDING_CAPACITY, # GCE capacity exhausted before render started
|
||||
JobStatus.FAILED,
|
||||
],
|
||||
JobStatus.REVIEW_COMPLETE: [JobStatus.RENDERING_VIDEO, JobStatus.PREP_COMPLETE, JobStatus.FAILED], # PREP_COMPLETE for prep-only jobs
|
||||
|
||||
# Video rendering (post-review) - instrumental was already selected during combined review
|
||||
# RENDER_PENDING_CAPACITY = parked when GCE encoding capacity is exhausted; auto-retried by scheduler.
|
||||
JobStatus.RENDERING_VIDEO: [
|
||||
JobStatus.INSTRUMENTAL_SELECTED,
|
||||
JobStatus.PREP_COMPLETE,
|
||||
JobStatus.RENDER_PENDING_CAPACITY,
|
||||
JobStatus.FAILED,
|
||||
],
|
||||
JobStatus.RENDER_PENDING_CAPACITY: [
|
||||
JobStatus.RENDERING_VIDEO, # auto-retry succeeded, picked up again
|
||||
JobStatus.REVIEW_COMPLETE, # admin / scheduler resets to re-trigger render
|
||||
JobStatus.FAILED, # exceeded max wait or operator gave up
|
||||
JobStatus.CANCELLED, # user cancelled while waiting
|
||||
],
|
||||
JobStatus.RENDERING_VIDEO: [JobStatus.INSTRUMENTAL_SELECTED, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs in DB
|
||||
# New jobs never enter this state; they go directly to INSTRUMENTAL_SELECTED after render
|
||||
@@ -199,7 +166,6 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
JobStatus.AWAITING_REVIEW, # Retry from combined review
|
||||
JobStatus.RENDER_PENDING_CAPACITY, # Operator parks a stale-failed job for auto-retry
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
@@ -274,13 +240,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)
|
||||
@@ -617,11 +577,6 @@ class JobCreate(BaseModel):
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
|
||||
|
||||
# Credit pricing: how many credits to charge for this job at creation time.
|
||||
# Search and upload jobs pass the default (1) and may top up later.
|
||||
# URL jobs with a known duration pass ceil(duration/600) credits.
|
||||
credits: int = 1
|
||||
|
||||
# Request metadata (set by API endpoint from request headers)
|
||||
request_metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
"""
|
||||
@@ -637,10 +592,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."""
|
||||
|
||||
@@ -20,10 +20,6 @@ class URLSubmissionRequest(BaseModel):
|
||||
user_email: Optional[str] = None
|
||||
is_private: Optional[bool] = None # Private (non-published) track mode
|
||||
|
||||
# Duration-based pricing: supplied by the client from YouTube metadata
|
||||
duration_seconds: Optional[float] = None # Known audio duration in seconds
|
||||
acknowledged_credits: Optional[int] = None # Client's expected credit cost (anti-mismatch guard)
|
||||
|
||||
|
||||
class UploadSubmissionRequest(BaseModel):
|
||||
"""Request to submit a job from an uploaded file."""
|
||||
@@ -42,13 +38,12 @@ class UploadSubmissionRequest(BaseModel):
|
||||
class CorrectionsSubmission(BaseModel):
|
||||
"""
|
||||
Request to submit corrected lyrics after human review.
|
||||
|
||||
|
||||
This is the critical human-in-the-loop interaction point.
|
||||
The corrections data comes from the lyrics-transcriber review interface.
|
||||
"""
|
||||
corrections: Dict[str, Any] # Full corrections JSON from frontend
|
||||
user_notes: Optional[str] = None # Optional notes from reviewer
|
||||
is_duet: Optional[bool] = None # When present, persists duet flag to state_data
|
||||
|
||||
@validator('corrections')
|
||||
def validate_corrections_format(cls, v):
|
||||
|
||||
+2
-37
@@ -10,7 +10,7 @@ Supports:
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from typing import Optional, List, Dict
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class UserRole(str, Enum):
|
||||
@@ -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)
|
||||
@@ -198,18 +191,6 @@ class VerifyMagicLinkRequest(BaseModel):
|
||||
token: str
|
||||
|
||||
|
||||
class ResendFromTokenRequest(BaseModel):
|
||||
"""Request to resend a magic link based on a previously-issued (expired/used) token."""
|
||||
token: str
|
||||
|
||||
|
||||
class ResendFromTokenResponse(BaseModel):
|
||||
"""Response after attempting to resend a magic link from a known token."""
|
||||
status: str # "sent" | "no_token"
|
||||
masked_email: Optional[str] = None
|
||||
message: str
|
||||
|
||||
|
||||
class VerifyMagicLinkResponse(BaseModel):
|
||||
"""Response after verifying magic link."""
|
||||
status: str
|
||||
@@ -257,22 +238,6 @@ class AddCreditsResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class AdminCreateUserRequest(BaseModel):
|
||||
"""Admin request to create a user account directly."""
|
||||
email: EmailStr
|
||||
display_name: Optional[str] = None
|
||||
initial_credits: int = 0
|
||||
credit_reason: str = "admin_grant"
|
||||
|
||||
|
||||
class AdminCreateUserResponse(BaseModel):
|
||||
"""Response after admin creates a user."""
|
||||
status: str
|
||||
email: str
|
||||
credits: int
|
||||
message: str
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
"""Response for listing users (admin only)."""
|
||||
users: List[UserPublic]
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Operational and maintenance scripts for the karaoke-gen backend."""
|
||||
@@ -1,199 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill original input audio into past jobs' Dropbox folders.
|
||||
|
||||
Restores files like ``<artist> - <title> (flacfetch).flac`` / ``(uploaded).mp3`` to
|
||||
the organised Dropbox track folders for completed jobs that predate the pipeline fix
|
||||
(the distributed pipeline stopped copying the source audio into the output folder).
|
||||
|
||||
Dry-run by default; pass ``--live`` to actually upload. NOTE: this cannot backfill the
|
||||
screen ``.mov`` files — those require re-encoding the job.
|
||||
|
||||
Usage:
|
||||
python -m backend.scripts.backfill_original_audio # dry-run, since 2026-03-01
|
||||
python -m backend.scripts.backfill_original_audio --live # actually upload
|
||||
python -m backend.scripts.backfill_original_audio --since 2026-02-01 --limit 50 -v
|
||||
"""
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.original_audio import (
|
||||
original_audio_gcs_path,
|
||||
original_audio_output_filename,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("backfill_original_audio")
|
||||
|
||||
# The regression window: screen/audio files stopped reaching Dropbox once the
|
||||
# distributed pipeline took over (last known-good folder ~Feb; PR #647/#650 Mar 31).
|
||||
DEFAULT_SINCE = "2026-03-01"
|
||||
|
||||
|
||||
def plan_job_backfill(job, *, storage, dropbox):
|
||||
"""Decide what to do for one job (existence checks only — no uploads).
|
||||
|
||||
Returns ``(action, detail)`` where action is one of:
|
||||
- ``"skip-no-dropbox"`` — job was never uploaded to Dropbox
|
||||
- ``"skip-no-audio-record"`` — no original-audio reference on the job
|
||||
- ``"skip-audio-missing-gcs"`` — original audio no longer in GCS (detail=gcs_path)
|
||||
- ``"skip-folder-missing"`` — the track's Dropbox folder doesn't exist (detail=folder)
|
||||
- ``"skip-already-present"`` — file already in the Dropbox folder (detail=remote_path)
|
||||
- ``"upload"`` — detail={gcs_path, remote_path, filename}
|
||||
"""
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
state = getattr(job, "state_data", None) or {}
|
||||
brand_code = state.get("brand_code")
|
||||
# Use the EFFECTIVE dropbox path — private (NOMADNP) tracks upload to the
|
||||
# NonPublished path, not the job's stored (public) dropbox_path. This mirrors
|
||||
# what the orchestrator does at distribution time.
|
||||
dropbox_path = get_effective_distribution_for_job(job).dropbox_path
|
||||
if not brand_code or not dropbox_path:
|
||||
return ("skip-no-dropbox", None)
|
||||
|
||||
gcs_path = original_audio_gcs_path(job)
|
||||
if not gcs_path:
|
||||
return ("skip-no-audio-record", None)
|
||||
if not storage.file_exists(gcs_path):
|
||||
return ("skip-audio-missing-gcs", gcs_path)
|
||||
|
||||
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
|
||||
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
|
||||
base_name = f"{safe_artist} - {safe_title}"
|
||||
filename = original_audio_output_filename(job, base_name)
|
||||
folder = f"{dropbox_path.rstrip('/')}/{brand_code} - {base_name}"
|
||||
remote_path = f"{folder}/{filename}"
|
||||
|
||||
# Only backfill into a track folder that already exists — never create a new
|
||||
# folder (guards against drifted brand/artist/title naming producing an orphan).
|
||||
if not dropbox.file_exists(folder):
|
||||
return ("skip-folder-missing", folder)
|
||||
|
||||
if dropbox.file_exists(remote_path):
|
||||
return ("skip-already-present", remote_path)
|
||||
|
||||
return ("upload", {"gcs_path": gcs_path, "remote_path": remote_path, "filename": filename})
|
||||
|
||||
|
||||
def _execute_upload(detail, *, storage, dropbox):
|
||||
"""Download the original audio from GCS and upload it to the Dropbox folder."""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
local = os.path.join(td, detail["filename"])
|
||||
storage.download_file(detail["gcs_path"], local)
|
||||
dropbox.upload_file(local, detail["remote_path"])
|
||||
|
||||
|
||||
def run_backfill(*, since, until=None, limit, environment, live):
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
jm = JobManager()
|
||||
storage = StorageService()
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
logger.error("Dropbox not configured; aborting.")
|
||||
return
|
||||
|
||||
# NOTE: created_at is stored as an ISO string in Firestore, so server-side
|
||||
# created_after/created_before datetime filters match nothing. We fetch the most
|
||||
# recent completed jobs (ordered by created_at desc) and filter dates in Python.
|
||||
# `limit` therefore bounds how far back we look — set it high enough to cover the
|
||||
# window since `since`.
|
||||
jobs = jm.list_jobs(status=JobStatus.COMPLETE, limit=limit)
|
||||
|
||||
def _created(j):
|
||||
c = getattr(j, "created_at", None)
|
||||
if c is None:
|
||||
return None
|
||||
return c.replace(tzinfo=None) if getattr(c, "tzinfo", None) else c
|
||||
|
||||
since_naive = since.replace(tzinfo=None)
|
||||
until_naive = until.replace(tzinfo=None) if until else None
|
||||
|
||||
def _in_window(j):
|
||||
c = _created(j)
|
||||
if c is None:
|
||||
return False
|
||||
if c < since_naive:
|
||||
return False
|
||||
if until_naive and c >= until_naive:
|
||||
return False
|
||||
return True
|
||||
|
||||
jobs = [j for j in jobs if _in_window(j)]
|
||||
|
||||
if environment:
|
||||
def _env(j):
|
||||
rm = getattr(j, "request_metadata", None)
|
||||
if rm is None:
|
||||
return None
|
||||
return rm.get("environment") if isinstance(rm, dict) else getattr(rm, "environment", None)
|
||||
jobs = [j for j in jobs if _env(j) == environment]
|
||||
|
||||
logger.info(
|
||||
"Considering %d completed jobs since %s (env=%s, fetch limit=%d)",
|
||||
len(jobs), since.date(), environment or "all", limit,
|
||||
)
|
||||
|
||||
tally = {}
|
||||
for job in jobs:
|
||||
try:
|
||||
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
|
||||
except Exception as e:
|
||||
# A transient GCS/Dropbox error while planning shouldn't abort the whole run.
|
||||
logger.error(" planning failed for %s: %s", getattr(job, "job_id", "?"), e)
|
||||
tally["error"] = tally.get("error", 0) + 1
|
||||
continue
|
||||
tally[action] = tally.get(action, 0) + 1
|
||||
if action == "upload":
|
||||
verb = "uploading" if live else "[DRY-RUN] would upload"
|
||||
logger.info("%s: %s -> %s", verb, job.job_id, detail["remote_path"])
|
||||
if live:
|
||||
try:
|
||||
_execute_upload(detail, storage=storage, dropbox=dropbox)
|
||||
except Exception as e:
|
||||
logger.error(" upload failed for %s: %s", job.job_id, e)
|
||||
tally["upload"] -= 1
|
||||
tally["error"] = tally.get("error", 0) + 1
|
||||
else:
|
||||
logger.debug("%s: %s (%s)", action, job.job_id, detail)
|
||||
|
||||
logger.info("=== Backfill summary (%s) ===", "LIVE" if live else "DRY-RUN")
|
||||
for k in sorted(tally):
|
||||
logger.info(" %-24s %d", k, tally[k])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--since", default=DEFAULT_SINCE, help="Only jobs created on/after YYYY-MM-DD")
|
||||
parser.add_argument("--until", default=None, help="Only jobs created before YYYY-MM-DD")
|
||||
parser.add_argument("--limit", type=int, default=5000,
|
||||
help="Max completed jobs to fetch (most-recent first). Bounds how far "
|
||||
"back the date window can reach.")
|
||||
parser.add_argument("--env", default=None, dest="environment",
|
||||
help="Filter to a request environment (e.g. production). Default: all "
|
||||
"(test jobs are skipped anyway — no brand code / Dropbox folder).")
|
||||
parser.add_argument("--live", action="store_true", help="Actually upload (default: dry-run)")
|
||||
parser.add_argument("-v", "--verbose", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(message)s",
|
||||
)
|
||||
|
||||
since = datetime.strptime(args.since, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
until = (
|
||||
datetime.strptime(args.until, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
if args.until else None
|
||||
)
|
||||
run_backfill(since=since, until=until, limit=args.limit, environment=args.environment, live=args.live)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -106,54 +106,6 @@ class AudioEditService:
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
# Fades must be anchored to a clip edge — FFmpeg's afade silences audio outside
|
||||
# the ramp, so a mid-clip fade would unexpectedly mute the rest of the track.
|
||||
# The tolerance matches the editor UI's edge gating (start < 1s / end within 1s).
|
||||
FADE_ANCHOR_TOLERANCE_SECONDS = 1.0
|
||||
|
||||
def fade_region(
|
||||
self, input_path: str, start: float, end: float, direction: str, output_path: str
|
||||
) -> AudioMetadata:
|
||||
"""Apply a fade in or out anchored to a clip edge (preserves duration).
|
||||
|
||||
direction='in' ramps the volume from silence to full over [0, end];
|
||||
direction='out' ramps from full to silence over [start, clip_end].
|
||||
|
||||
Anchoring is enforced server-side (not just in the UI) because FFmpeg's
|
||||
afade filter silences audio outside the ramp window: a fade-in is forced
|
||||
to begin at the clip start, and a fade-out to finish at the clip end, so a
|
||||
non-anchored request can never silently mute the rest of the track.
|
||||
"""
|
||||
if direction not in ("in", "out"):
|
||||
raise ValueError(f"Invalid fade direction: {direction}")
|
||||
if start < 0 or end <= start:
|
||||
raise ValueError(f"Invalid fade region: start={start}, end={end}")
|
||||
|
||||
total = self.get_metadata(input_path).duration_seconds
|
||||
tol = self.FADE_ANCHOR_TOLERANCE_SECONDS
|
||||
if end > total + tol:
|
||||
raise ValueError(f"Fade region exceeds clip duration ({end} > {total})")
|
||||
|
||||
if direction == "in":
|
||||
if start > tol:
|
||||
raise ValueError(f"fade_in must be anchored to the clip start (got start={start})")
|
||||
fade_start, fade_duration = 0.0, end
|
||||
else:
|
||||
if end < total - tol:
|
||||
raise ValueError(f"fade_out must be anchored to the clip end (got end={end}, duration={total})")
|
||||
fade_start, fade_duration = start, total - start
|
||||
|
||||
if fade_duration <= 0:
|
||||
raise ValueError(f"Fade region must have positive duration (got {fade_duration})")
|
||||
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-af", f"afade=t={direction}:st={fade_start}:d={fade_duration}",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
|
||||
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
|
||||
if position == "start":
|
||||
@@ -204,11 +156,6 @@ class AudioEditService:
|
||||
metadata = self.mute_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], local_output
|
||||
)
|
||||
elif operation in ("fade_in", "fade_out"):
|
||||
direction = "in" if operation == "fade_in" else "out"
|
||||
metadata = self.fade_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], direction, local_output
|
||||
)
|
||||
elif operation in ("join_start", "join_end"):
|
||||
# Download the upload file
|
||||
upload_gcs_path = params["upload_gcs_path"]
|
||||
|
||||
@@ -18,8 +18,7 @@ downloads since Cloud Run doesn't support BitTorrent peer connections.
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import List, Optional
|
||||
|
||||
import nest_asyncio
|
||||
|
||||
@@ -48,151 +47,6 @@ AudioSearchError = AudioFetcherError
|
||||
AudioDownloadResult = AudioFetchResult
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bulk Mode: tier-1 auto-selection.
|
||||
#
|
||||
# This is a faithful port of the frontend confidence-tier logic in
|
||||
# frontend/lib/audio-search-utils.ts (categorizeResult / getBestResult /
|
||||
# checkFilenameMismatch / getSearchConfidence). It operates on the dicts
|
||||
# produced by AudioSearchResult.to_dict() (keys: is_lossless, quality_data,
|
||||
# seeders, provider, release_type, target_file, title, index).
|
||||
#
|
||||
# MAINTENANCE SEAM: if the frontend tier rule changes, update both. The
|
||||
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_BEST_RESULT_PRIORITY = [
|
||||
"BEST CHOICE",
|
||||
"STUDIO ALBUMS",
|
||||
"HI-RES 24-BIT",
|
||||
"SINGLES",
|
||||
"COMPILATIONS",
|
||||
"SPOTIFY",
|
||||
"YOUTUBE",
|
||||
"OTHER",
|
||||
]
|
||||
|
||||
|
||||
def _categorize_result(result: Dict[str, Any]) -> str:
|
||||
"""Port of categorizeResult() from audio-search-utils.ts."""
|
||||
is_lossless = result.get("is_lossless") is True
|
||||
quality_data = result.get("quality_data") or {}
|
||||
is_24bit = quality_data.get("bit_depth") == 24
|
||||
seeders = result.get("seeders") or 0
|
||||
provider = (result.get("provider") or "").lower()
|
||||
release_type = (result.get("release_type") or "").lower()
|
||||
media = (quality_data.get("media") or "").lower()
|
||||
|
||||
if provider == "spotify":
|
||||
return "SPOTIFY"
|
||||
if provider == "youtube" or not is_lossless:
|
||||
return "YOUTUBE"
|
||||
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
|
||||
if is_lossless and media == "vinyl":
|
||||
return "VINYL RIPS"
|
||||
if is_lossless and seeders >= 50:
|
||||
return "BEST CHOICE"
|
||||
if is_lossless and is_24bit:
|
||||
return "HI-RES 24-BIT"
|
||||
if is_lossless and (
|
||||
release_type == "live album" or release_type == "bootleg" or "live" in release_type
|
||||
):
|
||||
return "LIVE VERSIONS"
|
||||
if is_lossless and release_type in ("compilation", "soundtrack", "anthology"):
|
||||
return "COMPILATIONS"
|
||||
if is_lossless and release_type in ("single", "ep"):
|
||||
return "SINGLES"
|
||||
if is_lossless and (release_type == "album" or not release_type):
|
||||
return "STUDIO ALBUMS"
|
||||
return "OTHER"
|
||||
|
||||
|
||||
def _get_best_result(results: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""Port of getBestResult() — highest-priority category, skipping vinyl."""
|
||||
if not results:
|
||||
return None
|
||||
best: Optional[Dict[str, Any]] = None
|
||||
best_priority = float("inf")
|
||||
for result in results:
|
||||
category = _categorize_result(result)
|
||||
if category == "VINYL RIPS":
|
||||
continue
|
||||
try:
|
||||
priority = _BEST_RESULT_PRIORITY.index(category)
|
||||
except ValueError:
|
||||
priority = float("inf")
|
||||
if priority < best_priority:
|
||||
best = result
|
||||
best_priority = priority
|
||||
elif priority == best_priority and best is not None:
|
||||
if (result.get("seeders") or 0) > (best.get("seeders") or 0):
|
||||
best = result
|
||||
return best if best is not None else results[0]
|
||||
|
||||
|
||||
def _check_filename_mismatch(search_title: str, result: Dict[str, Any]) -> bool:
|
||||
"""Port of checkFilenameMismatch() — True if the file is clearly another track."""
|
||||
if len(search_title) < 3:
|
||||
return False
|
||||
|
||||
target_file = result.get("target_file")
|
||||
if target_file:
|
||||
raw_filename = target_file.split("/")[-1] or target_file
|
||||
without_ext = re.sub(r"\.[^.]+$", "", raw_filename)
|
||||
filename = re.sub(r"^\d{1,3}\s*[-.\s]\s*", "", without_ext)
|
||||
elif result.get("title"):
|
||||
filename = result["title"]
|
||||
else:
|
||||
return False
|
||||
|
||||
def normalize(s: str) -> str:
|
||||
s = s.lower()
|
||||
s = re.sub(r"[_\-.]+", " ", s)
|
||||
s = re.sub(r"[^a-z0-9\s]", "", s)
|
||||
s = re.sub(r"\s+", " ", s)
|
||||
return s.strip()
|
||||
|
||||
norm_title = normalize(search_title)
|
||||
norm_file = normalize(filename)
|
||||
if not norm_file or not norm_title:
|
||||
return False
|
||||
|
||||
# Stricter than the frontend's substring check (intentional — for the bulk
|
||||
# AUTO-select path we'd rather park an uncertain match than auto-pick the
|
||||
# wrong track). A match requires every title word to appear as a whole word
|
||||
# in the filename, so "One" no longer matches "Someone".
|
||||
title_tokens = [t for t in norm_title.split() if t]
|
||||
file_tokens = set(norm_file.split())
|
||||
if not title_tokens:
|
||||
return False
|
||||
matches = all(tok in file_tokens for tok in title_tokens)
|
||||
return not matches
|
||||
|
||||
|
||||
def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -> Optional[int]:
|
||||
"""Return the index to auto-select, or None if no confident lossless pick.
|
||||
|
||||
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
|
||||
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
|
||||
must match ``search_title`` (the song the user searched for). Otherwise we
|
||||
defer to human selection.
|
||||
"""
|
||||
if not results:
|
||||
return None
|
||||
# Require a usable title before auto-selecting: a blank/too-short title can't
|
||||
# be verified against the filename, so defer to human selection.
|
||||
if len((search_title or "").strip()) < 3:
|
||||
return None
|
||||
best = _get_best_result(results)
|
||||
if best is None:
|
||||
return None
|
||||
if _categorize_result(best) != "BEST CHOICE":
|
||||
return None
|
||||
if _check_filename_mismatch(search_title, best):
|
||||
return None
|
||||
return best.get("index")
|
||||
|
||||
|
||||
class AudioSearchService:
|
||||
"""
|
||||
Service for searching and downloading audio files.
|
||||
@@ -368,17 +222,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]:
|
||||
"""
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
"""AI auto-correction suggestions for the lyrics review UI.
|
||||
|
||||
Stateless suggestion generation: the client posts its current working
|
||||
segments, the service returns word-level suggestions (replace / delete /
|
||||
insert_after) referencing word ids. Nothing is applied server-side — the
|
||||
reviewer accepts or rejects each suggestion in the UI.
|
||||
"""
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
get_auto_correct_service,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AutoCorrectService",
|
||||
"AutoCorrectServiceError",
|
||||
"get_auto_correct_service",
|
||||
]
|
||||
@@ -1,94 +0,0 @@
|
||||
"""Token pricing for auto-correct model calls.
|
||||
|
||||
Used to turn the per-call token usage we capture from each provider into an
|
||||
estimated USD cost, for both the production usage logs and the offline
|
||||
measurement script (``scripts/measure_autocorrect_cost.py``).
|
||||
|
||||
Prices are USD per 1,000,000 tokens.
|
||||
|
||||
- **Anthropic** prices are authoritative (published Claude API pricing).
|
||||
``output`` is the billed output rate, which already includes adaptive
|
||||
*thinking* tokens — they are billed as output and are not separable from
|
||||
the final answer in the Anthropic usage object.
|
||||
- **Gemini** prices are a best-known ESTIMATE for the Vertex preview tier and
|
||||
are clearly marked below. Verify against current Vertex pricing before
|
||||
relying on the dollar figure. Gemini thinking tokens ARE separable
|
||||
(``thoughts_token_count``) and are billed at the output rate, so we fold
|
||||
them into the output total.
|
||||
|
||||
The raw token counts are always logged alongside the dollar figure, so the
|
||||
cost here is a derived convenience — if a rate is stale, recompute from the
|
||||
logged tokens rather than trusting the historical USD value.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
class TokenUsage(TypedDict):
|
||||
"""Normalized, provider-agnostic usage for one model call.
|
||||
|
||||
``output_tokens`` is the total billed output (final answer + thinking).
|
||||
``thinking_tokens`` is informational only (None when the provider does
|
||||
not report it separately) — it is already counted inside ``output_tokens``.
|
||||
"""
|
||||
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
cache_read_tokens: int
|
||||
thinking_tokens: Optional[int]
|
||||
|
||||
|
||||
class _Rate(TypedDict):
|
||||
input: float
|
||||
output: float
|
||||
cache_read: float
|
||||
|
||||
|
||||
# USD per 1,000,000 tokens.
|
||||
MODEL_PRICING: dict[str, _Rate] = {
|
||||
# --- Anthropic (authoritative) ---
|
||||
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
|
||||
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
|
||||
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
|
||||
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
|
||||
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
|
||||
# tier; confirm against current Google pricing before trusting USD) ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
}
|
||||
|
||||
|
||||
def get_rate(model: str) -> Optional[_Rate]:
|
||||
"""Return the rate card for ``model``, or None if we have no pricing.
|
||||
|
||||
Falls back to a prefix match on the model family (e.g. a dated
|
||||
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
|
||||
so a minor model-id change doesn't silently drop cost tracking.
|
||||
"""
|
||||
if model in MODEL_PRICING:
|
||||
return MODEL_PRICING[model]
|
||||
for known, rate in MODEL_PRICING.items():
|
||||
if model.startswith(known):
|
||||
return rate
|
||||
return None
|
||||
|
||||
|
||||
def estimate_cost_usd(model: str, usage: Optional[TokenUsage]) -> Optional[float]:
|
||||
"""Estimate the USD cost of one model call from its token usage.
|
||||
|
||||
Returns None when usage is unavailable or the model has no known pricing,
|
||||
so callers can distinguish "free/zero" from "unknown".
|
||||
"""
|
||||
if not usage:
|
||||
return None
|
||||
rate = get_rate(model)
|
||||
if rate is None:
|
||||
return None
|
||||
input_tokens = usage.get("input_tokens") or 0
|
||||
output_tokens = usage.get("output_tokens") or 0
|
||||
cache_read = usage.get("cache_read_tokens") or 0
|
||||
return (
|
||||
input_tokens * rate["input"]
|
||||
+ output_tokens * rate["output"]
|
||||
+ cache_read * rate["cache_read"]
|
||||
) / 1_000_000.0
|
||||
@@ -1,145 +0,0 @@
|
||||
"""Prompt construction for AI auto-correction suggestions.
|
||||
|
||||
Kept in sync with the offline eval harness
|
||||
(lyrics-alignment-eval-dataset/auto-correct-eval/harness.py) — changes here
|
||||
should be re-scored against the 30-job ground-truth dataset.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"suggestions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"op": {
|
||||
"type": "string",
|
||||
"enum": ["replace", "delete", "insert_after"],
|
||||
},
|
||||
"start_idx": {"type": "integer"},
|
||||
"end_idx": {"type": "integer"},
|
||||
"new_text": {"type": "string"},
|
||||
"reason": {"type": "string"},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
],
|
||||
},
|
||||
"confidence": {"type": "number"},
|
||||
},
|
||||
"required": [
|
||||
"op",
|
||||
"start_idx",
|
||||
"end_idx",
|
||||
"new_text",
|
||||
"reason",
|
||||
"category",
|
||||
"confidence",
|
||||
],
|
||||
},
|
||||
}
|
||||
},
|
||||
"required": ["suggestions"],
|
||||
}
|
||||
|
||||
_BASE_SYSTEM_PROMPT = """\
|
||||
You are an expert lyrics transcription reviewer for a karaoke video company. \
|
||||
You are given an automatic speech transcription of a song's vocals (already \
|
||||
segmented into lines, each word tagged with a numeric index) plus lyrics for \
|
||||
the same song from internet sources. Internet sources are usually (not always) \
|
||||
closer to the true lyrics, but lack the transcription's timing and line layout.
|
||||
|
||||
Propose word-level corrections to the TRANSCRIPTION so its words match what is \
|
||||
actually sung. A human reviewer who has listened to the song will accept or \
|
||||
reject each suggestion individually, so precision matters far more than \
|
||||
recall: only suggest a change when you are confident a careful human reviewer \
|
||||
would make it. If reference sources disagree and you have no other evidence, \
|
||||
make no suggestion.
|
||||
|
||||
Guidelines:
|
||||
- Transcription errors are usually sound-alike mishearings: the wrong words \
|
||||
sound similar to the true lyric (e.g. "glory" vs "chlorine", "ladder" vs \
|
||||
"matter"). Prefer corrections that are phonetically plausible.
|
||||
- The same mishearing often repeats in every chorus; correct every occurrence.
|
||||
- Keep the transcription's line structure. NEVER suggest timing changes.
|
||||
- Match the casing and punctuation style of the surrounding transcription.
|
||||
- Do not censor or bowdlerise explicit lyrics.
|
||||
- Do not rewrite lines wholesale unless the transcription is clearly garbled \
|
||||
and a reference line is unambiguously what is sung at that point.
|
||||
- new_text may contain multiple words, or differ in word count from the span \
|
||||
it replaces.
|
||||
"""
|
||||
|
||||
_ADLIB_ALLOWED = """\
|
||||
- Parenthesised backing vocals / adlibs that the transcription contains but \
|
||||
references omit may be real (references often drop them). Only suggest \
|
||||
deleting them when they look like transcription hallucinations or the \
|
||||
references make clear they are not sung lead lines; use category \
|
||||
"adlib_removal" and lower confidence.
|
||||
"""
|
||||
|
||||
_ADLIB_FORBIDDEN = """\
|
||||
- NEVER suggest deleting backing vocals or adlibs solely because the \
|
||||
references omit them; references often drop adlibs that are really sung.
|
||||
"""
|
||||
|
||||
_INSERTIONS_FORBIDDEN = """\
|
||||
- NEVER use the "insert_after" operation; only suggest "replace" and \
|
||||
"delete" operations.
|
||||
"""
|
||||
|
||||
_OUTPUT_SPEC = """\
|
||||
Output JSON only, matching this shape exactly:
|
||||
{"suggestions": [{"op": "replace"|"delete"|"insert_after",
|
||||
"start_idx": <int>, "end_idx": <int>,
|
||||
"new_text": "<replacement, empty for delete>",
|
||||
"reason": "<short justification>",
|
||||
"category": "mishearing"|"grammar"|"adlib_removal"|"repeated_chorus_fix"|"formatting"|"other",
|
||||
"confidence": <0.0-1.0>}]}
|
||||
start_idx and end_idx are inclusive word indices. For "insert_after", \
|
||||
start_idx == end_idx == the index of the word the new text should follow. \
|
||||
If nothing needs changing, return {"suggestions": []}.
|
||||
"""
|
||||
|
||||
|
||||
def build_system_prompt(settings: AutoCorrectSettings) -> str:
|
||||
parts = [_BASE_SYSTEM_PROMPT]
|
||||
parts.append(_ADLIB_ALLOWED if settings.suggest_adlib_removal else _ADLIB_FORBIDDEN)
|
||||
if not settings.allow_insertions:
|
||||
parts.append(_INSERTIONS_FORBIDDEN)
|
||||
parts.append(_OUTPUT_SPEC)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def build_user_prompt(
|
||||
*,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: str | None,
|
||||
title: str | None,
|
||||
) -> str:
|
||||
"""Render segments (with global word indices) + reference sources."""
|
||||
lines = [f"ARTIST: {artist or 'unknown'}", f"TITLE: {title or 'unknown'}", "", "TRANSCRIPTION:"]
|
||||
idx = 0
|
||||
for li, seg in enumerate(segments):
|
||||
toks = []
|
||||
for w in seg.get("words") or []:
|
||||
toks.append(f"{idx}:{w.get('text', '')}")
|
||||
idx += 1
|
||||
lines.append(f"[L{li:03d}] " + " ".join(toks))
|
||||
for source, ref in (reference_lyrics or {}).items():
|
||||
lines.append("")
|
||||
lines.append(f"REFERENCE LYRICS ({source}):")
|
||||
for seg in ref.get("segments") or []:
|
||||
lines.append(seg.get("text", ""))
|
||||
return "\n".join(lines)
|
||||
@@ -1,717 +0,0 @@
|
||||
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
|
||||
from backend.services.auto_correct.prompts import (
|
||||
RESPONSE_SCHEMA,
|
||||
build_system_prompt,
|
||||
build_user_prompt,
|
||||
)
|
||||
from backend.services.auto_correct.settings import AutoCorrectSettings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_OPS = {"replace", "delete", "insert_after"}
|
||||
VALID_CATEGORIES = {
|
||||
"mishearing",
|
||||
"grammar",
|
||||
"adlib_removal",
|
||||
"repeated_chorus_fix",
|
||||
"formatting",
|
||||
"other",
|
||||
}
|
||||
|
||||
|
||||
class AutoCorrectServiceError(Exception):
|
||||
def __init__(
|
||||
self, message: str, *, status_code: int = 400, retryable: bool = False
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
# True for transient provider conditions (rate limits, overload) the
|
||||
# caller may safely retry; drives backoff in _call_model.
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
# Retry knobs for a single model call. Vertex 429 RESOURCE_EXHAUSTED is a
|
||||
# recurring, transient condition; a short app-level backoff lets quota recover
|
||||
# where the SDK's fast internal retry cannot. Kept small so a request never
|
||||
# stalls the review UI for long. Parsed defensively: a malformed env override
|
||||
# clamps to a safe value with a warning rather than crashing the backend at
|
||||
# import or breaking the retry loop.
|
||||
def _env_number(name: str, default: float, *, minimum: float, is_int: bool) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
val: float = int(raw) if is_int else float(raw)
|
||||
except ValueError:
|
||||
logger.warning("invalid %s=%r; using default %s", name, raw, default)
|
||||
return default
|
||||
import math as _math
|
||||
|
||||
if not _math.isfinite(val) or val < minimum:
|
||||
logger.warning(
|
||||
"%s=%s out of range (min %s); clamping to %s", name, val, minimum, minimum
|
||||
)
|
||||
return minimum
|
||||
return val
|
||||
|
||||
|
||||
_MODEL_CALL_MAX_ATTEMPTS = int(
|
||||
_env_number("AUTO_CORRECT_MODEL_MAX_ATTEMPTS", 3, minimum=1, is_int=True)
|
||||
)
|
||||
_MODEL_CALL_BACKOFF_SECONDS = float(
|
||||
_env_number("AUTO_CORRECT_MODEL_BACKOFF_SECONDS", 2.0, minimum=0.0, is_int=False)
|
||||
)
|
||||
|
||||
|
||||
def _is_transient_model_error(exc: BaseException) -> bool:
|
||||
"""True when a provider exception is a retryable rate-limit/overload.
|
||||
|
||||
Matches both structured status codes (google-genai ClientError/ServerError
|
||||
expose ``code``; Anthropic errors expose ``status_code``) and, as a
|
||||
fallback, the textual markers Vertex/Anthropic use — so detection survives
|
||||
SDK exception-class churn.
|
||||
"""
|
||||
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
|
||||
if isinstance(code, int) and code in {429, 500, 502, 503, 529}:
|
||||
return True
|
||||
text = str(exc).upper()
|
||||
markers = ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "OVERLOADED", "429", "503", "529")
|
||||
return any(m in text for m in markers)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Suggestion:
|
||||
id: str
|
||||
op: str # replace | delete | insert_after
|
||||
word_ids: list[str] # targeted words (replace/delete); [anchor] for insert_after
|
||||
segment_ids: list[str] # segments containing the targeted words
|
||||
original_text: str # current text of the targeted span ("" for insert_after)
|
||||
new_text: str # replacement text ("" for delete)
|
||||
reason: str
|
||||
category: str
|
||||
confidence: float
|
||||
# Multi-model compare metadata. In single-model mode models has one
|
||||
# entry and consensus == total_models == 1.
|
||||
models: list[str] = field(default_factory=list)
|
||||
consensus: int = 1
|
||||
total_models: int = 1
|
||||
# Set when other suggestions target overlapping words with a different
|
||||
# outcome — the UI lets the reviewer pick at most one per group.
|
||||
conflict_group: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoCorrectResult:
|
||||
suggestions: list[Suggestion]
|
||||
model: str # comma-joined when compare mode queried several models
|
||||
elapsed_seconds: float
|
||||
settings_applied: AutoCorrectSettings
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
# True when served from the per-job GCS cache (no LLM call was made).
|
||||
cached: bool = False
|
||||
|
||||
|
||||
class AutoCorrectService:
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
|
||||
def suggest(
|
||||
self,
|
||||
*,
|
||||
job_id: str,
|
||||
segments: list[dict],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> AutoCorrectResult:
|
||||
if not segments:
|
||||
raise AutoCorrectServiceError("segments is empty")
|
||||
if not reference_lyrics:
|
||||
raise AutoCorrectServiceError(
|
||||
"no reference lyrics available — auto-correction needs at least "
|
||||
"one internet/reference source to compare against",
|
||||
status_code=422,
|
||||
)
|
||||
|
||||
# Flat word list mirrors the prompt's global indices.
|
||||
flat: list[tuple[str, str, str]] = [] # (word_id, word_text, segment_id)
|
||||
for seg in segments:
|
||||
if not seg.get("id"):
|
||||
raise AutoCorrectServiceError("all segments must have ids")
|
||||
for w in seg.get("words") or []:
|
||||
if not w.get("id"):
|
||||
raise AutoCorrectServiceError("all words must have ids")
|
||||
flat.append((w["id"], w.get("text", ""), seg["id"]))
|
||||
|
||||
system_prompt = build_system_prompt(settings)
|
||||
user_prompt = build_user_prompt(
|
||||
segments=segments,
|
||||
reference_lyrics=reference_lyrics,
|
||||
artist=artist,
|
||||
title=title,
|
||||
)
|
||||
|
||||
models = self._models_for(settings)
|
||||
|
||||
# Re-running on byte-identical input (lyrics, references, settings,
|
||||
# models) returns the previous result instead of paying for another
|
||||
# LLM call. Word ids are part of the key, so cached suggestions
|
||||
# always reference words that still exist.
|
||||
cache_path = self._cache_path(
|
||||
job_id, models, settings, flat, reference_lyrics, artist, title
|
||||
)
|
||||
cached = self._cache_get(cache_path)
|
||||
if cached is not None:
|
||||
logger.info(
|
||||
"auto-correct cache hit job=%s suggestions=%d", job_id,
|
||||
len(cached.suggestions),
|
||||
)
|
||||
return cached
|
||||
|
||||
t0 = time.time()
|
||||
per_model: dict[str, list[Suggestion]] = {}
|
||||
# Token usage per successful model call (None when the provider's
|
||||
# usage object couldn't be read). Drives the cost log below.
|
||||
per_model_usage: dict[str, Optional[TokenUsage]] = {}
|
||||
warnings: list[str] = []
|
||||
if len(models) == 1:
|
||||
raw, usage = self._call_model(
|
||||
models[0], system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
per_model[models[0]] = suggestions
|
||||
per_model_usage[models[0]] = usage
|
||||
warnings.extend(vw)
|
||||
else:
|
||||
import concurrent.futures as cf
|
||||
|
||||
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
|
||||
futures = {
|
||||
ex.submit(
|
||||
self._call_model, m, system_prompt, user_prompt, job_id=job_id
|
||||
): m
|
||||
for m in models
|
||||
}
|
||||
for fut, m in futures.items():
|
||||
try:
|
||||
raw, usage = fut.result()
|
||||
suggestions, vw = self._validate(raw, flat, settings)
|
||||
except AutoCorrectServiceError as exc:
|
||||
# One model failing (call OR malformed output) must not
|
||||
# abort compare mode; the rest still return results.
|
||||
warnings.append(f"model {m} failed: {exc}")
|
||||
continue
|
||||
per_model[m] = suggestions
|
||||
per_model_usage[m] = usage
|
||||
warnings.extend(f"[{m}] {w}" for w in vw)
|
||||
if not per_model:
|
||||
raise AutoCorrectServiceError(
|
||||
"all AI models failed", status_code=502
|
||||
)
|
||||
|
||||
merged = self._merge(per_model, flat)
|
||||
elapsed = time.time() - t0
|
||||
model_label = ", ".join(per_model.keys())
|
||||
logger.info(
|
||||
"auto-correct job=%s models=%s words=%d suggestions=%d dropped_warnings=%d elapsed=%.1fs",
|
||||
job_id, model_label, len(flat), len(merged), len(warnings), elapsed,
|
||||
)
|
||||
self._log_usage(job_id, per_model_usage)
|
||||
result = AutoCorrectResult(
|
||||
suggestions=merged,
|
||||
model=model_label,
|
||||
elapsed_seconds=round(elapsed, 1),
|
||||
settings_applied=settings,
|
||||
warnings=warnings,
|
||||
)
|
||||
self._cache_put(cache_path, result)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _log_usage(
|
||||
job_id: str, per_model_usage: dict[str, Optional[TokenUsage]]
|
||||
) -> None:
|
||||
"""Emit greppable per-model and total cost lines for one suggest() call.
|
||||
|
||||
Token counts are ground truth; the USD figures are derived from
|
||||
``pricing.MODEL_PRICING`` and use ESTIMATED Gemini rates (see that
|
||||
module). Query in Cloud Logging via ``auto-correct usage`` /
|
||||
``auto-correct cost``. Observability only — never raises.
|
||||
"""
|
||||
total_cost = 0.0
|
||||
any_cost = False
|
||||
for model, usage in per_model_usage.items():
|
||||
cost = estimate_cost_usd(model, usage)
|
||||
if cost is not None:
|
||||
total_cost += cost
|
||||
any_cost = True
|
||||
if usage is None:
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s tokens=unavailable",
|
||||
job_id, model,
|
||||
)
|
||||
continue
|
||||
thinking = usage.get("thinking_tokens")
|
||||
logger.info(
|
||||
"auto-correct usage job=%s model=%s input_tokens=%d "
|
||||
"output_tokens=%d thinking_tokens=%s cache_read_tokens=%d "
|
||||
"est_cost_usd=%s",
|
||||
job_id,
|
||||
model,
|
||||
usage.get("input_tokens", 0),
|
||||
usage.get("output_tokens", 0),
|
||||
"na" if thinking is None else thinking,
|
||||
usage.get("cache_read_tokens", 0),
|
||||
"unknown" if cost is None else f"{cost:.4f}",
|
||||
)
|
||||
logger.info(
|
||||
"auto-correct cost job=%s models=%s total_est_cost_usd=%s",
|
||||
job_id,
|
||||
", ".join(per_model_usage.keys()),
|
||||
f"{total_cost:.4f}" if any_cost else "unknown",
|
||||
)
|
||||
|
||||
# ---- suggestion cache (GCS, best-effort) ----
|
||||
|
||||
def _get_storage(self):
|
||||
if not hasattr(self, "_storage"):
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._storage = StorageService()
|
||||
return self._storage
|
||||
|
||||
@staticmethod
|
||||
def _cache_path(
|
||||
job_id: str,
|
||||
models: list[str],
|
||||
settings: AutoCorrectSettings,
|
||||
flat: list[tuple[str, str, str]],
|
||||
reference_lyrics: dict[str, dict],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> str:
|
||||
payload = {
|
||||
"v": 1,
|
||||
"models": models,
|
||||
"settings": settings.to_dict(),
|
||||
"words": [[word_id, text] for word_id, text, _seg in flat],
|
||||
"references": {
|
||||
source: [seg.get("text", "") for seg in (ref.get("segments") or [])]
|
||||
for source, ref in sorted((reference_lyrics or {}).items())
|
||||
},
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
|
||||
).hexdigest()[:24]
|
||||
return f"jobs/{job_id}/lyrics/auto_correct_cache/{digest}.json"
|
||||
|
||||
def _cache_get(self, path: str) -> Optional[AutoCorrectResult]:
|
||||
"""Best-effort: any storage/shape problem is a cache miss, never an error."""
|
||||
try:
|
||||
storage = self._get_storage()
|
||||
if not storage.bucket.blob(path).exists():
|
||||
return None
|
||||
data = storage.download_json(path)
|
||||
return AutoCorrectResult(
|
||||
suggestions=[Suggestion(**s) for s in data["suggestions"]],
|
||||
model=data["model"],
|
||||
elapsed_seconds=0.0,
|
||||
settings_applied=AutoCorrectSettings(**data["settings_applied"]),
|
||||
warnings=list(data.get("warnings") or []),
|
||||
cached=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache read failed for %s", path, exc_info=True)
|
||||
return None
|
||||
|
||||
def _cache_put(self, path: str, result: AutoCorrectResult) -> None:
|
||||
"""Best-effort: a failed cache write never fails the request."""
|
||||
try:
|
||||
self._get_storage().upload_json(
|
||||
path,
|
||||
{
|
||||
"suggestions": [asdict(s) for s in result.suggestions],
|
||||
"model": result.model,
|
||||
"settings_applied": result.settings_applied.to_dict(),
|
||||
"warnings": result.warnings,
|
||||
"elapsed_seconds": result.elapsed_seconds,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("auto-correct cache write failed for %s", path, exc_info=True)
|
||||
|
||||
def _models_for(self, settings: AutoCorrectSettings) -> list[str]:
|
||||
if settings.compare_models:
|
||||
configured = [
|
||||
m.strip()
|
||||
for m in self.settings.auto_correct_compare_models.replace(",", ";").split(";")
|
||||
if m.strip()
|
||||
]
|
||||
# De-dupe while preserving order.
|
||||
seen: set[str] = set()
|
||||
models = [m for m in configured if not (m in seen or seen.add(m))]
|
||||
if len(models) >= 2:
|
||||
return models
|
||||
logger.warning(
|
||||
"compare_models requested but AUTO_CORRECT_COMPARE_MODELS has "
|
||||
"%d usable entries; falling back to single model", len(models),
|
||||
)
|
||||
return [self.settings.auto_correct_model]
|
||||
|
||||
@staticmethod
|
||||
def _merge(
|
||||
per_model: dict[str, list[Suggestion]],
|
||||
flat: list[tuple[str, str, str]],
|
||||
) -> list[Suggestion]:
|
||||
"""Deduplicate identical suggestions across models, tag consensus,
|
||||
assign conflict groups to overlapping non-identical suggestions, and
|
||||
sort by document position."""
|
||||
total = len(per_model)
|
||||
merged: dict[tuple, Suggestion] = {}
|
||||
for model, suggestions in per_model.items():
|
||||
for s in suggestions:
|
||||
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
|
||||
existing = merged.get(key)
|
||||
if existing is None:
|
||||
s.models = [model]
|
||||
s.consensus = 1
|
||||
s.total_models = total
|
||||
merged[key] = s
|
||||
else:
|
||||
existing.models.append(model)
|
||||
existing.consensus += 1
|
||||
existing.confidence = max(existing.confidence, s.confidence)
|
||||
|
||||
result = list(merged.values())
|
||||
|
||||
# Conflict groups: suggestions sharing any target word but not merged
|
||||
# above disagree about the same span — reviewer picks at most one.
|
||||
# (insert_after anchors are excluded: inserting after a word does not
|
||||
# conflict with editing that word.)
|
||||
by_word: dict[str, list[int]] = {}
|
||||
for i, s in enumerate(result):
|
||||
if s.op == "insert_after":
|
||||
continue
|
||||
for wid in s.word_ids:
|
||||
by_word.setdefault(wid, []).append(i)
|
||||
parent = list(range(len(result)))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
for overlapping in by_word.values():
|
||||
for other in overlapping[1:]:
|
||||
parent[find(other)] = find(overlapping[0])
|
||||
roots: dict[int, list[int]] = {}
|
||||
for i in range(len(result)):
|
||||
roots.setdefault(find(i), []).append(i)
|
||||
for members in roots.values():
|
||||
if len(members) < 2:
|
||||
continue
|
||||
group = str(uuid.uuid4())
|
||||
for i in members:
|
||||
result[i].conflict_group = group
|
||||
|
||||
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
|
||||
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
|
||||
return result
|
||||
|
||||
# ---- internals ----
|
||||
|
||||
def _call_model(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable.
|
||||
|
||||
Transient provider errors (rate limits / overload, flagged
|
||||
``retryable``) are retried with exponential backoff. Permanent errors
|
||||
(misconfig, malformed output) fail fast.
|
||||
"""
|
||||
for attempt in range(1, _MODEL_CALL_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
if model.startswith("claude"):
|
||||
return self._call_anthropic(
|
||||
model, system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
return self._call_gemini(
|
||||
model, system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
if not exc.retryable or attempt == _MODEL_CALL_MAX_ATTEMPTS:
|
||||
raise
|
||||
backoff = _MODEL_CALL_BACKOFF_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
"auto-correct model call transient failure job=%s model=%s "
|
||||
"attempt=%d/%d; retrying in %.1fs (%s)",
|
||||
job_id, model, attempt, _MODEL_CALL_MAX_ATTEMPTS, backoff, exc,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
# Unreachable: the loop either returns or raises on the final attempt.
|
||||
raise AssertionError("retry loop exited without returning or raising")
|
||||
|
||||
@staticmethod
|
||||
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from an Anthropic response.
|
||||
|
||||
``output_tokens`` already includes adaptive thinking tokens (billed as
|
||||
output); they are not separable here, so thinking_tokens is None.
|
||||
Returns None on any shape problem — usage must never break the call.
|
||||
"""
|
||||
try:
|
||||
u = response.usage
|
||||
return TokenUsage(
|
||||
input_tokens=int(getattr(u, "input_tokens", 0) or 0),
|
||||
output_tokens=int(getattr(u, "output_tokens", 0) or 0),
|
||||
cache_read_tokens=int(getattr(u, "cache_read_input_tokens", 0) or 0),
|
||||
thinking_tokens=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Anthropic usage", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _gemini_usage(response: Any) -> Optional[TokenUsage]:
|
||||
"""Best-effort usage from a Gemini (Vertex) response.
|
||||
|
||||
Gemini reports thinking separately (``thoughts_token_count``); it is
|
||||
billed at the output rate, so it's folded into output_tokens and also
|
||||
reported separately for visibility. Returns None on any shape problem.
|
||||
"""
|
||||
try:
|
||||
u = response.usage_metadata
|
||||
prompt = int(getattr(u, "prompt_token_count", 0) or 0)
|
||||
candidates = int(getattr(u, "candidates_token_count", 0) or 0)
|
||||
thoughts = int(getattr(u, "thoughts_token_count", 0) or 0)
|
||||
cached = int(getattr(u, "cached_content_token_count", 0) or 0)
|
||||
return TokenUsage(
|
||||
input_tokens=prompt,
|
||||
output_tokens=candidates + thoughts,
|
||||
cache_read_tokens=cached,
|
||||
thinking_tokens=thoughts,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("auto-correct: could not read Gemini usage", exc_info=True)
|
||||
return None
|
||||
|
||||
def _call_anthropic(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
import anthropic
|
||||
|
||||
if not os.environ.get("ANTHROPIC_API_KEY"):
|
||||
# No silent fallback to another provider — surface the
|
||||
# misconfiguration so it gets fixed, not masked.
|
||||
logger.error(
|
||||
"auto-correct model %s requires ANTHROPIC_API_KEY which is not set "
|
||||
"(job=%s)", model, job_id,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is not configured", status_code=502
|
||||
)
|
||||
|
||||
# Structured outputs require additionalProperties: false on objects;
|
||||
# the Vertex variant of the schema omits it, so inject here. Deep-copy
|
||||
# because the google-genai SDK mutates schema dicts in place (it adds
|
||||
# 'property_ordering', which the Anthropic API rejects).
|
||||
import copy
|
||||
|
||||
base = copy.deepcopy(RESPONSE_SCHEMA)
|
||||
for obj in (base, base["properties"]["suggestions"]["items"]):
|
||||
obj.pop("property_ordering", None)
|
||||
obj.pop("propertyOrdering", None)
|
||||
obj["additionalProperties"] = False
|
||||
strict_schema = base
|
||||
client = anthropic.Anthropic(timeout=120.0)
|
||||
try:
|
||||
response = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=16000,
|
||||
system=system_prompt,
|
||||
messages=[{"role": "user", "content": user_prompt}],
|
||||
thinking={"type": "adaptive"},
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
)
|
||||
except Exception as exc:
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._anthropic_usage(response)
|
||||
try:
|
||||
text = next(b.text for b in response.content if b.type == "text")
|
||||
return json.loads(text), usage
|
||||
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _call_gemini(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
# Milliseconds; bounds the call so a hung model never strands the UI.
|
||||
http_options=types.HttpOptions(timeout=120_000),
|
||||
)
|
||||
# Deep-copy: the google-genai SDK mutates the schema dict in place,
|
||||
# which would poison the shared module-level constant for other
|
||||
# providers running in the same process.
|
||||
import copy
|
||||
|
||||
try:
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
) from exc
|
||||
usage = self._gemini_usage(response)
|
||||
try:
|
||||
return json.loads(response.text), usage
|
||||
except (json.JSONDecodeError, TypeError) as exc:
|
||||
logger.exception(
|
||||
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI returned non-JSON output", status_code=502
|
||||
) from exc
|
||||
|
||||
def _validate(
|
||||
self,
|
||||
raw: Any,
|
||||
flat: list[tuple[str, str, str]],
|
||||
settings: AutoCorrectSettings,
|
||||
) -> tuple[list[Suggestion], list[str]]:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("suggestions"), list):
|
||||
raise AutoCorrectServiceError(
|
||||
"AI response missing 'suggestions' list", status_code=502
|
||||
)
|
||||
n = len(flat)
|
||||
out: list[Suggestion] = []
|
||||
warnings: list[str] = []
|
||||
for i, s in enumerate(raw["suggestions"]):
|
||||
problem = self._check(s, n, settings)
|
||||
if problem:
|
||||
warnings.append(f"dropped suggestion {i}: {problem}")
|
||||
continue
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
if s["op"] == "insert_after":
|
||||
word_ids = [flat[start][0]]
|
||||
segment_ids = [flat[start][2]]
|
||||
original_text = ""
|
||||
else:
|
||||
span = flat[start : end + 1]
|
||||
word_ids = [w[0] for w in span]
|
||||
segment_ids = sorted({w[2] for w in span})
|
||||
original_text = " ".join(w[1] for w in span)
|
||||
out.append(
|
||||
Suggestion(
|
||||
id=str(uuid.uuid4()),
|
||||
op=s["op"],
|
||||
word_ids=word_ids,
|
||||
segment_ids=segment_ids,
|
||||
original_text=original_text,
|
||||
new_text="" if s["op"] == "delete" else str(s["new_text"]).strip(),
|
||||
reason=str(s.get("reason", "")),
|
||||
category=s["category"] if s.get("category") in VALID_CATEGORIES else "other",
|
||||
confidence=max(0.0, min(1.0, float(s["confidence"]))),
|
||||
)
|
||||
)
|
||||
return out, warnings
|
||||
|
||||
@staticmethod
|
||||
def _check(s: Any, n_words: int, settings: AutoCorrectSettings) -> Optional[str]:
|
||||
if not isinstance(s, dict):
|
||||
return "not an object"
|
||||
op = s.get("op")
|
||||
if op not in VALID_OPS:
|
||||
return f"invalid op {op!r}"
|
||||
try:
|
||||
start, end = int(s["start_idx"]), int(s["end_idx"])
|
||||
confidence = float(s["confidence"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return "missing/invalid indices or confidence"
|
||||
if not (0 <= start <= end < n_words):
|
||||
return f"indices out of range ({start}..{end} of {n_words})"
|
||||
if op == "insert_after" and not settings.allow_insertions:
|
||||
return "insertions disabled by settings"
|
||||
if op == "insert_after" and start != end:
|
||||
return "insert_after requires start_idx == end_idx"
|
||||
new_text = str(s.get("new_text", "")).strip()
|
||||
if op in ("replace", "insert_after") and not new_text:
|
||||
return f"{op} with empty new_text"
|
||||
if op == "delete" and new_text:
|
||||
return "delete with non-empty new_text"
|
||||
if confidence < settings.min_confidence:
|
||||
return f"confidence {confidence:.2f} below threshold"
|
||||
if (
|
||||
s.get("category") == "adlib_removal"
|
||||
and not settings.suggest_adlib_removal
|
||||
):
|
||||
return "adlib removal disabled by settings"
|
||||
return None
|
||||
|
||||
|
||||
_service_instance: Optional[AutoCorrectService] = None
|
||||
|
||||
|
||||
def get_auto_correct_service() -> AutoCorrectService:
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = AutoCorrectService()
|
||||
return _service_instance
|
||||
@@ -1,47 +0,0 @@
|
||||
"""User-facing knobs for AI auto-correction suggestions."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoCorrectSettings:
|
||||
"""Reviewer-tunable behaviour for a suggestion run.
|
||||
|
||||
suggest_adlib_removal: allow suggestions that delete transcribed
|
||||
backing-vocal / adlib phrases absent from the references.
|
||||
allow_insertions: allow suggestions that insert words the
|
||||
transcription missed entirely.
|
||||
min_confidence: drop suggestions below this confidence server-side
|
||||
(the UI can filter further client-side).
|
||||
compare_models: query every configured compare model in parallel,
|
||||
deduplicate identical suggestions and report per-suggestion
|
||||
model consensus (slower, costs one call per model).
|
||||
"""
|
||||
|
||||
suggest_adlib_removal: bool = True
|
||||
allow_insertions: bool = True
|
||||
min_confidence: float = 0.0
|
||||
compare_models: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def settings_from_dict(data: dict) -> AutoCorrectSettings:
|
||||
known = {f for f in AutoCorrectSettings.__dataclass_fields__}
|
||||
unknown = set(data) - known
|
||||
if unknown:
|
||||
raise ValueError(f"unknown settings: {sorted(unknown)}")
|
||||
merged = {**AutoCorrectSettings().to_dict(), **data}
|
||||
if not isinstance(merged["suggest_adlib_removal"], bool):
|
||||
raise ValueError("suggest_adlib_removal must be a boolean")
|
||||
if not isinstance(merged["allow_insertions"], bool):
|
||||
raise ValueError("allow_insertions must be a boolean")
|
||||
if not isinstance(merged["compare_models"], bool):
|
||||
raise ValueError("compare_models must be a boolean")
|
||||
mc = merged["min_confidence"]
|
||||
if isinstance(mc, bool) or not isinstance(mc, (int, float)) or not 0.0 <= float(mc) <= 1.0:
|
||||
raise ValueError("min_confidence must be a number between 0 and 1")
|
||||
merged["min_confidence"] = float(mc)
|
||||
return AutoCorrectSettings(**merged)
|
||||
@@ -22,30 +22,6 @@ from backend.config import get_settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _destroy_old_secret_versions(client, secret_path: str, keep: int = 5) -> None:
|
||||
"""Destroy ENABLED secret versions beyond the newest `keep`.
|
||||
|
||||
OAuth credential secrets are rewritten on every refresh, which would
|
||||
otherwise accumulate hundreds of versions and cost ~$0.06/version/month
|
||||
in replica storage. Only the newest version is read (`versions/latest`),
|
||||
so older versions are dead weight.
|
||||
"""
|
||||
try:
|
||||
versions = list(client.list_secret_versions(request={"parent": secret_path}))
|
||||
enabled = [
|
||||
v for v in versions
|
||||
if v.state == v.State.ENABLED # type: ignore[attr-defined]
|
||||
]
|
||||
enabled.sort(key=lambda v: v.create_time, reverse=True)
|
||||
for v in enabled[keep:]:
|
||||
try:
|
||||
client.destroy_secret_version(request={"name": v.name})
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to destroy {v.name}: {e}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prune old secret versions for {secret_path}: {e}")
|
||||
|
||||
|
||||
class CredentialStatus(str, Enum):
|
||||
"""Status of OAuth credentials."""
|
||||
VALID = "valid"
|
||||
@@ -353,9 +329,7 @@ class CredentialManager:
|
||||
parent=secret_path,
|
||||
payload={"data": json.dumps(updated_data).encode("utf-8")}
|
||||
)
|
||||
|
||||
_destroy_old_secret_versions(client, secret_path, keep=5)
|
||||
|
||||
|
||||
logger.info(f"Updated {secret_name} with refreshed token")
|
||||
return True
|
||||
|
||||
@@ -447,21 +421,19 @@ class CredentialManager:
|
||||
"""Update stored Dropbox credentials."""
|
||||
try:
|
||||
from google.cloud import secretmanager
|
||||
|
||||
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
project_id = self.settings.google_cloud_project
|
||||
secret_path = f"projects/{project_id}/secrets/{self.DROPBOX_SECRET}"
|
||||
|
||||
|
||||
client.add_secret_version(
|
||||
parent=secret_path,
|
||||
payload={"data": json.dumps(creds).encode("utf-8")}
|
||||
)
|
||||
|
||||
_destroy_old_secret_versions(client, secret_path, keep=5)
|
||||
|
||||
|
||||
logger.info("Updated Dropbox credentials with refreshed token")
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update Dropbox credentials: {e}")
|
||||
return False
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
"""Custom lyrics generation package.
|
||||
|
||||
Stateless helpers that take transcribed lyrics + client custom-lyrics input
|
||||
and return syllable-aware customised lyrics via Gemini 3.1 Pro.
|
||||
"""
|
||||
@@ -1,129 +0,0 @@
|
||||
"""System and user prompt builders for custom-lyrics generation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings, params_for
|
||||
from backend.services.custom_lyrics.validator import LineValidation
|
||||
|
||||
|
||||
_BASE_SYSTEM = """You are a professional karaoke lyricist. Your task is to produce custom karaoke lyrics for a song, applying customisations the client has requested while making the result singable.
|
||||
|
||||
RULES:
|
||||
1. Each output line corresponds positionally to the same input line (line 1 -> line 1, etc.). Do not reorder.
|
||||
2. Preserve each line's role (verse/chorus/repeat). If the original repeats a chorus three times, the customised version should also repeat its corresponding chorus three times.
|
||||
3. Apply the client's customisations as faithfully as possible. If the client gave explicit "replace X with Y" instructions, follow them. If they gave a free-form theme or names without explicit mapping, use your best judgement to weave them in where they fit naturally.
|
||||
4. Where the client gave no clear customisation for a line, keep the original lyric unchanged.
|
||||
5. Output JSON only, matching the schema. No commentary, no surrounding prose."""
|
||||
|
||||
|
||||
_RULE_FIXED_COUNT = "6. The output MUST contain exactly the same number of lines as the input transcribed lyrics."
|
||||
_RULE_FLEXIBLE_COUNT = "6. You may output any number of lines that flows naturally; do not pad to match the input length."
|
||||
_RULE_NO_REWORD = "7. Do NOT paraphrase or reword the client's text. Use it verbatim wherever it appears in the input."
|
||||
_RULE_USE_ALL = "8. All client-provided content MUST appear in the output. Do not skip any of the client's words."
|
||||
|
||||
|
||||
def build_system_prompt(settings: GenerationSettings) -> str:
|
||||
parts = [_BASE_SYSTEM]
|
||||
parts.append(_RULE_FIXED_COUNT if settings.fixed_line_count else _RULE_FLEXIBLE_COUNT)
|
||||
if not settings.allow_reword:
|
||||
parts.append(_RULE_NO_REWORD)
|
||||
if not settings.allow_omit:
|
||||
parts.append(_RULE_USE_ALL)
|
||||
parts.append("")
|
||||
parts.append(f"GUIDANCE: {params_for(settings.strictness).prompt_phrase}")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _format_target_count(counts: list[int]) -> str:
|
||||
"""Render the 4-method target as a single ≈ approximate value (median for stability)."""
|
||||
if not counts:
|
||||
return "≈0 syl"
|
||||
sorted_c = sorted(counts)
|
||||
mid = sorted_c[len(sorted_c) // 2]
|
||||
return f"≈{mid} syl"
|
||||
|
||||
|
||||
def build_initial_user_prompt(
|
||||
*,
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
target_lines: list[str],
|
||||
target_syllables: list[list[int]],
|
||||
time_budgets: list[float],
|
||||
observed_rates: list[float],
|
||||
custom_text_block: str,
|
||||
notes: Optional[str],
|
||||
settings: GenerationSettings,
|
||||
) -> str:
|
||||
n = len(target_lines)
|
||||
annotated = []
|
||||
for i, line in enumerate(target_lines):
|
||||
meta = (
|
||||
f"[{_format_target_count(target_syllables[i])}, "
|
||||
f"{time_budgets[i]:.1f}s @ {observed_rates[i]:.1f} syl/s]"
|
||||
)
|
||||
annotated.append(f"{i + 1}. {meta} {line}")
|
||||
numbered = "\n".join(annotated)
|
||||
notes_block = notes.strip() if notes else "(none)"
|
||||
custom_block = custom_text_block if custom_text_block else "(see attached PDF)"
|
||||
line_count_clause = (
|
||||
f"exactly {n} lines" if settings.fixed_line_count else "an appropriate number of lines"
|
||||
)
|
||||
return (
|
||||
f"SONG: {artist or '(unknown artist)'} - {title or '(unknown title)'}\n\n"
|
||||
f"ORIGINAL TRANSCRIBED LYRICS ({n} lines, with per-line syllable target and time budget):\n"
|
||||
f"{numbered}\n\n"
|
||||
f"CLIENT CUSTOM LYRICS / INSTRUCTIONS:\n{custom_block}\n\n"
|
||||
f"ADDITIONAL NOTES FROM OPERATOR:\n{notes_block}\n\n"
|
||||
f"Produce the customised lyrics in JSON format with {line_count_clause}, "
|
||||
f"honouring the per-line syllable targets and time budgets where possible."
|
||||
)
|
||||
|
||||
|
||||
def build_repair_user_prompt(
|
||||
*,
|
||||
previous_output: list[str],
|
||||
violations: list[LineValidation],
|
||||
target_lines: list[str],
|
||||
target_syllables: list[list[int]],
|
||||
time_budgets: list[float],
|
||||
observed_rates: list[float],
|
||||
settings: GenerationSettings,
|
||||
) -> str:
|
||||
if not violations:
|
||||
return "no violations to fix; return previous output unchanged"
|
||||
|
||||
n = len(previous_output)
|
||||
violating_indices = {v.line_index for v in violations}
|
||||
keep_indices = sorted(i + 1 for i in range(n) if i not in violating_indices)
|
||||
keep_clause = (
|
||||
", ".join(str(i) for i in keep_indices) if keep_indices else "(none)"
|
||||
)
|
||||
|
||||
fix_blocks: list[str] = []
|
||||
for v in violations:
|
||||
i = v.line_index
|
||||
target_meta = _format_target_count(target_syllables[i])
|
||||
delta_sign = "+" if (v.candidate_syllables and v.target_syllables and
|
||||
max(v.candidate_syllables) > max(v.target_syllables)) else "-"
|
||||
actual = max(v.candidate_syllables) if v.candidate_syllables else 0
|
||||
fix_blocks.append(
|
||||
f"- Line {i + 1}: target {target_meta}, time budget {time_budgets[i]:.1f}s, "
|
||||
f"sung at ~{observed_rates[i]:.1f} syl/s.\n"
|
||||
f" Original transcribed line (for inspiration on how the budget can be filled): "
|
||||
f"\"{target_lines[i]}\"\n"
|
||||
f" You wrote: \"{v.candidate_text}\" "
|
||||
f"({actual} syl, {delta_sign}{v.min_delta} {'over' if delta_sign == '+' else 'under'}).\n"
|
||||
f" Trim or paraphrase to fit while preserving the client's intent."
|
||||
)
|
||||
|
||||
return (
|
||||
f"Your previous output had {len(violations)} lines that exceeded the syllable budget too far.\n"
|
||||
f"Please fix ONLY those lines. Keep every other line exactly the same as before.\n\n"
|
||||
f"Lines to fix:\n\n"
|
||||
f"{chr(10).join(fix_blocks)}\n\n"
|
||||
f"Lines to keep unchanged: {keep_clause}\n\n"
|
||||
f"Return JSON with all {n} lines, in original order, with the listed lines fixed "
|
||||
f"and all other lines unchanged."
|
||||
)
|
||||
@@ -1,34 +0,0 @@
|
||||
"""Result types for the custom-lyrics service."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings
|
||||
from backend.services.custom_lyrics.validator import LineValidation
|
||||
|
||||
|
||||
class StopReason(str, Enum):
|
||||
SUCCESS = "success"
|
||||
PLATEAU = "plateau"
|
||||
MAX_ITERS_REACHED = "max_iters_reached"
|
||||
LINE_COUNT_MISMATCH = "line_count_mismatch"
|
||||
VERBATIM_SKIP = "verbatim_skip"
|
||||
# A repair iteration failed (e.g. the model returned an empty/blocked
|
||||
# response); we keep the best result found so far instead of failing.
|
||||
REPAIR_FAILED = "repair_failed"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CustomLyricsResult:
|
||||
lines: list[str]
|
||||
line_metadata: list[LineValidation]
|
||||
iterations_used: int
|
||||
stop_reason: StopReason
|
||||
settings_applied: GenerationSettings
|
||||
model: str
|
||||
duration_ms: int
|
||||
new_segment_timing: Optional[list[tuple[float, float]]] = None
|
||||
line_count_mismatch: bool = False
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
@@ -1,638 +0,0 @@
|
||||
"""Custom lyrics service: validate-and-repair loop orchestrator."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.custom_lyrics.prompts import (
|
||||
build_initial_user_prompt,
|
||||
build_repair_user_prompt,
|
||||
build_system_prompt,
|
||||
)
|
||||
from backend.services.custom_lyrics.result import CustomLyricsResult, StopReason
|
||||
from backend.services.custom_lyrics.settings import (
|
||||
GenerationSettings,
|
||||
StrictnessLevel,
|
||||
params_for,
|
||||
)
|
||||
from backend.services.custom_lyrics.timing import redistribute_timing_proportional
|
||||
from backend.services.custom_lyrics.validator import (
|
||||
LineValidation,
|
||||
Severity,
|
||||
validate,
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.utils.syllable_counter import SyllableCounter
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
SUPPORTED_MIMES = {
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
||||
"application/pdf": "pdf",
|
||||
"text/plain": "txt",
|
||||
"text/markdown": "md",
|
||||
}
|
||||
|
||||
|
||||
def _format_worst_lines(validations: list[LineValidation], n: int = 3) -> list[dict]:
|
||||
"""Top-N failing lines for log breadcrumbs. Cuts text at 80 chars."""
|
||||
failing = sorted(
|
||||
(v for v in validations if not v.passes),
|
||||
key=lambda v: v.min_delta,
|
||||
reverse=True,
|
||||
)[:n]
|
||||
return [
|
||||
{
|
||||
"line_index": v.line_index,
|
||||
"min_delta": v.min_delta,
|
||||
"severity": v.severity.value,
|
||||
"target": v.target_text[:80],
|
||||
"candidate": v.candidate_text[:80],
|
||||
"target_syllables": v.target_syllables,
|
||||
"candidate_syllables": v.candidate_syllables,
|
||||
}
|
||||
for v in failing
|
||||
]
|
||||
|
||||
|
||||
class CustomLyricsServiceError(Exception):
|
||||
def __init__(self, message: str, *, status_code: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class CustomLyricsService:
|
||||
def __init__(self, counter: Optional[SyllableCounter] = None) -> None:
|
||||
self.settings = get_settings()
|
||||
self._counter = counter or SyllableCounter()
|
||||
|
||||
# ---- public ----
|
||||
|
||||
def generate(
|
||||
self,
|
||||
*,
|
||||
job_id: str,
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
custom_text: Optional[str],
|
||||
file_bytes: Optional[bytes],
|
||||
file_mime: Optional[str],
|
||||
file_name: Optional[str],
|
||||
notes: Optional[str],
|
||||
settings: GenerationSettings,
|
||||
) -> CustomLyricsResult:
|
||||
start = time.monotonic()
|
||||
n = len(target_lines)
|
||||
if n == 0:
|
||||
raise CustomLyricsServiceError(
|
||||
"target_lines must not be empty", status_code=400
|
||||
)
|
||||
if n > self.settings.custom_lyrics_max_input_lines:
|
||||
raise CustomLyricsServiceError(
|
||||
f"target_lines exceeds max ({self.settings.custom_lyrics_max_input_lines})",
|
||||
status_code=400,
|
||||
)
|
||||
if not custom_text and not file_bytes:
|
||||
raise CustomLyricsServiceError(
|
||||
"must provide custom_text or file_bytes", status_code=400
|
||||
)
|
||||
|
||||
custom_text_block, pdf_bytes = self._prepare_inputs(
|
||||
custom_text=custom_text,
|
||||
file_bytes=file_bytes,
|
||||
file_mime=file_mime,
|
||||
file_name=file_name,
|
||||
)
|
||||
|
||||
# Pre-compute per-line metadata (used for prompts AND for validator)
|
||||
target_syllables = [self._counter.count_per_line(line) for line in target_lines]
|
||||
time_budgets = [self._segment_duration(seg) for seg in target_segments]
|
||||
observed_rates = [
|
||||
(sum(s) / 4 / dur) if dur > 0 else 0.0
|
||||
for s, dur in zip(target_syllables, time_budgets)
|
||||
]
|
||||
|
||||
params = params_for(settings.strictness)
|
||||
sys_prompt = build_system_prompt(settings)
|
||||
initial_user_prompt = build_initial_user_prompt(
|
||||
artist=artist, title=title,
|
||||
target_lines=target_lines,
|
||||
target_syllables=target_syllables,
|
||||
time_budgets=time_budgets,
|
||||
observed_rates=observed_rates,
|
||||
custom_text_block=custom_text_block,
|
||||
notes=notes,
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_initial_call_start",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"model": self.settings.custom_lyrics_model,
|
||||
"input_lines": n,
|
||||
"settings": settings.to_dict(),
|
||||
"tolerance": params.tolerance,
|
||||
"max_iterations": params.max_iterations,
|
||||
"system_prompt_chars": len(sys_prompt),
|
||||
"user_prompt_chars": len(initial_user_prompt),
|
||||
"pdf_bytes": len(pdf_bytes) if pdf_bytes else 0,
|
||||
"input_lines_total_syllables": sum(sum(s) / 4 for s in target_syllables),
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
candidate_lines = self._call_gemini(
|
||||
system_prompt=sys_prompt,
|
||||
user_prompt=initial_user_prompt,
|
||||
pdf_bytes=pdf_bytes,
|
||||
settings=settings,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"custom_lyrics_initial_call_failed",
|
||||
extra={"job_id": job_id, "stage": "initial"},
|
||||
)
|
||||
raise
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_initial_call_complete",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"candidate_lines": len(candidate_lines),
|
||||
"expected_lines": n,
|
||||
"line_count_match": len(candidate_lines) == n,
|
||||
},
|
||||
)
|
||||
|
||||
# Verbatim path: skip the repair loop entirely
|
||||
if settings.strictness is StrictnessLevel.VERBATIM:
|
||||
metadata = self._validate_for_metadata_only(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
)
|
||||
return self._finalise(
|
||||
lines=candidate_lines,
|
||||
metadata=metadata,
|
||||
iterations_used=0,
|
||||
stop_reason=StopReason.VERBATIM_SKIP,
|
||||
settings=settings,
|
||||
target_lines=target_lines,
|
||||
target_segments=target_segments,
|
||||
start=start,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
# Validate-and-repair loop
|
||||
validations = self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=params.tolerance, fixed=settings.fixed_line_count,
|
||||
)
|
||||
best = (candidate_lines, validations)
|
||||
prev_score = self._score(validations)
|
||||
iteration = 0
|
||||
violation_count = sum(1 for v in validations if not v.passes)
|
||||
stop_reason = StopReason.SUCCESS if violation_count == 0 else StopReason.MAX_ITERS_REACHED
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_initial_validation",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"violations": prev_score[0],
|
||||
"total_min_delta": prev_score[1],
|
||||
"worst_lines": _format_worst_lines(validations),
|
||||
},
|
||||
)
|
||||
|
||||
while iteration < params.max_iterations:
|
||||
violations = [v for v in validations if not v.passes]
|
||||
if not violations:
|
||||
stop_reason = StopReason.SUCCESS
|
||||
break
|
||||
|
||||
repair_prompt = build_repair_user_prompt(
|
||||
previous_output=candidate_lines,
|
||||
violations=violations,
|
||||
target_lines=target_lines,
|
||||
target_syllables=target_syllables,
|
||||
time_budgets=time_budgets,
|
||||
observed_rates=observed_rates,
|
||||
settings=settings,
|
||||
)
|
||||
iter_num = iteration + 1
|
||||
logger.info(
|
||||
"custom_lyrics_repair_call_start",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"iteration": iter_num,
|
||||
"max_iterations": params.max_iterations,
|
||||
"violations_to_repair": len(violations),
|
||||
"repair_prompt_chars": len(repair_prompt),
|
||||
},
|
||||
)
|
||||
try:
|
||||
candidate_lines = self._call_gemini(
|
||||
system_prompt=sys_prompt,
|
||||
user_prompt=repair_prompt,
|
||||
pdf_bytes=pdf_bytes,
|
||||
settings=settings,
|
||||
)
|
||||
except Exception:
|
||||
# Repair is a best-effort *improvement* step. If a repair call
|
||||
# fails (e.g. the model returned an empty/blocked response, or a
|
||||
# transient Vertex error), we must NOT throw away the successful
|
||||
# initial result — that turned a working generation into a 500 and
|
||||
# a browser "NetworkError". Keep the best candidate found so far.
|
||||
# WARNING (not exception/ERROR): this is now a handled, non-fatal
|
||||
# degradation, so it should not trip the production error monitor.
|
||||
logger.warning(
|
||||
"custom_lyrics_repair_call_failed",
|
||||
exc_info=True,
|
||||
extra={"job_id": job_id, "iteration": iter_num, "stage": "repair"},
|
||||
)
|
||||
stop_reason = StopReason.REPAIR_FAILED
|
||||
break
|
||||
validations = self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=params.tolerance, fixed=settings.fixed_line_count,
|
||||
)
|
||||
|
||||
new_score = self._score(validations)
|
||||
improved = new_score < prev_score
|
||||
if improved:
|
||||
best = (candidate_lines, validations)
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_repair_iter_complete",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"iteration": iter_num,
|
||||
"violations_before": prev_score[0],
|
||||
"violations_after": new_score[0],
|
||||
"delta_total_before": prev_score[1],
|
||||
"delta_total_after": new_score[1],
|
||||
"improved": improved,
|
||||
"candidate_line_count": len(candidate_lines),
|
||||
"worst_lines": _format_worst_lines(validations),
|
||||
},
|
||||
)
|
||||
|
||||
# Plateau when score did not strictly improve
|
||||
if new_score >= prev_score:
|
||||
stop_reason = StopReason.PLATEAU
|
||||
iteration += 1
|
||||
break
|
||||
prev_score = new_score
|
||||
iteration += 1
|
||||
if new_score[0] == 0:
|
||||
stop_reason = StopReason.SUCCESS
|
||||
break
|
||||
|
||||
return self._finalise(
|
||||
lines=best[0],
|
||||
metadata=best[1],
|
||||
iterations_used=iteration,
|
||||
stop_reason=stop_reason,
|
||||
settings=settings,
|
||||
target_lines=target_lines,
|
||||
target_segments=target_segments,
|
||||
start=start,
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
# ---- helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _segment_duration(seg: Any) -> float:
|
||||
if isinstance(seg, dict):
|
||||
start = seg.get("start_time")
|
||||
end = seg.get("end_time")
|
||||
else:
|
||||
start = getattr(seg, "start_time", None)
|
||||
end = getattr(seg, "end_time", None)
|
||||
if start is None or end is None:
|
||||
return 0.0
|
||||
try:
|
||||
return max(0.0, float(end) - float(start))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
@staticmethod
|
||||
def _score(validations: list[LineValidation]) -> tuple[int, int]:
|
||||
"""Lower is better. Sort by (violation_count, total_min_delta)."""
|
||||
violations = sum(1 for v in validations if not v.passes)
|
||||
total = sum(v.min_delta for v in validations)
|
||||
return (violations, total)
|
||||
|
||||
def _validate_for_metadata_only(
|
||||
self,
|
||||
candidate_lines: list[str],
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
) -> list[LineValidation]:
|
||||
"""Validator run with infinite tolerance (everything passes); used for Verbatim."""
|
||||
if len(candidate_lines) != len(target_lines):
|
||||
return self._validate_with_length_handling(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
tolerance=10**9, fixed=False,
|
||||
)
|
||||
return validate(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
self._counter, tolerance=10**9,
|
||||
)
|
||||
|
||||
def _validate_with_length_handling(
|
||||
self,
|
||||
candidate_lines: list[str],
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
*,
|
||||
tolerance: int,
|
||||
fixed: bool,
|
||||
) -> list[LineValidation]:
|
||||
"""Handle length mismatches without raising:
|
||||
- If fixed=True and lengths differ, all positions count as violations
|
||||
beyond the overlap.
|
||||
- If fixed=False, only validate the overlap (variable line count is OK).
|
||||
"""
|
||||
if len(candidate_lines) == len(target_lines):
|
||||
return validate(
|
||||
candidate_lines, target_lines, target_segments,
|
||||
self._counter, tolerance=tolerance,
|
||||
)
|
||||
overlap = min(len(candidate_lines), len(target_lines))
|
||||
partial = validate(
|
||||
candidate_lines[:overlap], target_lines[:overlap],
|
||||
target_segments[:overlap], self._counter, tolerance=tolerance,
|
||||
)
|
||||
if fixed and len(candidate_lines) != len(target_lines):
|
||||
extra = abs(len(candidate_lines) - len(target_lines))
|
||||
for i in range(overlap, overlap + extra):
|
||||
idx = i
|
||||
tgt_text = target_lines[idx] if idx < len(target_lines) else ""
|
||||
cand_text = candidate_lines[idx] if idx < len(candidate_lines) else ""
|
||||
partial.append(LineValidation(
|
||||
line_index=idx,
|
||||
target_text=tgt_text,
|
||||
candidate_text=cand_text,
|
||||
target_syllables=[0, 0, 0, 0],
|
||||
candidate_syllables=[0, 0, 0, 0],
|
||||
min_delta=99,
|
||||
passes=False,
|
||||
severity=Severity.MAJOR,
|
||||
time_budget_seconds=0.0,
|
||||
))
|
||||
return partial
|
||||
|
||||
def _finalise(
|
||||
self,
|
||||
*,
|
||||
lines: list[str],
|
||||
metadata: list[LineValidation],
|
||||
iterations_used: int,
|
||||
stop_reason: StopReason,
|
||||
settings: GenerationSettings,
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
start: float,
|
||||
job_id: str,
|
||||
) -> CustomLyricsResult:
|
||||
n = len(target_lines)
|
||||
m = len(lines)
|
||||
line_count_mismatch = (m != n)
|
||||
|
||||
new_timing: Optional[list[tuple[float, float]]] = None
|
||||
if line_count_mismatch and not settings.fixed_line_count and target_segments:
|
||||
window_start = self._segment_start(target_segments[0])
|
||||
window_end = self._segment_end(target_segments[-1])
|
||||
new_timing = redistribute_timing_proportional(
|
||||
new_lines=lines,
|
||||
total_window=(window_start, window_end),
|
||||
counter=self._counter,
|
||||
)
|
||||
|
||||
warnings: list[str] = []
|
||||
if line_count_mismatch and settings.fixed_line_count:
|
||||
stop_reason = StopReason.LINE_COUNT_MISMATCH
|
||||
warnings.append(
|
||||
f"AI returned {m} lines but {n} were expected. "
|
||||
f"Manually adjust the textarea or click Regenerate."
|
||||
)
|
||||
|
||||
duration_ms = int((time.monotonic() - start) * 1000)
|
||||
result = CustomLyricsResult(
|
||||
lines=lines,
|
||||
line_metadata=metadata,
|
||||
iterations_used=iterations_used,
|
||||
stop_reason=stop_reason,
|
||||
settings_applied=settings,
|
||||
model=self.settings.custom_lyrics_model,
|
||||
duration_ms=duration_ms,
|
||||
new_segment_timing=new_timing,
|
||||
line_count_mismatch=line_count_mismatch,
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"custom_lyrics_generated",
|
||||
extra={
|
||||
"job_id": job_id,
|
||||
"model": result.model,
|
||||
"input_lines": n,
|
||||
"output_lines": m,
|
||||
"iterations_used": iterations_used,
|
||||
"stop_reason": stop_reason.value,
|
||||
"settings": settings.to_dict(),
|
||||
"final_violation_count": sum(1 for v in metadata if not v.passes),
|
||||
"line_count_mismatch": line_count_mismatch,
|
||||
"duration_ms": duration_ms,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _segment_start(seg: Any) -> float:
|
||||
v = seg["start_time"] if isinstance(seg, dict) else seg.start_time
|
||||
return float(v or 0.0)
|
||||
|
||||
@staticmethod
|
||||
def _segment_end(seg: Any) -> float:
|
||||
v = seg["end_time"] if isinstance(seg, dict) else seg.end_time
|
||||
return float(v or 0.0)
|
||||
|
||||
def _prepare_inputs(
|
||||
self,
|
||||
*,
|
||||
custom_text: Optional[str],
|
||||
file_bytes: Optional[bytes],
|
||||
file_mime: Optional[str],
|
||||
file_name: Optional[str],
|
||||
) -> tuple[str, Optional[bytes]]:
|
||||
text_chunks: list[str] = []
|
||||
if custom_text and custom_text.strip():
|
||||
text_chunks.append(custom_text.strip())
|
||||
|
||||
pdf_bytes: Optional[bytes] = None
|
||||
if file_bytes is not None:
|
||||
self._validate_file(file_bytes=file_bytes, file_mime=file_mime, file_name=file_name)
|
||||
kind = SUPPORTED_MIMES[file_mime]
|
||||
if kind == "pdf":
|
||||
pdf_bytes = file_bytes
|
||||
elif kind == "docx":
|
||||
text_chunks.append(self._extract_docx_text(file_bytes))
|
||||
elif kind in ("txt", "md"):
|
||||
text_chunks.append(file_bytes.decode("utf-8", errors="replace"))
|
||||
else:
|
||||
raise CustomLyricsServiceError(
|
||||
f"unsupported file kind: {kind}", status_code=400
|
||||
)
|
||||
|
||||
combined = "\n\n".join(chunk for chunk in text_chunks if chunk.strip())
|
||||
return combined, pdf_bytes
|
||||
|
||||
def _validate_file(
|
||||
self,
|
||||
*,
|
||||
file_bytes: bytes,
|
||||
file_mime: Optional[str],
|
||||
file_name: Optional[str],
|
||||
) -> None:
|
||||
max_bytes = self.settings.custom_lyrics_max_file_mb * 1024 * 1024
|
||||
if len(file_bytes) > max_bytes:
|
||||
raise CustomLyricsServiceError(
|
||||
f"file exceeds {self.settings.custom_lyrics_max_file_mb} MB limit",
|
||||
status_code=400,
|
||||
)
|
||||
if file_mime not in SUPPORTED_MIMES:
|
||||
raise CustomLyricsServiceError(
|
||||
f"unsupported file mime: {file_mime!r}; expected one of "
|
||||
f"{sorted(SUPPORTED_MIMES.keys())}",
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _extract_docx_text(file_bytes: bytes) -> str:
|
||||
try:
|
||||
import docx as docx_mod
|
||||
except ImportError as exc:
|
||||
raise CustomLyricsServiceError(
|
||||
"python-docx is not installed", status_code=500
|
||||
) from exc
|
||||
|
||||
try:
|
||||
doc = docx_mod.Document(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise CustomLyricsServiceError(
|
||||
f"could not parse .docx: {exc}", status_code=400
|
||||
) from exc
|
||||
|
||||
paragraphs = [p.text for p in doc.paragraphs if p.text and p.text.strip()]
|
||||
return "\n".join(paragraphs)
|
||||
|
||||
def _call_gemini(
|
||||
self,
|
||||
*,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
pdf_bytes: Optional[bytes],
|
||||
settings: GenerationSettings,
|
||||
) -> list[str]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
contents: list = [user_prompt]
|
||||
if pdf_bytes is not None:
|
||||
contents.append(
|
||||
types.Part.from_bytes(mime_type="application/pdf", data=pdf_bytes)
|
||||
)
|
||||
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.custom_lyrics_model,
|
||||
contents=contents,
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=0.4,
|
||||
response_mime_type="application/json",
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lines": {"type": "array", "items": {"type": "string"}}
|
||||
},
|
||||
"required": ["lines"],
|
||||
},
|
||||
),
|
||||
)
|
||||
# The model can return no text (safety block, MAX_TOKENS with no content,
|
||||
# empty candidate). `response.text` is then None and json.loads(None) would
|
||||
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
|
||||
# reports a confusing "NetworkError". Surface a clean, diagnosable error.
|
||||
text = response.text
|
||||
if text is None:
|
||||
raise CustomLyricsServiceError(
|
||||
f"The AI returned an empty response ({self._describe_empty_response(response)}). "
|
||||
f"Please try again.",
|
||||
status_code=502,
|
||||
)
|
||||
return self._parse_lines(text)
|
||||
|
||||
@staticmethod
|
||||
def _describe_empty_response(response: Any) -> str:
|
||||
"""Best-effort reason for an empty model response, for logs and messages."""
|
||||
parts: list[str] = []
|
||||
try:
|
||||
block_reason = getattr(getattr(response, "prompt_feedback", None), "block_reason", None)
|
||||
if block_reason:
|
||||
parts.append(f"prompt_block={getattr(block_reason, 'name', block_reason)}")
|
||||
except Exception: # pragma: no cover - defensive
|
||||
pass
|
||||
try:
|
||||
candidates = getattr(response, "candidates", None) or []
|
||||
if candidates:
|
||||
finish = getattr(candidates[0], "finish_reason", None)
|
||||
if finish is not None:
|
||||
parts.append(f"finish_reason={getattr(finish, 'name', finish)}")
|
||||
else:
|
||||
parts.append("no_candidates")
|
||||
except Exception: # pragma: no cover - defensive
|
||||
pass
|
||||
return ", ".join(parts) if parts else "unknown"
|
||||
|
||||
@staticmethod
|
||||
def _parse_lines(text: str) -> list[str]:
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise CustomLyricsServiceError(
|
||||
f"AI returned non-JSON output: {exc}", status_code=502
|
||||
) from exc
|
||||
if not isinstance(data, dict) or "lines" not in data:
|
||||
raise CustomLyricsServiceError(
|
||||
"AI response missing 'lines' field", status_code=502
|
||||
)
|
||||
lines = data["lines"]
|
||||
if not isinstance(lines, list) or not all(isinstance(x, str) for x in lines):
|
||||
raise CustomLyricsServiceError(
|
||||
"AI response 'lines' is not a list of strings", status_code=502
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
_service_instance: Optional[CustomLyricsService] = None
|
||||
|
||||
|
||||
def get_custom_lyrics_service() -> CustomLyricsService:
|
||||
global _service_instance
|
||||
if _service_instance is None:
|
||||
_service_instance = CustomLyricsService()
|
||||
return _service_instance
|
||||
@@ -1,81 +0,0 @@
|
||||
"""Operator-facing generation settings and strictness→params mapping."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, asdict
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
class StrictnessLevel(str, Enum):
|
||||
VERBATIM = "verbatim"
|
||||
LOOSE = "loose"
|
||||
BALANCED = "balanced"
|
||||
TIGHT = "tight"
|
||||
STRICT = "strict"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StrictnessParams:
|
||||
tolerance: int
|
||||
max_iterations: int
|
||||
prompt_phrase: str
|
||||
|
||||
|
||||
_STRICTNESS_TABLE: dict[StrictnessLevel, StrictnessParams] = {
|
||||
StrictnessLevel.VERBATIM: StrictnessParams(
|
||||
tolerance=10**6,
|
||||
max_iterations=0,
|
||||
prompt_phrase="Use the client's text as-is. Rhythm matching is not a goal.",
|
||||
),
|
||||
StrictnessLevel.LOOSE: StrictnessParams(
|
||||
tolerance=4,
|
||||
max_iterations=1,
|
||||
prompt_phrase="Aim to roughly match the original syllable count where convenient.",
|
||||
),
|
||||
StrictnessLevel.BALANCED: StrictnessParams(
|
||||
tolerance=2,
|
||||
max_iterations=2,
|
||||
prompt_phrase="Match each line's syllable count within 2 where possible.",
|
||||
),
|
||||
StrictnessLevel.TIGHT: StrictnessParams(
|
||||
tolerance=1,
|
||||
max_iterations=3,
|
||||
prompt_phrase="Closely match each line's syllable count. Aim for ±1 syllable.",
|
||||
),
|
||||
StrictnessLevel.STRICT: StrictnessParams(
|
||||
tolerance=0,
|
||||
max_iterations=4,
|
||||
prompt_phrase="Match each line's syllable count exactly. Rhythm precision is the priority.",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def params_for(level: StrictnessLevel) -> StrictnessParams:
|
||||
return _STRICTNESS_TABLE[level]
|
||||
|
||||
|
||||
@dataclass
|
||||
class GenerationSettings:
|
||||
allow_reword: bool = True
|
||||
allow_omit: bool = True
|
||||
fixed_line_count: bool = True
|
||||
strictness: StrictnessLevel = StrictnessLevel.BALANCED
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
d = asdict(self)
|
||||
d["strictness"] = self.strictness.value
|
||||
return d
|
||||
|
||||
|
||||
def settings_from_dict(data: dict[str, Any]) -> GenerationSettings:
|
||||
"""Construct GenerationSettings from a partial dict (used by the API layer)."""
|
||||
kwargs: dict[str, Any] = {}
|
||||
if "allow_reword" in data:
|
||||
kwargs["allow_reword"] = bool(data["allow_reword"])
|
||||
if "allow_omit" in data:
|
||||
kwargs["allow_omit"] = bool(data["allow_omit"])
|
||||
if "fixed_line_count" in data:
|
||||
kwargs["fixed_line_count"] = bool(data["fixed_line_count"])
|
||||
if "strictness" in data:
|
||||
kwargs["strictness"] = StrictnessLevel(data["strictness"]) # raises ValueError if invalid
|
||||
return GenerationSettings(**kwargs)
|
||||
@@ -1,65 +0,0 @@
|
||||
"""Proportional timing redistribution for variable line count."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class _CounterProtocol(Protocol):
|
||||
def count_per_line(self, line: str) -> list[int]: ...
|
||||
|
||||
|
||||
def _median_count(counts: list[int]) -> int:
|
||||
if not counts:
|
||||
return 0
|
||||
sorted_c = sorted(counts)
|
||||
n = len(sorted_c)
|
||||
if n % 2 == 1:
|
||||
return sorted_c[n // 2]
|
||||
# Even-length: integer-rounded average of the two middle values
|
||||
return (sorted_c[n // 2 - 1] + sorted_c[n // 2]) // 2
|
||||
|
||||
|
||||
def redistribute_timing_proportional(
|
||||
*,
|
||||
new_lines: list[str],
|
||||
total_window: tuple[float, float],
|
||||
counter: _CounterProtocol,
|
||||
) -> list[tuple[float, float]]:
|
||||
"""Distribute `total_window` across `new_lines` proportional to per-line syllable count.
|
||||
|
||||
Falls back to even distribution if all lines have 0 syllables.
|
||||
"""
|
||||
if not new_lines:
|
||||
raise ValueError("new_lines must not be empty")
|
||||
start, end = total_window
|
||||
if end <= start:
|
||||
raise ValueError(f"window invalid: ({start}, {end})")
|
||||
|
||||
syllables = [_median_count(counter.count_per_line(line)) for line in new_lines]
|
||||
total_syl = sum(syllables)
|
||||
|
||||
if total_syl == 0:
|
||||
# Even split fallback
|
||||
per_line = (end - start) / len(new_lines)
|
||||
return [
|
||||
(start + i * per_line, start + (i + 1) * per_line)
|
||||
for i in range(len(new_lines))
|
||||
]
|
||||
|
||||
# Treat zero-syllable lines as weight-1 so they get a non-zero slice.
|
||||
# Otherwise an empty/whitespace line in a mostly-non-empty set yields a
|
||||
# zero-length segment that the timing pipeline downstream may reject.
|
||||
weights = [s if s > 0 else 1 for s in syllables]
|
||||
total_weight = sum(weights)
|
||||
|
||||
out: list[tuple[float, float]] = []
|
||||
cursor = start
|
||||
duration = end - start
|
||||
for i, w in enumerate(weights):
|
||||
if i == len(weights) - 1:
|
||||
out.append((cursor, end)) # last slice goes to exact end (avoid float drift)
|
||||
else:
|
||||
slice_dur = duration * w / total_weight
|
||||
out.append((cursor, cursor + slice_dur))
|
||||
cursor += slice_dur
|
||||
return out
|
||||
@@ -1,93 +0,0 @@
|
||||
"""Pure validator over LLM-generated candidate lines vs. target lines."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
class Severity(str, Enum):
|
||||
OK = "ok"
|
||||
MINOR = "minor"
|
||||
MAJOR = "major"
|
||||
|
||||
|
||||
@dataclass
|
||||
class LineValidation:
|
||||
line_index: int
|
||||
target_text: str
|
||||
candidate_text: str
|
||||
target_syllables: list[int]
|
||||
candidate_syllables: list[int]
|
||||
min_delta: int
|
||||
passes: bool
|
||||
severity: Severity
|
||||
time_budget_seconds: float
|
||||
|
||||
|
||||
class _CounterProtocol(Protocol):
|
||||
def count_per_line(self, line: str) -> list[int]: ...
|
||||
def any_method_within(
|
||||
self, candidate_counts: list[int], target_counts: list[int], tolerance: int
|
||||
) -> bool: ...
|
||||
def min_delta(
|
||||
self, candidate_counts: list[int], target_counts: list[int]
|
||||
) -> int: ...
|
||||
|
||||
|
||||
def _segment_duration(seg: Any) -> float:
|
||||
"""Accepts dict or object with start_time/end_time; returns end - start (>= 0)."""
|
||||
if isinstance(seg, dict):
|
||||
start = seg.get("start_time")
|
||||
end = seg.get("end_time")
|
||||
else:
|
||||
start = getattr(seg, "start_time", None)
|
||||
end = getattr(seg, "end_time", None)
|
||||
if start is None or end is None:
|
||||
return 0.0
|
||||
try:
|
||||
return max(0.0, float(end) - float(start))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def validate(
|
||||
candidate_lines: list[str],
|
||||
target_lines: list[str],
|
||||
target_segments: list[Any],
|
||||
counter: _CounterProtocol,
|
||||
tolerance: int,
|
||||
) -> list[LineValidation]:
|
||||
"""Score each candidate line against its target. Pure; no I/O."""
|
||||
if not (len(candidate_lines) == len(target_lines) == len(target_segments)):
|
||||
raise ValueError(
|
||||
f"length mismatch: candidates={len(candidate_lines)} targets={len(target_lines)} "
|
||||
f"segments={len(target_segments)}"
|
||||
)
|
||||
|
||||
out: list[LineValidation] = []
|
||||
for i, (cand, tgt, seg) in enumerate(zip(candidate_lines, target_lines, target_segments)):
|
||||
target_counts = counter.count_per_line(tgt)
|
||||
candidate_counts = counter.count_per_line(cand)
|
||||
delta = counter.min_delta(candidate_counts, target_counts)
|
||||
passes = counter.any_method_within(candidate_counts, target_counts, tolerance)
|
||||
if passes:
|
||||
severity = Severity.OK
|
||||
elif delta <= tolerance + 2:
|
||||
severity = Severity.MINOR
|
||||
else:
|
||||
severity = Severity.MAJOR
|
||||
out.append(
|
||||
LineValidation(
|
||||
line_index=i,
|
||||
target_text=tgt,
|
||||
candidate_text=cand,
|
||||
target_syllables=target_counts,
|
||||
candidate_syllables=candidate_counts,
|
||||
min_delta=delta,
|
||||
passes=passes,
|
||||
severity=severity,
|
||||
time_budget_seconds=_segment_duration(seg),
|
||||
)
|
||||
)
|
||||
return out
|
||||
@@ -1,18 +0,0 @@
|
||||
"""Backward-compat shim. Real implementation lives in backend.services.custom_lyrics."""
|
||||
from backend.services.custom_lyrics.service import (
|
||||
CustomLyricsService,
|
||||
CustomLyricsServiceError,
|
||||
get_custom_lyrics_service,
|
||||
)
|
||||
from backend.services.custom_lyrics.result import CustomLyricsResult, StopReason
|
||||
from backend.services.custom_lyrics.settings import GenerationSettings, StrictnessLevel
|
||||
|
||||
__all__ = [
|
||||
"CustomLyricsService",
|
||||
"CustomLyricsServiceError",
|
||||
"CustomLyricsResult",
|
||||
"GenerationSettings",
|
||||
"StopReason",
|
||||
"StrictnessLevel",
|
||||
"get_custom_lyrics_service",
|
||||
]
|
||||
@@ -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"))
|
||||
@@ -156,37 +151,6 @@ class DropboxService:
|
||||
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
|
||||
return next_code
|
||||
|
||||
def file_exists(self, remote_path: str) -> bool:
|
||||
"""
|
||||
Check whether a file exists at the given Dropbox path.
|
||||
|
||||
Args:
|
||||
remote_path: Dropbox path (must start with /)
|
||||
|
||||
Returns:
|
||||
True if a file exists at the path, False otherwise.
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
if not remote_path.startswith("/"):
|
||||
remote_path = f"/{remote_path}"
|
||||
|
||||
try:
|
||||
self.client.files_get_metadata(remote_path)
|
||||
return True
|
||||
except ApiError as e:
|
||||
# Only a genuine "not found" means the file is absent. Re-raise other
|
||||
# API errors (auth, network, rate limit) so callers don't mistake a
|
||||
# transient failure for "missing" (e.g. the backfill uploading a dup).
|
||||
err = e.error
|
||||
if (
|
||||
hasattr(err, "is_path")
|
||||
and err.is_path()
|
||||
and err.get_path().is_not_found()
|
||||
):
|
||||
return False
|
||||
raise
|
||||
|
||||
def upload_file(self, local_path: str, remote_path: str) -> None:
|
||||
"""
|
||||
Upload a single file to Dropbox.
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
"""Reconcile a job's credit charge against the actual audio about to be processed.
|
||||
|
||||
Called at the convergence point immediately before the separation+transcription
|
||||
workers are triggered (post-edit if an edit occurred). The probe callable returns
|
||||
the duration in seconds of `job.input_media_gcs_path` (the to-be-processed audio).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Optional
|
||||
import logging
|
||||
|
||||
from backend.services.pricing import duration_to_credits, is_blocked
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReconcileResult:
|
||||
action: str # "proceed" | "pause" | "cancel"
|
||||
pending_additional_credits: int = 0
|
||||
actual_seconds: Optional[float] = None
|
||||
|
||||
|
||||
def reconcile_duration(
|
||||
job_id: str,
|
||||
job_manager,
|
||||
user_service,
|
||||
probe_duration: Callable[[object], Optional[float]],
|
||||
email_service=None,
|
||||
) -> ReconcileResult:
|
||||
job = job_manager.get_job(job_id)
|
||||
actual = probe_duration(job)
|
||||
state = dict(job.state_data or {})
|
||||
credits_charged = int(state.get("credits_charged", 1))
|
||||
|
||||
# Short-circuit for admin / payment-bypassed jobs: measure duration for
|
||||
# observability but do NOT pause, charge, refund, or cancel regardless of
|
||||
# how long the audio turns out to be.
|
||||
if state.get("payment_bypassed"):
|
||||
if actual is not None:
|
||||
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
|
||||
logger.info("Job %s: payment_bypassed=True, skipping reconcile (actual=%s s)", job_id, actual)
|
||||
return ReconcileResult(action="proceed", actual_seconds=actual)
|
||||
|
||||
if actual is None:
|
||||
logger.warning("Job %s: duration probe returned None; proceeding without reconcile", job_id)
|
||||
return ReconcileResult(action="proceed", actual_seconds=None)
|
||||
|
||||
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
|
||||
|
||||
if is_blocked(actual):
|
||||
if credits_charged > 0:
|
||||
user_service.add_credits(job.user_email, amount=credits_charged,
|
||||
reason="duration_over_limit_refund", job_id=job_id)
|
||||
job_manager.update_job(job_id, {"credit_refunded": True}) # suppress cancel_job's built-in 1-credit refund (we already refunded the full charge)
|
||||
job_manager.cancel_job(job_id, reason="Input audio exceeds the 60-minute limit")
|
||||
if email_service:
|
||||
email_service.send_duration_confirm_expired(
|
||||
to_email=job.user_email,
|
||||
artist=getattr(job, "artist", None),
|
||||
title=getattr(job, "title", None),
|
||||
credits_refunded=credits_charged,
|
||||
reason="over_limit",
|
||||
)
|
||||
return ReconcileResult(action="cancel", actual_seconds=actual)
|
||||
|
||||
required = duration_to_credits(actual)
|
||||
delta = required - credits_charged
|
||||
|
||||
if delta == 0:
|
||||
return ReconcileResult(action="proceed", actual_seconds=actual)
|
||||
|
||||
if delta < 0:
|
||||
user_service.add_credits(job.user_email, amount=abs(delta),
|
||||
reason="duration_refund", job_id=job_id)
|
||||
job_manager.update_job(job_id, {"state_data.credits_charged": required})
|
||||
return ReconcileResult(action="proceed", actual_seconds=actual)
|
||||
|
||||
# delta > 0 : owe more credits — pause for explicit re-confirmation.
|
||||
job_manager.update_job(job_id, {
|
||||
"state_data.duration_confirm_reason": "reconcile",
|
||||
"state_data.pending_additional_credits": delta,
|
||||
})
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_DURATION_CONFIRM,
|
||||
progress=16,
|
||||
message=f"This turned out longer than estimated — {delta} more credit(s) needed",
|
||||
)
|
||||
return ReconcileResult(action="pause", pending_additional_credits=delta, actual_seconds=actual)
|
||||
|
||||
|
||||
# --- Pipeline wiring (impure: uses singletons + ffprobe) ---
|
||||
|
||||
def _ffprobe_seconds(job, storage) -> Optional[float]:
|
||||
"""Header-only ffprobe of job.input_media_gcs_path via a signed URL.
|
||||
|
||||
Mirrors the async _get_audio_duration_ffprobe_signed helper in
|
||||
backend/api/routes/jobs.py, but as a sync function suitable for use
|
||||
in run_in_executor.
|
||||
"""
|
||||
gcs_path = getattr(job, "input_media_gcs_path", None)
|
||||
if not gcs_path:
|
||||
return None
|
||||
try:
|
||||
signed_url = storage.generate_signed_url(gcs_path, expiration_minutes=5)
|
||||
result = subprocess.run(
|
||||
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", signed_url],
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return float(json.loads(result.stdout)["format"]["duration"])
|
||||
except Exception as e:
|
||||
logger.warning("Job %s: ffprobe duration failed: %s", getattr(job, "id", "?"), e)
|
||||
return None
|
||||
|
||||
|
||||
async def reconcile_and_maybe_pause(job_id: str) -> bool:
|
||||
"""Resolve real singletons, probe duration, run reconcile_duration, return True if blocked.
|
||||
|
||||
Returns True when the job has been paused (AWAITING_DURATION_CONFIRM) or cancelled,
|
||||
meaning the caller must NOT trigger downstream workers.
|
||||
Returns False when the job should proceed normally.
|
||||
|
||||
Designed for the no-edit convergence point in audio_download_worker.py.
|
||||
"""
|
||||
# Import at function scope to avoid circular imports.
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.user_service import get_user_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
job_manager = JobManager()
|
||||
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
|
||||
|
||||
result = await asyncio.get_running_loop().run_in_executor(
|
||||
None,
|
||||
lambda: reconcile_duration(
|
||||
job_id,
|
||||
job_manager,
|
||||
user_service,
|
||||
lambda job: _ffprobe_seconds(job, storage),
|
||||
email_service,
|
||||
),
|
||||
)
|
||||
return result.action in ("pause", "cancel")
|
||||
@@ -2,24 +2,23 @@
|
||||
Email service for sending transactional emails.
|
||||
|
||||
Supports multiple providers:
|
||||
- Postmark (production)
|
||||
- SendGrid (recommended for production)
|
||||
- Console logging (for development/testing)
|
||||
|
||||
Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
|
||||
Future providers can be added:
|
||||
- Mailgun
|
||||
- AWS SES
|
||||
- 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 +26,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 +54,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):
|
||||
"""
|
||||
@@ -159,23 +120,17 @@ class PreviewEmailProvider(EmailProvider):
|
||||
return self.last_html
|
||||
|
||||
|
||||
class PostmarkEmailProvider(EmailProvider):
|
||||
class SendGridEmailProvider(EmailProvider):
|
||||
"""
|
||||
Postmark email provider for production.
|
||||
SendGrid email provider for production.
|
||||
|
||||
Requires POSTMARK_SERVER_TOKEN environment variable. Sends via the
|
||||
Postmark REST API directly (no SDK dependency).
|
||||
Requires SENDGRID_API_KEY environment variable.
|
||||
"""
|
||||
|
||||
API_URL = "https://api.postmarkapp.com/email"
|
||||
|
||||
def __init__(self, server_token: str, from_email: str, from_name: str = "Nomad Karaoke"):
|
||||
self.server_token = server_token
|
||||
def __init__(self, api_key: str, from_email: str, from_name: str = "Nomad Karaoke"):
|
||||
self.api_key = api_key
|
||||
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,108 +142,67 @@ 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:
|
||||
# Import here to avoid requiring sendgrid in all environments
|
||||
from sendgrid import SendGridAPIClient
|
||||
from sendgrid.helpers.mail import Mail, Email, To, Content, Cc, Bcc
|
||||
|
||||
sg = SendGridAPIClient(api_key=self.api_key)
|
||||
|
||||
# Use override sender if provided (for multi-tenant)
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
"From": f'"{self.from_name}" <{sender_email}>',
|
||||
"To": to_email,
|
||||
"Subject": subject,
|
||||
"HtmlBody": html_content,
|
||||
"MessageStream": "outbound",
|
||||
}
|
||||
if text_content:
|
||||
payload["TextBody"] = text_content
|
||||
|
||||
if cc_emails:
|
||||
payload["Cc"] = ", ".join(_dedupe_emails(cc_emails))
|
||||
if bcc_emails:
|
||||
payload["Bcc"] = ", ".join(_dedupe_emails(bcc_emails))
|
||||
|
||||
response = requests.post(
|
||||
self.API_URL,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-Postmark-Server-Token": self.server_token,
|
||||
},
|
||||
json=payload,
|
||||
timeout=10,
|
||||
message = Mail(
|
||||
from_email=Email(sender_email, self.from_name),
|
||||
to_emails=To(to_email),
|
||||
subject=subject,
|
||||
html_content=Content("text/html", html_content)
|
||||
)
|
||||
|
||||
if 200 <= response.status_code < 300:
|
||||
# Add CC recipients if provided (deduplicated and normalized)
|
||||
if cc_emails:
|
||||
# Normalize emails (lowercase, strip whitespace) and deduplicate
|
||||
seen = set()
|
||||
unique_cc_emails = []
|
||||
for cc_email in cc_emails:
|
||||
normalized = cc_email.strip().lower()
|
||||
if normalized and normalized not in seen:
|
||||
seen.add(normalized)
|
||||
unique_cc_emails.append(cc_email.strip())
|
||||
|
||||
for cc_email in unique_cc_emails:
|
||||
message.add_cc(Cc(cc_email))
|
||||
|
||||
# Add BCC recipients if provided (deduplicated and normalized)
|
||||
if bcc_emails:
|
||||
seen = set()
|
||||
unique_bcc_emails = []
|
||||
for bcc_email in bcc_emails:
|
||||
normalized = bcc_email.strip().lower()
|
||||
if normalized and normalized not in seen:
|
||||
seen.add(normalized)
|
||||
unique_bcc_emails.append(bcc_email.strip())
|
||||
|
||||
for bcc_email in unique_bcc_emails:
|
||||
message.add_bcc(Bcc(bcc_email))
|
||||
|
||||
if text_content:
|
||||
message.add_content(Content("text/plain", text_content))
|
||||
|
||||
response = sg.send(message)
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
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)
|
||||
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via SendGrid")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"SendGrid returned status {response.status_code}")
|
||||
return False
|
||||
|
||||
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
|
||||
try:
|
||||
err = response.json()
|
||||
logger.error(
|
||||
f"Postmark returned status {response.status_code}: "
|
||||
f"ErrorCode={err.get('ErrorCode')} Message={err.get('Message')}"
|
||||
)
|
||||
except ValueError:
|
||||
logger.error(f"Postmark returned status {response.status_code}: {response.text[:200]}")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _dedupe_emails(emails: List[str]) -> List[str]:
|
||||
"""Lowercase-normalize and deduplicate a list of email addresses, preserving order."""
|
||||
seen = set()
|
||||
out = []
|
||||
for em in emails:
|
||||
normalized = em.strip().lower()
|
||||
if normalized and normalized not in seen:
|
||||
seen.add(normalized)
|
||||
out.append(em.strip())
|
||||
return out
|
||||
except Exception:
|
||||
logger.exception("Failed to send email via SendGrid")
|
||||
return False
|
||||
|
||||
|
||||
class EmailService:
|
||||
@@ -313,171 +227,21 @@ class EmailService:
|
||||
self.buy_url = os.getenv("BUY_URL", self.frontend_url)
|
||||
|
||||
def _get_provider(self) -> EmailProvider:
|
||||
"""Get the configured email provider.
|
||||
|
||||
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
|
||||
back to console logging (dev/test only).
|
||||
"""
|
||||
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
|
||||
"""Get the configured email provider."""
|
||||
sendgrid_api_key = os.getenv("SENDGRID_API_KEY")
|
||||
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
from_name = os.getenv("EMAIL_FROM_NAME", "Nomad Karaoke")
|
||||
|
||||
if postmark_token:
|
||||
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)")
|
||||
return ConsoleEmailProvider()
|
||||
if sendgrid_api_key:
|
||||
logger.info("Using SendGrid email provider")
|
||||
return SendGridEmailProvider(sendgrid_api_key, from_email, from_name)
|
||||
else:
|
||||
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)
|
||||
return isinstance(self.provider, SendGridEmailProvider)
|
||||
|
||||
def send_magic_link(
|
||||
self,
|
||||
@@ -572,7 +336,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 +409,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 +551,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 +931,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 +1008,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,149 +1108,7 @@ class EmailService:
|
||||
f"{t(locale, 'emails.reviewReminder.expiryWarning')}"
|
||||
)
|
||||
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_duration_confirm_reminder(
|
||||
self,
|
||||
to_email: str,
|
||||
job_id: Optional[str] = None,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
pending_credits: Optional[int] = None,
|
||||
duration_seconds: Optional[int] = None,
|
||||
confirm_url: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
|
||||
|
||||
Sent when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes without
|
||||
the user confirming the extra cost.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
job_id: Job ID (used to build the confirm URL if not provided)
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
pending_credits: Number of additional credits required
|
||||
duration_seconds: Actual duration of the song in seconds
|
||||
confirm_url: Direct URL to the confirmation page
|
||||
locale: User's locale (future: translated; currently English)
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
if artist and title:
|
||||
subject = f"Your karaoke job needs you to confirm the cost — {artist} - {title}"
|
||||
else:
|
||||
subject = "Your karaoke job needs you to confirm the cost"
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
background-color: #fef3c7;
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.confirm-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.cost-box {
|
||||
background-color: #f0f9ff;
|
||||
border: 1px solid #93c5fd;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = (
|
||||
f" for <strong>{html.escape(artist)} — {html.escape(title)}</strong>"
|
||||
if artist and title
|
||||
else ""
|
||||
)
|
||||
song_name_text = f" for {artist} — {title}" if artist and title else ""
|
||||
|
||||
# Build cost detail line (best-effort — fields may be absent for older jobs)
|
||||
if pending_credits is not None and duration_seconds is not None:
|
||||
duration_mins = duration_seconds // 60
|
||||
duration_secs = duration_seconds % 60
|
||||
duration_str = f"{duration_mins}:{duration_secs:02d}"
|
||||
cost_detail_html = (
|
||||
f"<p>The song{song_name} turned out to be "
|
||||
f"<strong>{duration_str}</strong> long and requires "
|
||||
f"<strong>{pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''}</strong> to process.</p>"
|
||||
)
|
||||
cost_detail_text = (
|
||||
f"The song{song_name_text} turned out to be {duration_str} long and "
|
||||
f"requires {pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''} to process.\n"
|
||||
)
|
||||
elif pending_credits is not None:
|
||||
cost_detail_html = (
|
||||
f"<p>Processing{song_name} requires "
|
||||
f"<strong>{pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''}</strong>.</p>"
|
||||
)
|
||||
cost_detail_text = (
|
||||
f"Processing{song_name_text} requires {pending_credits} additional credit"
|
||||
f"{'s' if pending_credits != 1 else ''}.\n"
|
||||
)
|
||||
else:
|
||||
cost_detail_html = f"<p>Your karaoke job{song_name} requires a few extra credits to continue.</p>"
|
||||
cost_detail_text = f"Your karaoke job{song_name_text} requires a few extra credits to continue.\n"
|
||||
|
||||
# TODO(i18n): translate subject/body once duration-confirm keys are added to
|
||||
# backend/translations/{locale}.json. URL already uses the locale prefix.
|
||||
locale_prefix = get_locale_prefix(locale)
|
||||
url_to_use = confirm_url or (
|
||||
f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review"
|
||||
if job_id
|
||||
else f"{self.frontend_url}{locale_prefix}/app"
|
||||
)
|
||||
|
||||
content = f"""
|
||||
<div class="alert">
|
||||
⏰ Your job is waiting for your confirmation
|
||||
</div>
|
||||
|
||||
{cost_detail_html}
|
||||
|
||||
<p>Please visit your job to review the cost and confirm whether to continue processing.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(url_to_use)}" class="confirm-btn">Confirm cost & continue</a>
|
||||
</p>
|
||||
|
||||
<p>If you have any questions, just reply to this email — we're happy to help.</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = (
|
||||
f"Your karaoke job is waiting for your confirmation.\n\n"
|
||||
f"{cost_detail_text}\n"
|
||||
f"Please visit your job to confirm: {url_to_use}\n\n"
|
||||
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,149 +1201,7 @@ class EmailService:
|
||||
f"{t(locale, 'emails.reviewExpired.helpOffer')}"
|
||||
)
|
||||
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_duration_confirm_expired(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
credits_refunded: int = 0,
|
||||
locale: str = "en",
|
||||
reason: str = "timeout",
|
||||
) -> bool:
|
||||
"""
|
||||
Send duration-confirm cancellation notification email.
|
||||
|
||||
Two cancellation reasons are supported via the ``reason`` parameter:
|
||||
|
||||
- ``"timeout"`` (default): job was auto-cancelled after 48 hours in
|
||||
AWAITING_DURATION_CONFIRM because the user never confirmed the extra cost.
|
||||
- ``"over_limit"`` : job was immediately cancelled because the audio
|
||||
duration exceeds the supported 60-minute ceiling.
|
||||
|
||||
Args:
|
||||
to_email: User's email address
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
credits_refunded: Number of credits that were refunded
|
||||
locale: User locale (reserved for future i18n; currently English)
|
||||
reason: "timeout" or "over_limit" — controls the cancellation message
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
if reason == "over_limit":
|
||||
if artist and title:
|
||||
subject = f"Your karaoke job was cancelled — audio exceeds 60 minutes ({artist} - {title})"
|
||||
else:
|
||||
subject = "Your karaoke job was cancelled — audio exceeds 60 minutes"
|
||||
else:
|
||||
if artist and title:
|
||||
subject = f"Your karaoke job was cancelled — cost not confirmed in time ({artist} - {title})"
|
||||
else:
|
||||
subject = "Your karaoke job was cancelled — cost not confirmed in time"
|
||||
|
||||
extra_styles = """
|
||||
.info-box {
|
||||
background-color: #f0f9ff;
|
||||
border: 1px solid #93c5fd;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.credit-badge {
|
||||
display: inline-block;
|
||||
background-color: #22c55e;
|
||||
color: #ffffff;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.create-btn {
|
||||
display: inline-block;
|
||||
background-color: #ff7acc;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
margin: 16px 0;
|
||||
}
|
||||
"""
|
||||
|
||||
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
|
||||
song_name_text = f" for {artist} - {title}" if artist and title else ""
|
||||
credits_word = "credit" if credits_refunded == 1 else "credits"
|
||||
|
||||
refund_notice_html = (
|
||||
f"<p>We've refunded <span class=\"credit-badge\">{credits_refunded} {credits_word}</span> "
|
||||
f"to your account.</p>"
|
||||
if credits_refunded > 0
|
||||
else "<p>Your account has been updated.</p>"
|
||||
)
|
||||
refund_notice_text = (
|
||||
f"We've refunded {credits_refunded} {credits_word} to your account."
|
||||
if credits_refunded > 0
|
||||
else "Your account has been updated."
|
||||
)
|
||||
|
||||
if reason == "over_limit":
|
||||
cancel_reason_html = (
|
||||
f"Your karaoke job{song_name} was automatically cancelled because the audio "
|
||||
f"exceeds the supported 60-minute limit."
|
||||
)
|
||||
cancel_reason_text = (
|
||||
f"Your karaoke job{song_name_text} was automatically cancelled because the "
|
||||
f"audio exceeds the supported 60-minute limit."
|
||||
)
|
||||
else:
|
||||
cancel_reason_html = (
|
||||
f"Your karaoke job{song_name} was automatically cancelled because the extra cost "
|
||||
f"was not confirmed within 48 hours."
|
||||
)
|
||||
cancel_reason_text = (
|
||||
f"Your karaoke job{song_name_text} was automatically cancelled because the extra "
|
||||
f"cost was not confirmed within 48 hours."
|
||||
)
|
||||
|
||||
# TODO(i18n): translate subject/body once duration-confirm keys are added to
|
||||
# backend/translations/{locale}.json. URL already uses the locale prefix.
|
||||
locale_prefix = get_locale_prefix(locale)
|
||||
app_url = f"{self.frontend_url}{locale_prefix}/app"
|
||||
|
||||
content = f"""
|
||||
<div class="info-box">
|
||||
{cancel_reason_html}
|
||||
</div>
|
||||
|
||||
{refund_notice_html}
|
||||
|
||||
<p>You can start a new job at any time — your credits are ready to use.</p>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(app_url)}" class="create-btn">Create a new job</a>
|
||||
</p>
|
||||
|
||||
<p>If you have any questions, just reply to this email — we're happy to help.</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = (
|
||||
f"{cancel_reason_text}\n\n"
|
||||
f"{refund_notice_text}\n\n"
|
||||
f"You can start a new job at any time: {app_url}\n\n"
|
||||
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 +1251,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 +1344,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,
|
||||
@@ -1936,13 +1416,8 @@ class EmailService:
|
||||
# Use "ET" (Eastern Time) to be correct for both EST and EDT
|
||||
deadline_str = deadline_eastern.strftime("%B %d, %Y at %I:%M %p") + " ET"
|
||||
|
||||
# Link to /app/ with admin login token for one-click access, deep-linked to the
|
||||
# awaiting-audio-selection queue so the made-for-you order is shown immediately
|
||||
# (made-for-you cards render there; the status param pre-selects the filter).
|
||||
app_url = (
|
||||
f"{self.frontend_url.rstrip('/')}/app/"
|
||||
f"?admin_token={admin_login_token}&status=awaiting_audio_selection"
|
||||
)
|
||||
# Link to /app/ with admin login token for one-click access
|
||||
app_url = f"{self.frontend_url.rstrip('/')}/app/?admin_token={admin_login_token}"
|
||||
|
||||
content = f"""
|
||||
<div class="order-info">
|
||||
@@ -1974,7 +1449,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 +1581,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 +1696,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 +1751,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,
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Typed exceptions for encoding worker lifecycle failures.
|
||||
|
||||
These let callers distinguish between transient capacity issues (retry will
|
||||
likely help) and unexpected start failures (something is actually broken).
|
||||
"""
|
||||
|
||||
from typing import FrozenSet
|
||||
|
||||
|
||||
CAPACITY_ERROR_CODES: FrozenSet[str] = frozenset({
|
||||
"ZONE_RESOURCE_POOL_EXHAUSTED",
|
||||
"ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS",
|
||||
"STOCKOUT",
|
||||
"QUOTA_EXCEEDED",
|
||||
})
|
||||
|
||||
|
||||
class EncodingWorkerStartError(Exception):
|
||||
"""Raised when an attempt to start an encoding worker VM fails.
|
||||
|
||||
Carries the GCE error code so callers can react to specific failure modes.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
vm_name: str = "",
|
||||
zone: str = "",
|
||||
code: str = "",
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.vm_name = vm_name
|
||||
self.zone = zone
|
||||
self.code = code
|
||||
|
||||
|
||||
class EncodingWorkerCapacityError(EncodingWorkerStartError):
|
||||
"""A capacity-related GCE failure (e.g. ZONE_RESOURCE_POOL_EXHAUSTED).
|
||||
|
||||
The zone temporarily cannot allocate the requested machine type. Callers
|
||||
should treat this as recoverable — retrying after a wait, or trying an
|
||||
alternate zone, is likely to succeed.
|
||||
"""
|
||||
|
||||
|
||||
# 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:
|
||||
return EncodingWorkerCapacityError(
|
||||
f"VM {vm_name} could not be started in {zone}: {code} — {message}",
|
||||
vm_name=vm_name,
|
||||
zone=zone,
|
||||
code=code,
|
||||
)
|
||||
return EncodingWorkerStartError(
|
||||
f"VM {vm_name} start failed in {zone}: {code or 'unknown error'} — {message or 'no message'}",
|
||||
vm_name=vm_name,
|
||||
zone=zone,
|
||||
code=code,
|
||||
)
|
||||
@@ -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__)
|
||||
|
||||
|
||||
@@ -67,17 +65,6 @@ class EncodingOutput:
|
||||
lossless_mkv_path: Optional[str] = None # MKV with FLAC (for YouTube)
|
||||
lossy_720p_mp4_path: Optional[str] = None # 720p web version
|
||||
|
||||
# Standalone 5-second screen videos generated from the title/end images.
|
||||
# Kept so they land in the Dropbox folder (regression after #647/#650 moved
|
||||
# screen generation to the encoder). Not used downstream.
|
||||
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,16 +381,10 @@ 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"):
|
||||
output_files["with_vocals_mp4"] = path
|
||||
elif filename_lower.endswith("(title).mov"):
|
||||
output_files["title_mov"] = path
|
||||
elif filename_lower.endswith("(end).mov"):
|
||||
output_files["end_mov"] = path
|
||||
self.logger.info(f"Converted output_files list to dict: {output_files}")
|
||||
else:
|
||||
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
|
||||
@@ -415,20 +396,11 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
lossless_mkv_path=output_files.get("mkv_4k"),
|
||||
lossy_720p_mp4_path=output_files.get("mp4_720p"),
|
||||
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}")
|
||||
|
||||
@@ -17,40 +17,15 @@ Usage:
|
||||
|
||||
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
|
||||
|
||||
import aiohttp
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.encoding_errors import (
|
||||
ENCODING_RESTART_FAILURE_CODE,
|
||||
EncodingJobLostError,
|
||||
EncodingJobNotFoundError,
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Per-URL submission throttle. The encoding worker has a ThreadPoolExecutor
|
||||
# of 4 workers (gce_encoding/main.py). Submitting more concurrent jobs than
|
||||
# that to a single VM caused `Connection reset by peer` errors on the 5th+
|
||||
# job during the May 6 fallback storm — 7 jobs simultaneously hammered
|
||||
# fallback-a after the primary failed.
|
||||
#
|
||||
# Limit to 3 concurrent renders per URL per Cloud Run instance, leaving 1
|
||||
# worker thread for status polls / preview / health checks. With multiple
|
||||
# Cloud Run instances this is not a global cap (would require a distributed
|
||||
# lock) but it caps each instance's contribution to the storm — empirically
|
||||
# enough to prevent the failure mode.
|
||||
_DEFAULT_SUBMISSION_CONCURRENCY = int(
|
||||
os.environ.get("ENCODING_SUBMISSION_CONCURRENCY", "3")
|
||||
)
|
||||
|
||||
# Retry configuration for handling transient failures (e.g., worker restarts during deployments).
|
||||
#
|
||||
# During a CI deployment, the encoding worker is restarted via systemctl. The restart
|
||||
@@ -69,106 +44,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.
|
||||
|
||||
Some aiohttp connection errors have empty str(e), which made the original
|
||||
"GCE worker connection failed after 8 attempts: " log line useless during
|
||||
the 2026-04-24 cold-start incident (job 2c577535). Always include the
|
||||
type name so operators can tell what failure class hit them.
|
||||
"""
|
||||
msg = str(e)
|
||||
return f"{type(e).__name__}: {msg}" if msg else type(e).__name__
|
||||
|
||||
|
||||
class EncodingService:
|
||||
"""Service for dispatching encoding jobs to GCE worker."""
|
||||
@@ -183,24 +58,12 @@ class EncodingService:
|
||||
self._url_cached_at = 0
|
||||
self._URL_CACHE_TTL = 30 # seconds
|
||||
|
||||
# Per-URL submission semaphores. Lazily created on first use so we
|
||||
# don't bind to the wrong event loop at import time. Bound at
|
||||
# _DEFAULT_SUBMISSION_CONCURRENCY to keep concurrent renders per
|
||||
# worker VM under the worker's own ThreadPool capacity.
|
||||
self._url_semaphores: Dict[str, asyncio.Semaphore] = {}
|
||||
self._url_semaphores_lock: Optional[asyncio.Lock] = None
|
||||
self._submission_concurrency = _DEFAULT_SUBMISSION_CONCURRENCY
|
||||
|
||||
def set_worker_manager(self, manager):
|
||||
"""Set the worker manager for dynamic URL resolution from Firestore."""
|
||||
self._worker_manager = manager
|
||||
|
||||
def _get_worker_url(self) -> str:
|
||||
"""Get the current worker URL from Firestore (with TTL cache).
|
||||
|
||||
Returns config.active_url, which is normally the primary URL but
|
||||
switches to the capacity-fallback override when a primary-zone
|
||||
outage caused us to start a fallback VM in another zone.
|
||||
"""Get the current primary worker URL from Firestore (with TTL cache).
|
||||
|
||||
Falls back to static URL from config if worker_manager is not set.
|
||||
"""
|
||||
@@ -210,7 +73,7 @@ class EncodingService:
|
||||
|
||||
if self._worker_manager:
|
||||
config = self._worker_manager.get_config()
|
||||
self._cached_url = config.active_url
|
||||
self._cached_url = config.primary_url
|
||||
self._url_cached_at = now
|
||||
return self._cached_url
|
||||
|
||||
@@ -219,135 +82,6 @@ class EncodingService:
|
||||
self._load_credentials()
|
||||
return self._url
|
||||
|
||||
def _invalidate_cached_url(self) -> None:
|
||||
"""Force the next _get_worker_url() to re-read from Firestore.
|
||||
|
||||
Called after the worker manager updates active_override (e.g. on
|
||||
capacity fallback) so the in-flight request loop picks up the new URL.
|
||||
"""
|
||||
self._cached_url = None
|
||||
self._url_cached_at = 0.0
|
||||
|
||||
@asynccontextmanager
|
||||
async def _submission_slot(self, url: str, job_id: str) -> AsyncIterator[None]:
|
||||
"""Bound the number of concurrent renders/encodes per worker URL.
|
||||
|
||||
The encoding worker has 4 thread-pool workers; submitting 7+ at once
|
||||
causes `Connection reset by peer` mid-encode (observed during the
|
||||
May 6 fallback storm). This semaphore caps each Cloud Run instance's
|
||||
concurrent submissions per URL at `_submission_concurrency`,
|
||||
leaving headroom for status polls and previews.
|
||||
|
||||
Captures the URL at entry — if the worker manager swaps active_url
|
||||
mid-operation (capacity fallback) we keep the original slot. The
|
||||
slot count for the new URL will be slightly understated until the
|
||||
next submission, which is acceptable: the fallback path is rare,
|
||||
and the goal is preventing the orchestrator-side thundering herd.
|
||||
"""
|
||||
# Lazily create the per-loop lock so we bind to the right event loop
|
||||
if self._url_semaphores_lock is None:
|
||||
self._url_semaphores_lock = asyncio.Lock()
|
||||
|
||||
async with self._url_semaphores_lock:
|
||||
sem = self._url_semaphores.get(url)
|
||||
if sem is None:
|
||||
sem = asyncio.Semaphore(self._submission_concurrency)
|
||||
self._url_semaphores[url] = sem
|
||||
|
||||
# Brief log only when we actually have to wait — keeps the happy
|
||||
# path quiet but surfaces contention during a fallback storm.
|
||||
if sem.locked():
|
||||
logger.info(
|
||||
f"[job:{job_id}] Waiting for encoding submission slot "
|
||||
f"(url={url}, in_flight>={self._submission_concurrency})"
|
||||
)
|
||||
async with sem:
|
||||
yield
|
||||
|
||||
def _build_worker_candidates(self) -> list:
|
||||
"""Build the ranked 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.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return []
|
||||
try:
|
||||
config = self._worker_manager.get_config()
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"Could not read worker config for candidates: {_format_exception(e)}")
|
||||
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,
|
||||
}]
|
||||
|
||||
# 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.
|
||||
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
|
||||
|
||||
# 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
|
||||
]
|
||||
|
||||
def _load_credentials(self):
|
||||
"""Load encoding worker URL and API key from config/secrets."""
|
||||
if self._initialized:
|
||||
@@ -381,87 +115,27 @@ class EncodingService:
|
||||
"""Check if GCE preview encoding is enabled and configured."""
|
||||
return self.settings.use_gce_preview_encoding and self.is_configured
|
||||
|
||||
async def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
|
||||
def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
|
||||
"""Safety net: try to start the encoding worker VM on first connection failure.
|
||||
|
||||
Two paths:
|
||||
- VM already RUNNING/STAGING (deploy restart): return after the start
|
||||
attempt; the existing 90s retry loop covers the systemctl restart window.
|
||||
- VM was TERMINATED (cold start): block on wait_for_worker_ready until
|
||||
the VM is up and /health returns 200. The next retry attempt will
|
||||
then succeed immediately. If the readiness wait times out, log and
|
||||
return — the retry loop will surface the failure with a clear error.
|
||||
|
||||
If the worker_manager is not set (e.g. dev mode with static URL), this
|
||||
is a no-op.
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: GCE could not allocate capacity (e.g.
|
||||
ZONE_RESOURCE_POOL_EXHAUSTED). Caller should bail out of any
|
||||
retry loop — no point hammering an HTTP endpoint that will
|
||||
never come up — and surface the error to the job.
|
||||
If the worker_manager is available, calls ensure_primary_running() so the VM
|
||||
starts booting during the retry window. If worker_manager is not set (e.g. dev
|
||||
mode with static URL), this is a no-op.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return
|
||||
|
||||
candidates = self._build_worker_candidates()
|
||||
try:
|
||||
if candidates and len(candidates) > 1:
|
||||
# Multi-zone path: try primary, then fallbacks in alt zones.
|
||||
result = self._worker_manager.ensure_any_running(candidates)
|
||||
# If we fell back, the worker manager just persisted the
|
||||
# active_override URL — invalidate our cache so the next
|
||||
# request hits the right VM.
|
||||
if result.get("fell_back"):
|
||||
self._invalidate_cached_url()
|
||||
result = self._worker_manager.ensure_primary_running()
|
||||
if result["started"]:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
|
||||
)
|
||||
else:
|
||||
result = self._worker_manager.ensure_primary_running()
|
||||
except EncodingWorkerStartError:
|
||||
# Every candidate exhausted (or single-zone primary failed) — both
|
||||
# capacity errors and other start failures (e.g. 503
|
||||
# SERVICE_UNAVAILABLE from the GCE backend) are transient and the
|
||||
# render worker should park the job for retry rather than hard-fail
|
||||
# with a misleading "connection timeout" message. EncodingWorker
|
||||
# CapacityError subclasses StartError, so this catches both.
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): "
|
||||
f"{_format_exception(e)}"
|
||||
)
|
||||
return
|
||||
|
||||
if result["started"]:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
|
||||
)
|
||||
try:
|
||||
await self._worker_manager.wait_for_worker_ready(
|
||||
result["vm_name"],
|
||||
f"{result['primary_url']}/health",
|
||||
# Pass the candidate's zone — without this, multi-zone
|
||||
# fallback successfully starts a VM in (e.g.) us-central1-a
|
||||
# but readiness wait looks for it in the manager's default
|
||||
# zone (us-central1-c), gets 404, gives up, and the next
|
||||
# request hits a still-booting VM and times out.
|
||||
zone=result.get("zone"),
|
||||
)
|
||||
logger.info(
|
||||
f"[job:{job_id}] Cold-started VM {result['vm_name']} is now ready"
|
||||
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
|
||||
)
|
||||
except TimeoutError as e:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Cold-start readiness wait timed out: {e}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Cold-start readiness wait failed (non-fatal): "
|
||||
f"{_format_exception(e)}"
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
|
||||
|
||||
async def _request_with_retry(
|
||||
self,
|
||||
@@ -471,8 +145,6 @@ class EncodingService:
|
||||
json_payload: Optional[Dict[str, Any]] = None,
|
||||
timeout: float = 30.0,
|
||||
job_id: str = "unknown",
|
||||
path: Optional[str] = None,
|
||||
allow_failover: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Make an HTTP request with retry logic for transient failures.
|
||||
@@ -482,25 +154,11 @@ class EncodingService:
|
||||
|
||||
Args:
|
||||
method: HTTP method (GET, POST)
|
||||
url: Initial request URL (used for the first attempt)
|
||||
url: Request URL
|
||||
headers: Request headers
|
||||
json_payload: JSON body for POST requests
|
||||
timeout: Request timeout in seconds
|
||||
job_id: Job ID for logging
|
||||
path: Endpoint path (e.g. "/render-video"). When set, retry attempts
|
||||
AFTER the warmup runs re-resolve the URL via _get_worker_url() +
|
||||
path. This is what lets multi-zone fallback take effect mid-loop:
|
||||
the warmup may set a new active_override (e.g. switching to a
|
||||
fallback VM in another zone) and invalidate the URL cache; the
|
||||
next retry then targets the freshly-routed URL instead of the
|
||||
original primary which is dead.
|
||||
allow_failover: When True (default), a connection error fires the
|
||||
fallback-VM warmup and lets retries re-resolve the URL. Set False
|
||||
for requests pinned to a specific worker (in-flight status polls):
|
||||
a pinned poll must never re-route to active_url nor spin up a
|
||||
fallback VM, because a different/fresh VM cannot have the job — it
|
||||
would only return "not found" and orphan a render that is actually
|
||||
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
|
||||
|
||||
Returns:
|
||||
Dict with keys:
|
||||
@@ -515,22 +173,8 @@ class EncodingService:
|
||||
"""
|
||||
last_exception = None
|
||||
backoff = INITIAL_BACKOFF_SECONDS
|
||||
warmup_ran = False
|
||||
|
||||
for attempt in range(MAX_RETRIES + 1):
|
||||
# Re-resolve URL on retries after the warmup has fired, so that any
|
||||
# active_override change made by the warmup actually takes effect.
|
||||
# Without this, all 8 retry attempts hammer the original (dead)
|
||||
# URL even though the warmup successfully routed to a fallback VM.
|
||||
if allow_failover and path and warmup_ran and self._worker_manager is not None:
|
||||
resolved = f"{self._get_worker_url()}{path}"
|
||||
if resolved != url:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Re-resolved encoding URL after warmup: "
|
||||
f"{url} -> {resolved}"
|
||||
)
|
||||
url = resolved
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if method.upper() == "POST":
|
||||
@@ -554,33 +198,18 @@ class EncodingService:
|
||||
}
|
||||
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
|
||||
last_exception = e
|
||||
if allow_failover and attempt == 0:
|
||||
try:
|
||||
await self._warmup_encoding_worker_fallback(job_id)
|
||||
warmup_ran = True
|
||||
except EncodingWorkerStartError as start_err:
|
||||
# No VM could be started — capacity exhaustion or
|
||||
# transient backend errors (e.g. 503). Hammering the
|
||||
# HTTP endpoint 7 more times won't help; surface the
|
||||
# typed error so the render worker can park the job
|
||||
# for auto-retry rather than fail hard.
|
||||
logger.error(
|
||||
f"[job:{job_id}] Encoding worker start failed, "
|
||||
f"aborting retries: {start_err}"
|
||||
)
|
||||
raise start_err from e
|
||||
if attempt == 0:
|
||||
self._warmup_encoding_worker_fallback(job_id)
|
||||
if attempt < MAX_RETRIES:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] GCE worker connection failed "
|
||||
f"(attempt {attempt + 1}/{MAX_RETRIES + 1}): {_format_exception(e)}. "
|
||||
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
|
||||
f"Retrying in {backoff:.1f}s..."
|
||||
)
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 2, MAX_BACKOFF_SECONDS)
|
||||
else:
|
||||
logger.error(
|
||||
f"[job:{job_id}] GCE worker connection failed "
|
||||
f"after {MAX_RETRIES + 1} attempts: {_format_exception(e)}"
|
||||
f"[job:{job_id}] GCE worker connection failed after {MAX_RETRIES + 1} attempts: {e}"
|
||||
)
|
||||
|
||||
raise last_exception
|
||||
@@ -612,8 +241,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = "/encode"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
url = f"{self._get_worker_url()}/encode"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {
|
||||
"job_id": job_id,
|
||||
@@ -631,7 +259,6 @@ class EncodingService:
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -660,23 +287,12 @@ class EncodingService:
|
||||
|
||||
return resp["json"]
|
||||
|
||||
async def get_job_status(
|
||||
self, job_id: str, worker_url: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the status of an encoding job.
|
||||
|
||||
Args:
|
||||
job_id: Job identifier
|
||||
worker_url: When set, pin the request to this worker base URL instead
|
||||
of resolving the current active_url. In-flight polls must stay on
|
||||
the worker that accepted the job: a blue-green deploy can swap the
|
||||
active_url primary pointer mid-render, and an unpinned poll would
|
||||
migrate to the new primary — which never received the job and 404s
|
||||
"not found", orphaning a render that is succeeding on the original
|
||||
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
|
||||
disables failover (allow_failover=False) so it never re-routes nor
|
||||
starts a fallback VM.
|
||||
|
||||
Returns:
|
||||
Job status including: status, progress, error, output_files
|
||||
@@ -686,11 +302,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = f"/status/{job_id}"
|
||||
if worker_url:
|
||||
url = f"{worker_url}{path}"
|
||||
else:
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
url = f"{self._get_worker_url()}/status/{job_id}"
|
||||
headers = {"X-API-Key": self._api_key}
|
||||
|
||||
resp = await self._request_with_retry(
|
||||
@@ -699,16 +311,12 @@ class EncodingService:
|
||||
headers=headers,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
# When pinned, never re-resolve or fail over — the job lives on this
|
||||
# exact worker; do not pass `path` (which drives re-resolution).
|
||||
path=None if worker_url else path,
|
||||
allow_failover=not worker_url,
|
||||
)
|
||||
|
||||
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']}")
|
||||
|
||||
@@ -720,8 +328,6 @@ class EncodingService:
|
||||
poll_interval: float = 10.0,
|
||||
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.
|
||||
@@ -736,11 +342,6 @@ class EncodingService:
|
||||
poll_interval: Seconds between status checks
|
||||
timeout: Maximum time to wait (default 1 hour)
|
||||
progress_callback: Optional callback(progress: int) for progress updates
|
||||
worker_url: Worker base URL the job was submitted to. When set, every
|
||||
poll is pinned to this worker (see get_job_status) so a mid-render
|
||||
blue-green primary swap can't migrate the poll to a worker that
|
||||
never received the job. When None, polls resolve active_url (legacy
|
||||
behaviour, e.g. direct callers/tests).
|
||||
|
||||
Returns:
|
||||
Final job status with output files
|
||||
@@ -754,46 +355,18 @@ 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)
|
||||
status = await self.get_job_status(job_id)
|
||||
# Reset failure counter on successful poll
|
||||
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 +391,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 +405,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)
|
||||
@@ -869,10 +425,7 @@ class EncodingService:
|
||||
"""
|
||||
Submit encoding job and wait for completion.
|
||||
|
||||
This is a convenience method that combines submit + wait. The
|
||||
submission is bounded by a per-URL semaphore so concurrent renders
|
||||
from the same Cloud Run instance can't overwhelm a single worker
|
||||
VM (see `_submission_slot`).
|
||||
This is a convenience method that combines submit + wait.
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
@@ -886,36 +439,23 @@ class EncodingService:
|
||||
"""
|
||||
config = encoding_config or {"formats": ["mp4_4k", "mp4_720p"]}
|
||||
|
||||
# Resolve URL up front so the semaphore is keyed by the actual
|
||||
# target VM (matters when capacity fallback is active — see
|
||||
# _submission_slot for the URL-change semantics).
|
||||
target_url = self._get_worker_url()
|
||||
# Submit the job
|
||||
submit_result = await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
|
||||
|
||||
async with self._submission_slot(target_url, job_id):
|
||||
# Submit the job
|
||||
submit_result = await self.submit_encoding_job(
|
||||
job_id, input_gcs_path, output_gcs_path, config,
|
||||
)
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
|
||||
# If cached, return immediately — encoding already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
|
||||
return {"status": "complete", "output_files": submit_result.get("output_files")}
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# If in_progress, another request is encoding it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
|
||||
|
||||
# Pin polls to the worker the job landed on (see render_video_on_gce).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actually doing CPU work for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
|
||||
async def submit_preview_encoding_job(
|
||||
self,
|
||||
@@ -950,8 +490,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = "/encode-preview"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
url = f"{self._get_worker_url()}/encode-preview"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {
|
||||
"job_id": job_id,
|
||||
@@ -974,7 +513,6 @@ class EncodingService:
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -1039,19 +577,11 @@ class EncodingService:
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
|
||||
|
||||
# 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(
|
||||
@@ -1078,8 +608,7 @@ class EncodingService:
|
||||
if not self.is_configured:
|
||||
raise RuntimeError("Encoding service not configured")
|
||||
|
||||
path = "/render-video"
|
||||
url = f"{self._get_worker_url()}{path}"
|
||||
url = f"{self._get_worker_url()}/render-video"
|
||||
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
|
||||
payload = {"job_id": job_id, **render_config}
|
||||
|
||||
@@ -1092,7 +621,6 @@ class EncodingService:
|
||||
json_payload=payload,
|
||||
timeout=30.0,
|
||||
job_id=job_id,
|
||||
path=path,
|
||||
)
|
||||
|
||||
if resp["status"] == 401:
|
||||
@@ -1134,10 +662,7 @@ class EncodingService:
|
||||
"""
|
||||
Submit render-video job and wait for completion.
|
||||
|
||||
This is a convenience method that combines submit + wait. The
|
||||
submission is bounded by a per-URL semaphore so concurrent renders
|
||||
from the same Cloud Run instance can't overwhelm a single worker
|
||||
VM (see `_submission_slot`).
|
||||
This is a convenience method that combines submit + wait.
|
||||
|
||||
Args:
|
||||
job_id: Unique job identifier
|
||||
@@ -1147,43 +672,27 @@ class EncodingService:
|
||||
Returns:
|
||||
Final job status with output files and metadata
|
||||
"""
|
||||
# Resolve URL up front so the semaphore is keyed by the actual
|
||||
# target VM. If capacity fallback later swaps active_url, the slot
|
||||
# accounting is slightly off for that operation but the new
|
||||
# submissions land on the right counter.
|
||||
target_url = self._get_worker_url()
|
||||
# Submit the job
|
||||
submit_result = await self.submit_render_video_job(job_id, render_config)
|
||||
|
||||
async with self._submission_slot(target_url, job_id):
|
||||
# Submit the job
|
||||
submit_result = await self.submit_render_video_job(job_id, render_config)
|
||||
# If cached, return immediately — rendering already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
|
||||
return {
|
||||
"status": "complete",
|
||||
"output_files": submit_result.get("output_files"),
|
||||
"metadata": submit_result.get("metadata"),
|
||||
}
|
||||
|
||||
# If cached, return immediately — rendering already done
|
||||
submit_status = submit_result.get("status")
|
||||
if submit_status == "cached":
|
||||
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
|
||||
return {
|
||||
"status": "complete",
|
||||
"output_files": submit_result.get("output_files"),
|
||||
"metadata": submit_result.get("metadata"),
|
||||
}
|
||||
# If in_progress, another request is rendering it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
|
||||
|
||||
# If in_progress, another request is rendering it — just wait for that
|
||||
if submit_status == "in_progress":
|
||||
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
|
||||
|
||||
# Pin status polls to the worker the job actually landed on. Resolving
|
||||
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
|
||||
# the URL cache) while being BEFORE any later blue-green deploy swap —
|
||||
# so the poll follows the job, not the floating active_url primary
|
||||
# pointer (incident 2026-06-16, job d3af33ae).
|
||||
pinned_url = self._get_worker_url()
|
||||
|
||||
# Wait for completion (still holding the slot — the worker is
|
||||
# actively rendering for `job_id` until poll returns
|
||||
# complete/failed).
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback, worker_url=pinned_url
|
||||
)
|
||||
# Wait for completion
|
||||
return await self.wait_for_completion(
|
||||
job_id, progress_callback=progress_callback
|
||||
)
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -25,59 +25,16 @@ Usage:
|
||||
result = manager.ensure_primary_running()
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
import aiohttp
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.services.encoding_errors import (
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
classify_gce_error,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# How long to wait for a compute.instances.start operation to settle. The GCE
|
||||
# operation itself is fast (1-2s) — we just need to know whether it succeeded
|
||||
# or returned an immediate error like ZONE_RESOURCE_POOL_EXHAUSTED.
|
||||
START_OPERATION_TIMEOUT_SECONDS = 30.0
|
||||
|
||||
# A GCE instances.start returning 503 SERVICE_UNAVAILABLE (or 500/INTERNAL) is a
|
||||
# transient GCP control-plane error — distinct from a capacity STOCKOUT — and
|
||||
# usually succeeds on a quick retry. Retry the start a few times in-zone with
|
||||
# backoff before letting the caller fail over to another zone.
|
||||
START_TRANSIENT_MAX_RETRIES = 3
|
||||
START_TRANSIENT_BACKOFF_SECONDS = 5.0
|
||||
# Substrings (matched case-insensitively against the GCE error code/message)
|
||||
# that mark a retryable transient control-plane failure.
|
||||
_TRANSIENT_START_MARKERS = (
|
||||
"503",
|
||||
"service unavailable",
|
||||
"internal error",
|
||||
"internalerror",
|
||||
"backenderror",
|
||||
"500",
|
||||
)
|
||||
|
||||
CONFIG_COLLECTION = "config"
|
||||
|
||||
|
||||
def _is_transient_start_error(error: "EncodingWorkerStartError") -> bool:
|
||||
"""True if a VM-start failure looks like a retryable transient GCP error.
|
||||
|
||||
Capacity errors (ZONE_RESOURCE_POOL_EXHAUSTED etc.) are NOT transient in the
|
||||
same zone — retrying in-zone is pointless, the caller should fail over. Those
|
||||
are a distinct subclass and are excluded by the caller.
|
||||
"""
|
||||
haystack = f"{getattr(error, 'code', '') or ''} {error}".lower()
|
||||
return any(marker in haystack for marker in _TRANSIENT_START_MARKERS)
|
||||
CONFIG_DOCUMENT = "encoding-worker"
|
||||
ENCODING_WORKER_PORT = 8080
|
||||
|
||||
@@ -98,19 +55,6 @@ class EncodingWorkerConfig:
|
||||
last_activity_at: Optional[str]
|
||||
deploy_in_progress: bool
|
||||
deploy_in_progress_since: Optional[str]
|
||||
# Optional capacity-fallback override: when ensure_any_running falls back
|
||||
# to a non-primary VM (e.g. due to ZONE_RESOURCE_POOL_EXHAUSTED), these
|
||||
# fields point at the active fallback so requests target the right VM.
|
||||
# Cleared when the primary becomes healthy again.
|
||||
active_override_vm: Optional[str] = None
|
||||
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:
|
||||
@@ -120,49 +64,6 @@ class EncodingWorkerConfig:
|
||||
def secondary_url(self) -> str:
|
||||
return f"http://{self.secondary_ip}:{ENCODING_WORKER_PORT}"
|
||||
|
||||
@property
|
||||
def active_url(self) -> str:
|
||||
"""URL the encoding service should target right now.
|
||||
|
||||
Returns the capacity-fallback override if set, otherwise the primary
|
||||
URL. The override mechanism lets us route around a zone that's
|
||||
temporarily out of c4d-highcpu-32 capacity without rewriting the
|
||||
blue-green primary/secondary tracking.
|
||||
"""
|
||||
if self.active_override_ip:
|
||||
return f"http://{self.active_override_ip}:{ENCODING_WORKER_PORT}"
|
||||
return self.primary_url
|
||||
|
||||
|
||||
@dataclass
|
||||
class EncodingWorkerCandidate:
|
||||
"""A VM that ensure_any_running may try to start.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
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."""
|
||||
@@ -203,11 +104,6 @@ class EncodingWorkerManager:
|
||||
last_activity_at=data.get("last_activity_at"),
|
||||
deploy_in_progress=data.get("deploy_in_progress", False),
|
||||
deploy_in_progress_since=data.get("deploy_in_progress_since"),
|
||||
active_override_vm=data.get("active_override_vm"),
|
||||
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:
|
||||
@@ -265,81 +161,55 @@ class EncodingWorkerManager:
|
||||
# VM lifecycle operations (Task 2)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_vm_status(self, vm_name: str, zone: Optional[str] = None) -> str:
|
||||
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING).
|
||||
|
||||
Pass `zone` for fallback VMs that live in alternate zones.
|
||||
"""
|
||||
def get_vm_status(self, vm_name: str) -> str:
|
||||
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING)."""
|
||||
instance = self._compute.get(
|
||||
project=self._project_id,
|
||||
zone=zone or self._zone,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
return instance.status
|
||||
|
||||
def start_vm(self, vm_name: str, zone: Optional[str] = None) -> None:
|
||||
def start_vm(self, vm_name: str) -> None:
|
||||
"""Start a VM if it is not already running or starting.
|
||||
|
||||
Waits for the start operation to complete and raises a typed error if
|
||||
GCE rejects the request (e.g. ZONE_RESOURCE_POOL_EXHAUSTED). Caller
|
||||
should still poll get_vm_status / wait_for_worker_ready before
|
||||
dispatching work — operation success only means GCE accepted the start,
|
||||
not that the VM has finished booting.
|
||||
|
||||
Args:
|
||||
vm_name: VM to start.
|
||||
zone: Override the manager's default zone. Required when starting
|
||||
capacity-fallback VMs in alternate zones.
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: zone is out of capacity for the
|
||||
machine type. Retry from a different zone or after a wait.
|
||||
EncodingWorkerStartError: any other start failure.
|
||||
Fire-and-forget: returns immediately. Caller should poll get_vm_status
|
||||
if they need to wait for the VM to be fully RUNNING.
|
||||
"""
|
||||
target_zone = zone or self._zone
|
||||
status = self.get_vm_status(vm_name, zone=target_zone)
|
||||
status = self.get_vm_status(vm_name)
|
||||
if status in ("RUNNING", "STAGING"):
|
||||
logger.info("VM %s is already %s, skipping start", vm_name, status)
|
||||
return
|
||||
logger.info("Starting VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
|
||||
operation = self._compute.start(
|
||||
logger.info("Starting VM %s (current status: %s)", vm_name, status)
|
||||
self._compute.start(
|
||||
project=self._project_id,
|
||||
zone=target_zone,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
self._wait_for_compute_operation(operation, vm_name=vm_name, zone=target_zone)
|
||||
|
||||
def stop_vm(self, vm_name: str, zone: Optional[str] = None) -> None:
|
||||
def stop_vm(self, vm_name: str) -> None:
|
||||
"""Stop a VM if it is not already stopped or stopping."""
|
||||
target_zone = zone or self._zone
|
||||
status = self.get_vm_status(vm_name, zone=target_zone)
|
||||
status = self.get_vm_status(vm_name)
|
||||
if status in ("TERMINATED", "STOPPING"):
|
||||
logger.info("VM %s is already %s, skipping stop", vm_name, status)
|
||||
return
|
||||
logger.info("Stopping VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
|
||||
logger.info("Stopping VM %s (current status: %s)", vm_name, status)
|
||||
self._compute.stop(
|
||||
project=self._project_id,
|
||||
zone=target_zone,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
|
||||
def ensure_primary_running(self) -> dict:
|
||||
"""Ensure the primary encoding worker VM is running.
|
||||
|
||||
Reads config, starts primary VM if stopped, and updates activity
|
||||
timestamp. Waits for the start operation to settle so that capacity
|
||||
errors surface immediately instead of being hidden behind a 120s
|
||||
readiness wait.
|
||||
Reads config, starts primary VM if stopped, and updates activity timestamp.
|
||||
|
||||
Returns:
|
||||
dict with keys:
|
||||
- started (bool): True if VM was started, False if already running
|
||||
- vm_name (str): Name of the primary VM
|
||||
- primary_url (str): URL of the primary encoding worker
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: zone is exhausted for the machine type.
|
||||
EncodingWorkerStartError: any other start failure.
|
||||
"""
|
||||
config = self.get_config()
|
||||
vm_name = config.primary_vm
|
||||
@@ -349,12 +219,11 @@ class EncodingWorkerManager:
|
||||
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info("Primary VM %s is %s, starting it", vm_name, status)
|
||||
operation = self._compute.start(
|
||||
self._compute.start(
|
||||
project=self._project_id,
|
||||
zone=self._zone,
|
||||
instance=vm_name,
|
||||
)
|
||||
self._wait_for_compute_operation(operation, vm_name=vm_name, zone=self._zone)
|
||||
started = True
|
||||
else:
|
||||
logger.info("Primary VM %s is already %s", vm_name, status)
|
||||
@@ -364,359 +233,7 @@ class EncodingWorkerManager:
|
||||
return {
|
||||
"started": started,
|
||||
"vm_name": vm_name,
|
||||
"zone": self._zone,
|
||||
"primary_url": config.primary_url,
|
||||
}
|
||||
|
||||
def ensure_any_running(self, candidates: list) -> dict:
|
||||
"""Start any candidate VM; retry the whole set on an all-zones transient blip.
|
||||
|
||||
Delegates to :meth:`_ensure_any_running_once` (one attempt per candidate).
|
||||
If EVERY candidate fails with a *transient* error — e.g. a brief 503
|
||||
SERVICE_UNAVAILABLE control-plane blip that hits all zones at once — and
|
||||
none hit real capacity exhaustion, retry the whole candidate set a few
|
||||
times with backoff before giving up. Capacity exhaustion is NOT spun on
|
||||
here (retrying in seconds won't conjure hardware); the render worker parks
|
||||
the job and the 24h auto-retry cron handles a sustained shortage.
|
||||
"""
|
||||
if not candidates:
|
||||
raise ValueError("ensure_any_running requires at least one candidate")
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
return self._ensure_any_running_once(candidates)
|
||||
except EncodingWorkerCapacityError:
|
||||
raise
|
||||
except EncodingWorkerStartError as e:
|
||||
if attempt <= START_TRANSIENT_MAX_RETRIES and _is_transient_start_error(e):
|
||||
backoff = START_TRANSIENT_BACKOFF_SECONDS * attempt
|
||||
logger.warning(
|
||||
"All encoding candidates failed transiently (pass %d/%d): %s — "
|
||||
"retrying whole set in %.0fs",
|
||||
attempt, START_TRANSIENT_MAX_RETRIES + 1, e, backoff,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
continue
|
||||
raise
|
||||
|
||||
def _ensure_any_running_once(self, candidates: list) -> dict:
|
||||
"""Start the first candidate VM that GCE accepts; raise if all are exhausted.
|
||||
|
||||
Iterates `candidates` in order, attempting to start each one. A
|
||||
capacity error (ZONE_RESOURCE_POOL_EXHAUSTED, etc.) on candidate N
|
||||
triggers a try of candidate N+1. Other start failures abort the
|
||||
whole call.
|
||||
|
||||
On fallback success (a non-first candidate started), persists the
|
||||
fallback's URL as `active_override_*` in Firestore so subsequent
|
||||
encoding requests target the right VM. The first candidate (the
|
||||
primary) succeeding clears any stale override.
|
||||
|
||||
Args:
|
||||
candidates: List of EncodingWorkerCandidate, ordered by preference.
|
||||
Typically [primary, secondary, *fallbacks_in_alt_zones].
|
||||
|
||||
Returns:
|
||||
dict {started, vm_name, zone, primary_url, fell_back}
|
||||
fell_back is True iff the chosen VM is not the first candidate.
|
||||
|
||||
Raises:
|
||||
EncodingWorkerCapacityError: all candidates rejected with
|
||||
capacity errors.
|
||||
EncodingWorkerStartError: any non-capacity start failure.
|
||||
ValueError: empty candidate list.
|
||||
"""
|
||||
if not candidates:
|
||||
raise ValueError("ensure_any_running requires at least one candidate")
|
||||
|
||||
# Track the last error so we can raise something representative if
|
||||
# every candidate fails. Capacity errors are preferred (they're more
|
||||
# actionable for the user-facing message) but generic start errors
|
||||
# also trigger fallback — observed failure modes include 503
|
||||
# SERVICE_UNAVAILABLE from the GCE backend, which behaves like
|
||||
# capacity exhaustion (transient, retry on a different VM/zone helps).
|
||||
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)
|
||||
started = False
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info(
|
||||
"Trying candidate %d/%d: VM %s in %s (status %s)",
|
||||
index + 1, len(candidates), candidate.vm_name,
|
||||
candidate.zone, status,
|
||||
)
|
||||
self.start_vm(candidate.vm_name, zone=candidate.zone)
|
||||
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
|
||||
if fell_back:
|
||||
self._set_active_override(candidate)
|
||||
else:
|
||||
self._clear_active_override()
|
||||
|
||||
return {
|
||||
"started": started,
|
||||
"vm_name": candidate.vm_name,
|
||||
"zone": candidate.zone,
|
||||
"primary_url": candidate.url,
|
||||
"fell_back": fell_back,
|
||||
}
|
||||
except EncodingWorkerCapacityError as cap_err:
|
||||
logger.warning(
|
||||
"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
|
||||
except EncodingWorkerStartError as start_err:
|
||||
# Other start failures (e.g. 503 SERVICE_UNAVAILABLE from the
|
||||
# GCE backend) are also transient — try the next candidate
|
||||
# rather than giving up. If all candidates fail with these
|
||||
# generic errors and no candidate hit a capacity error, we
|
||||
# surface the last generic error.
|
||||
logger.warning(
|
||||
"Candidate %s in %s start failed (%s), trying next candidate",
|
||||
candidate.vm_name, candidate.zone, start_err.code or "no-code",
|
||||
)
|
||||
last_start_error = start_err
|
||||
if not _is_transient_start_error(start_err):
|
||||
last_non_transient_error = start_err
|
||||
continue
|
||||
|
||||
# Every candidate failed. Raise the most actionable / least-retryable
|
||||
# representative error so the caller (ensure_any_running) retries the
|
||||
# whole set ONLY when every failure was a transient blip:
|
||||
# capacity > non-transient start error > transient start error
|
||||
# A capacity error means a real shortage (park + 24h retry handles it);
|
||||
# a non-transient error (e.g. PERMISSION_DENIED) means something is
|
||||
# actually broken — neither should trigger the fast whole-set retry.
|
||||
if last_capacity_error is not None:
|
||||
raise last_capacity_error
|
||||
if last_non_transient_error is not None:
|
||||
raise last_non_transient_error
|
||||
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()
|
||||
self._doc_ref().update({
|
||||
"active_override_vm": candidate.vm_name,
|
||||
"active_override_ip": candidate.ip,
|
||||
"active_override_zone": candidate.zone,
|
||||
"active_override_set_at": now,
|
||||
})
|
||||
logger.info(
|
||||
"Set active_override to %s in %s (capacity fallback)",
|
||||
candidate.vm_name, candidate.zone,
|
||||
)
|
||||
|
||||
def _clear_active_override(self) -> None:
|
||||
"""Clear active_override fields (primary is healthy again).
|
||||
|
||||
Idempotent: safe to call when no override is currently set.
|
||||
"""
|
||||
snapshot = self._doc_ref().get()
|
||||
if not snapshot.exists:
|
||||
return
|
||||
data = snapshot.to_dict() or {}
|
||||
if not data.get("active_override_vm"):
|
||||
return # nothing to clear
|
||||
self._doc_ref().update({
|
||||
"active_override_vm": None,
|
||||
"active_override_ip": None,
|
||||
"active_override_zone": None,
|
||||
"active_override_set_at": None,
|
||||
})
|
||||
logger.info("Cleared active_override (primary is healthy again)")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Compute operation helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _wait_for_compute_operation(
|
||||
self,
|
||||
operation: Any,
|
||||
*,
|
||||
vm_name: str,
|
||||
zone: str,
|
||||
timeout: float = START_OPERATION_TIMEOUT_SECONDS,
|
||||
) -> None:
|
||||
"""Block on a compute v1 ExtendedOperation; raise typed exceptions on error.
|
||||
|
||||
google.cloud.compute_v1 returns an ExtendedOperation. Calling .result()
|
||||
blocks until done; successful operations return None, failures raise.
|
||||
Some failure modes set .error_code/.error_message on the operation
|
||||
without raising (depending on SDK version), so we check both paths.
|
||||
"""
|
||||
result_exc: Optional[BaseException] = None
|
||||
try:
|
||||
if hasattr(operation, "result"):
|
||||
operation.result(timeout=timeout)
|
||||
except Exception as e: # noqa: BLE001 — we re-raise as a typed error below
|
||||
result_exc = e
|
||||
|
||||
code = (getattr(operation, "error_code", "") or "")
|
||||
message = (getattr(operation, "error_message", "") or "")
|
||||
|
||||
if not code and result_exc is None:
|
||||
return # Success.
|
||||
|
||||
if not code and result_exc is not None:
|
||||
# Operation raised but did not set error_code (e.g. timeout, transport
|
||||
# failure). Fall back to the raised exception text.
|
||||
raise EncodingWorkerStartError(
|
||||
f"VM {vm_name} start operation failed in {zone}: {result_exc}",
|
||||
vm_name=vm_name,
|
||||
zone=zone,
|
||||
code="",
|
||||
) from result_exc
|
||||
|
||||
# error_code populated — classify it.
|
||||
raise classify_gce_error(code, message, vm_name=vm_name, zone=zone) from result_exc
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Task 3: cold-start readiness gate
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def wait_for_worker_ready(
|
||||
self,
|
||||
vm_name: str,
|
||||
health_url: str,
|
||||
*,
|
||||
zone: Optional[str] = None,
|
||||
vm_timeout: float = 120.0,
|
||||
health_timeout: float = 180.0,
|
||||
poll_interval: float = 5.0,
|
||||
) -> None:
|
||||
"""Block until the VM is RUNNING and the worker /health endpoint returns 200.
|
||||
|
||||
Two-phase wait, used after ensure_primary_running() reports started=True
|
||||
(i.e., the VM was actually TERMINATED and is cold-booting):
|
||||
|
||||
Phase 1 — poll get_vm_status until RUNNING (max vm_timeout seconds)
|
||||
Phase 2 — poll GET health_url until 200 (max health_timeout seconds)
|
||||
|
||||
Connection errors and non-200 responses during phase 2 are treated as
|
||||
"not ready, keep polling". A TimeoutError is raised if either phase
|
||||
exceeds its budget.
|
||||
|
||||
Args:
|
||||
vm_name: Name of the GCE VM to poll.
|
||||
health_url: Full URL of the worker /health endpoint
|
||||
(e.g. "http://10.0.0.1:8080/health").
|
||||
zone: Override the manager's default zone. Required when waiting on
|
||||
capacity-fallback VMs that live in alternate zones — without
|
||||
this override the status poll hits the wrong zone and 404s
|
||||
("instance not found"), the readiness wait gives up, and the
|
||||
next request hits a VM that hasn't finished booting.
|
||||
vm_timeout: Max seconds to wait for VM RUNNING.
|
||||
health_timeout: Max seconds to wait for /health 200.
|
||||
poll_interval: Seconds between polls in either phase.
|
||||
|
||||
Raises:
|
||||
TimeoutError: If VM never reaches RUNNING, or /health never returns 200.
|
||||
"""
|
||||
# Phase 1: VM status
|
||||
loop = asyncio.get_event_loop()
|
||||
deadline = loop.time() + vm_timeout
|
||||
last_status = None
|
||||
last_log = 0.0
|
||||
while loop.time() < deadline:
|
||||
last_status = self.get_vm_status(vm_name, zone=zone)
|
||||
if last_status == "RUNNING":
|
||||
logger.info("VM %s reached RUNNING", vm_name)
|
||||
break
|
||||
now = loop.time()
|
||||
if now - last_log >= 30.0:
|
||||
logger.info("Waiting for VM %s (status=%s)", vm_name, last_status)
|
||||
last_log = now
|
||||
await asyncio.sleep(poll_interval)
|
||||
else:
|
||||
raise TimeoutError(
|
||||
f"VM {vm_name} did not reach RUNNING within {vm_timeout}s "
|
||||
f"(last status: {last_status})"
|
||||
)
|
||||
|
||||
# Phase 2: worker /health
|
||||
deadline = loop.time() + health_timeout
|
||||
last_log = 0.0
|
||||
last_detail = "no response"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
while loop.time() < deadline:
|
||||
try:
|
||||
async with session.get(health_url, timeout=5.0) as resp:
|
||||
if resp.status == 200:
|
||||
logger.info("Worker at %s is healthy", health_url)
|
||||
return
|
||||
last_detail = f"HTTP {resp.status}"
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as e:
|
||||
last_detail = f"{type(e).__name__}: {e}" if str(e) else type(e).__name__
|
||||
now = loop.time()
|
||||
if now - last_log >= 30.0:
|
||||
logger.info("Waiting for worker /health at %s (last: %s)", health_url, last_detail)
|
||||
last_log = now
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
raise TimeoutError(
|
||||
f"Worker at {health_url} did not become healthy within {health_timeout}s "
|
||||
f"(last: {last_detail})"
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1 +0,0 @@
|
||||
"""Production error monitoring service for Nomad Karaoke."""
|
||||
@@ -1,177 +0,0 @@
|
||||
"""Configuration for the production error monitoring service.
|
||||
|
||||
All constants, service lists, and environment-driven configuration
|
||||
functions used across the error monitor modules.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GCP project settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
GCP_PROJECT: str = os.environ.get("GCP_PROJECT", "nomadkaraoke")
|
||||
GCP_REGION: str = os.environ.get("GCP_REGION", "us-central1")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Log querying settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: How far back to look for errors on each run (minutes).
|
||||
LOOKBACK_MINUTES: int = 15
|
||||
|
||||
#: Maximum number of log entries to fetch per service per run.
|
||||
MAX_LOG_ENTRIES: int = 500
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monitored services
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MONITORED_CLOUD_RUN_SERVICES: list[str] = [
|
||||
"karaoke-backend",
|
||||
"karaoke-decide",
|
||||
"audio-separator",
|
||||
# Gen2 Cloud Functions appear as Cloud Run services in logs
|
||||
"gdrive-validator",
|
||||
"github-runner-manager",
|
||||
"backup-to-aws",
|
||||
"divebar-mirror",
|
||||
"kn-data-sync",
|
||||
"divebar-lookup",
|
||||
"encoding-worker-idle-shutdown",
|
||||
]
|
||||
|
||||
MONITORED_CLOUD_RUN_JOBS: list[str] = [
|
||||
"video-encoding-job",
|
||||
"lyrics-transcription-job",
|
||||
"audio-separation-job",
|
||||
"audio-download-job",
|
||||
]
|
||||
|
||||
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
|
||||
# Their names are in MONITORED_CLOUD_RUN_SERVICES above.
|
||||
MONITORED_CLOUD_FUNCTIONS: list[str] = []
|
||||
|
||||
MONITORED_GCE_INSTANCES: list[str] = [
|
||||
"encoding-worker-a",
|
||||
"encoding-worker-b",
|
||||
"flacfetch-vm",
|
||||
"divebar-sync-vm",
|
||||
]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Service dependency map
|
||||
# Human-readable description of which services depend on which workers.
|
||||
# Used as LLM context when generating root-cause analysis.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SERVICE_DEPENDENCY_MAP: str = """\
|
||||
karaoke-backend (main API)
|
||||
→ video-encoding-job (Cloud Run Job, triggered per order)
|
||||
→ lyrics-transcription-job (Cloud Run Job, triggered after audio-sep)
|
||||
→ audio-separation-job (Cloud Run Job, runs on Cloud Run GPU)
|
||||
→ audio-download-job (Cloud Run Job, uses flacfetch-vm)
|
||||
→ gdrive-validator (Cloud Function, validates output files)
|
||||
→ encoding-worker-a/b (GCE VMs, long-running encoding workers)
|
||||
|
||||
karaoke-decide (catalog / discovery API)
|
||||
→ kn_data_sync (Cloud Function, syncs KaraokeNerds catalog)
|
||||
→ divebar_mirror (Cloud Function, mirrors Divebar catalog)
|
||||
→ divebar_lookup (Cloud Function, single-song lookup)
|
||||
|
||||
audio-separator (Cloud Run service, GPU stem separation)
|
||||
→ audio-separation-job (Cloud Run Job, launched by audio-separator)
|
||||
|
||||
flacfetch-vm (GCE VM)
|
||||
→ audio-download-job (initiated by karaoke-backend)
|
||||
|
||||
divebar-sync-vm (GCE VM)
|
||||
→ divebar_mirror (Cloud Function, reads from this VM)
|
||||
|
||||
Shared infrastructure:
|
||||
→ runner_manager (Cloud Function, manages encoding worker lifecycle)
|
||||
→ encoding_worker_idle (Cloud Function, shuts down idle encoding workers)
|
||||
→ backup_to_aws (Cloud Function, daily GCS → S3 backup)
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM analysis settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-2.0-flash-001")
|
||||
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "us-central1")
|
||||
|
||||
#: Minimum number of active error patterns required before triggering LLM analysis.
|
||||
MIN_PATTERNS_FOR_ANALYSIS: int = 3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Spike detection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: An error count is a spike if it exceeds SPIKE_MULTIPLIER × baseline average.
|
||||
SPIKE_MULTIPLIER: float = 5.0
|
||||
|
||||
#: Minimum absolute error count before spike detection fires (avoids noise).
|
||||
SPIKE_MIN_COUNT: int = 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auto-resolution settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Multiply LOOKBACK_MINUTES by this to get auto-resolve window in minutes.
|
||||
AUTO_RESOLVE_MULTIPLIER: int = 8
|
||||
|
||||
#: Minimum hours before a pattern can be auto-resolved.
|
||||
AUTO_RESOLVE_MIN_HOURS: int = 6
|
||||
|
||||
#: Maximum hours before a pattern is force-resolved even if still active.
|
||||
AUTO_RESOLVE_MAX_HOURS: int = 168 # 1 week
|
||||
|
||||
#: Fallback resolve window (hours) if baseline data is unavailable.
|
||||
AUTO_RESOLVE_FALLBACK_HOURS: int = 48
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discord settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maximum Discord messages to send per monitor run (rate-limit guard).
|
||||
MAX_DISCORD_MESSAGES_PER_RUN: int = 10
|
||||
|
||||
#: Discord API hard limit on message length.
|
||||
DISCORD_MAX_MESSAGE_LENGTH: int = 2000
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pattern tracking settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maximum number of active error patterns to track in Firestore.
|
||||
MAX_ACTIVE_PATTERNS: int = 500
|
||||
|
||||
#: Rolling window used when computing error baselines.
|
||||
ROLLING_WINDOW_DAYS: int = 7
|
||||
|
||||
#: Maximum length of a normalized error message stored in Firestore.
|
||||
MAX_NORMALIZED_MESSAGE_LENGTH: int = 200
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_llm_enabled() -> bool:
|
||||
"""Return True if LLM analysis is enabled via the LLM_ANALYSIS_ENABLED env var."""
|
||||
return os.environ.get("LLM_ANALYSIS_ENABLED", "false").strip().lower() == "true"
|
||||
|
||||
|
||||
def get_discord_webhook_secret_name() -> str:
|
||||
"""Return the Secret Manager secret name for the Discord webhook URL."""
|
||||
return os.environ.get("DISCORD_WEBHOOK_SECRET_NAME", "error-monitor-discord-webhook")
|
||||
|
||||
|
||||
def get_digest_mode() -> bool:
|
||||
"""Return True if the monitor should run in digest mode (batch alerts instead of immediate).
|
||||
|
||||
In digest mode all alerts are bundled into a single Discord message sent at
|
||||
the end of the run, rather than sending one message per error pattern.
|
||||
"""
|
||||
return os.environ.get("DIGEST_MODE", "false").strip().lower() == "true"
|
||||
@@ -1,323 +0,0 @@
|
||||
"""Discord alert client for the production error monitoring service.
|
||||
|
||||
Provides formatting functions for each alert type, and an ErrorMonitorDiscord
|
||||
webhook client that rate-limits outbound messages to MAX_DISCORD_MESSAGES_PER_RUN
|
||||
per monitor run.
|
||||
|
||||
Usage:
|
||||
from backend.services.error_monitor.discord import (
|
||||
ErrorMonitorDiscord,
|
||||
format_new_pattern_alert,
|
||||
format_incident_alert,
|
||||
format_auto_resolved_alert,
|
||||
format_spike_alert,
|
||||
format_daily_digest,
|
||||
)
|
||||
|
||||
discord = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/...")
|
||||
msg = format_new_pattern_alert(...)
|
||||
discord.send_message(msg)
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
DISCORD_MAX_MESSAGE_LENGTH,
|
||||
MAX_DISCORD_MESSAGES_PER_RUN,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SEVERITY_EMOJI: dict[str, str] = {
|
||||
"P0": "🚨",
|
||||
"P1": "🔴",
|
||||
"P2": "⚠️",
|
||||
"P3": "🟡",
|
||||
}
|
||||
|
||||
_EASTERN = ZoneInfo("America/New_York")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _now_eastern() -> str:
|
||||
"""Return the current Eastern time as 'HH:MM AM/PM ET' (DST-aware)."""
|
||||
now = datetime.now(tz=_EASTERN)
|
||||
return now.strftime("%I:%M %p ET").lstrip("0")
|
||||
|
||||
|
||||
def _truncate(msg: str) -> str:
|
||||
"""Truncate *msg* to DISCORD_MAX_MESSAGE_LENGTH characters."""
|
||||
if len(msg) <= DISCORD_MAX_MESSAGE_LENGTH:
|
||||
return msg
|
||||
suffix = "…"
|
||||
return msg[: DISCORD_MAX_MESSAGE_LENGTH - len(suffix)] + suffix
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Formatting functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def format_new_pattern_alert(
|
||||
service: str,
|
||||
resource_type: str,
|
||||
normalized_message: str,
|
||||
sample_message: str,
|
||||
count: int,
|
||||
first_seen: str,
|
||||
) -> str:
|
||||
"""Format a Discord alert for a newly-detected error pattern.
|
||||
|
||||
Args:
|
||||
service: Name of the service emitting the error.
|
||||
resource_type: GCP resource type (e.g. 'cloud_run_service', 'gce_instance').
|
||||
normalized_message: Normalised error pattern string.
|
||||
sample_message: A representative raw log message.
|
||||
count: Number of occurrences seen so far.
|
||||
first_seen: ISO 8601 timestamp when the pattern was first seen.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"🔴 **New Error Pattern Detected**",
|
||||
f"",
|
||||
f"**Service:** {service}",
|
||||
f"**Resource type:** {resource_type}",
|
||||
f"**Pattern:** {normalized_message}",
|
||||
f"**Sample:** {sample_message}",
|
||||
f"**Count:** {count}",
|
||||
f"**First seen:** {first_seen}",
|
||||
f"**Alerted at:** {_now_eastern()}",
|
||||
f"",
|
||||
f"To investigate: `/prod-investigate {service} \"{normalized_message}\"`",
|
||||
]
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_incident_alert(
|
||||
title: str,
|
||||
severity: str,
|
||||
root_cause: str,
|
||||
suggested_fix: str,
|
||||
primary_service: str,
|
||||
patterns: list[dict],
|
||||
) -> str:
|
||||
"""Format a Discord alert for an analysed incident (LLM-generated).
|
||||
|
||||
Args:
|
||||
title: Short incident title.
|
||||
severity: Severity level — one of P0, P1, P2, P3.
|
||||
root_cause: Human-readable root-cause analysis.
|
||||
suggested_fix: Recommended remediation steps.
|
||||
primary_service: The main service involved in the incident.
|
||||
patterns: List of dicts, each with keys: service, normalized_message, count.
|
||||
Only the first 5 are shown; normalized_message is truncated to 80 chars.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
emoji = SEVERITY_EMOJI.get(severity, "⚠️")
|
||||
lines = [
|
||||
f"{emoji} **[{severity}] {title}**",
|
||||
f"",
|
||||
f"**Primary service:** {primary_service}",
|
||||
f"**Root cause:** {root_cause}",
|
||||
f"**Suggested fix:** {suggested_fix}",
|
||||
]
|
||||
|
||||
shown_patterns = patterns[:5]
|
||||
if shown_patterns:
|
||||
lines.append("")
|
||||
lines.append(f"**Patterns ({len(shown_patterns)} of {len(patterns)}):**")
|
||||
for p in shown_patterns:
|
||||
svc = p.get("service", "unknown")
|
||||
msg = p.get("normalized_message", "")[:80]
|
||||
cnt = p.get("count", 0)
|
||||
lines.append(f" • `{svc}` — {msg} ({cnt}x)")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Alerted at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_auto_resolved_alert(resolved_patterns: list[dict]) -> str:
|
||||
"""Format a consolidated auto-resolved alert.
|
||||
|
||||
Args:
|
||||
resolved_patterns: List of dicts, each with keys: service, message, hours_silent.
|
||||
Only the first 8 are shown; message is truncated to 60 chars.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"✅ **Patterns Auto-Resolved**",
|
||||
f"",
|
||||
]
|
||||
|
||||
shown = resolved_patterns[:8]
|
||||
if shown:
|
||||
for p in shown:
|
||||
svc = p.get("service", "unknown")
|
||||
msg = p.get("message", "")[:60]
|
||||
hours = p.get("hours_silent", 0)
|
||||
lines.append(f" • `{svc}` — {msg} (silent {hours}h)")
|
||||
else:
|
||||
lines.append(" *(no patterns)*")
|
||||
|
||||
if len(resolved_patterns) > 8:
|
||||
lines.append(f" … and {len(resolved_patterns) - 8} more")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Resolved at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_spike_alert(
|
||||
service: str,
|
||||
normalized_message: str,
|
||||
current_count: int,
|
||||
rolling_average: float,
|
||||
) -> str:
|
||||
"""Format a Discord alert for an error rate spike.
|
||||
|
||||
Args:
|
||||
service: Name of the service.
|
||||
normalized_message: Normalised error pattern string.
|
||||
current_count: Error count in the current window.
|
||||
rolling_average: Baseline rolling average count.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
if rolling_average > 0:
|
||||
multiplier = current_count / rolling_average
|
||||
multiplier_str = f"{multiplier:.1f}x"
|
||||
else:
|
||||
multiplier_str = "∞x"
|
||||
|
||||
lines = [
|
||||
f"⚠️ **Error Rate Spike Detected**",
|
||||
f"",
|
||||
f"**Service:** {service}",
|
||||
f"**Pattern:** {normalized_message}",
|
||||
f"**Current count:** {current_count}",
|
||||
f"**Normal (rolling avg):** {rolling_average}",
|
||||
f"**Multiplier:** {multiplier_str} above normal",
|
||||
f"",
|
||||
f"**Alerted at:** {_now_eastern()}",
|
||||
]
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_daily_digest(
|
||||
total_errors: int,
|
||||
new_patterns: int,
|
||||
resolved_patterns: int,
|
||||
active_patterns: int,
|
||||
per_service_counts: dict,
|
||||
) -> str:
|
||||
"""Format the daily 24h error digest.
|
||||
|
||||
Args:
|
||||
total_errors: Total error count in the last 24 hours.
|
||||
new_patterns: Number of new error patterns detected.
|
||||
resolved_patterns: Number of patterns auto-resolved.
|
||||
active_patterns: Total number of currently active patterns.
|
||||
per_service_counts: Mapping of service name → error count.
|
||||
Displayed sorted by count descending.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"📊 **Daily Error Digest (24h)**",
|
||||
f"",
|
||||
f"**Total errors:** {total_errors}",
|
||||
f"**New patterns:** {new_patterns}",
|
||||
f"**Resolved patterns:** {resolved_patterns}",
|
||||
f"**Active patterns:** {active_patterns}",
|
||||
]
|
||||
|
||||
if per_service_counts:
|
||||
lines.append("")
|
||||
lines.append("**Per-service breakdown:**")
|
||||
sorted_services = sorted(per_service_counts.items(), key=lambda kv: kv[1], reverse=True)
|
||||
for svc, cnt in sorted_services:
|
||||
lines.append(f" • `{svc}`: {cnt}")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Generated at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discord webhook client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorMonitorDiscord:
|
||||
"""Webhook client for sending error monitor alerts to Discord.
|
||||
|
||||
Enforces a per-run rate limit of MAX_DISCORD_MESSAGES_PER_RUN to avoid
|
||||
flooding the channel during high-volume incident windows.
|
||||
|
||||
Attributes:
|
||||
webhook_url: The Discord incoming webhook URL.
|
||||
messages_sent: Counter of messages attempted this run (success or failure).
|
||||
"""
|
||||
|
||||
def __init__(self, webhook_url: str) -> None:
|
||||
self.webhook_url = webhook_url
|
||||
self.messages_sent: int = 0
|
||||
|
||||
def send_message(self, content: str) -> bool:
|
||||
"""Send a message to the configured Discord webhook.
|
||||
|
||||
Rate-limits: if messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN, the
|
||||
message is silently skipped and False is returned without incrementing
|
||||
the counter.
|
||||
|
||||
Args:
|
||||
content: The message text to send (should be pre-formatted and
|
||||
pre-truncated to ≤2000 chars).
|
||||
|
||||
Returns:
|
||||
True if the message was sent successfully, False otherwise.
|
||||
"""
|
||||
if self.messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN:
|
||||
logger.warning(
|
||||
"Discord rate limit reached (%d messages sent this run); skipping message.",
|
||||
self.messages_sent,
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
self.webhook_url,
|
||||
json={"content": content},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.debug("Discord message sent successfully.")
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error("Failed to send Discord message: %s", exc)
|
||||
return False
|
||||
finally:
|
||||
self.messages_sent += 1
|
||||
@@ -1,502 +0,0 @@
|
||||
"""Firestore adapter for the production error monitoring service.
|
||||
|
||||
Handles all CRUD for three Firestore collections:
|
||||
- error_patterns: normalized error patterns (pattern_id as doc ID)
|
||||
- error_incidents: groups of related patterns (incident_id as doc ID)
|
||||
- discord_alerts: audit trail for Discord messages (alert_id as doc ID)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
AUTO_RESOLVE_FALLBACK_HOURS,
|
||||
AUTO_RESOLVE_MAX_HOURS,
|
||||
AUTO_RESOLVE_MIN_HOURS,
|
||||
AUTO_RESOLVE_MULTIPLIER,
|
||||
ROLLING_WINDOW_DAYS,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class PatternData:
|
||||
"""Input data for creating or updating an error pattern."""
|
||||
|
||||
pattern_id: str
|
||||
service: str
|
||||
resource_type: str
|
||||
normalized_message: str
|
||||
sample_message: str
|
||||
count: int
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
@dataclass
|
||||
class UpsertResult:
|
||||
"""Result of an upsert_pattern operation."""
|
||||
|
||||
pattern_id: str
|
||||
is_new: bool
|
||||
previous_status: str | None = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Collection names
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_COL_PATTERNS = "error_patterns"
|
||||
_COL_INCIDENTS = "error_incidents"
|
||||
_COL_ALERTS = "discord_alerts"
|
||||
|
||||
# Statuses that can be queried as "active"
|
||||
_ACTIVE_STATUSES = ["new", "acknowledged", "known"]
|
||||
|
||||
# Statuses from which a pattern is reactivated when the error recurs
|
||||
_REACTIVATION_STATUSES = {"auto_resolved", "fixed"}
|
||||
|
||||
# Statuses eligible for auto-resolve checking
|
||||
_AUTO_RESOLVE_ELIGIBLE = {"new", "acknowledged"}
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
"""Return current UTC datetime."""
|
||||
return datetime.now(tz=timezone.utc)
|
||||
|
||||
|
||||
def _iso(dt: datetime) -> str:
|
||||
"""Serialise a datetime to ISO-8601 string."""
|
||||
return dt.isoformat()
|
||||
|
||||
|
||||
def _generate_id(prefix: str, fmt: str) -> str:
|
||||
"""Generate a time-stamped ID with 8 hex random suffix.
|
||||
|
||||
Args:
|
||||
prefix: e.g. "inc" or "alert"
|
||||
fmt: strftime format string applied to utcnow(), e.g. "%Y%m%d_%H%M"
|
||||
"""
|
||||
ts = _utcnow().strftime(fmt)
|
||||
suffix = secrets.token_hex(4) # 8 hex chars
|
||||
return f"{prefix}_{ts}_{suffix}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Adapter
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorPatternsAdapter:
|
||||
"""Firestore CRUD adapter for error monitoring collections.
|
||||
|
||||
Args:
|
||||
db: Optional Firestore client. If omitted, a default client for the
|
||||
``nomadkaraoke`` GCP project is constructed on first use.
|
||||
"""
|
||||
|
||||
def __init__(self, db=None) -> None:
|
||||
if db is None:
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
self._db = db
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — read
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_pattern(self, pattern_id: str) -> dict | None:
|
||||
"""Return the pattern document as a dict, or None if it doesn't exist.
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID in the ``error_patterns`` collection.
|
||||
"""
|
||||
snap = self._db.collection(_COL_PATTERNS).document(pattern_id).get()
|
||||
if not snap.exists:
|
||||
return None
|
||||
return snap.to_dict()
|
||||
|
||||
def get_active_patterns(self) -> list[dict]:
|
||||
"""Return all patterns with status in [new, acknowledged, known]."""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "in", _ACTIVE_STATUSES
|
||||
)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
def get_patterns_for_auto_resolve(self) -> list[dict]:
|
||||
"""Return active patterns eligible for auto-resolution (new or acknowledged)."""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "in", list(_AUTO_RESOLVE_ELIGIBLE)
|
||||
)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
def get_unalerted_new_patterns(self) -> list[dict]:
|
||||
"""Return patterns with status="new" and alerted_at=None.
|
||||
|
||||
These are typically patterns written by a path other than the current
|
||||
monitor cycle — most notably frontend crashes ingested via
|
||||
``POST /api/client-errors``. The monitor uses this to ensure out-of-band
|
||||
patterns still get a Discord alert on the next scheduled run.
|
||||
"""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "==", "new"
|
||||
).where("alerted_at", "==", None)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — upsert
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def upsert_pattern(self, data: PatternData) -> UpsertResult:
|
||||
"""Create a new pattern or update an existing one.
|
||||
|
||||
New pattern:
|
||||
- status="new", severity="P3"
|
||||
- Initialize ``rolling_counts`` with one entry for this run.
|
||||
|
||||
Existing pattern:
|
||||
- Increment ``total_count`` and append to ``rolling_counts``.
|
||||
- If status was ``auto_resolved`` or ``fixed`` → reactivate (set status="new").
|
||||
- Prune ``rolling_counts`` entries older than ROLLING_WINDOW_DAYS.
|
||||
|
||||
Returns:
|
||||
UpsertResult with ``is_new=True`` for brand-new patterns *and* for
|
||||
reactivated patterns (auto_resolved → new, fixed → new).
|
||||
"""
|
||||
doc_ref = self._db.collection(_COL_PATTERNS).document(data.pattern_id)
|
||||
snap = doc_ref.get()
|
||||
ts_iso = _iso(data.timestamp)
|
||||
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count}
|
||||
|
||||
if not snap.exists:
|
||||
# ── brand new pattern ──────────────────────────────────────────
|
||||
doc_ref.set(
|
||||
{
|
||||
"pattern_id": data.pattern_id,
|
||||
"service": data.service,
|
||||
"resource_type": data.resource_type,
|
||||
"normalized_message": data.normalized_message,
|
||||
"sample_message": data.sample_message,
|
||||
"status": "new",
|
||||
"severity": "P3",
|
||||
"total_count": data.count,
|
||||
"rolling_counts": [new_rolling_entry],
|
||||
"first_seen": ts_iso,
|
||||
"last_seen": ts_iso,
|
||||
"alerted_at": None,
|
||||
"created_at": ts_iso,
|
||||
"updated_at": ts_iso,
|
||||
}
|
||||
)
|
||||
return UpsertResult(pattern_id=data.pattern_id, is_new=True)
|
||||
|
||||
# ── existing pattern ───────────────────────────────────────────────
|
||||
existing = snap.to_dict()
|
||||
prev_status = existing.get("status", "new")
|
||||
|
||||
rolling_counts: list[dict] = list(existing.get("rolling_counts") or [])
|
||||
rolling_counts.append(new_rolling_entry)
|
||||
rolling_counts = self._prune_rolling_counts(rolling_counts)
|
||||
|
||||
update: dict[str, Any] = {
|
||||
"total_count": existing.get("total_count", 0) + data.count,
|
||||
"rolling_counts": rolling_counts,
|
||||
"last_seen": ts_iso,
|
||||
"sample_message": data.sample_message,
|
||||
"updated_at": ts_iso,
|
||||
}
|
||||
|
||||
# Reactivation: pattern was considered resolved/fixed but error recurred
|
||||
is_new = False
|
||||
if prev_status in _REACTIVATION_STATUSES:
|
||||
update["status"] = "new"
|
||||
update["alerted_at"] = None
|
||||
is_new = True
|
||||
|
||||
doc_ref.update(update)
|
||||
return UpsertResult(
|
||||
pattern_id=data.pattern_id,
|
||||
is_new=is_new,
|
||||
previous_status=prev_status,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — status changes
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def auto_resolve_pattern(self, pattern_id: str, hours_silent: float) -> None:
|
||||
"""Mark a pattern as auto-resolved.
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID.
|
||||
hours_silent: How many hours the pattern has been silent.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"status": "auto_resolved",
|
||||
"auto_resolve_hours_silent": hours_silent,
|
||||
"auto_resolved_at": _iso(_utcnow()),
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
def resolve_pattern(
|
||||
self,
|
||||
pattern_id: str,
|
||||
pr_url: str | None = None,
|
||||
note: str = "",
|
||||
) -> None:
|
||||
"""Mark a pattern as fixed (human-resolved).
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID.
|
||||
pr_url: Optional URL of the PR that fixed this pattern.
|
||||
note: Optional human-readable note about the fix.
|
||||
"""
|
||||
now_iso = _iso(_utcnow())
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"status": "fixed",
|
||||
"fixed_by": {
|
||||
"pr_url": pr_url,
|
||||
"note": note,
|
||||
"fixed_at": now_iso,
|
||||
},
|
||||
"updated_at": now_iso,
|
||||
}
|
||||
)
|
||||
|
||||
def update_pattern_alerted(self, pattern_id: str) -> None:
|
||||
"""Set the ``alerted_at`` timestamp on a pattern.
|
||||
|
||||
Called after a Discord alert has been successfully sent for the pattern.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"alerted_at": _iso(_utcnow()),
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
def merge_pattern(self, source_id: str, target_id: str, reason: str) -> None:
|
||||
"""Merge *source* into *target* by muting the source pattern.
|
||||
|
||||
Args:
|
||||
source_id: Pattern to mute.
|
||||
target_id: Pattern that the source is being merged into.
|
||||
reason: Human-readable rationale for the merge.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(source_id).update(
|
||||
{
|
||||
"status": "muted",
|
||||
"merged_into": target_id,
|
||||
"merge_reason": reason,
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auto-resolve logic
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def check_auto_resolve(self, pattern: dict) -> float | None:
|
||||
"""Determine whether *pattern* should be auto-resolved.
|
||||
|
||||
Computes the frequency-aware silence threshold and compares it against
|
||||
how long the pattern has been silent.
|
||||
|
||||
Args:
|
||||
pattern: A pattern document dict (as returned by get_pattern).
|
||||
|
||||
Returns:
|
||||
The number of hours the pattern has been silent if the threshold is
|
||||
exceeded, or ``None`` if the pattern should not yet be resolved.
|
||||
"""
|
||||
status = pattern.get("status", "")
|
||||
if status not in _AUTO_RESOLVE_ELIGIBLE:
|
||||
return None
|
||||
|
||||
last_seen_str = pattern.get("last_seen")
|
||||
if not last_seen_str:
|
||||
return None
|
||||
|
||||
last_seen = datetime.fromisoformat(last_seen_str)
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
|
||||
# Ensure both datetimes are tz-aware for subtraction
|
||||
if last_seen.tzinfo is None:
|
||||
last_seen = last_seen.replace(tzinfo=timezone.utc)
|
||||
|
||||
hours_silent = (now - last_seen).total_seconds() / 3600.0
|
||||
|
||||
rolling_counts = pattern.get("rolling_counts") or []
|
||||
threshold = self._compute_resolve_threshold(rolling_counts)
|
||||
|
||||
if hours_silent >= threshold:
|
||||
return hours_silent
|
||||
return None
|
||||
|
||||
def _compute_resolve_threshold(self, rolling_counts: list[dict]) -> float:
|
||||
"""Compute the frequency-aware auto-resolve threshold in hours.
|
||||
|
||||
Algorithm:
|
||||
1. If fewer than 3 data points → return AUTO_RESOLVE_FALLBACK_HOURS (48).
|
||||
2. Compute mean interval between consecutive timestamps.
|
||||
3. threshold = mean_interval_hours * AUTO_RESOLVE_MULTIPLIER.
|
||||
4. Clamp result to [AUTO_RESOLVE_MIN_HOURS, AUTO_RESOLVE_MAX_HOURS].
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
|
||||
|
||||
Returns:
|
||||
Threshold in hours (float).
|
||||
"""
|
||||
if len(rolling_counts) < 3:
|
||||
return float(AUTO_RESOLVE_FALLBACK_HOURS)
|
||||
|
||||
# Parse timestamps and sort ascending
|
||||
timestamps: list[datetime] = []
|
||||
for entry in rolling_counts:
|
||||
ts = datetime.fromisoformat(entry["ts"])
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
timestamps.append(ts)
|
||||
timestamps.sort()
|
||||
|
||||
# Compute pairwise intervals
|
||||
intervals_hours: list[float] = []
|
||||
for i in range(1, len(timestamps)):
|
||||
delta = (timestamps[i] - timestamps[i - 1]).total_seconds() / 3600.0
|
||||
intervals_hours.append(delta)
|
||||
|
||||
if not intervals_hours:
|
||||
return float(AUTO_RESOLVE_FALLBACK_HOURS)
|
||||
|
||||
mean_interval = sum(intervals_hours) / len(intervals_hours)
|
||||
threshold = mean_interval * AUTO_RESOLVE_MULTIPLIER
|
||||
|
||||
# Clamp to configured bounds
|
||||
threshold = max(float(AUTO_RESOLVE_MIN_HOURS), threshold)
|
||||
threshold = min(float(AUTO_RESOLVE_MAX_HOURS), threshold)
|
||||
return threshold
|
||||
|
||||
def _prune_rolling_counts(self, rolling_counts: list[dict]) -> list[dict]:
|
||||
"""Remove rolling_count entries older than ROLLING_WINDOW_DAYS.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
|
||||
|
||||
Returns:
|
||||
Filtered list with only recent entries.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return []
|
||||
|
||||
cutoff = _utcnow() - timedelta(days=ROLLING_WINDOW_DAYS)
|
||||
result = []
|
||||
for entry in rolling_counts:
|
||||
ts = datetime.fromisoformat(entry["ts"])
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ts >= cutoff:
|
||||
result.append(entry)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Incidents
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_incident(
|
||||
self,
|
||||
title: str,
|
||||
root_cause: str,
|
||||
severity: str,
|
||||
suggested_fix: str,
|
||||
primary_service: str,
|
||||
pattern_ids: list[str],
|
||||
used_llm: bool,
|
||||
) -> str:
|
||||
"""Create a new incident document and link associated patterns.
|
||||
|
||||
Args:
|
||||
title: Short human-readable title.
|
||||
root_cause: LLM-generated or manual root-cause description.
|
||||
severity: Severity string (e.g. "P1", "P2", "P3").
|
||||
suggested_fix: Suggested remediation steps.
|
||||
primary_service: The primary affected service.
|
||||
pattern_ids: List of pattern_ids that belong to this incident.
|
||||
used_llm: Whether LLM analysis was used to generate this incident.
|
||||
|
||||
Returns:
|
||||
The generated incident_id string.
|
||||
"""
|
||||
incident_id = _generate_id("inc", "%Y%m%d_%H%M")
|
||||
now_iso = _iso(_utcnow())
|
||||
|
||||
self._db.collection(_COL_INCIDENTS).document(incident_id).set(
|
||||
{
|
||||
"incident_id": incident_id,
|
||||
"title": title,
|
||||
"root_cause": root_cause,
|
||||
"severity": severity,
|
||||
"suggested_fix": suggested_fix,
|
||||
"primary_service": primary_service,
|
||||
"pattern_ids": pattern_ids,
|
||||
"used_llm": used_llm,
|
||||
"created_at": now_iso,
|
||||
"updated_at": now_iso,
|
||||
"status": "open",
|
||||
}
|
||||
)
|
||||
|
||||
# Link each pattern back to this incident
|
||||
for pattern_id in pattern_ids:
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"incident_id": incident_id,
|
||||
"updated_at": now_iso,
|
||||
}
|
||||
)
|
||||
|
||||
return incident_id
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Discord audit trail
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def log_discord_alert(
|
||||
self,
|
||||
alert_type: str,
|
||||
content: str,
|
||||
success: bool,
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
"""Write an audit record to the ``discord_alerts`` collection.
|
||||
|
||||
Args:
|
||||
alert_type: Category of alert (e.g. "new_pattern", "digest").
|
||||
content: The message body that was (or would have been) sent.
|
||||
success: Whether the Discord webhook call succeeded.
|
||||
metadata: Optional additional data (pattern_ids, incident_id, etc.).
|
||||
"""
|
||||
alert_id = _generate_id("alert", "%Y%m%d_%H%M%S")
|
||||
now_iso = _iso(_utcnow())
|
||||
|
||||
self._db.collection(_COL_ALERTS).document(alert_id).set(
|
||||
{
|
||||
"alert_id": alert_id,
|
||||
"alert_type": alert_type,
|
||||
"content": content,
|
||||
"success": success,
|
||||
"metadata": metadata or {},
|
||||
"created_at": now_iso,
|
||||
}
|
||||
)
|
||||
@@ -1,157 +0,0 @@
|
||||
"""Frontend error ingestion helpers.
|
||||
|
||||
Converts an inbound browser crash report into a ``PatternData`` suitable for
|
||||
the shared ``ErrorPatternsAdapter``. The adapter + existing error-monitor
|
||||
Cloud Run Job handle all alerting / Discord plumbing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from backend.services.error_monitor.firestore_adapter import PatternData
|
||||
from backend.services.error_monitor.normalizer import (
|
||||
compute_pattern_hash,
|
||||
normalize_message,
|
||||
)
|
||||
|
||||
MAX_SAMPLE_MESSAGE_CHARS = 4000
|
||||
MAX_URL_CHARS = 512
|
||||
|
||||
# Crawlers/bots execute our JS (e.g. bingbot/Googlebot run headless Chrome) and
|
||||
# trip React DOM-reconciliation errors that no real user ever sees. Their reports
|
||||
# are pure alert-channel noise, so we drop them at ingestion. Matches the common
|
||||
# crawler tokens plus the generic bot/crawler/spider/headless markers that
|
||||
# well-behaved automated agents put in their UA string.
|
||||
_BOT_UA_RE = re.compile(
|
||||
# Generic markers. The bot forms are anchored so we never match the "bot"
|
||||
# inside ordinary words like "robot": a standalone "bot" token (\bbot\b does
|
||||
# not match inside "robot" — no word boundary there) or the crawler
|
||||
# "<name>bot/<version>" convention, with "robot/" explicitly excluded.
|
||||
r"\bbot\b|(?<!ro)bot/|spider|crawler|crawl\b|slurp|bingpreview|headless|"
|
||||
# Explicit crawler names (some don't use the "/version" convention).
|
||||
r"googlebot|bingbot|applebot|yandex|baiduspider|duckduckbot|"
|
||||
r"ahrefs|semrush|petalbot|facebookexternalhit|"
|
||||
r"chrome-lighthouse|google page speed|python-requests|curl/|wget/",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def is_bot_user_agent(user_agent: str | None) -> bool:
|
||||
"""Return True if the UA looks like a crawler/bot/automated agent.
|
||||
|
||||
Conservative: only matches explicit bot markers, so a real browser UA (which
|
||||
never contains these tokens) is never misclassified.
|
||||
"""
|
||||
if not user_agent:
|
||||
return False
|
||||
return bool(_BOT_UA_RE.search(user_agent))
|
||||
|
||||
|
||||
@dataclass
|
||||
class FrontendErrorReport:
|
||||
"""In-memory representation of an inbound crash report."""
|
||||
|
||||
message: str
|
||||
stack: str | None
|
||||
url: str
|
||||
user_agent: str
|
||||
release: str
|
||||
user_email: str | None
|
||||
viewport: dict | None
|
||||
locale: str
|
||||
extra: dict | None
|
||||
|
||||
|
||||
def sanitize_url(url: str) -> str:
|
||||
"""Strip query and fragment from a URL; cap length; tolerate junk."""
|
||||
if not url:
|
||||
return ""
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
if not parts.scheme:
|
||||
return url[:MAX_URL_CHARS]
|
||||
cleaned = urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
|
||||
return cleaned[:MAX_URL_CHARS]
|
||||
except ValueError:
|
||||
return url[:MAX_URL_CHARS]
|
||||
|
||||
|
||||
def _stack_for_hashing(report: FrontendErrorReport) -> str:
|
||||
"""Pick the most stable signal we have for pattern dedup.
|
||||
|
||||
Prefer the stack (stable across invocations) over the message (sometimes
|
||||
has interpolated values). Falls back to message if no stack.
|
||||
"""
|
||||
if report.stack:
|
||||
return report.stack
|
||||
return report.message
|
||||
|
||||
|
||||
def build_pattern_data(
|
||||
report: FrontendErrorReport, now: datetime | None = None
|
||||
) -> PatternData:
|
||||
"""Convert an inbound report to a PatternData ready for upsert."""
|
||||
if now is None:
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
|
||||
raw = _stack_for_hashing(report)
|
||||
normalized = normalize_message(raw)
|
||||
pattern_id = compute_pattern_hash("frontend", normalized)
|
||||
|
||||
# sample_message is human-readable context. Keep the error message plus a
|
||||
# trimmed stack + sanitized URL so the Discord alert is self-contained.
|
||||
sample_parts: list[str] = []
|
||||
if report.message:
|
||||
sample_parts.append(report.message.strip())
|
||||
if report.stack and report.stack.strip() != (report.message or "").strip():
|
||||
sample_parts.append(report.stack.strip())
|
||||
clean_url = sanitize_url(report.url)
|
||||
if clean_url:
|
||||
sample_parts.append(f"URL: {clean_url}")
|
||||
if report.user_agent:
|
||||
sample_parts.append(f"UA: {report.user_agent[:200]}")
|
||||
if report.release:
|
||||
sample_parts.append(f"Build: {report.release}")
|
||||
sample_message = "\n".join(sample_parts)[:MAX_SAMPLE_MESSAGE_CHARS]
|
||||
|
||||
return PatternData(
|
||||
pattern_id=pattern_id,
|
||||
service="frontend",
|
||||
resource_type="browser",
|
||||
normalized_message=normalized,
|
||||
sample_message=sample_message,
|
||||
count=1,
|
||||
timestamp=now,
|
||||
)
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""In-memory sliding-window limiter. One instance per process is enough —
|
||||
this runs inside Cloud Run which scales to multiple instances, so the
|
||||
effective limit is (per_ip_per_minute * num_instances). That's fine for our
|
||||
threat model (non-malicious browsers reporting their own crashes).
|
||||
"""
|
||||
|
||||
def __init__(self, max_per_minute: int = 60) -> None:
|
||||
self._max = max_per_minute
|
||||
self._hits: dict[str, list[float]] = {}
|
||||
|
||||
def allow(self, ip: str, now_ts: float) -> bool:
|
||||
cutoff = now_ts - 60.0
|
||||
hits = [t for t in self._hits.get(ip, []) if t >= cutoff]
|
||||
if len(hits) >= self._max:
|
||||
self._hits[ip] = hits
|
||||
return False
|
||||
hits.append(now_ts)
|
||||
self._hits[ip] = hits
|
||||
# simple cleanup: if the map gets huge, drop stale keys
|
||||
if len(self._hits) > 10_000:
|
||||
self._hits = {
|
||||
k: [t for t in v if t >= cutoff]
|
||||
for k, v in self._hits.items()
|
||||
if any(t >= cutoff for t in v)
|
||||
}
|
||||
return True
|
||||
@@ -1,133 +0,0 @@
|
||||
"""Known infrastructure noise patterns for the production error monitoring service.
|
||||
|
||||
Filters out transient, expected log messages so the error monitor is not flooded
|
||||
with Cloud Run cold-start probes, deploy events, spot VM preemptions, and similar
|
||||
operational noise.
|
||||
|
||||
Usage:
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
reason = should_ignore(service, message)
|
||||
if reason:
|
||||
# skip this log entry — it's known infrastructure noise
|
||||
...
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class IgnoreReason:
|
||||
"""Describes why a log entry should be suppressed.
|
||||
|
||||
Attributes:
|
||||
pattern_name: Machine-readable name of the matching ignore pattern.
|
||||
reason: Human-readable explanation of why this is infrastructure noise.
|
||||
"""
|
||||
|
||||
pattern_name: str
|
||||
reason: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compiled ignore patterns (applied in order)
|
||||
# All patterns use re.IGNORECASE for case-insensitive matching.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
|
||||
(
|
||||
"startup_probe",
|
||||
re.compile(r"startup probe failed", re.IGNORECASE),
|
||||
"Cloud Run cold start — startup probe failure is transient and expected",
|
||||
),
|
||||
(
|
||||
"ready_condition",
|
||||
re.compile(r"ready condition status changed", re.IGNORECASE),
|
||||
"Cloud Run deploy event — readiness condition change is expected on deploy",
|
||||
),
|
||||
(
|
||||
"spot_preemption",
|
||||
re.compile(r"instance was preempted", re.IGNORECASE),
|
||||
"Spot/preemptible VM preemption — expected behaviour for spot instances",
|
||||
),
|
||||
(
|
||||
"idle_shutdown",
|
||||
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
|
||||
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
|
||||
),
|
||||
(
|
||||
"encoding_worker_capacity_retry",
|
||||
# Only the TRANSIENT start failures: GCE 503/SERVICE UNAVAILABLE or a
|
||||
# capacity code (ZONE_RESOURCE_POOL_EXHAUSTED / STOCKOUT / QUOTA_EXCEEDED
|
||||
# — see encoding_errors.CAPACITY_ERROR_CODES). The render worker parks
|
||||
# these for auto-retry. A non-transient EncodingWorkerStartError (other /
|
||||
# unknown code) shares the "aborting retries" prefix but must still page,
|
||||
# so we require the transient signal, not just the prefix.
|
||||
# Bind the transient signal to the GCE error CODE field — which appears
|
||||
# immediately after "start failed in <zone>: " / "could not be started in
|
||||
# <zone>: " (see encoding_errors.classify_gce_error). Matching the code in
|
||||
# position (not anywhere in the line) prevents a non-transient failure
|
||||
# whose message text merely contains "503" from being suppressed.
|
||||
re.compile(
|
||||
r"encoding worker start failed, aborting retries:.*?"
|
||||
r"(?:start failed|could not be started) in [\w.-]+:\s*"
|
||||
r"(?:503\b|service unavailable|zone_resource_pool_exhausted"
|
||||
r"|stockout|quota_exceeded)",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
(
|
||||
"GCE encoding worker VM start hit a transient GCP condition (zone "
|
||||
"capacity exhaustion or 503 SERVICE UNAVAILABLE) — the render worker "
|
||||
"parks the job for auto-retry rather than failing it. Non-transient "
|
||||
"start failures still alert."
|
||||
),
|
||||
),
|
||||
(
|
||||
"health_check_404",
|
||||
re.compile(
|
||||
r"(?:GET|HEAD)\b[^\n]*?/health[^\n]*?\b(?:404|not found)\b",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
"Load balancer health check returning 404 — transient during cold start",
|
||||
),
|
||||
(
|
||||
"scheduler_retry",
|
||||
re.compile(r"cloud scheduler.*retry", re.IGNORECASE),
|
||||
"Cloud Scheduler transient retry — expected on intermittent job failures",
|
||||
),
|
||||
(
|
||||
"runner_startup",
|
||||
re.compile(r"github\.runner\..*(?:starting|stopping|idle)", re.IGNORECASE),
|
||||
"GitHub Actions runner lifecycle event — expected during runner start/stop",
|
||||
),
|
||||
(
|
||||
"container_shutdown",
|
||||
re.compile(r"container called exit\(0\)", re.IGNORECASE),
|
||||
"Container clean exit — exit code 0 indicates a graceful, expected shutdown",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def should_ignore(service: str, message: str) -> IgnoreReason | None:
|
||||
"""Check whether a log entry matches a known infrastructure noise pattern.
|
||||
|
||||
The check is purely message-based; ``service`` is accepted for API symmetry
|
||||
and future service-specific overrides but does not gate any pattern today.
|
||||
|
||||
Args:
|
||||
service: The originating service name (e.g. ``"karaoke-backend"``).
|
||||
message: The raw log message string to evaluate.
|
||||
|
||||
Returns:
|
||||
An :class:`IgnoreReason` if the message matches a known noise pattern,
|
||||
or ``None`` if the message should be processed normally.
|
||||
"""
|
||||
if not message:
|
||||
return None
|
||||
|
||||
for pattern_name, pattern, reason in _IGNORE_PATTERNS:
|
||||
if pattern.search(message):
|
||||
return IgnoreReason(pattern_name=pattern_name, reason=reason)
|
||||
|
||||
return None
|
||||
@@ -1,429 +0,0 @@
|
||||
"""LLM-powered incident analysis and duplicate detection for the error monitor.
|
||||
|
||||
Uses Gemini Flash via the google-generativeai library to:
|
||||
1. Group related error patterns into incidents with root-cause analysis.
|
||||
2. Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
Both functions fall back gracefully when the LLM is unavailable or returns
|
||||
unparseable output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LLM_ANALYSIS_MODEL,
|
||||
LLM_VERTEX_LOCATION,
|
||||
MIN_PATTERNS_FOR_ANALYSIS,
|
||||
SERVICE_DEPENDENCY_MAP,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dataclasses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Incident:
|
||||
"""A grouped incident produced by LLM analysis or the fallback grouper."""
|
||||
|
||||
title: str
|
||||
root_cause: str | None
|
||||
severity: str # P0 / P1 / P2 / P3
|
||||
suggested_fix: str | None
|
||||
primary_service: str
|
||||
pattern_indices: list[int]
|
||||
|
||||
|
||||
@dataclass
|
||||
class IncidentAnalysis:
|
||||
"""The result of an incident grouping pass."""
|
||||
|
||||
incidents: list[Incident]
|
||||
used_llm: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplicateGroup:
|
||||
"""A canonical pattern plus the new patterns that duplicate it."""
|
||||
|
||||
canonical_index: int
|
||||
duplicate_indices: list[int]
|
||||
reason: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM call helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_RETRY_ATTEMPTS = 3
|
||||
_RETRY_BASE_DELAY = 2.0 # seconds
|
||||
|
||||
|
||||
def _call_llm(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
temperature: float = 0.2,
|
||||
) -> str:
|
||||
"""Call Gemini and return the response text.
|
||||
|
||||
Retries up to _RETRY_ATTEMPTS times with exponential back-off on failure.
|
||||
|
||||
Args:
|
||||
system_prompt: System instruction for the model.
|
||||
user_prompt: User-facing prompt content.
|
||||
temperature: Sampling temperature (lower = more deterministic).
|
||||
|
||||
Returns:
|
||||
The model's response text.
|
||||
|
||||
Raises:
|
||||
Exception: Re-raises the last exception after all retries are exhausted.
|
||||
"""
|
||||
last_exc: Exception | None = None
|
||||
|
||||
for attempt in range(_RETRY_ATTEMPTS):
|
||||
try:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=GCP_PROJECT,
|
||||
location=LLM_VERTEX_LOCATION,
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=LLM_ANALYSIS_MODEL,
|
||||
contents=user_prompt,
|
||||
config=genai_types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=temperature,
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last_exc = exc
|
||||
delay = _RETRY_BASE_DELAY * (2**attempt)
|
||||
logger.warning(
|
||||
"LLM call failed (attempt %d/%d): %s — retrying in %.1fs",
|
||||
attempt + 1,
|
||||
_RETRY_ATTEMPTS,
|
||||
exc,
|
||||
delay,
|
||||
)
|
||||
time.sleep(delay)
|
||||
|
||||
raise last_exc # type: ignore[misc]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Response parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_MD_CODE_BLOCK_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)```", re.IGNORECASE)
|
||||
|
||||
|
||||
def _strip_markdown_code_block(text: str) -> str:
|
||||
"""Remove surrounding ```json ... ``` or ``` ... ``` fences if present."""
|
||||
match = _MD_CODE_BLOCK_RE.search(text)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _parse_llm_response(text: str) -> IncidentAnalysis | None:
|
||||
"""Parse the LLM response text into an IncidentAnalysis.
|
||||
|
||||
Args:
|
||||
text: Raw LLM output, possibly wrapped in a markdown code block.
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis on success, None on any parse failure.
|
||||
"""
|
||||
if not text:
|
||||
return None
|
||||
|
||||
cleaned = _strip_markdown_code_block(text)
|
||||
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("LLM returned non-JSON response (first 200 chars): %.200s", text)
|
||||
return None
|
||||
|
||||
if "incidents" not in data:
|
||||
logger.warning("LLM response missing 'incidents' key: %s", list(data.keys()))
|
||||
return None
|
||||
|
||||
incidents: list[Incident] = []
|
||||
for raw in data["incidents"]:
|
||||
try:
|
||||
incidents.append(
|
||||
Incident(
|
||||
title=raw.get("title", "Unknown incident"),
|
||||
root_cause=raw.get("root_cause"),
|
||||
severity=raw.get("severity", "P2"),
|
||||
suggested_fix=raw.get("suggested_fix"),
|
||||
primary_service=raw.get("primary_service", "unknown"),
|
||||
pattern_indices=raw.get("pattern_indices", []),
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Skipping malformed incident entry: %s — %s", raw, exc)
|
||||
|
||||
return IncidentAnalysis(incidents=incidents, used_llm=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fallback grouper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _fallback_group_by_service(patterns: list[dict]) -> IncidentAnalysis:
|
||||
"""Group patterns by service name when the LLM is unavailable.
|
||||
|
||||
Each unique service becomes one P2 incident containing all of that
|
||||
service's pattern indices.
|
||||
|
||||
Args:
|
||||
patterns: List of error pattern dicts (must include 'service' key).
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis with used_llm=False.
|
||||
"""
|
||||
service_to_indices: dict[str, list[int]] = defaultdict(list)
|
||||
for idx, pattern in enumerate(patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
service_to_indices[service].append(idx)
|
||||
|
||||
incidents = [
|
||||
Incident(
|
||||
title=f"Errors in {service}",
|
||||
root_cause=None,
|
||||
severity="P2",
|
||||
suggested_fix=None,
|
||||
primary_service=service,
|
||||
pattern_indices=indices,
|
||||
)
|
||||
for service, indices in service_to_indices.items()
|
||||
]
|
||||
|
||||
return IncidentAnalysis(incidents=incidents, used_llm=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main analysis functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_ANALYZE_SYSTEM_PROMPT = f"""\
|
||||
You are an expert site-reliability engineer for Nomad Karaoke, a karaoke video
|
||||
generation platform running on Google Cloud Platform.
|
||||
|
||||
Your task is to analyse a list of active error patterns detected across
|
||||
production services, group them into meaningful incidents, and identify root
|
||||
causes.
|
||||
|
||||
## Service dependency map
|
||||
|
||||
{SERVICE_DEPENDENCY_MAP}
|
||||
|
||||
## Severity definitions
|
||||
|
||||
- P0: Service is completely down / total outage
|
||||
- P1: Major pipeline broken — orders cannot complete
|
||||
- P2: Degraded performance — some orders affected
|
||||
- P3: Minor / cosmetic issue with no direct user impact
|
||||
|
||||
## Output format
|
||||
|
||||
Respond with a single JSON object (no markdown fencing) with this schema:
|
||||
|
||||
{{
|
||||
"incidents": [
|
||||
{{
|
||||
"title": "<short human-readable title>",
|
||||
"root_cause": "<root cause or null>",
|
||||
"severity": "P0|P1|P2|P3",
|
||||
"suggested_fix": "<actionable suggestion or null>",
|
||||
"primary_service": "<service name>",
|
||||
"pattern_indices": [<list of 0-based indices from the input list>]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
Group related patterns together into a single incident where they share a
|
||||
common root cause (e.g., a downstream dependency failure). Unrelated patterns
|
||||
should be in separate incidents. Every input pattern must appear in exactly
|
||||
one incident.
|
||||
"""
|
||||
|
||||
_DEDUP_SYSTEM_PROMPT = """\
|
||||
You are an expert at identifying near-duplicate error patterns in production
|
||||
monitoring systems.
|
||||
|
||||
Your task is to compare a list of NEW error patterns against a list of
|
||||
EXISTING (canonical) patterns and identify which new patterns are essentially
|
||||
duplicates of existing ones — i.e., they describe the same underlying error
|
||||
but with slightly different wording due to variation in log messages.
|
||||
|
||||
## Output format
|
||||
|
||||
Respond with a single JSON object (no markdown fencing) with this schema:
|
||||
|
||||
{
|
||||
"duplicates": [
|
||||
{
|
||||
"canonical_index": <0-based index into the EXISTING patterns list>,
|
||||
"duplicate_indices": [<0-based indices into the NEW patterns list>],
|
||||
"reason": "<brief explanation>"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
If no duplicates are found, return {"duplicates": []}.
|
||||
"""
|
||||
|
||||
|
||||
def analyze_patterns(patterns: list[dict]) -> IncidentAnalysis | None:
|
||||
"""Group error patterns into incidents using Gemini LLM analysis.
|
||||
|
||||
Returns None if there are fewer than MIN_PATTERNS_FOR_ANALYSIS patterns.
|
||||
Falls back to service-based grouping when the LLM fails or returns an
|
||||
unparseable response.
|
||||
|
||||
Args:
|
||||
patterns: List of error pattern dicts to analyse.
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis, or None if insufficient patterns.
|
||||
"""
|
||||
if len(patterns) < MIN_PATTERNS_FOR_ANALYSIS:
|
||||
return None
|
||||
|
||||
user_prompt = _build_analyze_user_prompt(patterns)
|
||||
|
||||
try:
|
||||
raw_response = _call_llm(_ANALYZE_SYSTEM_PROMPT, user_prompt, temperature=0.2)
|
||||
result = _parse_llm_response(raw_response)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
logger.warning("LLM returned unparseable response; falling back to service grouping")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("LLM analysis failed: %s — falling back to service grouping", exc)
|
||||
|
||||
return _fallback_group_by_service(patterns)
|
||||
|
||||
|
||||
def find_duplicate_patterns(
|
||||
new_patterns: list[dict],
|
||||
existing_patterns: list[dict],
|
||||
) -> list[DuplicateGroup]:
|
||||
"""Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
Returns an empty list if either input list is empty, or if the LLM call
|
||||
fails for any reason.
|
||||
|
||||
Args:
|
||||
new_patterns: Newly detected error patterns to check.
|
||||
existing_patterns: Currently tracked (canonical) error patterns.
|
||||
|
||||
Returns:
|
||||
List of DuplicateGroup objects (may be empty).
|
||||
"""
|
||||
if not new_patterns or not existing_patterns:
|
||||
return []
|
||||
|
||||
user_prompt = _build_dedup_user_prompt(new_patterns, existing_patterns)
|
||||
|
||||
try:
|
||||
raw_response = _call_llm(_DEDUP_SYSTEM_PROMPT, user_prompt, temperature=0.1)
|
||||
return _parse_duplicate_response(raw_response)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Duplicate detection LLM call failed: %s", exc)
|
||||
return []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt builders
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_analyze_user_prompt(patterns: list[dict]) -> str:
|
||||
"""Build the user prompt listing patterns for incident grouping."""
|
||||
lines = ["Error patterns to analyse:\n"]
|
||||
for idx, pattern in enumerate(patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
count = pattern.get("count", 0)
|
||||
lines.append(f"[{idx}] service={service!r} count={count} message={message!r}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_dedup_user_prompt(
|
||||
new_patterns: list[dict],
|
||||
existing_patterns: list[dict],
|
||||
) -> str:
|
||||
"""Build the user prompt listing existing and new patterns for dedup."""
|
||||
lines = ["EXISTING (canonical) patterns:\n"]
|
||||
for idx, pattern in enumerate(existing_patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
lines.append(f"[{idx}] service={service!r} message={message!r}")
|
||||
|
||||
lines.append("\nNEW patterns to check:\n")
|
||||
for idx, pattern in enumerate(new_patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
lines.append(f"[{idx}] service={service!r} message={message!r}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _parse_duplicate_response(text: str) -> list[DuplicateGroup]:
|
||||
"""Parse the LLM response for duplicate detection.
|
||||
|
||||
Args:
|
||||
text: Raw LLM output.
|
||||
|
||||
Returns:
|
||||
List of DuplicateGroup objects, or [] on any failure.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
cleaned = _strip_markdown_code_block(text)
|
||||
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Dedup LLM returned non-JSON: %.200s", text)
|
||||
return []
|
||||
|
||||
if "duplicates" not in data:
|
||||
logger.warning("Dedup LLM response missing 'duplicates' key")
|
||||
return []
|
||||
|
||||
groups: list[DuplicateGroup] = []
|
||||
for raw in data["duplicates"]:
|
||||
try:
|
||||
groups.append(
|
||||
DuplicateGroup(
|
||||
canonical_index=int(raw["canonical_index"]),
|
||||
duplicate_indices=list(raw.get("duplicate_indices", [])),
|
||||
reason=raw.get("reason", ""),
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Skipping malformed duplicate entry: %s — %s", raw, exc)
|
||||
|
||||
return groups
|
||||
Loaded 100 of 1017 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user