mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
Compare commits
No files matched your search
@@ -14,17 +14,18 @@ name: Build GHA Runner Images
|
||||
# 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.
|
||||
# 5. Delete older images in the family, keeping only the newest (GPU/windows images
|
||||
# are 15-21 GiB each; roll back by re-running this workflow at an older ref).
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
variants:
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
|
||||
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all" (= all except build)'
|
||||
required: false
|
||||
default: 'all'
|
||||
skip_prune:
|
||||
description: 'Skip deprecation of old images (debugging)'
|
||||
description: 'Skip pruning (deletion) of old images (debugging)'
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
@@ -41,7 +42,7 @@ env:
|
||||
BUILD_REGION: us-central1
|
||||
BUILD_ZONE: us-central1-a
|
||||
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
|
||||
KEEP_IMAGES_PER_FAMILY: 3
|
||||
KEEP_IMAGES_PER_FAMILY: 1
|
||||
|
||||
jobs:
|
||||
resolve-matrix:
|
||||
@@ -54,7 +55,10 @@ jobs:
|
||||
run: |
|
||||
requested='${{ github.event.inputs.variants || 'all' }}'
|
||||
if [[ "$requested" == "all" || -z "$requested" ]]; then
|
||||
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
# "build" (docker-build label) is excluded from "all": no job uses it
|
||||
# since deploy-backend moved to ubuntu-latest + Cloud Build
|
||||
# (2026-10-01). Still buildable via an explicit variants=build.
|
||||
echo 'variants=["general","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
|
||||
echo "variants=$json" >> "$GITHUB_OUTPUT"
|
||||
@@ -271,7 +275,7 @@ jobs:
|
||||
run: |
|
||||
gcloud compute instances delete "$VM" --zone="$ZONE" --project="$PROJECT" --quiet || true
|
||||
|
||||
- name: Deprecate old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
|
||||
- name: Prune old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
|
||||
if: ${{ github.event.inputs.skip_prune != 'true' }}
|
||||
env:
|
||||
PROJECT: ${{ env.GCP_PROJECT }}
|
||||
@@ -279,20 +283,45 @@ jobs:
|
||||
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 \
|
||||
# DELETE (not deprecate — deprecated images still bill for storage)
|
||||
# every image in this family beyond the newest $KEEP. The dispatcher
|
||||
# boots from the family URL, which always resolves to the newest image,
|
||||
# so older ones are only rollback insurance (~$0.05/GB-mo; gpu images
|
||||
# are ~21 GB each). Previously this step used an invalid
|
||||
# `-deprecated.state:*` filter: gcloud errored to stderr, stdout was
|
||||
# empty, and it silently reported "Nothing to deprecate" every month
|
||||
# while images piled up (31 runner images, ~$18/mo, by 2026-09).
|
||||
# Match the family EXACTLY client-side: a gcloud `family=gha-runner-gpu`
|
||||
# filter is a word-boundary regex that ALSO matches gha-runner-gpu-windows.
|
||||
# Rank by ACTIVE (non-deprecated) images: the family URL skips deprecated
|
||||
# images, so the newest $KEEP active ones are the real rollback path.
|
||||
# Deprecated images never count toward $KEEP.
|
||||
rows=$(gcloud compute images list \
|
||||
--project="$PROJECT" \
|
||||
--filter="family=$FAMILY AND status=READY AND -deprecated.state:*" \
|
||||
--no-standard-images \
|
||||
--show-deprecated \
|
||||
--sort-by='~creationTimestamp' \
|
||||
--format='value(name)' | tail -n +$((KEEP+1)))
|
||||
if [[ -z "$to_deprecate" ]]; then
|
||||
echo "Nothing to deprecate."
|
||||
--format='value(name,family,deprecated.state)' | awk -v f="$FAMILY" '$2==f')
|
||||
active=$(echo "$rows" | awk 'NF==2 {print $1}')
|
||||
if [[ -z "$active" ]]; then
|
||||
echo "::error::No active images found in family $FAMILY (list failed?) — refusing to prune."
|
||||
exit 1
|
||||
fi
|
||||
keep=$(echo "$active" | head -n "$KEEP")
|
||||
to_delete=$(echo "$rows" | awk '{print $1}' | grep -vxF "$keep" || true)
|
||||
if [[ -z "$to_delete" ]]; then
|
||||
echo "Nothing to prune (<= $KEEP images in $FAMILY)."
|
||||
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"
|
||||
# Never delete an image some existing disk was created from (e.g. a
|
||||
# long-lived VM still on an older image).
|
||||
in_use=$(gcloud compute disks list --project="$PROJECT" \
|
||||
--format='value(sourceImage.basename())' | sort -u)
|
||||
for img in $to_delete; do
|
||||
if grep -qx "$img" <<<"$in_use"; then
|
||||
echo "Keeping $img (source image of an existing disk)"
|
||||
continue
|
||||
fi
|
||||
echo "Deleting $img"
|
||||
gcloud compute images delete "$img" --project="$PROJECT" --quiet
|
||||
done
|
||||
+428
-533
File diff suppressed because it is too large.
Load diff
@@ -55,21 +55,26 @@ jobs:
|
||||
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.
|
||||
# freshness (None = any object).
|
||||
# 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.
|
||||
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. Secrets DO
|
||||
# upload to S3 nightly, so they stay at 36h. GCS job files are NOT
|
||||
# tracked: their off-site copy was stopped 2026-10-01 (egress cost
|
||||
# cut) — they rely on GCS versioning + soft-delete only.
|
||||
# Git repos are also weekly (Sundays) AND incremental since
|
||||
# 2026-09-26 — only repos pushed that week get a fresh bundle, so a
|
||||
# quiet week legitimately leaves every .bundle older than 8 days.
|
||||
# Freshness is judged on git-repos/manifest.json instead (rewritten
|
||||
# every weekly run), and the manifest's contents are checked below so
|
||||
# a run where every repo failed still reads as stale.
|
||||
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"),
|
||||
("Git repos", "git-repos/manifest.json", 192, None),
|
||||
]
|
||||
|
||||
s3 = boto3.client("s3")
|
||||
@@ -97,6 +102,19 @@ jobs:
|
||||
line = f"{label}: {age_h}h old (limit {max_hours}h) — last {latest.isoformat()}"
|
||||
(stale if age > max_hours * 3600 else ok).append(line)
|
||||
|
||||
# Git manifest contents: ANY bundle error alerts, even though the
|
||||
# manifest itself is fresh. The git step is weekly + incremental, so
|
||||
# a repo that failed keeps an ever-older S3 bundle until the next
|
||||
# Sunday — silence here would let it drift past the 7-day RPO.
|
||||
try:
|
||||
import json as _json
|
||||
m = _json.loads(s3.get_object(Bucket=BUCKET, Key="git-repos/manifest.json")["Body"].read())
|
||||
if int(m.get("errors", 0)) > 0:
|
||||
failed = [r.get("full_name") for r in m.get("repos", []) if r.get("status") == "error"]
|
||||
stale.append(f"Git repos: last run had {m.get('errors')} bundle errors: {', '.join(failed[:10])}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
stale.append(f"Git repos: could not read manifest.json ({e})")
|
||||
|
||||
summary = ["## DR backup freshness", ""]
|
||||
if stale:
|
||||
summary.append("### Stale")
|
||||
|
||||
@@ -33,6 +33,11 @@ on:
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
self_heal_force_llm:
|
||||
description: 'Self-healing test: comma-separated Stripe step ids to force through the LLM fallback (e.g. selectCard). Learned recipes still open an auto-merge PR.'
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -46,10 +51,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # keyless GCP auth, only to read the Gemini key for self-healing
|
||||
|
||||
outputs:
|
||||
session_token: ${{ steps.extract_token.outputs.token }}
|
||||
result: ${{ steps.test_result.outputs.result }}
|
||||
failure_reason: ${{ steps.test_result.outputs.failure_reason }}
|
||||
healed: ${{ steps.self_heal.outputs.healed }}
|
||||
env:
|
||||
HAS_GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY != '' }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@@ -74,6 +86,48 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
# ── Self-healing Stripe Checkout: LLM fallback key ───────────────────
|
||||
# The Stripe step runner (frontend/e2e/helpers/self-healing) falls back
|
||||
# to Gemini when every deterministic variant of a step fails. The key is
|
||||
# the AI Studio key (billed outside the nomadkaraoke project). Prefer a
|
||||
# GEMINI_API_KEY repo secret; otherwise read it from Secret Manager via
|
||||
# keyless auth. All of this is best-effort: without a key the test runs
|
||||
# deterministic-only, exactly as before.
|
||||
- name: Authenticate to Google Cloud (Gemini key)
|
||||
id: gcp_auth
|
||||
if: ${{ env.HAS_GEMINI_SECRET != 'true' }}
|
||||
continue-on-error: true
|
||||
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
|
||||
if: steps.gcp_auth.outcome == 'success'
|
||||
continue-on-error: true
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
|
||||
- name: Load Gemini key for self-healing fallback
|
||||
continue-on-error: true
|
||||
env:
|
||||
GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY }}
|
||||
GCP_AUTHED: ${{ steps.gcp_auth.outcome == 'success' }}
|
||||
run: |
|
||||
KEY="$GEMINI_SECRET"
|
||||
if [ -z "$KEY" ] && [ "$GCP_AUTHED" = "true" ]; then
|
||||
KEY=$(gcloud secrets versions access latest --secret=gemini-api-key --project=nomadkaraoke 2>/dev/null || true)
|
||||
fi
|
||||
# Drop the deployer credentials before any test code runs.
|
||||
if [ -n "${GOOGLE_GHA_CREDS_PATH:-}" ]; then rm -f "$GOOGLE_GHA_CREDS_PATH"; fi
|
||||
if [ -n "${CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE:-}" ]; then rm -f "$CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE"; fi
|
||||
if [ -n "$KEY" ]; then
|
||||
echo "::add-mask::$KEY"
|
||||
echo "GEMINI_API_KEY=$KEY" >> "$GITHUB_ENV"
|
||||
echo "Self-healing LLM fallback: enabled"
|
||||
else
|
||||
echo "::warning::Self-healing LLM fallback disabled (no Gemini key) — Stripe steps run deterministic-only"
|
||||
fi
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
@@ -93,9 +147,14 @@ jobs:
|
||||
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 }}
|
||||
E2E_STRIPE_ZIP: ${{ secrets.E2E_STRIPE_ZIP }}
|
||||
E2E_SELF_HEAL_FORCE_LLM: ${{ inputs.self_heal_force_llm || '' }}
|
||||
# No real card available → 'checkout-only' (no charge). Set the repo variable
|
||||
# E2E_REAL_PAYMENT=true to go back to buying a credit with E2E_STRIPE_CARD_*.
|
||||
E2E_PAYMENT_MODE: ${{ vars.E2E_REAL_PAYMENT == 'true' && 'real' || 'checkout-only' }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
|
||||
echo "=== Stage 1: Credit Purchase via Real Stripe (mode: $E2E_PAYMENT_MODE) ==="
|
||||
echo "Time: $(date)"
|
||||
npx playwright test credit-purchase-real.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
@@ -115,8 +174,46 @@ jobs:
|
||||
echo "result=success" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
# A declined card is an issuer/card problem, not a broken checkout —
|
||||
# say so in the alerts (marker comes from e2e/helpers/stripe-checkout.ts).
|
||||
REASON=$(grep -m1 -o 'STRIPE_CARD_DECLINED:.*' frontend/test-output-payment.log 2>/dev/null | sed 's/ — .*//' | tr -d '"\\' || true)
|
||||
if [ -n "$REASON" ]; then
|
||||
echo "failure_reason=Test card declined, not a checkout bug (${REASON#STRIPE_CARD_DECLINED: }). Check the card/issuer for a fraud hold, then re-run." >> "$GITHUB_OUTPUT"
|
||||
echo "::error::$REASON"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Detect self-healed Stripe steps
|
||||
id: self_heal
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
run: |
|
||||
REPORT=test-results/self-heal/self-heal-report.json
|
||||
LEARNED=test-results/self-heal/learned-variants.json
|
||||
if [ -f "$REPORT" ]; then
|
||||
{
|
||||
echo "### Stripe Checkout self-healing"
|
||||
echo '```json'
|
||||
jq '{flowVerified, llmCalls, learnedWritten, added, outcomes: [.outcomes[] | {stepId, status, via, variant, model, reason}]}' "$REPORT"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
# Only promote recipes from a run whose purchase was verified server-side.
|
||||
if [ "${{ steps.test_result.outputs.result }}" = "success" ] && [ -f "$LEARNED" ]; then
|
||||
echo "healed=true" >> "$GITHUB_OUTPUT"
|
||||
echo "::warning::Stripe Checkout changed — LLM fallback healed it; an auto-merge PR will record the new variant"
|
||||
else
|
||||
echo "healed=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload self-heal learned variants
|
||||
if: steps.self_heal.outputs.healed == 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: self-heal-learned-${{ github.run_number }}
|
||||
path: frontend/test-results/self-heal/
|
||||
retention-days: 30
|
||||
|
||||
- name: Extract session token
|
||||
id: extract_token
|
||||
if: steps.test_result.outputs.result == 'success'
|
||||
@@ -132,8 +229,21 @@ jobs:
|
||||
echo "token=" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload artifacts
|
||||
- name: Scrub secrets from artifacts (public repo)
|
||||
id: scrub
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
env:
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
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_SESSION_TOKEN: ${{ steps.extract_token.outputs.token }}
|
||||
run: node e2e/scripts/scrub-artifacts.mjs --drop-videos --blank-inputs test-results test-output-payment.log
|
||||
|
||||
- name: Upload artifacts
|
||||
if: always() && steps.scrub.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-payment-results-${{ github.run_number }}
|
||||
@@ -144,15 +254,180 @@ jobs:
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
env:
|
||||
# Via env + jq, never ${{ }} in the script: the reason contains Stripe's message text.
|
||||
REASON: ${{ steps.test_result.outputs.failure_reason || 'Payment flow is broken. Customers may not be receiving credits.' }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
|
||||
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 }}"
|
||||
jq -n --arg reason "$REASON" --arg run "$RUN_NUMBER" --arg url "$RUN_URL" \
|
||||
'{embeds: [{title: "🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase", description: "\($reason)\n\n**Run:** #\($run)\n**Details:** \($url)", color: 15158332}]}' |
|
||||
curl -s -H "Content-Type: application/json" -d @- "$WEBHOOK"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Self-heal: record LLM-discovered Stripe variants via an auto-merging PR
|
||||
# =========================================================================
|
||||
# One Stripe layout change → one LLM-healed run → one data-only PR (only
|
||||
# learned-variants.json) that auto-merges, so the next run replays the
|
||||
# recipe deterministically. No human in the loop.
|
||||
#
|
||||
# Merge gates for a bot PR (all verified live with #1117, 2026-10-03):
|
||||
# - its `pull_request` CI run is created "action_required" and, until run,
|
||||
# supersedes other CI Gate results → we approve it via the API;
|
||||
# - the `protect main` ruleset's require_extra_approval_for_unattributed_changes
|
||||
# (GitHub default true since ~Aug 2026) would demand a human review for
|
||||
# bot-authored changes → set to false on ruleset 11423976;
|
||||
# - review threads must be resolved → `@coderabbitai ignore` in the body.
|
||||
self-heal-pr:
|
||||
name: "Self-heal: auto-merge PR"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: e2e-credit-purchase
|
||||
# Only learn from main — branch runs (e.g. testing self_heal_force_llm on a
|
||||
# feature branch) must not open PRs against main.
|
||||
if: always() && needs.e2e-credit-purchase.outputs.healed == 'true' && github.ref == 'refs/heads/main'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
actions: write
|
||||
outputs:
|
||||
pr_url: ${{ steps.pr.outputs.pr_url }}
|
||||
unchanged: ${{ steps.pr.outputs.unchanged }}
|
||||
steps:
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
|
||||
- name: Download learned variants
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: self-heal-learned-${{ github.run_number }}
|
||||
path: /tmp/self-heal
|
||||
|
||||
- name: Open auto-merge PR
|
||||
id: pr
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TARGET=frontend/e2e/helpers/self-healing/learned-variants.json
|
||||
|
||||
# A bot-authored PR's `pull_request` CI run is created as
|
||||
# "action_required" (awaiting approval) and, until it runs, supersedes
|
||||
# any other CI Gate result for the ruleset. Approve it; succeed once a
|
||||
# pull_request run exists that is past approval.
|
||||
approve_ci() {
|
||||
local branch=$1 runs pending active
|
||||
for _ in $(seq 1 18); do
|
||||
runs=$(gh run list --workflow ci.yml --branch "$branch" --event pull_request --json databaseId,status,conclusion) || { sleep 10; continue; }
|
||||
pending=$(jq -r '.[] | select(.conclusion == "action_required" or .status == "waiting" or .status == "action_required") | .databaseId' <<<"$runs") || pending=""
|
||||
active=$(jq '[.[] | select(.conclusion != "action_required" and .status != "waiting" and .status != "action_required")] | length' <<<"$runs") || active=0
|
||||
for id in $pending; do
|
||||
if gh api -X POST "repos/${{ github.repository }}/actions/runs/$id/approve" >/dev/null; then
|
||||
echo "Approved CI run $id"
|
||||
else
|
||||
echo "::warning::Could not approve CI run $id with GITHUB_TOKEN"
|
||||
fi
|
||||
done
|
||||
if [ -z "$pending" ] && [ "$active" -gt 0 ]; then
|
||||
echo "CI is running for $branch"
|
||||
return 0
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
return 1
|
||||
}
|
||||
REPORT=/tmp/self-heal/self-heal-report.json
|
||||
|
||||
OPEN=$(gh pr list --label e2e-self-heal --state open --json url --jq '.[0].url // ""')
|
||||
if [ -n "$OPEN" ]; then
|
||||
echo "A self-heal PR is already open ($OPEN) — not opening another; making sure its CI can run"
|
||||
echo "pr_url=$OPEN" >> "$GITHUB_OUTPUT"
|
||||
OPEN_BRANCH=$(gh pr view "$OPEN" --json headRefName --jq .headRefName || true)
|
||||
if [ -z "$OPEN_BRANCH" ] || ! approve_ci "$OPEN_BRANCH"; then
|
||||
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cp /tmp/self-heal/learned-variants.json "$TARGET"
|
||||
if git diff --quiet -- "$TARGET"; then
|
||||
echo "learned-variants.json unchanged vs main — nothing to do"
|
||||
echo "unchanged=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
STEPS=$(jq -r '[.outcomes[] | select(.status == "healed") | .stepId] | unique | join(", ")' "$REPORT")
|
||||
BRANCH="self-heal/stripe-checkout-${{ github.run_id }}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git checkout -b "$BRANCH"
|
||||
git add "$TARGET"
|
||||
git commit -m "test(e2e): self-heal Stripe Checkout steps: $STEPS" -m "Learned by the LLM fallback in $RUN_URL (purchase verified server-side)."
|
||||
git push origin "$BRANCH"
|
||||
|
||||
gh label create e2e-self-heal --color FBCA04 --description "Auto-generated by the self-healing Stripe E2E" 2>/dev/null || true
|
||||
{
|
||||
echo "## 🩹 Stripe Checkout self-heal"
|
||||
echo
|
||||
echo "Stripe changed its hosted checkout page. In [run #${{ github.run_number }}]($RUN_URL) every deterministic variant of **$STEPS** failed; the Gemini fallback completed the step(s), and the purchase was then **verified server-side** (credit granted)."
|
||||
echo
|
||||
echo "This PR only adds the recipe(s) to \`learned-variants.json\`, so future runs replay them deterministically (no LLM). It auto-merges once CI passes."
|
||||
echo
|
||||
echo "### Learned recipes"
|
||||
echo '```json'
|
||||
jq '[.outcomes[] | select(.status == "healed") | {stepId, model, llmCalls, actions}]' "$REPORT"
|
||||
echo '```'
|
||||
echo
|
||||
echo "@coderabbitai ignore"
|
||||
echo
|
||||
echo "🤖 Generated by the E2E Daily self-healing workflow"
|
||||
} > /tmp/pr-body.md
|
||||
|
||||
PR_URL=$(gh pr create --base main --head "$BRANCH" --label e2e-self-heal \
|
||||
--title "test(e2e): self-heal Stripe Checkout ($STEPS)" --body-file /tmp/pr-body.md)
|
||||
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
|
||||
gh pr merge "$PR_URL" --auto --squash
|
||||
|
||||
if approve_ci "$BRANCH"; then
|
||||
echo "Opened $PR_URL (auto-merge enabled, CI approved)"
|
||||
else
|
||||
# Fallback: dispatched CI (allowed from GITHUB_TOKEN) puts a CI Gate
|
||||
# check on the head SHA if no pull_request run ever appears.
|
||||
gh workflow run ci.yml --ref "$BRANCH"
|
||||
echo "ci_needs_approval=true" >> "$GITHUB_OUTPUT"
|
||||
echo "::warning::CI for $PR_URL may need a one-click approval (PR → Checks → Approve and run)"
|
||||
fi
|
||||
|
||||
- name: Discord notification (self-heal)
|
||||
# Recipe already on main (e.g. merged between checkout and now) → nothing to report.
|
||||
if: always() && steps.pr.outputs.unchanged != 'true'
|
||||
run: |
|
||||
PR="${{ steps.pr.outputs.pr_url }}"
|
||||
if [ -n "$PR" ] && [ "${{ steps.pr.outputs.ci_needs_approval }}" = "true" ]; then
|
||||
TITLE="🩹 E2E self-healed Stripe — PR needs a CI approval click"
|
||||
DESC="LLM fallback healed a Stripe Checkout change. The auto-merge PR's CI run awaits approval (open the PR → Checks → Approve and run): $PR"
|
||||
COLOR=16776960
|
||||
elif [ -n "$PR" ]; then
|
||||
TITLE="🩹 E2E self-healed a Stripe Checkout change"
|
||||
DESC="Stripe changed its checkout page; the LLM fallback got through and the purchase was verified. Auto-merge PR: $PR"
|
||||
COLOR=16776960
|
||||
else
|
||||
TITLE="⚠️ E2E self-heal PR could not be opened"
|
||||
DESC="The LLM fallback healed a Stripe step but opening the PR failed — see the run."
|
||||
COLOR=15105570
|
||||
fi
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"$TITLE\", \"description\": \"$DESC\n\n**Run:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": $COLOR}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
# =========================================================================
|
||||
# Stage 2: Happy Path (uses credit from Stage 1)
|
||||
# =========================================================================
|
||||
@@ -254,8 +529,19 @@ jobs:
|
||||
echo "result=failure" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
- name: Scrub secrets from artifacts (public repo)
|
||||
id: scrub
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
env:
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
|
||||
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report test-output-happy-path.log
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always() && steps.scrub.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-results-${{ github.run_number }}
|
||||
@@ -266,7 +552,7 @@ jobs:
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload video recordings
|
||||
if: always()
|
||||
if: always() && steps.scrub.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-videos-${{ github.run_number }}
|
||||
@@ -309,7 +595,7 @@ jobs:
|
||||
notify:
|
||||
name: "Notify"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [e2e-credit-purchase, e2e-happy-path]
|
||||
needs: [e2e-credit-purchase, e2e-happy-path, self-heal-pr]
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
@@ -336,8 +622,9 @@ jobs:
|
||||
E2E Daily Test Results
|
||||
======================
|
||||
|
||||
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
|
||||
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}${{ vars.E2E_REAL_PAYMENT != 'true' && ' [checkout-only: no real payment]' || '' }}${{ needs.e2e-credit-purchase.outputs.failure_reason && format(' — {0}', needs.e2e-credit-purchase.outputs.failure_reason) || '' }}
|
||||
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
|
||||
Stripe self-heal: ${{ needs.e2e-credit-purchase.outputs.healed == 'true' && format('Stripe changed its checkout; LLM fallback healed it. Auto-merge PR: {0}', needs.self-heal-pr.outputs.pr_url || (needs.self-heal-pr.outputs.unchanged == 'true' && '(already on main)' || '(failed to open — see run)')) || 'not needed' }}
|
||||
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
|
||||
@@ -83,8 +83,17 @@ jobs:
|
||||
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload logs
|
||||
- name: Scrub secrets from artifacts (public repo)
|
||||
id: scrub
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
env:
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report e2e-output.log
|
||||
|
||||
- name: Upload logs
|
||||
if: always() && steps.scrub.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
name: PyPI prune reminder
|
||||
|
||||
# PyPI caps total *project* size at 10 GB. karaoke-gen auto-publishes a ~62 MiB
|
||||
# wheel on every merge to main (~3 GB/month), so the project refills the cap
|
||||
# every few months and `poetry publish` then fails with "Project size too large".
|
||||
# PyPI caps total *project* size at 10 GB. karaoke-gen publishes a ~62 MiB wheel
|
||||
# whenever CLI code changes (scripts/pypi_publish_gate.py), so the project slowly
|
||||
# refills the cap and `poetry publish` then fails with "Project size too large".
|
||||
#
|
||||
# PyPI has NO deletion API (upload tokens are upload-only), so this can't
|
||||
# auto-delete. Instead it runs monthly, computes the retention plan
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PROJECT: karaoke-gen
|
||||
KEEP_DAYS: "60"
|
||||
KEEP_DAYS: "30"
|
||||
# Only nag once the project crosses this watermark — pruning holds it at
|
||||
# ~4-7 GB, and there are always old releases to consolidate, so without a
|
||||
# threshold this would open an issue every month for no real reason. 7 GB
|
||||
|
||||
@@ -92,6 +92,7 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
|
||||
### Infrastructure
|
||||
- **All GCP changes via Pulumi PRs** - changes in `infrastructure/` deploy automatically on merge to main
|
||||
- **`infrastructure/` is the shared platform IaC home**: the GCP project (`infrastructure/`) and the Nomad Karaoke Cloudflare account (`infrastructure/cloudflare/`, own Pulumi project + stack, see its README). Never hand-edit Cloudflare config that stack manages; app repos keep only app-specific stacks
|
||||
- **Always run `pulumi up` locally BEFORE merging PRs** - CI deploys run on spot VMs that can be preempted mid-apply, causing partial state. Apply locally first, then merge (CI re-runs as no-op)
|
||||
- Never modify GCP resources directly via console or `gcloud` CLI
|
||||
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
|
||||
@@ -112,7 +113,7 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- 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
|
||||
- Translation uses Gemini 3.8 Flash via the **Gemini Developer API** (key: `GEMINI_API_KEY`, else Secret Manager `gemini-api-key` via your gcloud login — `frontend/scripts/gemini_client.py`) with GCS cache for efficiency. **Vertex AI is disabled in the GCP project — never use `vertexai=True`; backend code uses `backend/services/gemini_client.get_genai_client()`.**
|
||||
- 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')`
|
||||
@@ -149,9 +150,12 @@ 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
|
||||
The worker is a **Spot** c4d-highcpu-16 blue-green primary pair (`encoding-worker-a`/`-b`,
|
||||
us-central1-c) plus ONE stopped on-demand fallback (`encoding-worker-fallback-c2df`,
|
||||
c2d-highcpu-16, us-central1-f) — 3 VMs since 2026-09-26. Idle VMs stop after 5 min.
|
||||
CI blue-green redeploys the worker only when worker code changed
|
||||
(`infrastructure/encoding-worker/worker_code_paths.txt`); force it via Actions → CI →
|
||||
Run workflow → "Force a blue-green redeploy of the GCE encoding worker". 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
|
||||
|
||||
@@ -73,6 +73,18 @@ RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pip install --upgrade pip && \
|
||||
pip install -e .
|
||||
|
||||
# Pre-build matplotlib's font cache at BUILD time. Without it, the first
|
||||
# `import matplotlib.pyplot` on every new Cloud Run instance scanned all the
|
||||
# Noto fonts above (20-40s of GIL-holding CPU) and froze the API's event loop
|
||||
# — prod logged "Matplotlib is building the font cache" in 17 of 28
|
||||
# "servers unavailable" banner episodes (2026-10-03 analysis). The cache lives
|
||||
# in MPLCONFIGDIR so it ships in the image instead of the in-memory $HOME.
|
||||
ENV MPLCONFIGDIR=/opt/mplconfig
|
||||
RUN mkdir -p /opt/mplconfig && \
|
||||
python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.font_manager as fm; print(len(fm.fontManager.ttflist), 'fonts cached')" && \
|
||||
ls /opt/mplconfig/fontlist-*.json && \
|
||||
chmod -R a+rwX /opt/mplconfig
|
||||
|
||||
# Now copy actual source code (AFTER deps installed, so code changes don't
|
||||
# invalidate the expensive pip install layer in registry cache)
|
||||
COPY karaoke_gen /app/karaoke_gen
|
||||
|
||||
@@ -311,6 +311,10 @@ def require_review_auth_factory(job_id_param: str = "job_id"):
|
||||
)
|
||||
|
||||
logger.info(f"Review access granted via full auth ({auth_result.user_type}) for job {job_id}")
|
||||
# Who is reviewing — handlers record it on first open
|
||||
# (state_data.review_started_by, see JobManager.record_review_started).
|
||||
request.state.review_auth_email = auth_result.user_email
|
||||
request.state.review_auth_is_admin = bool(auth_result.is_admin)
|
||||
return job_id, "full"
|
||||
|
||||
# Try review token
|
||||
|
||||
+273
-124
@@ -21,6 +21,7 @@ from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.tempo_label import strip_tempo_suffix
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.audio_search_service import get_audio_search_service, NoResultsError, AudioSearchError
|
||||
@@ -97,6 +98,8 @@ class JobUpdateRequest(BaseModel):
|
||||
review_mode: Optional[str] = None
|
||||
# Backing-vocals preference: "auto" | "clean" | "review"
|
||||
backing_preference: Optional[str] = None
|
||||
# Translated lyrics language code ("" turns it off)
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
# Editable boolean fields
|
||||
enable_cdg: Optional[bool] = None
|
||||
@@ -135,6 +138,7 @@ EDITABLE_JOB_FIELDS = {
|
||||
"is_private",
|
||||
"review_mode",
|
||||
"backing_preference",
|
||||
"translation_language",
|
||||
# Exempts a job from the stale-review auto-expiry (48h cancel+refund) —
|
||||
# the stale_review_processor skips made_for_you jobs. Used for admin-driven
|
||||
# batches (e.g. KaraokeHunt outreach) that must wait at review indefinitely.
|
||||
@@ -142,6 +146,13 @@ EDITABLE_JOB_FIELDS = {
|
||||
}
|
||||
|
||||
|
||||
def _tempo_label_reset_updates(job) -> dict:
|
||||
"""Updates that undo an audio-editor tempo label (for resets that restore normal-speed audio)."""
|
||||
if getattr(job, "tempo_factor", None) is None:
|
||||
return {}
|
||||
return {"title": strip_tempo_suffix(job.title), "tempo_factor": None}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Stats Endpoints
|
||||
# =============================================================================
|
||||
@@ -452,7 +463,7 @@ class CacheStatsResponse(BaseModel):
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/audio-searches", response_model=AudioSearchListResponse)
|
||||
async def list_audio_searches(
|
||||
def list_audio_searches(
|
||||
limit: int = 50,
|
||||
status_filter: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
@@ -659,7 +670,7 @@ async def clear_audio_search_cache(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/reset-worker-state")
|
||||
async def reset_worker_state(
|
||||
def reset_worker_state(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -869,7 +880,7 @@ def _extract_files_recursive(
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/files", response_model=JobFilesResponse)
|
||||
async def get_job_files(
|
||||
def get_job_files(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -1013,6 +1024,16 @@ async def update_job(
|
||||
detail='review_mode must be "auto" or "always_review"',
|
||||
)
|
||||
|
||||
# Translated lyrics: "" / null turns it off; otherwise a supported language code
|
||||
if "translation_language" in updates:
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
|
||||
raw = updates["translation_language"]
|
||||
code = normalize_language(raw) if raw else None
|
||||
if raw and code is None:
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported translation_language: {raw}")
|
||||
updates["translation_language"] = code
|
||||
|
||||
# backing_preference likewise gates the instrumental decision — reject typos.
|
||||
if "backing_preference" in updates and updates["backing_preference"] not in (
|
||||
"auto", "clean", "review",
|
||||
@@ -1054,7 +1075,7 @@ async def update_job(
|
||||
f"Auto-deleting outputs for job {job_id} (toggled to private by {admin_email})"
|
||||
)
|
||||
# Call the delete-outputs endpoint directly (same module)
|
||||
await delete_job_outputs(job_id, auth_data)
|
||||
await asyncio.to_thread(delete_job_outputs, job_id, auth_data)
|
||||
auto_deleted = True
|
||||
except HTTPException:
|
||||
# delete_job_outputs raises HTTPException on validation failures,
|
||||
@@ -1302,6 +1323,9 @@ async def reset_job(
|
||||
# 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)
|
||||
# A reset starts a new run: drop any failed admin re-render's marker.
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
clear_updates.update(clear_admin_rerender_update(job))
|
||||
|
||||
# Add timeline event
|
||||
clear_updates["timeline"] = ArrayUnion([timeline_event])
|
||||
@@ -1317,6 +1341,8 @@ async def reset_job(
|
||||
f"Admin reset job {job_id}: Restoring input_media_gcs_path "
|
||||
f"to original: {original_path}"
|
||||
)
|
||||
# The original audio is back at its normal speed, so drop any tempo label.
|
||||
clear_updates.update(_tempo_label_reset_updates(job))
|
||||
|
||||
# Execute the update
|
||||
job_ref.update(clear_updates)
|
||||
@@ -1562,7 +1588,7 @@ ALL_WORKER_PROGRESS_KEYS = [
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/clear-workers", response_model=ClearWorkersResponse)
|
||||
async def clear_worker_state(
|
||||
def clear_worker_state(
|
||||
job_id: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -1650,7 +1676,7 @@ TERMINAL_STATES = {"complete", "prep_complete", "failed", "cancelled"}
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/delete-outputs", response_model=DeleteOutputsResponse)
|
||||
async def delete_job_outputs(
|
||||
def delete_job_outputs(
|
||||
job_id: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -1675,7 +1701,6 @@ async def delete_job_outputs(
|
||||
Returns:
|
||||
Deletion results for each service
|
||||
"""
|
||||
import re
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
@@ -1701,97 +1726,29 @@ async def delete_job_outputs(
|
||||
)
|
||||
|
||||
state_data = job.state_data or {}
|
||||
results = {
|
||||
"youtube": {"status": "skipped", "reason": "no youtube_url in state_data"},
|
||||
"dropbox": {"status": "skipped", "reason": "no brand_code or dropbox_path"},
|
||||
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
|
||||
}
|
||||
from backend.services.published_outputs_cleanup import (
|
||||
delete_dropbox_folder,
|
||||
delete_gdrive_files,
|
||||
delete_youtube_video,
|
||||
snapshot_published_outputs,
|
||||
)
|
||||
|
||||
# Snapshot current outputs before cleanup (preserved in timeline metadata)
|
||||
deleted_outputs = {}
|
||||
if state_data.get('youtube_url'):
|
||||
deleted_outputs['youtube_url'] = state_data['youtube_url']
|
||||
if state_data.get('dropbox_link'):
|
||||
deleted_outputs['dropbox_link'] = state_data['dropbox_link']
|
||||
if state_data.get('brand_code'):
|
||||
deleted_outputs['brand_code'] = state_data['brand_code']
|
||||
if state_data.get('gdrive_files'):
|
||||
deleted_outputs['gdrive_files'] = state_data['gdrive_files']
|
||||
deleted_outputs = snapshot_published_outputs(state_data)
|
||||
|
||||
log_to_job(job_id, "admin", "INFO", f"Output deletion initiated by {admin_email}", {"deleted_outputs": deleted_outputs})
|
||||
|
||||
# Clean up YouTube
|
||||
youtube_url = state_data.get('youtube_url')
|
||||
if youtube_url:
|
||||
try:
|
||||
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
|
||||
if video_id_match:
|
||||
video_id = video_id_match.group(1)
|
||||
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
youtube_service = get_youtube_service()
|
||||
if youtube_service.is_configured:
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict()
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
results["youtube"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"video_id": video_id
|
||||
}
|
||||
else:
|
||||
results["youtube"] = {"status": "skipped", "reason": "YouTube credentials not configured"}
|
||||
else:
|
||||
results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
|
||||
results["youtube"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Dropbox
|
||||
# Shared helpers (same as Edit / admin re-render): the Dropbox folder name is
|
||||
# sanitised exactly like the uploader names it.
|
||||
brand_code = state_data.get('brand_code')
|
||||
dropbox_path = getattr(job, 'dropbox_path', None)
|
||||
if brand_code and dropbox_path:
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
dropbox = get_dropbox_service()
|
||||
if dropbox.is_configured:
|
||||
base_name = f"{job.artist} - {job.title}"
|
||||
folder_name = f"{brand_code} - {base_name}"
|
||||
full_path = f"{dropbox_path}/{folder_name}"
|
||||
success = dropbox.delete_folder(full_path)
|
||||
results["dropbox"] = {
|
||||
"status": "success" if success else "failed",
|
||||
"path": full_path
|
||||
}
|
||||
else:
|
||||
results["dropbox"] = {"status": "skipped", "reason": "Dropbox credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
|
||||
results["dropbox"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Clean up Google Drive
|
||||
gdrive_files = state_data.get('gdrive_files')
|
||||
if gdrive_files:
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
gdrive = get_gdrive_service()
|
||||
if gdrive.is_configured:
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
results["gdrive"] = {
|
||||
"status": "success" if all_success else "partial",
|
||||
"files": delete_results
|
||||
}
|
||||
else:
|
||||
results["gdrive"] = {"status": "skipped", "reason": "Google Drive credentials not configured"}
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
|
||||
results["gdrive"] = {"status": "error", "error": str(e)}
|
||||
results = {
|
||||
"youtube": delete_youtube_video(job_id, state_data.get('youtube_url')),
|
||||
"dropbox": delete_dropbox_folder(
|
||||
job_id, getattr(job, 'dropbox_path', None), brand_code, job.artist, job.title
|
||||
),
|
||||
# Mirror cleanup happens below for any brand_code, Drive files or not.
|
||||
"gdrive": delete_gdrive_files(job_id, state_data.get('gdrive_files'), brand_code, cleanup_mirror=False),
|
||||
}
|
||||
|
||||
# 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.
|
||||
@@ -1819,7 +1776,8 @@ async def delete_job_outputs(
|
||||
# Recycle brand code if Dropbox and GDrive cleanup both succeeded
|
||||
dropbox_success = results["dropbox"]["status"] in ("success", "skipped")
|
||||
gdrive_success = results["gdrive"]["status"] in ("success", "skipped")
|
||||
if brand_code and dropbox_success and gdrive_success:
|
||||
from backend.services.brand_code_service import is_preserved_brand_code
|
||||
if brand_code and dropbox_success and gdrive_success and not is_preserved_brand_code(job, brand_code):
|
||||
try:
|
||||
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
|
||||
prefix, number = BrandCodeService.parse_brand_code(brand_code)
|
||||
@@ -1829,6 +1787,8 @@ async def delete_job_outputs(
|
||||
except (ValueError, Exception) as e:
|
||||
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
|
||||
results["brand_code"] = {"status": "failed", "error": str(e)}
|
||||
elif brand_code and is_preserved_brand_code(job, brand_code):
|
||||
results["brand_code"] = {"status": "skipped", "reason": "Tenant-supplied code (not allocated)"}
|
||||
elif brand_code:
|
||||
logger.warning(f"Brand code {brand_code} NOT recycled: cleanup incomplete (dropbox={results['dropbox']['status']}, gdrive={results['gdrive']['status']})")
|
||||
results["brand_code"] = {"status": "skipped", "reason": "Dropbox/GDrive cleanup incomplete"}
|
||||
@@ -1851,6 +1811,9 @@ async def delete_job_outputs(
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
cleared_keys.append(key)
|
||||
# Outputs are gone; a failed admin re-render's marker no longer applies.
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
update_payload.update(clear_admin_rerender_update(job))
|
||||
|
||||
# Add timeline event with structured metadata
|
||||
timeline_event = {
|
||||
@@ -1921,7 +1884,7 @@ class OrphanedOutputsCleanupRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/orphaned-outputs/cleanup")
|
||||
async def cleanup_orphaned_outputs(
|
||||
def cleanup_orphaned_outputs(
|
||||
req: OrphanedOutputsCleanupRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
) -> dict:
|
||||
@@ -2039,7 +2002,7 @@ async def cleanup_orphaned_outputs(
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
|
||||
async def get_job_completion_message(
|
||||
def get_job_completion_message(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -2103,7 +2066,7 @@ async def get_job_completion_message(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/send-completion-email", response_model=SendCompletionEmailResponse)
|
||||
async def send_job_completion_email(
|
||||
def send_job_completion_email(
|
||||
job_id: str,
|
||||
request: SendCompletionEmailRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -2181,7 +2144,7 @@ class MintLoginLinkRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/users/{email}/login-link")
|
||||
async def mint_user_login_link(
|
||||
def mint_user_login_link(
|
||||
email: str,
|
||||
request: MintLoginLinkRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2220,7 +2183,7 @@ class ImpersonateUserResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/users/{email}/impersonate", response_model=ImpersonateUserResponse)
|
||||
async def impersonate_user(
|
||||
def impersonate_user(
|
||||
email: str,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -2438,6 +2401,135 @@ async def regenerate_screens(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Regenerate (storage retention) Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class AdminRegenerateRequest(BaseModel):
|
||||
"""Request body for POST /api/admin/jobs/{job_id}/regenerate."""
|
||||
notify_customer: bool = Field(
|
||||
False, description="Email/push the customer when the regenerate completes",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/regenerate")
|
||||
async def admin_regenerate_job(
|
||||
job_id: str,
|
||||
body: Optional[AdminRegenerateRequest] = None,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Rebuild a completed job's GCS outputs (storage retention), admin only.
|
||||
|
||||
Re-separates stems first if they were purged, then regenerates screens,
|
||||
the lyrics video, every final and the packages in GCS. Unlike
|
||||
``/rerender`` nothing is deleted or re-published (YouTube/Dropbox/GDrive
|
||||
untouched, same brand code). No rate limit.
|
||||
"""
|
||||
from backend.services.regenerate_service import RegenerateService
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
|
||||
body = body or AdminRegenerateRequest()
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
job_manager = JobManager()
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
try:
|
||||
result = await RegenerateService(job_manager).start(
|
||||
job, requested_by=admin_email, source="admin", notify_customer=body.notify_customer,
|
||||
)
|
||||
except RerenderError as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
return {
|
||||
"status": "processing",
|
||||
"job_id": job_id,
|
||||
"needs_stems": result["needs_stems"],
|
||||
"notify_customer": body.notify_customer,
|
||||
"message": "Regenerate started (GCS only; nothing re-published).",
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Re-render Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class AdminRerenderRequest(BaseModel):
|
||||
"""Request body for POST /api/admin/jobs/{job_id}/rerender."""
|
||||
notify_customer: bool = Field(
|
||||
False,
|
||||
description="Email/push the customer when the re-render completes (default: no notification)",
|
||||
)
|
||||
|
||||
|
||||
class AdminRerenderResponse(BaseModel):
|
||||
"""Response from the admin re-render endpoint."""
|
||||
status: str
|
||||
job_id: str
|
||||
message: str
|
||||
brand_code: Optional[str] = None
|
||||
notify_customer: bool
|
||||
previous_outputs: Dict[str, Any]
|
||||
cleanup_results: Dict[str, Any]
|
||||
warnings: List[str] = []
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/rerender", response_model=AdminRerenderResponse)
|
||||
async def admin_rerender_job(
|
||||
job_id: str,
|
||||
body: Optional[AdminRerenderRequest] = None,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Re-render a completed job end to end without review (admin only).
|
||||
|
||||
Regenerates title/end screens, the karaoke video, every encoded format and
|
||||
the CDG/TXT packages from the job's existing reviewed lyrics and
|
||||
instrumental selection, with the job's existing style snapshot. Published
|
||||
outputs (YouTube video, Google Drive files, Dropbox folder) the re-render
|
||||
will re-publish are deleted up front and re-published under the SAME brand
|
||||
code when the pipeline finishes (the YouTube URL changes); outputs for
|
||||
destinations no longer configured are left in place (see ``warnings``).
|
||||
The customer (and Discord / community voters) are only notified on
|
||||
completion when ``notify_customer`` is true.
|
||||
|
||||
Works for tenant and consumer, public and private jobs in ``complete``
|
||||
status (or ``failed`` after a previous admin re-render).
|
||||
"""
|
||||
from backend.services.admin_rerender_service import AdminRerenderService
|
||||
from backend.services.theme_rerender_service import RerenderError
|
||||
|
||||
body = body or AdminRerenderRequest()
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
job_manager = JobManager()
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
try:
|
||||
result = await AdminRerenderService(job_manager).start(
|
||||
job, requested_by=admin_email, notify_customer=body.notify_customer
|
||||
)
|
||||
except RerenderError as e:
|
||||
logger.warning(f"Admin {admin_email} re-render of job {job_id} rejected ({e.status_code}): {e}")
|
||||
raise HTTPException(status_code=e.status_code, detail=str(e))
|
||||
|
||||
logger.info(
|
||||
f"Admin {admin_email} started re-render of job {job_id} "
|
||||
f"(notify_customer={body.notify_customer}, brand_code={result['brand_code']})"
|
||||
)
|
||||
return AdminRerenderResponse(
|
||||
status="processing",
|
||||
job_id=job_id,
|
||||
message="Re-render started. Published outputs will be replaced when it completes.",
|
||||
brand_code=result["brand_code"],
|
||||
notify_customer=body.notify_customer,
|
||||
previous_outputs=result["previous_outputs"],
|
||||
cleanup_results=result["cleanup_results"],
|
||||
warnings=result.get("warnings") or [],
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Restart Job Endpoint
|
||||
# =============================================================================
|
||||
@@ -2528,6 +2620,12 @@ async def restart_job(
|
||||
workers_triggered = []
|
||||
error_msg = None
|
||||
|
||||
# A restart starts a new run: drop any failed admin re-render's marker —
|
||||
# folded into the restart's own atomic update below, so a restart that is
|
||||
# rejected (e.g. 400 on preserve_audio_stems) keeps the marker.
|
||||
from backend.services.admin_rerender_service import clear_admin_rerender_update
|
||||
marker_clear = clear_admin_rerender_update(job)
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
db = job_manager.firestore.db
|
||||
job_ref = db.collection("jobs").document(job_id)
|
||||
@@ -2580,6 +2678,9 @@ async def restart_job(
|
||||
]
|
||||
|
||||
update_payload = {}
|
||||
update_payload.update(marker_clear)
|
||||
if marker_clear:
|
||||
cleared_keys.append("admin_rerender")
|
||||
for key in keys_to_clear:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
@@ -2633,6 +2734,9 @@ async def restart_job(
|
||||
]
|
||||
|
||||
update_payload = {}
|
||||
update_payload.update(marker_clear)
|
||||
if marker_clear:
|
||||
cleared_keys.append("admin_rerender")
|
||||
for key in keys_to_clear:
|
||||
if key in state_data:
|
||||
update_payload[f"state_data.{key}"] = DELETE_FIELD
|
||||
@@ -2811,7 +2915,7 @@ OVERRIDE_AUDIO_ALLOWED_STATES = {
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/override-audio-source", response_model=OverrideAudioSourceResponse)
|
||||
async def override_audio_source(
|
||||
def override_audio_source(
|
||||
job_id: str,
|
||||
request: OverrideAudioSourceRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2905,9 +3009,12 @@ async def override_audio_source(
|
||||
update_payload["error_message"] = DELETE_FIELD
|
||||
update_payload["error_details"] = DELETE_FIELD
|
||||
|
||||
# Fresh audio will be at normal speed: drop any tempo label from the title
|
||||
update_payload.update(_tempo_label_reset_updates(job))
|
||||
|
||||
# Set audio search fields based on current artist/title
|
||||
search_artist = job.artist
|
||||
search_title = job.title
|
||||
search_title = strip_tempo_suffix(job.title) if getattr(job, "tempo_factor", None) is not None else job.title
|
||||
update_payload["audio_search_artist"] = search_artist
|
||||
update_payload["audio_search_title"] = search_title
|
||||
|
||||
@@ -3113,7 +3220,7 @@ class WebhookEventItem(BaseModel):
|
||||
|
||||
|
||||
@router.get("/payments/summary", response_model=RevenueSummaryResponse)
|
||||
async def get_payment_summary(
|
||||
def get_payment_summary(
|
||||
days: int = 30,
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -3128,7 +3235,7 @@ async def get_payment_summary(
|
||||
|
||||
|
||||
@router.get("/payments/revenue-chart", response_model=List[RevenueChartPoint])
|
||||
async def get_revenue_chart(
|
||||
def get_revenue_chart(
|
||||
days: int = 30,
|
||||
group_by: str = "day",
|
||||
exclude_test: bool = True,
|
||||
@@ -3141,7 +3248,7 @@ async def get_revenue_chart(
|
||||
|
||||
|
||||
@router.get("/payments", response_model=PaymentListResponse)
|
||||
async def list_payments(
|
||||
def list_payments(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
order_type: Optional[str] = None,
|
||||
@@ -3161,7 +3268,7 @@ async def list_payments(
|
||||
|
||||
|
||||
@router.get("/payments/balance", response_model=StripeBalanceResponse)
|
||||
async def get_stripe_balance(
|
||||
def get_stripe_balance(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get current Stripe account balance."""
|
||||
@@ -3171,7 +3278,7 @@ async def get_stripe_balance(
|
||||
|
||||
|
||||
@router.get("/payments/payouts", response_model=List[PayoutItem])
|
||||
async def get_payouts(
|
||||
def get_payouts(
|
||||
limit: int = 20,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3182,7 +3289,7 @@ async def get_payouts(
|
||||
|
||||
|
||||
@router.get("/payments/disputes", response_model=List[DisputeItem])
|
||||
async def get_disputes(
|
||||
def get_disputes(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get open and recent disputes."""
|
||||
@@ -3192,7 +3299,7 @@ async def get_disputes(
|
||||
|
||||
|
||||
@router.get("/payments/webhook-events", response_model=List[WebhookEventItem])
|
||||
async def get_webhook_events(
|
||||
def get_webhook_events(
|
||||
limit: int = 50,
|
||||
event_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
@@ -3205,7 +3312,7 @@ async def get_webhook_events(
|
||||
|
||||
|
||||
@router.get("/payments/by-user/{email}")
|
||||
async def get_user_payments(
|
||||
def get_user_payments(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3216,7 +3323,7 @@ async def get_user_payments(
|
||||
|
||||
|
||||
@router.get("/users/{email}/emails")
|
||||
async def get_user_emails(
|
||||
def get_user_emails(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3227,7 +3334,7 @@ async def get_user_emails(
|
||||
|
||||
|
||||
@router.get("/emails/{message_id}")
|
||||
async def get_email_detail(
|
||||
def get_email_detail(
|
||||
message_id: str,
|
||||
source: str = "postmark",
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -3247,7 +3354,7 @@ async def get_email_detail(
|
||||
|
||||
|
||||
@router.get("/payments/{session_id}")
|
||||
async def get_payment_detail(
|
||||
def get_payment_detail(
|
||||
session_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
@@ -3261,7 +3368,7 @@ async def get_payment_detail(
|
||||
|
||||
|
||||
@router.post("/payments/{session_id}/refund", response_model=RefundResponse)
|
||||
async def refund_payment(
|
||||
def refund_payment(
|
||||
session_id: str,
|
||||
request: RefundRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -3319,7 +3426,7 @@ async def refund_payment(
|
||||
|
||||
|
||||
@router.post("/payments/normalize-emails")
|
||||
async def normalize_payment_emails(
|
||||
def normalize_payment_emails(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""One-time backfill: lowercase all customer_email values in stripe_payments."""
|
||||
@@ -3329,7 +3436,7 @@ async def normalize_payment_emails(
|
||||
|
||||
|
||||
@router.post("/backfill/user-stats")
|
||||
async def backfill_user_stats(
|
||||
def backfill_user_stats(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""One-time backfill: recalculate total_jobs_completed and total_spent for all users."""
|
||||
@@ -3822,7 +3929,7 @@ async def get_audio_edit_review_detail(
|
||||
|
||||
|
||||
@router.get("/abuse/related/{email}")
|
||||
async def find_related_accounts(
|
||||
def find_related_accounts(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -3872,7 +3979,7 @@ async def find_related_accounts(
|
||||
|
||||
|
||||
@router.get("/abuse/correlations")
|
||||
async def find_account_correlations(
|
||||
def find_account_correlations(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -3922,7 +4029,7 @@ async def find_account_correlations(
|
||||
|
||||
|
||||
@router.get("/abuse/suspicious")
|
||||
async def find_suspicious_accounts(
|
||||
def find_suspicious_accounts(
|
||||
min_jobs: int = 2,
|
||||
max_spend: int = 0,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
@@ -3961,7 +4068,7 @@ async def find_suspicious_accounts(
|
||||
|
||||
|
||||
@router.get("/abuse/by-ip/{ip_address:path}")
|
||||
async def find_users_by_ip(
|
||||
def find_users_by_ip(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -3986,7 +4093,7 @@ async def find_users_by_ip(
|
||||
|
||||
|
||||
@router.get("/abuse/by-fingerprint/{fingerprint}")
|
||||
async def find_users_by_fingerprint(
|
||||
def find_users_by_fingerprint(
|
||||
fingerprint: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -4011,7 +4118,7 @@ async def find_users_by_fingerprint(
|
||||
|
||||
|
||||
@router.post("/abuse/backfill-ips")
|
||||
async def backfill_signup_ips(
|
||||
def backfill_signup_ips(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -4110,7 +4217,7 @@ class IpBatchRequest(BaseModel):
|
||||
|
||||
|
||||
@router.get("/abuse/ip-info/{ip_address:path}")
|
||||
async def get_ip_info(
|
||||
def get_ip_info(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -4120,7 +4227,7 @@ async def get_ip_info(
|
||||
|
||||
|
||||
@router.post("/abuse/ip-info/batch")
|
||||
async def get_ip_info_batch(
|
||||
def get_ip_info_batch(
|
||||
request: IpBatchRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -4262,7 +4369,7 @@ class CommunityRequestListResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/community-requests", response_model=CommunityRequestListResponse)
|
||||
async def list_community_requests(
|
||||
def list_community_requests(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Full history of requests-board submissions across every status — who asked,
|
||||
@@ -4316,7 +4423,7 @@ class CommunityReviewActionResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/community-reviews", response_model=CommunityReviewListResponse)
|
||||
async def list_community_reviews(
|
||||
def list_community_reviews(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List requests-board picks the daily picker flagged because an existing
|
||||
@@ -4401,3 +4508,45 @@ async def action_community_review(
|
||||
status="made", request_id=request_id,
|
||||
message=f"Making our version (job {result.get('job_id')}).",
|
||||
)
|
||||
|
||||
|
||||
class PersistUploadsResponse(BaseModel):
|
||||
dry_run: bool
|
||||
jobs: Dict[str, Any] # job_id -> {"copied", "updated"} | {"would_copy"} | {"error"} | {"orphan"}
|
||||
|
||||
|
||||
@router.post("/persist-uploads", response_model=PersistUploadsResponse)
|
||||
def persist_uploads(dry_run: bool = True, auth_data: AuthResult = Depends(require_admin)):
|
||||
"""Backfill: copy every job's ``uploads/{job_id}/**`` into ``jobs/{job_id}/input/``.
|
||||
|
||||
Same operation the workers run on entry (``input_persistence``), for jobs that
|
||||
no worker will touch again. Folders with no job document (abandoned uploads)
|
||||
are reported as ``orphan`` and left in place. Plain ``def``: blocking GCS and
|
||||
Firestore calls run in the threadpool.
|
||||
"""
|
||||
from backend.services.input_persistence import persist_job_inputs, persisted_path
|
||||
|
||||
storage = StorageService()
|
||||
job_manager = JobManager()
|
||||
by_job: Dict[str, List[str]] = {}
|
||||
for blob in storage.bucket.list_blobs(prefix="uploads/"):
|
||||
parts = blob.name.split("/")
|
||||
if len(parts) > 2 and parts[1]:
|
||||
by_job.setdefault(parts[1], []).append(blob.name)
|
||||
|
||||
results: Dict[str, Any] = {}
|
||||
for job_id, names in sorted(by_job.items()):
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
if job is None:
|
||||
results[job_id] = {"orphan": len(names)}
|
||||
continue
|
||||
if dry_run:
|
||||
results[job_id] = {"would_copy": {n: persisted_path(job_id, n) for n in names}}
|
||||
continue
|
||||
copied, updates = persist_job_inputs(job, storage, job_manager)
|
||||
results[job_id] = {"copied": copied, "updated": updates}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"persist-uploads: job {job_id} failed: {e}")
|
||||
results[job_id] = {"error": str(e)}
|
||||
return PersistUploadsResponse(dry_run=dry_run, jobs=results)
|
||||
@@ -146,6 +146,7 @@ class AudioSearchRequest(BaseModel):
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
|
||||
@@ -310,10 +311,9 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
|
||||
environment = headers.get('x-environment', '')
|
||||
client_id = headers.get('x-client-id', '')
|
||||
|
||||
custom_headers = {}
|
||||
for key, value in headers.items():
|
||||
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
|
||||
custom_headers[key] = value
|
||||
# Secret-bearing headers are redacted: custom_headers is visible to the job owner.
|
||||
from backend.utils.request_helpers import collect_custom_headers
|
||||
custom_headers = collect_custom_headers(headers)
|
||||
|
||||
metadata = {
|
||||
'client_ip': client_ip,
|
||||
@@ -729,17 +729,17 @@ async def search_audio(
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
|
||||
if effective_dropbox_path:
|
||||
result = credential_manager.check_dropbox_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if effective_gdrive_folder_id:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
|
||||
@@ -809,6 +809,7 @@ async def search_audio(
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
is_private=body.is_private,
|
||||
# Tenant scoping
|
||||
tenant_id=tenant_config.id if tenant_config else "",
|
||||
@@ -1110,7 +1111,7 @@ async def search_audio_standalone(
|
||||
|
||||
|
||||
@router.get("/audio-search/{job_id}/results")
|
||||
async def get_audio_search_results(
|
||||
def get_audio_search_results(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
):
|
||||
@@ -1435,7 +1436,7 @@ async def provide_url_for_job(
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/attach-upload-url", response_model=AttachUploadUrlsResponse)
|
||||
async def attach_upload_url(
|
||||
def attach_upload_url(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
body: AttachUploadUrlsRequest,
|
||||
@@ -1470,7 +1471,7 @@ async def attach_upload_url(
|
||||
|
||||
|
||||
@router.post("/audio-search/{job_id}/attach-upload-complete", response_model=AttachResponse)
|
||||
async def attach_upload_complete(
|
||||
def attach_upload_complete(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
|
||||
@@ -91,7 +91,7 @@ class CredentialValidationResponse(BaseModel):
|
||||
# ===========================================================================
|
||||
|
||||
@router.get("/status", response_model=AllCredentialsStatusResponse)
|
||||
async def get_credentials_status():
|
||||
def get_credentials_status():
|
||||
"""
|
||||
Get the status of all OAuth credentials.
|
||||
|
||||
@@ -126,7 +126,7 @@ async def get_credentials_status():
|
||||
|
||||
|
||||
@router.get("/status/{service}", response_model=CredentialStatusResponse)
|
||||
async def get_service_credential_status(service: str, request: Request):
|
||||
def get_service_credential_status(service: str, request: Request):
|
||||
"""
|
||||
Get the status of a specific service's OAuth credentials.
|
||||
|
||||
@@ -155,7 +155,7 @@ async def get_service_credential_status(service: str, request: Request):
|
||||
|
||||
|
||||
@router.post("/validate", response_model=CredentialValidationResponse)
|
||||
async def validate_credentials(request: CredentialValidationRequest, http_request: Request):
|
||||
def validate_credentials(request: CredentialValidationRequest, http_request: Request):
|
||||
"""
|
||||
Validate that credentials are available for requested services.
|
||||
|
||||
@@ -200,7 +200,7 @@ async def validate_credentials(request: CredentialValidationRequest, http_reques
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/youtube/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start YouTube device authorization flow.
|
||||
|
||||
@@ -238,7 +238,7 @@ async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] =
|
||||
|
||||
|
||||
@router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
async def poll_youtube_device_auth(device_code: str):
|
||||
def poll_youtube_device_auth(device_code: str):
|
||||
"""
|
||||
Poll for YouTube device authorization completion.
|
||||
|
||||
@@ -263,7 +263,7 @@ async def poll_youtube_device_auth(device_code: str):
|
||||
|
||||
|
||||
@router.post("/gdrive/device", response_model=DeviceAuthStartResponse)
|
||||
async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None):
|
||||
"""
|
||||
Start Google Drive device authorization flow.
|
||||
|
||||
@@ -296,7 +296,7 @@ async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = N
|
||||
|
||||
|
||||
@router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse)
|
||||
async def poll_gdrive_device_auth(device_code: str):
|
||||
def poll_gdrive_device_auth(device_code: str):
|
||||
"""
|
||||
Poll for Google Drive device authorization completion.
|
||||
"""
|
||||
@@ -316,7 +316,7 @@ async def poll_gdrive_device_auth(device_code: str):
|
||||
# ===========================================================================
|
||||
|
||||
@router.post("/test-alert")
|
||||
async def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
|
||||
def test_credential_alert(background_tasks: BackgroundTasks, request: Request):
|
||||
"""
|
||||
Test the credential alert mechanism.
|
||||
|
||||
|
||||
@@ -261,6 +261,7 @@ class BulkSettings(BaseModel):
|
||||
# Full-auto review (workstream C): batch default autonomy + backing preference.
|
||||
review_mode: str = "auto"
|
||||
backing_preference: str = "auto"
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
|
||||
class BulkSubmitRequest(BaseModel):
|
||||
@@ -347,6 +348,7 @@ async def bulk_submit(
|
||||
is_private=body.settings.is_private,
|
||||
review_mode=body.settings.review_mode,
|
||||
backing_preference=body.settings.backing_preference,
|
||||
translation_language=body.settings.translation_language,
|
||||
brand_prefix=settings.default_brand_prefix,
|
||||
enable_youtube_upload=settings.default_enable_youtube_upload,
|
||||
youtube_description=settings.default_youtube_description,
|
||||
@@ -443,7 +445,7 @@ def _bucket(status: str, pending_search: bool) -> str:
|
||||
|
||||
|
||||
@router.get("/{batch_id}", response_model=BulkBatchResponse)
|
||||
async def bulk_batch(
|
||||
def bulk_batch(
|
||||
request: Request,
|
||||
batch_id: str,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
|
||||
@@ -19,6 +19,7 @@ from backend.services.error_monitor.frontend_ingestion import (
|
||||
RateLimiter,
|
||||
build_pattern_data,
|
||||
is_bot_user_agent,
|
||||
is_opaque_script_error,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
@@ -80,6 +81,15 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
|
||||
)
|
||||
return ClientErrorResponse(pattern_id="bot-ignored", is_new=False)
|
||||
|
||||
# Opaque cross-origin "Script error." — no file/line, not our code.
|
||||
if is_opaque_script_error(payload.message, payload.source, payload.extra):
|
||||
logger.info(
|
||||
"frontend_crash_ignored_opaque_script_error url=%s source=%s",
|
||||
sanitize_url(payload.url),
|
||||
payload.source,
|
||||
)
|
||||
return ClientErrorResponse(pattern_id="opaque-script-error-ignored", is_new=False)
|
||||
|
||||
report = FrontendErrorReport(
|
||||
message=payload.message,
|
||||
stack=payload.stack,
|
||||
@@ -104,5 +114,13 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
|
||||
result.pattern_id,
|
||||
result.is_new,
|
||||
payload.source,
|
||||
# Full client diagnostics + breadcrumbs, searchable in Cloud Logging
|
||||
# (the alert sample only carries a trimmed summary).
|
||||
extra={
|
||||
"error_pattern_id": result.pattern_id,
|
||||
"client_url": sanitize_url(payload.url),
|
||||
"client_release": payload.release,
|
||||
"client_extra": payload.extra,
|
||||
},
|
||||
)
|
||||
return ClientErrorResponse(pattern_id=result.pattern_id, is_new=result.is_new)
|
||||
@@ -0,0 +1,212 @@
|
||||
"""POST /api/client-events — persistent telemetry for user-visible degradation.
|
||||
|
||||
Records every time the frontend shows a user a degraded-service surface (the
|
||||
orange "trouble reaching our servers" banner, the stronger "temporarily
|
||||
unavailable" error, a failed lyrics load, a slow/failed waveform), with enough
|
||||
metadata to review frequency and context later. Two sinks per event:
|
||||
|
||||
1. A structured INFO log line (``client_event type=…``) — queryable in Cloud
|
||||
Logging / Log Analytics alongside backend symptoms from the same window.
|
||||
2. A Firestore doc in ``client_events`` — survives log retention, cheap to
|
||||
aggregate for "how often are users seeing this?" reviews.
|
||||
|
||||
Identity (2026-10-03): the client sends its session token (if any) and the
|
||||
server resolves ``user_email`` / ``is_admin`` / ``is_internal`` / ``is_test``
|
||||
from it — a client-supplied email is never trusted (and is ignored). Each
|
||||
event also carries the FingerprintJS ``device_fingerprint`` (same visitorId the
|
||||
magic-link abuse checks use), a per-tab ``tab_id`` and an ``episode_id`` that
|
||||
groups one degradation episode (first banner → ``banner_recovered``).
|
||||
|
||||
The watchdog in ``backend/services/loop_watchdog.py`` writes server-side
|
||||
``server_loop_stall`` docs into the same collection; clients cannot submit
|
||||
that type.
|
||||
|
||||
Unauthenticated (review-token users must be able to report) and rate-limited
|
||||
per IP, mirroring /api/client-errors. The limiter is process-local, so the
|
||||
effective ceiling is 120/min/IP × live instances — acceptable for this threat
|
||||
model (non-malicious browsers, 60s client-side per-type throttle); Cloudflare's
|
||||
zone-wide rate limit sits in front as a flood backstop. Events are dropped,
|
||||
never queued, when the limiter trips — telemetry, not a delivery guarantee.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Literal, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from backend.utils.test_data import is_internal_email, is_test_email
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
RateLimiter,
|
||||
is_bot_user_agent,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/client-events", tags=["client-events"])
|
||||
|
||||
# Sized for a legitimate worst case from ONE IP: a many-tab burst (e.g. 16 review
|
||||
# tabs at once) where every tab reports a banner + a waveform event — that must be
|
||||
# fully recorded, not self-suppressed. Each tab throttles per-type client-side.
|
||||
_limiter = RateLimiter(max_per_minute=120)
|
||||
_db_singleton = None
|
||||
|
||||
# The full closed set of reportable events. Reject anything else so the
|
||||
# collection stays reviewable (no free-form types accumulating).
|
||||
EventType = Literal[
|
||||
"banner_reconnecting",
|
||||
"banner_unavailable",
|
||||
"banner_waking",
|
||||
"banner_recovered",
|
||||
"lyrics_load_failed",
|
||||
"waveform_slow",
|
||||
"waveform_failed",
|
||||
]
|
||||
|
||||
|
||||
def _get_db():
|
||||
global _db_singleton
|
||||
if _db_singleton is None:
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
_db_singleton = firestore.Client(project="nomadkaraoke")
|
||||
return _db_singleton
|
||||
|
||||
|
||||
class ClientEventPayload(BaseModel):
|
||||
type: EventType
|
||||
url: str = Field("", max_length=2048)
|
||||
job_id: Optional[str] = Field(None, max_length=64)
|
||||
# Legacy field from pre-2026-10-03 frontends — accepted but IGNORED (the
|
||||
# server resolves identity from the bearer token instead).
|
||||
user_email: Optional[str] = Field(None, max_length=320)
|
||||
device_fingerprint: Optional[str] = Field(None, max_length=128)
|
||||
tab_id: Optional[str] = Field(None, max_length=64)
|
||||
episode_id: Optional[str] = Field(None, max_length=64)
|
||||
locale: str = Field("en", max_length=10)
|
||||
release: str = Field("", max_length=64)
|
||||
# Small free-form context (stall age, http status, elapsed ms, probe state…).
|
||||
# Size-capped server-side; values are stored as-is.
|
||||
detail: Optional[dict] = None
|
||||
|
||||
@field_validator("url", "locale", "release")
|
||||
@classmethod
|
||||
def strip(cls, v: str) -> str:
|
||||
return (v or "").strip()
|
||||
|
||||
|
||||
def _capped_detail(detail: Optional[dict]) -> dict[str, Any]:
|
||||
"""Keep detail reviewable: at most 12 keys, scalar-ish values, short strings."""
|
||||
if not isinstance(detail, dict):
|
||||
return {}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in list(detail.items())[:12]:
|
||||
k = str(key)[:40]
|
||||
if isinstance(value, (int, float, bool)) or value is None:
|
||||
out[k] = value
|
||||
else:
|
||||
out[k] = str(value)[:200]
|
||||
return out
|
||||
|
||||
|
||||
_TENANT_HOST_EXCLUDE = {"gen", "www", "api", "app", "decide", "localhost"}
|
||||
|
||||
|
||||
def _tenant_from_url(url: str) -> Optional[str]:
|
||||
"""``randy-vild.nomadkaraoke.com/...`` → ``randy-vild``; consumer hosts → None."""
|
||||
try:
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
except ValueError:
|
||||
return None
|
||||
if not host.endswith(".nomadkaraoke.com"):
|
||||
return None
|
||||
sub = host[: -len(".nomadkaraoke.com")]
|
||||
if not sub or "." in sub or sub in _TENANT_HOST_EXCLUDE:
|
||||
return None
|
||||
return sub
|
||||
|
||||
|
||||
def _resolve_identity(request: Request) -> dict[str, Any]:
|
||||
"""Resolve the caller from its bearer token. Never raises; anonymous on failure."""
|
||||
identity: dict[str, Any] = {
|
||||
"user_email": None, "is_admin": False, "is_internal": False, "is_test": False,
|
||||
}
|
||||
auth = request.headers.get("authorization", "")
|
||||
if not auth.lower().startswith("bearer "):
|
||||
return identity
|
||||
token = auth[7:].strip()
|
||||
if not token:
|
||||
return identity
|
||||
try:
|
||||
from backend.services.auth_service import get_auth_service
|
||||
|
||||
result = get_auth_service().validate_token_full(token)
|
||||
except Exception:
|
||||
logger.debug("client_event token resolution failed", exc_info=True)
|
||||
return identity
|
||||
if not result.is_valid:
|
||||
return identity
|
||||
email = result.user_email
|
||||
identity["user_email"] = email
|
||||
identity["is_admin"] = bool(result.is_admin)
|
||||
identity["is_internal"] = bool(email and is_internal_email(email))
|
||||
identity["is_test"] = bool(email and is_test_email(email))
|
||||
return identity
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many events")
|
||||
|
||||
user_agent = request.headers.get("user-agent", "")[:1024]
|
||||
if is_bot_user_agent(user_agent):
|
||||
return {"status": "ignored"}
|
||||
|
||||
# Sync handler → runs in FastAPI's threadpool, so the token lookup
|
||||
# (Firestore) never touches the event loop.
|
||||
identity = _resolve_identity(request)
|
||||
|
||||
event = {
|
||||
"type": payload.type,
|
||||
"source": "client",
|
||||
"url": sanitize_url(payload.url),
|
||||
"tenant": _tenant_from_url(payload.url),
|
||||
"job_id": payload.job_id,
|
||||
**identity,
|
||||
"device_fingerprint": payload.device_fingerprint,
|
||||
"tab_id": payload.tab_id,
|
||||
"episode_id": payload.episode_id,
|
||||
"locale": payload.locale,
|
||||
"release": payload.release,
|
||||
"user_agent": user_agent,
|
||||
"detail": _capped_detail(payload.detail),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
# Sink 1: structured log line — correlate with backend symptoms in Logging.
|
||||
logger.info(
|
||||
"client_event type=%s job_id=%s user=%s admin=%s fp=%s episode=%s url=%s release=%s detail=%s",
|
||||
event["type"],
|
||||
event["job_id"],
|
||||
event["user_email"],
|
||||
event["is_admin"],
|
||||
event["device_fingerprint"],
|
||||
event["episode_id"],
|
||||
event["url"],
|
||||
event["release"],
|
||||
event["detail"],
|
||||
)
|
||||
|
||||
# Sink 2: Firestore — best-effort; telemetry must never error back to users.
|
||||
try:
|
||||
_get_db().collection("client_events").add(event)
|
||||
except Exception:
|
||||
logger.exception("Failed to persist client event (non-fatal)")
|
||||
|
||||
return {"status": "recorded"}
|
||||
@@ -13,6 +13,7 @@ abuse posture identical to the rest of the review surface: you can only warm
|
||||
the shared encoding VM if you already have review access to a real job.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Tuple
|
||||
from fastapi import APIRouter, Depends
|
||||
@@ -56,7 +57,13 @@ async def warmup_encoding_worker(
|
||||
reviewer previews a render. ``job_id`` scopes auth to the job under review.
|
||||
"""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
# ensure_primary_running does Firestore reads + GCE compute-API calls
|
||||
# (instances.get / instances.start) that can take 10s+. Run it off the
|
||||
# event loop: on the single-process server a sync call here froze the
|
||||
# WHOLE instance for ~11s on every review-page open with a cold VM,
|
||||
# stalling that same page's audio/lyrics requests behind it
|
||||
# (2026-09-19, follow-up to the concurrent-load investigation).
|
||||
result = await asyncio.to_thread(manager.ensure_primary_running)
|
||||
if result["started"]:
|
||||
logger.info(f"Started encoding worker VM: {result['vm_name']}")
|
||||
return result
|
||||
@@ -89,7 +96,8 @@ async def heartbeat_encoding_worker(
|
||||
job under review.
|
||||
"""
|
||||
try:
|
||||
manager.update_activity()
|
||||
# Sync Firestore write — keep it off the event loop (see warmup above).
|
||||
await asyncio.to_thread(manager.update_activity)
|
||||
return {"status": "ok"}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update encoding worker heartbeat: {e}")
|
||||
|
||||
@@ -15,6 +15,7 @@ import json
|
||||
import logging
|
||||
import tempfile
|
||||
import os
|
||||
import re
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Any, Tuple, Literal
|
||||
@@ -71,6 +72,29 @@ def _select_mixed_audio_files(files):
|
||||
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
|
||||
|
||||
|
||||
# A tenant track code is used verbatim as a folder/filename prefix, so it is kept
|
||||
# to a short, filesystem-safe token: letters and digits, optionally joined by "-"
|
||||
# or "_" (e.g. "VS6588", "VS-6588").
|
||||
_TRACK_CODE_RE = re.compile(r"^[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*$")
|
||||
_TRACK_CODE_MAX_LEN = 24
|
||||
|
||||
|
||||
def normalize_track_code(raw: Optional[str]) -> Optional[str]:
|
||||
"""Return a cleaned tenant track code, None when blank; 400 when unsafe."""
|
||||
code = (raw or "").strip()
|
||||
if not code:
|
||||
return None
|
||||
if len(code) > _TRACK_CODE_MAX_LEN or not _TRACK_CODE_RE.match(code):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
f"Invalid track code '{code[:40]}': use letters and numbers only "
|
||||
f"(optionally joined by - or _), up to {_TRACK_CODE_MAX_LEN} characters, e.g. VS6588"
|
||||
),
|
||||
)
|
||||
return code.upper()
|
||||
|
||||
|
||||
def _apply_tenant_overrides(
|
||||
dist: EffectiveDistributionSettings,
|
||||
tenant_config,
|
||||
@@ -188,6 +212,7 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
|
||||
class CreateJobFromUrlResponse(BaseModel):
|
||||
@@ -250,6 +275,7 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Field("auto", description="'auto' (skip review when confident) or 'always_review'")
|
||||
backing_preference: str = Field("auto", description="'auto' (retain backing where safe), 'clean', or 'review'")
|
||||
translation_language: Optional[str] = Field(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none")
|
||||
|
||||
# Non-interactive mode
|
||||
non_interactive: bool = Field(False, description="Skip interactive steps (lyrics review, instrumental selection)")
|
||||
@@ -260,6 +286,13 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
# Bulk-upload grouping: jobs created from the same tenant bulk batch share a
|
||||
# batch_id (stamped into state_data) so they can be grouped/filtered later.
|
||||
batch_id: Optional[str] = Field(None, description="Groups jobs created together in one tenant bulk batch")
|
||||
requires_audio_edit: bool = Field(False, description="Pause after upload for user to edit input audio")
|
||||
|
||||
# Tenant-supplied track code (e.g. Vocal Star's "VS6588"). Tenant portals only:
|
||||
# it becomes the job's brand code, so the output folder and every delivered file
|
||||
# are prefixed with the tenant's own catalogue code instead of an allocated
|
||||
# "<PREFIX>-NNNN" number.
|
||||
track_code: Optional[str] = Field(None, description="Tenant's own catalogue code for this track (tenant portals only)")
|
||||
|
||||
# Upload mechanism. "signed_put" (default) returns single-shot signed PUT
|
||||
# URLs; "resumable" returns GCS resumable session URIs that support chunked
|
||||
@@ -343,11 +376,9 @@ def extract_request_metadata(request: Request, created_from: str = "upload", aut
|
||||
client_id = headers.get('x-client-id', '') # Customer/user identifier
|
||||
|
||||
# Collect all X-* custom headers (excluding standard ones we already captured)
|
||||
custom_headers = {}
|
||||
for key, value in headers.items():
|
||||
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
|
||||
# Normalize header name to original casing if possible
|
||||
custom_headers[key] = value
|
||||
# Secret-bearing headers are redacted: custom_headers is visible to the job owner.
|
||||
from backend.utils.request_helpers import collect_custom_headers
|
||||
custom_headers = collect_custom_headers(headers)
|
||||
|
||||
metadata = {
|
||||
'client_ip': client_ip,
|
||||
@@ -377,6 +408,20 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
|
||||
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
|
||||
|
||||
|
||||
def _require_theme_exists(theme_id: Optional[str], locale: str) -> None:
|
||||
"""Reject an unknown theme BEFORE the job document is created.
|
||||
|
||||
``_prepare_theme_for_job`` runs after ``create_job``; if the theme lookup
|
||||
failed there, the request 400'd but left an orphaned PENDING job behind
|
||||
(e.g. a tenant bulk submit right after the tenant was created).
|
||||
"""
|
||||
if theme_id and not get_theme_service().theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id)
|
||||
)
|
||||
|
||||
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
@@ -419,8 +464,14 @@ def _prepare_theme_for_job(
|
||||
color_overrides=color_overrides_model
|
||||
)
|
||||
|
||||
# Get YouTube description template if available
|
||||
youtube_desc = theme_service.get_youtube_description(theme_id)
|
||||
# Settings.default_youtube_description is the single source of truth for
|
||||
# YouTube descriptions. A theme's legacy youtube_description.txt is only a
|
||||
# fallback when no canonical template is configured — otherwise it silently
|
||||
# overrode the template on every themed job (the nomad theme's copy was stale
|
||||
# Fiverr text, which the daily description-backfill worker then had to undo).
|
||||
youtube_desc = None
|
||||
if not get_settings().default_youtube_description:
|
||||
youtube_desc = theme_service.get_youtube_description(theme_id)
|
||||
|
||||
logger.info(f"Prepared theme '{theme_id}' for job {job_id}")
|
||||
|
||||
@@ -477,6 +528,7 @@ async def upload_and_create_job(
|
||||
# Review autonomy + backing-vocals preference (full-auto review, workstream C)
|
||||
review_mode: str = Form("auto", description="'auto' (skip review when confident) or 'always_review'"),
|
||||
backing_preference: str = Form("auto", description="'auto' (retain backing where safe), 'clean', or 'review'"),
|
||||
translation_language: Optional[str] = Form(None, description="Translated lyrics language code (e.g. 'es') shown beneath each line; omit for none"),
|
||||
# Private (non-published) track mode
|
||||
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
|
||||
# Audio editing
|
||||
@@ -588,17 +640,17 @@ async def upload_and_create_job(
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
|
||||
if dist.dropbox_path:
|
||||
result = credential_manager.check_dropbox_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
|
||||
@@ -708,6 +760,7 @@ async def upload_and_create_job(
|
||||
# Review autonomy + backing-vocals preference (full-auto review)
|
||||
review_mode=review_mode,
|
||||
backing_preference=backing_preference,
|
||||
translation_language=translation_language,
|
||||
# Private (non-published) track mode
|
||||
is_private=is_private,
|
||||
# Tenant scoping
|
||||
@@ -715,6 +768,7 @@ async def upload_and_create_job(
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
_require_theme_exists(effective_theme_id, locale)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -906,7 +960,7 @@ async def upload_and_create_job(
|
||||
distribution_services: Dict[str, Any] = {}
|
||||
|
||||
if dist.dropbox_path:
|
||||
dropbox_result = credential_manager.check_dropbox_credentials()
|
||||
dropbox_result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
|
||||
distribution_services["dropbox"] = {
|
||||
"enabled": True,
|
||||
"path": dist.dropbox_path,
|
||||
@@ -915,7 +969,7 @@ async def upload_and_create_job(
|
||||
}
|
||||
|
||||
if dist.gdrive_folder_id:
|
||||
gdrive_result = credential_manager.check_gdrive_credentials()
|
||||
gdrive_result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
|
||||
distribution_services["gdrive"] = {
|
||||
"enabled": True,
|
||||
"folder_id": dist.gdrive_folder_id,
|
||||
@@ -924,7 +978,7 @@ async def upload_and_create_job(
|
||||
}
|
||||
|
||||
if effective_enable_youtube_upload:
|
||||
youtube_result = credential_manager.check_youtube_credentials()
|
||||
youtube_result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
|
||||
distribution_services["youtube"] = {
|
||||
"enabled": True,
|
||||
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
|
||||
@@ -1081,8 +1135,20 @@ async def _validate_audio_durations(
|
||||
Returns:
|
||||
Tuple of (is_valid, audio_duration, instrumental_duration)
|
||||
"""
|
||||
# Two GCS downloads + two full decodes (15s+ seen in prod) — never on the loop.
|
||||
return await asyncio.to_thread(
|
||||
_validate_audio_durations_sync, storage, audio_gcs_path, instrumental_gcs_path, tolerance_seconds
|
||||
)
|
||||
|
||||
|
||||
def _validate_audio_durations_sync(
|
||||
storage: StorageService,
|
||||
audio_gcs_path: str,
|
||||
instrumental_gcs_path: str,
|
||||
tolerance_seconds: float,
|
||||
) -> Tuple[bool, float, float]:
|
||||
from pydub import AudioSegment
|
||||
|
||||
|
||||
temp_dir = tempfile.mkdtemp(prefix="duration_check_")
|
||||
try:
|
||||
# Download audio file
|
||||
@@ -1113,6 +1179,69 @@ async def _validate_audio_durations(
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
|
||||
# Conforming decodes both files and runs ffmpeg in the API process (2Gi, /tmp is
|
||||
# in-memory); cap how many run at once per instance.
|
||||
_CONFORM_SEMAPHORE = asyncio.Semaphore(2)
|
||||
|
||||
|
||||
def _conform_mismatched_instrumental_sync(
|
||||
storage: StorageService,
|
||||
job_id: str,
|
||||
audio_gcs_path: str,
|
||||
instrumental_gcs_path: str,
|
||||
) -> Optional[Tuple[str, Dict[str, Any]]]:
|
||||
from backend.services.instrumental_conform import InstrumentalConformError, conform_instrumental
|
||||
|
||||
temp_dir = tempfile.mkdtemp(prefix="instrumental_conform_")
|
||||
try:
|
||||
audio_local = os.path.join(temp_dir, "audio" + Path(audio_gcs_path).suffix)
|
||||
instrumental_local = os.path.join(temp_dir, "instrumental" + Path(instrumental_gcs_path).suffix)
|
||||
out_local = os.path.join(temp_dir, "conformed.flac")
|
||||
storage.download_file(audio_gcs_path, audio_local)
|
||||
storage.download_file(instrumental_gcs_path, instrumental_local)
|
||||
try:
|
||||
result = conform_instrumental(audio_local, instrumental_local, out_local)
|
||||
except InstrumentalConformError as e:
|
||||
if not e.mismatch:
|
||||
raise
|
||||
logger.warning(f"Job {job_id}: instrumental could not be conformed: {e}")
|
||||
return None
|
||||
conformed_gcs_path = f"uploads/{job_id}/conformed/existing_instrumental.flac"
|
||||
storage.upload_file(out_local, conformed_gcs_path)
|
||||
return conformed_gcs_path, {**result.to_dict(), "original_gcs_path": instrumental_gcs_path}
|
||||
finally:
|
||||
import shutil
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
|
||||
async def _conform_mismatched_instrumental(
|
||||
storage: StorageService,
|
||||
job_id: str,
|
||||
audio_gcs_path: str,
|
||||
instrumental_gcs_path: str,
|
||||
locale: str = "en",
|
||||
) -> Optional[Tuple[str, Dict[str, Any]]]:
|
||||
"""Line the instrumental up with the mix and fit it to the mix's length.
|
||||
|
||||
Returns (conformed GCS path, adjustment details), or None when the files
|
||||
don't line up (almost certainly the wrong instrumental). The original upload
|
||||
is kept; the conformed copy lives outside the ``audio/`` prefix so it's never
|
||||
mistaken for the mixed audio. Infrastructure failures (GCS, ffmpeg crash)
|
||||
raise a retryable 503 rather than cancelling the job as a "wrong file".
|
||||
"""
|
||||
async with _CONFORM_SEMAPHORE:
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
_conform_mismatched_instrumental_sync, storage, job_id, audio_gcs_path, instrumental_gcs_path
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: conforming instrumental failed unexpectedly: {e}", exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=t(locale, "jobs.instrumentalConformUnavailable"),
|
||||
) from e
|
||||
|
||||
|
||||
def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
|
||||
"""Generate the GCS path for a file based on its type."""
|
||||
ext = Path(filename).suffix.lower()
|
||||
@@ -1192,6 +1321,10 @@ async def create_job_with_upload_urls(
|
||||
detail=f"Invalid file extension '{ext}' for file_type '{file_info.file_type}'. Allowed: {allowed_extensions}"
|
||||
)
|
||||
|
||||
track_code = normalize_track_code(body.track_code)
|
||||
if track_code and not tenant_config:
|
||||
raise HTTPException(status_code=400, detail="Track codes are only supported on tenant portals")
|
||||
|
||||
# Apply default distribution settings from environment if not provided
|
||||
dist = get_effective_distribution_settings(
|
||||
dropbox_path=body.dropbox_path,
|
||||
@@ -1228,17 +1361,17 @@ async def create_job_with_upload_urls(
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not effective_is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
|
||||
if dist.dropbox_path:
|
||||
result = credential_manager.check_dropbox_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not effective_is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
|
||||
@@ -1299,12 +1432,15 @@ async def create_job_with_upload_urls(
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
is_private=effective_is_private,
|
||||
keep_brand_code=track_code,
|
||||
# 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),
|
||||
)
|
||||
_require_theme_exists(effective_theme_id, locale)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -1316,6 +1452,17 @@ async def create_job_with_upload_urls(
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
# The job stays PENDING until the client PUTs the files and calls
|
||||
# uploads-complete. Flag it so the dashboard can say "Waiting for upload"
|
||||
# (not the misleading "Setting up") and the stale-upload sweep can cancel
|
||||
# + refund jobs whose browser upload never finished.
|
||||
job_manager.update_state_data(job_id, 'awaiting_upload', True)
|
||||
|
||||
# Store requires_audio_edit flag in state_data (start_job_processing parks
|
||||
# at the audio editor when set)
|
||||
if body.requires_audio_edit:
|
||||
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
|
||||
|
||||
# Stamp bulk-batch grouping so jobs created together can be grouped/filtered later.
|
||||
if body.batch_id:
|
||||
job_manager.update_state_data(job_id, 'batch_id', body.batch_id)
|
||||
@@ -1428,6 +1575,17 @@ async def mark_uploads_complete(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
|
||||
|
||||
# A signed-in user may not finalize someone else's job. (Token auth without
|
||||
# an email — trusted API integrations creating jobs on behalf of a
|
||||
# body.user_email — keeps working, as before this check existed.)
|
||||
if (
|
||||
not auth_result.is_admin
|
||||
and auth_result.user_email
|
||||
and job.user_email
|
||||
and auth_result.user_email.lower() != job.user_email.lower()
|
||||
):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
# Verify job is in pending state
|
||||
if job.status != JobStatus.PENDING:
|
||||
raise HTTPException(
|
||||
@@ -1501,30 +1659,67 @@ async def mark_uploads_complete(
|
||||
storage_service, audio_gcs_path, instrumental_gcs_path
|
||||
)
|
||||
if not duration_valid:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"error": "duration_mismatch",
|
||||
"message": f"Instrumental duration ({instrumental_duration:.2f}s) does not match audio duration ({audio_duration:.2f}s). "
|
||||
f"Difference must be within 0.5 seconds.",
|
||||
"audio_duration": audio_duration,
|
||||
"instrumental_duration": instrumental_duration,
|
||||
"difference": abs(audio_duration - instrumental_duration),
|
||||
}
|
||||
# Different edits of the same song (extra count-in, longer or
|
||||
# shorter outro) are lined up with the mix automatically; only a
|
||||
# file that doesn't correlate with the mix at all is rejected.
|
||||
conform = await _conform_mismatched_instrumental(
|
||||
storage_service, job_id, audio_gcs_path, instrumental_gcs_path, locale
|
||||
)
|
||||
logger.info(f"Duration validation passed: audio={audio_duration:.2f}s, instrumental={instrumental_duration:.2f}s")
|
||||
if conform is None:
|
||||
# Cancel (refunds the credit) so the job isn't stranded PENDING
|
||||
# with uploaded files — the stale-upload sweep skips those.
|
||||
job_manager.cancel_job(
|
||||
job_id,
|
||||
reason=(
|
||||
f"Instrumental duration ({instrumental_duration:.2f}s) does not match "
|
||||
f"audio duration ({audio_duration:.2f}s) and could not be aligned"
|
||||
),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"error": "duration_mismatch",
|
||||
"message": t(locale, "jobs.uploadDurationMismatchCancelled",
|
||||
instrumental_duration=f"{instrumental_duration:.1f}",
|
||||
audio_duration=f"{audio_duration:.1f}"),
|
||||
"audio_duration": audio_duration,
|
||||
"instrumental_duration": instrumental_duration,
|
||||
"difference": abs(audio_duration - instrumental_duration),
|
||||
}
|
||||
)
|
||||
conformed_path, conform_info = conform
|
||||
update_data['existing_instrumental_gcs_path'] = conformed_path
|
||||
job_manager.update_state_data(job_id, 'instrumental_conformed', conform_info)
|
||||
logger.info(f"Job {job_id}: conformed instrumental to mix length: {conform_info}")
|
||||
else:
|
||||
logger.info(f"Duration validation passed: audio={audio_duration:.2f}s, instrumental={instrumental_duration:.2f}s")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning(f"Duration validation failed with error: {e}. Proceeding without validation.")
|
||||
# Don't block the job if we can't validate - the video worker will fail more gracefully
|
||||
|
||||
# uploads/ expires (bucket lifecycle): keep the user's instrumental at the job
|
||||
# root (where the video pipeline stages it anyway) so later re-renders,
|
||||
# regenerates and edits still have it.
|
||||
if (update_data.get('existing_instrumental_gcs_path') or '').startswith('uploads/'):
|
||||
from backend.utils.existing_instrumental import persistent_instrumental_path
|
||||
source = update_data['existing_instrumental_gcs_path']
|
||||
dest = persistent_instrumental_path(job_id, source)
|
||||
try:
|
||||
storage_service.copy_blob(source, dest)
|
||||
update_data['existing_instrumental_gcs_path'] = dest
|
||||
logger.info(f"Job {job_id}: persisted existing instrumental {source} -> {dest}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: couldn't persist existing instrumental {source}: {e}")
|
||||
|
||||
# Add style assets to update if any
|
||||
if style_assets:
|
||||
update_data['style_assets'] = style_assets
|
||||
|
||||
# Update job with GCS paths
|
||||
job_manager.update_job(job_id, update_data)
|
||||
job_manager.delete_state_data_keys(job_id, ['awaiting_upload'])
|
||||
|
||||
logger.info(f"Validated uploads for job {job_id}: {body.uploaded_files}")
|
||||
|
||||
@@ -1547,7 +1742,7 @@ async def mark_uploads_complete(
|
||||
updated_job = job_manager.get_job(job_id)
|
||||
|
||||
if updated_job.dropbox_path:
|
||||
dropbox_result = credential_manager.check_dropbox_credentials()
|
||||
dropbox_result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
|
||||
distribution_services["dropbox"] = {
|
||||
"enabled": True,
|
||||
"path": updated_job.dropbox_path,
|
||||
@@ -1555,7 +1750,7 @@ async def mark_uploads_complete(
|
||||
}
|
||||
|
||||
if updated_job.gdrive_folder_id:
|
||||
gdrive_result = credential_manager.check_gdrive_credentials()
|
||||
gdrive_result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
|
||||
distribution_services["gdrive"] = {
|
||||
"enabled": True,
|
||||
"folder_id": updated_job.gdrive_folder_id,
|
||||
@@ -1563,7 +1758,7 @@ async def mark_uploads_complete(
|
||||
}
|
||||
|
||||
if updated_job.enable_youtube_upload:
|
||||
youtube_result = credential_manager.check_youtube_credentials()
|
||||
youtube_result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
|
||||
distribution_services["youtube"] = {
|
||||
"enabled": True,
|
||||
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
|
||||
@@ -1751,7 +1946,7 @@ class ValidateUrlResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
|
||||
async def validate_job_url(
|
||||
def validate_job_url(
|
||||
request: Request,
|
||||
body: ValidateUrlRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -1881,17 +2076,17 @@ async def create_job_from_url(
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if effective_enable_youtube_upload and not body.is_private:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
|
||||
if dist.dropbox_path:
|
||||
result = credential_manager.check_dropbox_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"dropbox ({result.message})")
|
||||
|
||||
if dist.gdrive_folder_id and not body.is_private:
|
||||
result = credential_manager.check_gdrive_credentials()
|
||||
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"gdrive ({result.message})")
|
||||
|
||||
@@ -1959,12 +2154,14 @@ async def create_job_from_url(
|
||||
non_interactive=body.non_interactive,
|
||||
review_mode=body.review_mode,
|
||||
backing_preference=body.backing_preference,
|
||||
translation_language=body.translation_language,
|
||||
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),
|
||||
)
|
||||
_require_theme_exists(effective_theme_id, locale)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -2103,7 +2300,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
|
||||
|
||||
|
||||
@router.post("/jobs/create-finalise-only")
|
||||
async def create_finalise_only_job(
|
||||
def create_finalise_only_job(
|
||||
request: Request,
|
||||
body: CreateFinaliseOnlyJobRequest,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
@@ -2272,6 +2469,7 @@ async def create_finalise_only_job(
|
||||
# UI language the job was submitted in (admin-only signal)
|
||||
locale=get_full_locale_from_request(request),
|
||||
)
|
||||
_require_theme_exists(effective_theme_id, locale)
|
||||
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
|
||||
job_id = job.job_id
|
||||
|
||||
@@ -2339,7 +2537,7 @@ async def create_finalise_only_job(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/finalise-uploads-complete")
|
||||
async def mark_finalise_uploads_complete(
|
||||
def mark_finalise_uploads_complete(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
@@ -2565,7 +2763,7 @@ async def mark_finalise_uploads_complete(
|
||||
# ============================================================================
|
||||
|
||||
@router.post("/jobs/{job_id}/style-upload-urls")
|
||||
async def get_style_upload_urls(
|
||||
def get_style_upload_urls(
|
||||
job_id: str,
|
||||
body: StyleUploadUrlsRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -2645,7 +2843,7 @@ async def get_style_upload_urls(
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/style-uploads-complete")
|
||||
async def complete_style_uploads(
|
||||
def complete_style_uploads(
|
||||
job_id: str,
|
||||
body: StyleUploadsCompleteRequest,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Health check routes.
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import logging
|
||||
import subprocess
|
||||
@@ -217,7 +218,7 @@ async def check_flacfetch_service_status() -> Dict[str, Any]:
|
||||
|
||||
async def check_encoding_worker_status() -> Dict[str, Any]:
|
||||
"""Check if GCE encoding worker is available and healthy."""
|
||||
encoding_service = get_encoding_service()
|
||||
encoding_service = await asyncio.to_thread(get_encoding_service)
|
||||
|
||||
if not encoding_service.is_configured:
|
||||
return {
|
||||
@@ -312,16 +313,14 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
|
||||
|
||||
def check_audio_separator_status() -> Dict[str, Any]:
|
||||
"""Check audio separator availability without calling the remote GPU service."""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
"""Report audio separation availability.
|
||||
|
||||
Separation runs in the ``audio-separation-job`` GPU Cloud Run Job (local
|
||||
GPU mode, models baked into the image). The standalone ``audio-separator``
|
||||
Cloud Run GPU service was shut down on 2026-10-01 (cost cut), so there is
|
||||
no remote service to probe — this reports the installed package version
|
||||
only and never calls out to anything.
|
||||
"""
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
@@ -331,41 +330,20 @@ def check_audio_separator_status() -> Dict[str, Any]:
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"mode": "gpu_job",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return the installed audio-separator package version.
|
||||
Return audio separation status (installed audio-separator package version).
|
||||
|
||||
Does NOT call the remote GPU service — that would cold-start an expensive
|
||||
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
|
||||
installed package version, which matches what the audio worker uses.
|
||||
|
||||
No authentication required.
|
||||
Does NOT call any remote service — separation runs in the
|
||||
audio-separation-job GPU Cloud Run Job. No authentication required.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
return check_audio_separator_status()
|
||||
|
||||
|
||||
def _get_encoding_worker_manager():
|
||||
@@ -450,7 +428,7 @@ async def system_status(
|
||||
# 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
|
||||
# (…-fallback-c2df), 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
|
||||
@@ -569,7 +547,7 @@ async def detailed_health_check() -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/health/preload-status")
|
||||
async def preload_status() -> Dict[str, Any]:
|
||||
def preload_status() -> Dict[str, Any]:
|
||||
"""
|
||||
Check status of preloaded resources for performance optimization.
|
||||
|
||||
@@ -631,7 +609,7 @@ async def preload_status() -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/health/job-consistency")
|
||||
async def job_consistency_check(
|
||||
def job_consistency_check(
|
||||
status: Optional[str] = None,
|
||||
limit: int = 50
|
||||
) -> Dict[str, Any]:
|
||||
|
||||
+283
-28
@@ -27,7 +27,8 @@ from backend.workers.video_worker import generate_video
|
||||
from backend.workers.render_video_worker import process_render_video
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.job_manager import JobManager, PREP_PHASE_STATUSES
|
||||
from backend.utils.loop_bridge import run_in_body_thread, run_on_loop
|
||||
from backend.services.tracing import (
|
||||
extract_trace_context,
|
||||
start_span_with_context,
|
||||
@@ -141,7 +142,7 @@ async def sync_disposable_domains_endpoint(
|
||||
|
||||
|
||||
@router.post("/workers/audio", response_model=WorkerResponse)
|
||||
async def trigger_audio_worker(
|
||||
def trigger_audio_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -204,8 +205,28 @@ async def trigger_auto_approval_eval(
|
||||
return {"job_id": job_id, **result}
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/vocal-gaps")
|
||||
async def analyze_vocal_gaps_endpoint(
|
||||
job_id: str,
|
||||
dry_run: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Find sung stretches with no transcribed lyrics for a job (admin only).
|
||||
|
||||
Shadow-mode calibration/backfill for the missing-lyrics detector: downloads the
|
||||
lead-vocal stem server-side, analyzes the job's current lyrics and stores
|
||||
``state_data.vocal_gaps`` (unless ``dry_run``). Never changes job status.
|
||||
"""
|
||||
from backend.services.auto_approval.executor import analyze_job_vocal_gaps
|
||||
|
||||
logger.info(f"[job:{job_id}] vocal gap analysis requested (dry_run={dry_run})")
|
||||
result = await asyncio.to_thread(analyze_job_vocal_gaps, job_id, not dry_run)
|
||||
return {"job_id": job_id, **result}
|
||||
|
||||
|
||||
@router.post("/workers/lyrics", response_model=WorkerResponse)
|
||||
async def trigger_lyrics_worker(
|
||||
def trigger_lyrics_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -318,19 +339,41 @@ async def trigger_screens_worker(
|
||||
add_span_event("worker_skipped", {"reason": skip_response.status})
|
||||
return skip_response
|
||||
|
||||
# Add task to background tasks
|
||||
background_tasks.add_task(generate_screens, job_id)
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
if not get_settings().enable_cloud_tasks:
|
||||
# Direct-HTTP mode (local dev): the caller uses a 30s timeout, so keep
|
||||
# the fire-and-forget background task there.
|
||||
background_tasks.add_task(generate_screens, job_id)
|
||||
add_span_event("worker_started")
|
||||
return WorkerResponse(
|
||||
status="started",
|
||||
job_id=job_id,
|
||||
message="Screens generation worker started"
|
||||
)
|
||||
|
||||
# Cloud Tasks mode (prod): run the worker INLINE and respond when it's done.
|
||||
# As a post-response BackgroundTask it ran on throttled CPU
|
||||
# (--cpu-throttling only allocates CPU while a request is open) and
|
||||
# its sync work blocked the event loop for every other request; inline,
|
||||
# the open request keeps CPU allocated and the heavy steps run in worker
|
||||
# threads. generate_screens handles its own failures (marks the job
|
||||
# failed), so always 200 — a non-2xx would make Cloud Tasks re-run it.
|
||||
add_span_event("worker_started")
|
||||
try:
|
||||
ok = await generate_screens(job_id)
|
||||
except Exception as e: # noqa: BLE001 — never trigger a Cloud Tasks retry storm
|
||||
logger.exception(f"[job:{job_id}] screens worker raised: {e}")
|
||||
ok = False
|
||||
return WorkerResponse(
|
||||
status="started",
|
||||
status="completed" if ok else "failed",
|
||||
job_id=job_id,
|
||||
message="Screens generation worker started"
|
||||
message="Screens generation finished" if ok else "Screens generation failed",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/workers/video", response_model=WorkerResponse)
|
||||
async def trigger_video_worker(
|
||||
def trigger_video_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -371,7 +414,7 @@ async def trigger_video_worker(
|
||||
|
||||
|
||||
@router.post("/workers/render-video", response_model=WorkerResponse)
|
||||
async def trigger_render_video_worker(
|
||||
def trigger_render_video_worker(
|
||||
request: WorkerRequest,
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -516,6 +559,7 @@ async def check_idle_reminder(
|
||||
audio_hash=job.audio_hash,
|
||||
review_token=job.review_token,
|
||||
instrumental_token=job.instrumental_token,
|
||||
request_metadata=getattr(job, 'request_metadata', None),
|
||||
)
|
||||
|
||||
if success:
|
||||
@@ -542,7 +586,7 @@ async def check_idle_reminder(
|
||||
|
||||
|
||||
@router.post("/youtube-queue/process")
|
||||
async def process_youtube_upload_queue(
|
||||
def process_youtube_upload_queue(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
@@ -582,7 +626,7 @@ async def process_youtube_upload_queue(
|
||||
|
||||
|
||||
@router.post("/process-stale-reviews")
|
||||
async def process_stale_reviews_endpoint(
|
||||
def process_stale_reviews_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
@@ -595,8 +639,12 @@ async def process_stale_reviews_endpoint(
|
||||
|
||||
- Jobs in review for >= 24h get a reminder email
|
||||
- Jobs in review for >= 48h are auto-cancelled with credit refund
|
||||
- Signed-URL upload jobs whose browser upload never finished (>= 2h) are
|
||||
auto-cancelled with credit refund
|
||||
- Free-to-paid conversion emails (when CONVERSION_EMAILS_ENABLED)
|
||||
"""
|
||||
from backend.workers.stale_review_processor import process_stale_reviews
|
||||
from backend.workers.stale_upload_processor import process_stale_uploads
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
|
||||
@@ -609,6 +657,19 @@ async def process_stale_reviews_endpoint(
|
||||
logger.info(f"STALE_REVIEW_PROCESS complete: {result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"STALE_REVIEW_PROCESS failed: {e}")
|
||||
try:
|
||||
upload_result = await asyncio.to_thread(process_stale_uploads)
|
||||
logger.info(f"STALE_UPLOAD_PROCESS complete: {upload_result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"STALE_UPLOAD_PROCESS failed: {e}")
|
||||
# Free-to-paid conversion emails ride on this hourly cron (no-op unless
|
||||
# CONVERSION_EMAILS_ENABLED); see backend/services/conversion_emails.py
|
||||
try:
|
||||
from backend.services.conversion_emails import process_conversion_emails
|
||||
conversion_result = await asyncio.to_thread(process_conversion_emails)
|
||||
logger.info(f"CONVERSION_EMAILS complete: {conversion_result}")
|
||||
except Exception as e:
|
||||
logger.exception(f"CONVERSION_EMAILS failed: {e}")
|
||||
|
||||
background_tasks.add_task(_process)
|
||||
|
||||
@@ -620,7 +681,7 @@ async def process_stale_reviews_endpoint(
|
||||
|
||||
|
||||
@router.post("/youtube-backfill/run")
|
||||
async def youtube_backfill_run_endpoint(
|
||||
def youtube_backfill_run_endpoint(
|
||||
http_request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
max_updates: Optional[int] = None,
|
||||
@@ -656,6 +717,119 @@ async def youtube_backfill_run_endpoint(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/storage-retention/run")
|
||||
async def storage_retention_run_endpoint(
|
||||
dry_run: Optional[bool] = None,
|
||||
job_ids: Optional[str] = None,
|
||||
min_age_days: Optional[int] = None,
|
||||
max_jobs: Optional[int] = None,
|
||||
include_orphans: bool = False,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Purge regenerable files of old completed jobs (storage retention).
|
||||
|
||||
Called daily by Cloud Scheduler. DRY-RUN unless STORAGE_RETENTION_DRY_RUN is
|
||||
false: it then only writes a report to GCS (path returned). See
|
||||
backend/services/storage_retention.py for the policy.
|
||||
|
||||
Manual/testing params:
|
||||
- ``job_ids=a,b`` scopes the pass to those jobs and runs synchronously
|
||||
(returns the full report). Only a scoped pass may override ``dry_run=false``
|
||||
or ``min_age_days`` — a global real purge only happens via the setting.
|
||||
- ``max_jobs`` caps the jobs planned/purged; ``include_orphans`` adds a
|
||||
report section on jobs/ folders with no Firestore doc (report only).
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from backend.config import get_settings
|
||||
from backend.services.storage_retention import StorageRetentionService
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.storage_retention_enabled:
|
||||
return {"status": "disabled", "message": "STORAGE_RETENTION_ENABLED is false"}
|
||||
|
||||
scoped = [j.strip() for j in (job_ids or "").split(",") if j.strip()]
|
||||
if not scoped:
|
||||
if dry_run is False and settings.storage_retention_dry_run:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="A global real purge needs STORAGE_RETENTION_DRY_RUN=false; pass job_ids to scope a real run.",
|
||||
)
|
||||
if min_age_days is not None:
|
||||
raise HTTPException(status_code=400, detail="min_age_days can only be overridden with job_ids")
|
||||
effective_dry_run = settings.storage_retention_dry_run if dry_run is None else dry_run
|
||||
|
||||
if scoped:
|
||||
report = await asyncio.to_thread(
|
||||
StorageRetentionService().run,
|
||||
dry_run=effective_dry_run, job_ids=scoped, min_age_days=min_age_days, max_jobs=max_jobs,
|
||||
)
|
||||
return {"status": "complete", "report": report}
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
report_path = StorageRetentionService.default_report_path(now, effective_dry_run)
|
||||
|
||||
# A full pass takes minutes: run it as the storage-retention-job Cloud Run
|
||||
# Job. (The API service throttles CPU outside requests, which starves a
|
||||
# BackgroundTask, and Cloudflare cuts requests at 100s.)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
started = await get_worker_service().trigger_storage_retention_job(
|
||||
dry_run=effective_dry_run, report_path=report_path,
|
||||
max_jobs=max_jobs, include_orphans=include_orphans,
|
||||
)
|
||||
if not started:
|
||||
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
|
||||
return {
|
||||
"status": "started",
|
||||
"dry_run": effective_dry_run,
|
||||
"report_path": f"gs://{settings.gcs_bucket_name}/{report_path}",
|
||||
}
|
||||
|
||||
|
||||
ORPHAN_DELETE_CONFIRMATION = "delete-orphan-job-folders"
|
||||
|
||||
|
||||
@router.post("/storage-retention/orphans")
|
||||
async def storage_retention_orphans_endpoint(
|
||||
dry_run: bool = True,
|
||||
confirm: Optional[str] = None,
|
||||
max_folders: Optional[int] = None,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
One-off cleanup of ``jobs/{id}/`` folders with no job record: keep ``input/``,
|
||||
delete everything else (backend/services/storage_retention.py purge_orphans).
|
||||
|
||||
DRY-RUN unless ``dry_run=false&confirm=delete-orphan-job-folders``. Independent
|
||||
of STORAGE_RETENTION_DRY_RUN and never run by the scheduler. Runs as the
|
||||
storage-retention-job Cloud Run Job; the report path is returned.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from backend.config import get_settings
|
||||
from backend.services.storage_retention import REPORT_PREFIX
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
if not dry_run and confirm != ORPHAN_DELETE_CONFIRMATION:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"A real orphan cleanup needs confirm={ORPHAN_DELETE_CONFIRMATION}",
|
||||
)
|
||||
settings = get_settings()
|
||||
now = datetime.now(timezone.utc)
|
||||
report_path = f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json"
|
||||
started = await get_worker_service().trigger_storage_retention_job(
|
||||
dry_run=dry_run, report_path=report_path, mode="orphans", max_folders=max_folders,
|
||||
)
|
||||
if not started:
|
||||
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
|
||||
return {
|
||||
"status": "started",
|
||||
"mode": "orphans",
|
||||
"dry_run": dry_run,
|
||||
"report_path": f"gs://{settings.gcs_bucket_name}/{report_path}",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/community-daily-pick")
|
||||
async def community_daily_pick_endpoint(
|
||||
http_request: Request,
|
||||
@@ -767,7 +941,10 @@ async def trigger_gdrive_validation_endpoint(
|
||||
add_span_attribute("brand_code", str(brand_code))
|
||||
|
||||
try:
|
||||
result = trigger_gdrive_validation(brand_code=brand_code, expect_cdg=expect_cdg)
|
||||
# Sync OIDC fetch + HTTP POST (up to 60s) — off the event loop.
|
||||
result = await asyncio.to_thread(
|
||||
trigger_gdrive_validation, brand_code=brand_code, expect_cdg=expect_cdg
|
||||
)
|
||||
if result is None:
|
||||
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
|
||||
|
||||
@@ -785,10 +962,20 @@ async def retry_pending_render_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Cron: auto-retry RENDER_PENDING_CAPACITY jobs — see ``_retry_pending_render_jobs_sync``.
|
||||
|
||||
Firestore scans + updates run in a worker thread (they stalled the loop on
|
||||
every tick); render triggers run back on the loop.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
return await run_in_body_thread(_retry_pending_render_jobs_sync, http_request, loop)
|
||||
|
||||
|
||||
def _retry_pending_render_jobs_sync(http_request: Request, loop: asyncio.AbstractEventLoop):
|
||||
"""
|
||||
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
|
||||
|
||||
Called every 5 minutes by Cloud Scheduler. When the GCE encoding worker
|
||||
Called every 10 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
|
||||
@@ -909,7 +1096,7 @@ async def retry_pending_render_jobs(
|
||||
continue
|
||||
|
||||
try:
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
run_on_loop(loop, 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:
|
||||
@@ -942,10 +1129,21 @@ async def recover_stuck_jobs(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Cron watchdog for stuck jobs — see ``_recover_stuck_jobs_sync``.
|
||||
|
||||
Its Firestore scans were the #1 event-loop staller (~260 stalls in a week,
|
||||
up to 5s each), so the scan runs in a worker thread; worker re-triggers run
|
||||
back on the loop.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
return await run_in_body_thread(_recover_stuck_jobs_sync, http_request, loop)
|
||||
|
||||
|
||||
def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventLoop):
|
||||
"""
|
||||
Detect and recover jobs stuck in a processing status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
Called by Cloud Scheduler (every 10 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
|
||||
@@ -1031,7 +1229,7 @@ async def recover_stuck_jobs(
|
||||
# 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):
|
||||
if _retrigger_parked_download(job_manager, worker_service, job_id, loop):
|
||||
download_retried.append(job_id)
|
||||
|
||||
# --- Orphaned renders: re-park for automatic retry ---
|
||||
@@ -1073,16 +1271,17 @@ async def recover_stuck_jobs(
|
||||
continue
|
||||
logger.warning(f"[job:{job_id}] REVIEW_COMPLETE stalled >10 min with no render — re-triggering")
|
||||
try:
|
||||
if await worker_service.trigger_render_video_worker(job_id):
|
||||
if run_on_loop(loop, worker_service.trigger_render_video_worker(job_id)):
|
||||
render_retriggered.append(job_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
|
||||
|
||||
# --- DOWNLOADING with lyrics done but screens never triggered: lost screens trigger ---
|
||||
# --- Prep phase with lyrics done but screens never triggered: lost screens trigger ---
|
||||
# The lyrics worker triggers screen generation once transcription completes
|
||||
# (audio separation is decoupled). If that dispatch is lost — historically a
|
||||
# fire-and-forget task cancelled on Cloud Run Job loop teardown, now awaited,
|
||||
# but a Cloud Tasks enqueue can still fail — the job sits at `downloading` with
|
||||
# but a Cloud Tasks enqueue can still fail — the job sits in its prep status
|
||||
# (`downloading`, or `audio_edit_complete` for audio-edited jobs) with
|
||||
# lyrics_complete=True and never advances, with no error. Re-trigger is
|
||||
# idempotent (advance_to_screens_if_ready status-guards + the screens worker
|
||||
# no-ops a duplicate). Mirrors the REVIEW_COMPLETE lost-render recovery above.
|
||||
@@ -1092,7 +1291,7 @@ async def recover_stuck_jobs(
|
||||
# in. DOWNLOADING is a transient processing state (jobs move through in
|
||||
# minutes), so this ceiling is far above any realistic concurrent population.
|
||||
dl_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING.value)
|
||||
filter=FieldFilter("status", "in", sorted(s.value for s in PREP_PHASE_STATUSES))
|
||||
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
|
||||
for doc in dl_query:
|
||||
if len(screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
|
||||
@@ -1104,15 +1303,63 @@ async def recover_stuck_jobs(
|
||||
if not _prep_screens_stalled(job):
|
||||
continue
|
||||
logger.warning(
|
||||
f"[job:{job_id}] DOWNLOADING stalled >10 min with lyrics complete but "
|
||||
f"[job:{job_id}] {job.status} stalled >10 min with lyrics complete but "
|
||||
"no screens — re-triggering"
|
||||
)
|
||||
try:
|
||||
if await job_manager.advance_to_screens_if_ready(job_id):
|
||||
if run_on_loop(loop, job_manager.advance_to_screens_if_ready(job_id)):
|
||||
screens_retriggered.append(job_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] screens re-trigger failed: {e}")
|
||||
|
||||
# --- Storage-retention stems restore whose audio job died silently ---
|
||||
# (hard-killed GPU task: no except block ran, the job sits at
|
||||
# lyrics_complete with stems_restore=running forever). Fail it so the
|
||||
# customer/admin gets a Retry button; the retry re-runs the restore.
|
||||
stems_restore_failed = []
|
||||
from backend.services.stems_restore import restore_stalled
|
||||
lc_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.LYRICS_COMPLETE.value)
|
||||
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
|
||||
regen_screens_retriggered = []
|
||||
for doc in lc_query:
|
||||
data = doc.to_dict() or {}
|
||||
sd = data.get("state_data") or {}
|
||||
job_id = data.get("job_id", doc.id)
|
||||
# A re-render / regenerate / visibility flow parks the job at
|
||||
# lyrics_complete only until its screens dispatch starts (which moves it
|
||||
# to generating_screens within seconds). Still here after 10 min with no
|
||||
# stems restore running = the dispatch was lost (or skipped by a stale
|
||||
# screens_progress mark): clear the mark and re-trigger.
|
||||
if sd.get("regen_restore_status") and not sd.get("stems_restore"):
|
||||
if len(regen_screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
|
||||
continue
|
||||
job = job_manager.get_job(job_id)
|
||||
age = _job_updated_age_seconds(job) if job else None
|
||||
if job and age is not None and age > PREP_SCREENS_STALL_SECONDS:
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD as _DEL
|
||||
logger.warning(f"[job:{job_id}] Re-render parked at lyrics_complete >10 min — re-triggering screens")
|
||||
job_manager.update_job(job_id, {"state_data.screens_progress": _DEL})
|
||||
try:
|
||||
if run_on_loop(loop, worker_service.trigger_screens_worker(job_id)):
|
||||
regen_screens_retriggered.append(job_id)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] re-render screens re-trigger failed: {e}")
|
||||
continue
|
||||
if not sd.get("stems_restore"):
|
||||
continue
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job or not restore_stalled(job):
|
||||
continue
|
||||
logger.warning(f"[job:{job_id}] Stems restore stalled >60 min — failing for retry")
|
||||
job_manager.update_job(job_id, {"state_data.stems_restore.status": "failed"})
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message="Restoring this track's audio stems timed out. Retry the job to try again.",
|
||||
error_details={"stage": "stems_restore", "reason": "stalled"},
|
||||
)
|
||||
stems_restore_failed.append(job_id)
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
@@ -1141,6 +1388,8 @@ async def recover_stuck_jobs(
|
||||
"render_retriggered_count": len(render_retriggered),
|
||||
"screens_retriggered_jobs": screens_retriggered,
|
||||
"screens_retriggered_count": len(screens_retriggered),
|
||||
"stems_restore_failed_jobs": stems_restore_failed,
|
||||
"regen_screens_retriggered_jobs": regen_screens_retriggered,
|
||||
}
|
||||
|
||||
|
||||
@@ -1167,7 +1416,7 @@ def _job_updated_age_seconds(job):
|
||||
|
||||
|
||||
def _prep_screens_stalled(job) -> bool:
|
||||
"""True when a DOWNLOADING job has lyrics complete but has sat >10 min without
|
||||
"""True when a prep-phase job has lyrics complete but has sat >10 min without
|
||||
advancing to screen generation — i.e. the screens trigger was lost.
|
||||
|
||||
While audio separation is still running it keeps ``updated_at`` fresh, so this
|
||||
@@ -1263,8 +1512,14 @@ def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str)
|
||||
))
|
||||
|
||||
|
||||
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."""
|
||||
def _retrigger_parked_download(
|
||||
job_manager: JobManager, worker_service, job_id: str, loop: asyncio.AbstractEventLoop
|
||||
) -> bool:
|
||||
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job.
|
||||
|
||||
Called from the recover-stuck-jobs worker thread: the Firestore writes run
|
||||
here, only the trigger coroutine goes back to the loop.
|
||||
"""
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
job_manager.update_job(job_id, {"error_message": None, "error_details": None})
|
||||
@@ -1278,7 +1533,7 @@ async def _retrigger_parked_download(job_manager: JobManager, worker_service, jo
|
||||
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)
|
||||
run_on_loop(loop, 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
|
||||
|
||||
+664
-182
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,94 @@
|
||||
"""POST /api/karaokehunt/request — intake for retired-KaraokeHunt-app requests.
|
||||
|
||||
A Cloudflare Worker on create.karaokehunt.com (the URL baked into the
|
||||
unchangeable app binary) answers the app instantly and forwards each payload
|
||||
here with a shared secret. This route validates + logs the payload, then runs
|
||||
the full conversion synchronously (see ``workers/karaokehunt_conversion``) —
|
||||
the Worker doesn't wait for us, so latency is a non-issue and uvicorn finishes
|
||||
the handler even if the forwarding subrequest is reaped.
|
||||
|
||||
Unauthenticated by necessity (the app can't auth), gated three ways: the
|
||||
shared secret (503 until configured — deploys dark), a per-IP rate limit, and
|
||||
the conversion worker's own daily job cap + per-song dedup.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.config import get_settings
|
||||
from backend.services.error_monitor.frontend_ingestion import RateLimiter
|
||||
from backend.workers import karaokehunt_conversion
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/karaokehunt", tags=["karaokehunt"])
|
||||
|
||||
# ~1 legit request every 3 days historically; 10/min/IP is already generous.
|
||||
_limiter = RateLimiter(max_per_minute=10)
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str:
|
||||
# The Worker forwards the app's real IP; direct callers fall back to peer IP.
|
||||
return (request.headers.get("x-kh-client-ip")
|
||||
or (request.client.host if request.client else "unknown"))
|
||||
|
||||
|
||||
@router.post("/request", status_code=200)
|
||||
async def intake_karaokehunt_request(request: Request) -> dict:
|
||||
settings = get_settings()
|
||||
if not settings.karaokehunt_forwarder_secret:
|
||||
raise HTTPException(status_code=503, detail="not configured")
|
||||
|
||||
provided = request.headers.get("x-kh-forwarder-secret", "")
|
||||
if not hmac.compare_digest(provided, settings.karaokehunt_forwarder_secret):
|
||||
raise HTTPException(status_code=403, detail="forbidden")
|
||||
|
||||
if not _limiter.allow(_client_ip(request), time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many requests")
|
||||
|
||||
# The live app binary's exact schema is unverifiable (built from a
|
||||
# FlutterFlow export newer than any repo branch), so parse leniently:
|
||||
# any JSON object is accepted and logged; unusable ones become
|
||||
# outcome="invalid" audit rows rather than errors.
|
||||
try:
|
||||
payload = await request.json()
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("payload must be a JSON object")
|
||||
except Exception: # noqa: BLE001
|
||||
raise HTTPException(status_code=400, detail="invalid JSON")
|
||||
|
||||
doc = karaokehunt_conversion.create_intake(
|
||||
payload,
|
||||
client_ip=_client_ip(request),
|
||||
user_agent=request.headers.get("user-agent", "")[:512],
|
||||
)
|
||||
if doc["outcome"] == "invalid":
|
||||
return {"status": "success", "id": doc["id"]}
|
||||
|
||||
try:
|
||||
result = await karaokehunt_conversion.process_intake(doc["id"])
|
||||
logger.info("karaokehunt: processed %s -> %s", doc["id"], result.get("status"))
|
||||
except Exception: # noqa: BLE001 — the intake doc + reprocess endpoint carry retries
|
||||
logger.exception("karaokehunt: conversion failed for %s", doc["id"])
|
||||
try:
|
||||
karaokehunt_conversion._get_db().collection(
|
||||
karaokehunt_conversion.COLLECTION
|
||||
).document(doc["id"]).update({"outcome": "error", "error": "unhandled exception"})
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("karaokehunt: failed to mark %s as error", doc["id"])
|
||||
|
||||
# The app ignores the body; always succeed so nothing user-visible breaks.
|
||||
return {"status": "success", "id": doc["id"]}
|
||||
|
||||
|
||||
@router.post("/internal/reprocess/{doc_id}")
|
||||
async def reprocess_karaokehunt_request(
|
||||
doc_id: str, auth_result=Depends(require_admin)
|
||||
) -> dict:
|
||||
"""Admin retry for a failed/errored intake (idempotent markers prevent
|
||||
double credits/jobs). Also accepts force=true via query for terminal docs."""
|
||||
return await karaokehunt_conversion.process_intake(doc_id, force=True)
|
||||
@@ -0,0 +1,475 @@
|
||||
"""kjbox partner API — singer email-code sign-in + "free at the show" credits.
|
||||
|
||||
kjbox (the KJ device app at live karaoke nights) lets a patron verify their
|
||||
email inside the kjbox singer web page, then creates gen jobs AS that real gen
|
||||
user (with the returned session token) so they get normal gen delivery emails.
|
||||
|
||||
Every endpoint requires ``X-Kjbox-Secret`` (503 until ``KJBOX_PARTNER_SECRET``
|
||||
is configured — deploys dark; 403 if wrong). Contract:
|
||||
|
||||
- POST /api/kjbox/auth/send-code {email, locale?, venue?} → {"status": "sent"}
|
||||
- POST /api/kjbox/auth/verify-code {email, code} → {session_token, user,
|
||||
credits_granted, credit_status}
|
||||
- POST /api/kjbox/credits/show-credit (+ Authorization: Bearer <session>)
|
||||
{idempotency_key, venue?, only_if_empty?}
|
||||
→ {granted, credits}
|
||||
|
||||
A venue is many singers behind one IP, so gen's 2-signups-per-IP cap does NOT
|
||||
apply here; instead a partner-wide rolling-24h cap on new VERIFIED accounts
|
||||
(accounts are only created at verify-code), a per-email code throttle, and a
|
||||
per-user daily show-credit cap bound abuse.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hmac
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.routes.users import (
|
||||
_build_user_public,
|
||||
_mask_email,
|
||||
_precompute_credit_eval,
|
||||
complete_verified_login,
|
||||
)
|
||||
from backend.config import get_settings, is_production
|
||||
from backend.i18n import SUPPORTED_LOCALES, t
|
||||
from backend.services.email_service import EmailService, get_email_service
|
||||
from backend.services.email_validation_service import get_email_validation_service
|
||||
from backend.services.kjbox_partner_service import (
|
||||
CODE_EXPIRY_MINUTES,
|
||||
LOGIN_CODES_COLLECTION,
|
||||
KjboxPartnerService,
|
||||
CodeThrottled,
|
||||
ShowCreditCapReached,
|
||||
TransactionContention,
|
||||
VerifyOutcome,
|
||||
)
|
||||
from backend.services.user_service import UserService, get_user_service
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/kjbox", tags=["kjbox"])
|
||||
|
||||
SIGNUP_SOURCE = "kjbox"
|
||||
_MAX_EMAIL_LEN = 254
|
||||
_MAX_VENUE_LEN = 200
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ auth gate
|
||||
|
||||
def require_kjbox_partner(x_kjbox_secret: Optional[str] = Header(default=None)) -> str:
|
||||
"""Shared-secret gate. Returns the secret (also used as the code-hash pepper)."""
|
||||
secret = get_settings().kjbox_partner_secret
|
||||
if not secret:
|
||||
raise HTTPException(status_code=503, detail="not configured")
|
||||
if not hmac.compare_digest((x_kjbox_secret or "").encode(), secret.encode()):
|
||||
raise HTTPException(status_code=403, detail="forbidden")
|
||||
return secret
|
||||
|
||||
|
||||
def get_kjbox_service(
|
||||
secret: str = Depends(require_kjbox_partner),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
) -> KjboxPartnerService:
|
||||
return KjboxPartnerService(user_service.db, pepper=secret)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- models
|
||||
|
||||
class SendCodeRequest(BaseModel):
|
||||
email: str
|
||||
locale: Optional[str] = None
|
||||
venue: Optional[str] = Field(default=None, max_length=_MAX_VENUE_LEN)
|
||||
|
||||
|
||||
class SendCodeResponse(BaseModel):
|
||||
status: str
|
||||
|
||||
|
||||
class VerifyCodeRequest(BaseModel):
|
||||
email: str
|
||||
code: str = Field(max_length=32)
|
||||
|
||||
|
||||
class VerifyCodeResponse(BaseModel):
|
||||
session_token: str
|
||||
user: dict
|
||||
credits_granted: int
|
||||
credit_status: str
|
||||
|
||||
|
||||
class ShowCreditRequest(BaseModel):
|
||||
idempotency_key: str = Field(min_length=1, max_length=128)
|
||||
venue: Optional[str] = Field(default=None, max_length=_MAX_VENUE_LEN)
|
||||
# Grant only if the singer currently has no credits (< 1). The key is claimed
|
||||
# only when a credit is actually granted, so a later call with the same key
|
||||
# and only_if_empty=false grants iff this one didn't.
|
||||
only_if_empty: bool = False
|
||||
|
||||
|
||||
class ShowCreditResponse(BaseModel):
|
||||
granted: bool
|
||||
credits: int
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- helpers
|
||||
|
||||
def _normalize_email(raw: str) -> str:
|
||||
email = (raw or "").strip().lower()
|
||||
local, _, domain = email.partition("@")
|
||||
if (not local or "." not in domain or len(email) > _MAX_EMAIL_LEN
|
||||
or any(c.isspace() for c in email) or email.count("@") != 1):
|
||||
raise HTTPException(status_code=422, detail="invalid_email")
|
||||
return email
|
||||
|
||||
|
||||
def _split_locale(raw: Optional[str]) -> tuple[Optional[str], Optional[str]]:
|
||||
"""Return (email_locale in en/es/de or None, ui_locale primary subtag or None)."""
|
||||
if not raw:
|
||||
return None, None
|
||||
primary = raw.strip().replace("_", "-").split("-")[0].lower()
|
||||
if not primary.isalpha() or len(primary) < 2:
|
||||
return None, None
|
||||
return (primary if primary in SUPPORTED_LOCALES else None), primary
|
||||
|
||||
|
||||
def _pretend_sent() -> SendCodeResponse:
|
||||
return SendCodeResponse(status="sent")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ endpoints
|
||||
|
||||
@router.post("/auth/send-code", response_model=SendCodeResponse)
|
||||
def send_code(
|
||||
body: SendCodeRequest,
|
||||
http_request: Request,
|
||||
svc: KjboxPartnerService = Depends(get_kjbox_service),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
email_service: EmailService = Depends(get_email_service),
|
||||
):
|
||||
settings = get_settings()
|
||||
email = _normalize_email(body.email)
|
||||
email_locale, ui_locale = _split_locale(body.locale)
|
||||
locale = email_locale or "en"
|
||||
venue = (body.venue or "").strip() or None
|
||||
|
||||
email_validation = get_email_validation_service()
|
||||
if email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"kjbox: blocked disposable email {_mask_email(email)}")
|
||||
raise HTTPException(status_code=422, detail=t(locale, "users.disposableEmailBlocked"))
|
||||
if email_validation.is_email_blocked(email):
|
||||
logger.warning(f"kjbox: blocked email {_mask_email(email)} — pretending success")
|
||||
return _pretend_sent()
|
||||
ip_address = get_client_ip(http_request)
|
||||
if ip_address and email_validation.is_ip_blocked(ip_address):
|
||||
logger.warning(f"kjbox: blocked IP {ip_address} — pretending success")
|
||||
return _pretend_sent()
|
||||
|
||||
if not email_service.is_configured() and is_production():
|
||||
logger.error("kjbox: email service not configured - cannot send codes")
|
||||
raise HTTPException(status_code=503, detail="email not configured")
|
||||
|
||||
# No account is created here — only once the email is verified (verify-code),
|
||||
# so unverified addresses can neither burn the signup cap nor create accounts
|
||||
# for other people's emails. Venue/locale ride on the code record until then.
|
||||
user = user_service.get_user(email)
|
||||
try:
|
||||
issued = svc.issue_code(
|
||||
email,
|
||||
max_per_hour=settings.kjbox_codes_per_email_per_hour,
|
||||
needs_credit_eval=(
|
||||
not (user and getattr(user, "welcome_credits_granted", False))
|
||||
and not is_test_email(email)
|
||||
),
|
||||
locale=email_locale,
|
||||
ui_locale=ui_locale,
|
||||
venue=venue,
|
||||
ip_address=ip_address,
|
||||
user_agent=http_request.headers.get("user-agent"),
|
||||
)
|
||||
except (CodeThrottled, TransactionContention):
|
||||
# Contention on one email's code doc = a burst of parallel sends to the
|
||||
# same address, which is exactly what the throttle exists to stop.
|
||||
raise HTTPException(status_code=429, detail="too_many_codes")
|
||||
|
||||
sent = email_service.send_kjbox_login_code(
|
||||
email, issued.code, expiry_minutes=CODE_EXPIRY_MINUTES, locale=locale,
|
||||
)
|
||||
if not sent:
|
||||
if getattr(email_service, "last_send_suppressed", False):
|
||||
logger.info(f"kjbox: code recipient {_mask_email(email)} is Postmark-suppressed")
|
||||
else:
|
||||
logger.error(f"kjbox: failed to send code email to {_mask_email(email)}")
|
||||
|
||||
# Warm the welcome-credit AI evaluation while the singer reads their email,
|
||||
# so verify-code is instant (same optimisation as magic links).
|
||||
if issued.needs_credit_eval:
|
||||
threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(issued.doc_id, email, LOGIN_CODES_COLLECTION),
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
return SendCodeResponse(status="sent")
|
||||
|
||||
|
||||
@router.post("/auth/verify-code", response_model=VerifyCodeResponse)
|
||||
def verify_code(
|
||||
body: VerifyCodeRequest,
|
||||
http_request: Request,
|
||||
svc: KjboxPartnerService = Depends(get_kjbox_service),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
email_service: EmailService = Depends(get_email_service),
|
||||
):
|
||||
settings = get_settings()
|
||||
email = _normalize_email(body.email)
|
||||
|
||||
# New accounts are created (and counted against the partner-wide cap) only
|
||||
# here, after the email is proven. Check the cap BEFORE consuming the code so
|
||||
# a capped singer can retry the same code later.
|
||||
existing = user_service.get_user(email)
|
||||
if existing is None and svc.count_recent_signups() >= settings.kjbox_signup_cap_per_24h:
|
||||
logger.warning("kjbox: partner-wide verified-signup cap reached")
|
||||
raise HTTPException(status_code=429, detail="signup_cap")
|
||||
|
||||
outcome, record = svc.verify_code(email, body.code)
|
||||
if outcome == VerifyOutcome.TOO_MANY_ATTEMPTS:
|
||||
raise HTTPException(status_code=429, detail="too_many_attempts")
|
||||
if outcome == VerifyOutcome.INVALID:
|
||||
raise HTTPException(status_code=401, detail="invalid_code")
|
||||
if outcome != VerifyOutcome.OK or record is None:
|
||||
raise HTTPException(status_code=401, detail="expired")
|
||||
|
||||
user = user_service.get_user(email)
|
||||
if user is None:
|
||||
# No signup_ip: the caller is the kjbox box, whose IP is the whole
|
||||
# venue's — recording it would trip gen's per-IP cap for everyone there.
|
||||
user = user_service.get_or_create_user(
|
||||
email, signup_source=SIGNUP_SOURCE, signup_venue=record.get("venue"),
|
||||
)
|
||||
svc.record_signup(email, record.get("venue"))
|
||||
logger.info(f"kjbox: created verified gen user {_mask_email(email)} (venue={record.get('venue')!r})")
|
||||
# Same first-login definition as magic-link verify (checked before last_login_at is set).
|
||||
is_first_login = user.total_jobs_created == 0 and not user.last_login_at
|
||||
user = user_service.update_user(
|
||||
email, email_verified=True, last_login_at=datetime.utcnow(),
|
||||
) or user
|
||||
|
||||
precomputed_eval = {
|
||||
k: record.get(k)
|
||||
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
|
||||
if record.get(k) is not None
|
||||
} or None
|
||||
email_locale = record.get("locale")
|
||||
|
||||
result = complete_verified_login(
|
||||
user,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
is_first_login=is_first_login,
|
||||
precomputed_eval=precomputed_eval,
|
||||
grant_welcome_credit=True,
|
||||
referral_code=None,
|
||||
locale=email_locale,
|
||||
ui_locale=record.get("ui_locale"),
|
||||
ip_address=get_client_ip(http_request),
|
||||
user_agent=http_request.headers.get("user-agent"),
|
||||
tenant_id=None,
|
||||
device_fingerprint=None,
|
||||
email_locale=email_locale or user.locale or "en",
|
||||
)
|
||||
logger.info(f"kjbox: verified {_mask_email(email)} (credit_status={result.credit_status})")
|
||||
|
||||
return VerifyCodeResponse(
|
||||
session_token=result.session.token,
|
||||
user=_build_user_public(result.user).model_dump(mode="json"),
|
||||
credits_granted=result.credits_granted,
|
||||
credit_status=result.credit_status,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/credits/show-credit", response_model=ShowCreditResponse)
|
||||
def show_credit(
|
||||
body: ShowCreditRequest,
|
||||
svc: KjboxPartnerService = Depends(get_kjbox_service),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
"""Quietly grant +1 credit so a singer's make-it job is free at the show.
|
||||
|
||||
No "credits added" email. Idempotent per ``idempotency_key`` (claimed only
|
||||
when a credit is granted); ``only_if_empty`` grants only at a 0 balance;
|
||||
capped per user per rolling 24h. All decisions + the increment are one
|
||||
Firestore transaction.
|
||||
"""
|
||||
settings = get_settings()
|
||||
scheme, _, token = (authorization or "").partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise HTTPException(status_code=401, detail="invalid_session")
|
||||
valid, user, _msg = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail="invalid_session")
|
||||
|
||||
email = user.email.lower()
|
||||
venue = (body.venue or "").strip() or None
|
||||
user_ref = user_service.get_user_doc_ref(email)
|
||||
if user_ref is None:
|
||||
raise HTTPException(status_code=401, detail="invalid_session")
|
||||
|
||||
try:
|
||||
result = svc.grant_show_credit(
|
||||
user_ref,
|
||||
email,
|
||||
body.idempotency_key,
|
||||
venue=venue,
|
||||
only_if_empty=body.only_if_empty,
|
||||
max_per_24h=settings.kjbox_show_credits_per_user_per_24h,
|
||||
)
|
||||
except ShowCreditCapReached:
|
||||
raise HTTPException(status_code=429, detail="show_credit_cap")
|
||||
except LookupError:
|
||||
raise HTTPException(status_code=401, detail="invalid_session")
|
||||
except TransactionContention:
|
||||
# Nothing was written; kjbox retries with the same idempotency key.
|
||||
raise HTTPException(status_code=409, detail="busy_retry")
|
||||
|
||||
if result.granted:
|
||||
logger.info(f"kjbox: show credit granted to {_mask_email(email)} (venue={venue!r}) → {result.credits}")
|
||||
return ShowCreditResponse(granted=result.granted, credits=result.credits)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- review link
|
||||
|
||||
class ReviewLinkRequest(BaseModel):
|
||||
locale: Optional[str] = None
|
||||
|
||||
|
||||
class ReviewLinkResponse(BaseModel):
|
||||
url: str
|
||||
status: str
|
||||
# "admin" = the KJ / support already opened the review; "owner" = the
|
||||
# singer did; None = nobody has opened it yet.
|
||||
review_started_by: Optional[str] = None
|
||||
|
||||
|
||||
_REVIEW_LINK_STATUSES = ("awaiting_review", "in_review")
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/review-link", response_model=ReviewLinkResponse)
|
||||
async def review_link(
|
||||
job_id: str,
|
||||
body: ReviewLinkRequest,
|
||||
_secret: str = Depends(require_kjbox_partner),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
"""One-click sign-in link straight to the singer's own job's lyrics review.
|
||||
|
||||
Backs the "Tap here to review it yourself" link on the kjbox singer page:
|
||||
the same single-use ``job_review:<id>`` magic link the kjbox review email
|
||||
carries, minted on demand. Only the job's owner (the Bearer session) may
|
||||
get one, and only while the job is in review (409 ``not_in_review``).
|
||||
"""
|
||||
scheme, _, token = (authorization or "").partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise HTTPException(status_code=401, detail="invalid_session")
|
||||
locale = body.locale if body.locale in SUPPORTED_LOCALES else "en"
|
||||
# Session check, job read and token mint are blocking Firestore calls —
|
||||
# keep them off the event loop (it serves every in-flight request).
|
||||
url, status, started_by = await asyncio.to_thread(
|
||||
_mint_review_link, user_service, token, job_id, locale)
|
||||
return ReviewLinkResponse(url=url, status=status, review_started_by=started_by)
|
||||
|
||||
|
||||
def _mint_review_link(user_service: UserService, token: str, job_id: str, locale: str):
|
||||
"""Blocking half of ``review_link`` → (url, status, review_started_by)."""
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.job_notification_service import build_review_login_url
|
||||
|
||||
valid, user, _msg = user_service.validate_session(token)
|
||||
if not valid or not user:
|
||||
raise HTTPException(status_code=401, detail="invalid_session")
|
||||
job = JobManager().get_job(job_id)
|
||||
# Same 404 for "missing" and "not yours" — don't confirm other users' job ids.
|
||||
if not job or (job.user_email or "").lower() != user.email.lower():
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
status = str(getattr(job.status, "value", job.status))
|
||||
if status not in _REVIEW_LINK_STATUSES:
|
||||
raise HTTPException(status_code=409, detail="not_in_review")
|
||||
url = build_review_login_url(job.job_id, job.user_email, locale=locale)
|
||||
if not url:
|
||||
raise HTTPException(status_code=502, detail="link_unavailable")
|
||||
started_by = (job.state_data or {}).get("review_started_by") if status == "in_review" else None
|
||||
return url, status, started_by
|
||||
|
||||
|
||||
# ---------------------------------------------------------- search resolve
|
||||
|
||||
class ResolveRequest(BaseModel):
|
||||
query: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
_RESOLVE_CACHE_MAX = 2000
|
||||
_RESOLVE_PER_MINUTE = 120
|
||||
_resolve_cache: "dict[str, dict]" = {}
|
||||
_resolve_calls: "list[float]" = []
|
||||
_resolve_lock = threading.Lock()
|
||||
|
||||
|
||||
def _resolve_budget_ok() -> bool:
|
||||
"""Partner-wide in-process cap on AI calls (cache hits are free)."""
|
||||
import time
|
||||
now = time.monotonic()
|
||||
with _resolve_lock:
|
||||
while _resolve_calls and _resolve_calls[0] < now - 60:
|
||||
_resolve_calls.pop(0)
|
||||
if len(_resolve_calls) >= _RESOLVE_PER_MINUTE:
|
||||
return False
|
||||
_resolve_calls.append(now)
|
||||
return True
|
||||
|
||||
|
||||
@router.post("/catalog/resolve")
|
||||
async def catalog_resolve(body: ResolveRequest, _secret: str = Depends(require_kjbox_partner)):
|
||||
"""Split + auto-correct a singer's free-text song search.
|
||||
|
||||
kjbox calls this only when its own catalogue search found nothing, then
|
||||
shows gen's AudioSourceStep "Tidied to … / keep what I typed" (re-searching
|
||||
when the song changed, and pre-filling its generate form). The AI splits the
|
||||
one-line query; the job flow's judge_match catalog pass then tidies it, so
|
||||
the canonical artist/title match what gen's own job form would use.
|
||||
Response = the match judge verdict shape + typed_artist / typed_title.
|
||||
Never 5xx on model trouble: kind "none".
|
||||
"""
|
||||
from backend.services.match_judge.free_text import _none, resolve_and_tidy
|
||||
|
||||
query = " ".join(body.query.split())
|
||||
if not query:
|
||||
raise HTTPException(status_code=422, detail="empty_query")
|
||||
key = query.casefold()
|
||||
with _resolve_lock:
|
||||
hit = _resolve_cache.get(key)
|
||||
if hit is not None:
|
||||
# Same query modulo case/spacing: the verdict applies, but echo THIS
|
||||
# request's text where the verdict fell back to the typed query.
|
||||
if not hit.get("typed_artist"):
|
||||
hit = {**hit, "typed_title": query}
|
||||
return hit
|
||||
if not _resolve_budget_ok():
|
||||
raise HTTPException(status_code=429, detail="rate_limited")
|
||||
verdict = await resolve_and_tidy(query)
|
||||
if verdict.get("reason") != "unavailable": # don't cache transient failures
|
||||
with _resolve_lock:
|
||||
if len(_resolve_cache) >= _RESOLVE_CACHE_MAX:
|
||||
_resolve_cache.pop(next(iter(_resolve_cache)))
|
||||
_resolve_cache[key] = verdict
|
||||
return verdict or _none(query)
|
||||
@@ -88,7 +88,7 @@ class TestNotificationResponse(BaseModel):
|
||||
# Routes
|
||||
|
||||
@router.get("/vapid-public-key", response_model=VapidPublicKeyResponse)
|
||||
async def get_vapid_public_key():
|
||||
def get_vapid_public_key():
|
||||
"""
|
||||
Get the VAPID public key for push subscription.
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ class SuccessResponse(BaseModel):
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/blocklists", response_model=BlocklistsResponse)
|
||||
async def get_blocklists(
|
||||
def get_blocklists(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""Get all blocklist data with domain source separation."""
|
||||
@@ -98,7 +98,7 @@ async def get_blocklists(
|
||||
|
||||
|
||||
@router.post("/blocklists/disposable-domains", response_model=SuccessResponse)
|
||||
async def add_disposable_domain(
|
||||
def add_disposable_domain(
|
||||
request: DomainRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -118,7 +118,7 @@ async def add_disposable_domain(
|
||||
|
||||
|
||||
@router.delete("/blocklists/disposable-domains/{domain}", response_model=SuccessResponse)
|
||||
async def remove_disposable_domain(
|
||||
def remove_disposable_domain(
|
||||
domain: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -136,7 +136,7 @@ async def remove_disposable_domain(
|
||||
|
||||
|
||||
@router.post("/blocklists/allowlisted-domains", response_model=SuccessResponse)
|
||||
async def add_allowlisted_domain(
|
||||
def add_allowlisted_domain(
|
||||
request: DomainRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -150,7 +150,7 @@ async def add_allowlisted_domain(
|
||||
|
||||
|
||||
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
|
||||
async def remove_allowlisted_domain(
|
||||
def remove_allowlisted_domain(
|
||||
domain: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -187,7 +187,7 @@ async def trigger_sync(
|
||||
|
||||
|
||||
@router.post("/blocklists/blocked-emails", response_model=SuccessResponse)
|
||||
async def add_blocked_email(
|
||||
def add_blocked_email(
|
||||
request: EmailRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -207,7 +207,7 @@ async def add_blocked_email(
|
||||
|
||||
|
||||
@router.delete("/blocklists/blocked-emails/{email}", response_model=SuccessResponse)
|
||||
async def remove_blocked_email(
|
||||
def remove_blocked_email(
|
||||
email: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -225,7 +225,7 @@ async def remove_blocked_email(
|
||||
|
||||
|
||||
@router.post("/blocklists/blocked-ips", response_model=SuccessResponse)
|
||||
async def add_blocked_ip(
|
||||
def add_blocked_ip(
|
||||
request: IPRequest,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -245,7 +245,7 @@ async def add_blocked_ip(
|
||||
|
||||
|
||||
@router.delete("/blocklists/blocked-ips/{ip_address}", response_model=SuccessResponse)
|
||||
async def remove_blocked_ip(
|
||||
def remove_blocked_ip(
|
||||
ip_address: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
@@ -267,7 +267,7 @@ async def remove_blocked_ip(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/youtube-queue", response_model=YouTubeQueueListResponse)
|
||||
async def get_youtube_queue(
|
||||
def get_youtube_queue(
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
@@ -288,7 +288,7 @@ async def get_youtube_queue(
|
||||
|
||||
|
||||
@router.post("/youtube-queue/{job_id}/retry", response_model=SuccessResponse)
|
||||
async def retry_youtube_upload(
|
||||
def retry_youtube_upload(
|
||||
job_id: str,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
|
||||
@@ -41,7 +41,7 @@ class GenerateFlyerRequest(BaseModel):
|
||||
|
||||
|
||||
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
|
||||
async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
"""
|
||||
Public endpoint: get interstitial data for a referral link.
|
||||
|
||||
@@ -76,14 +76,14 @@ async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_my_dashboard(auth=Depends(require_auth)):
|
||||
def get_my_dashboard(auth=Depends(require_auth)):
|
||||
"""Get referral dashboard data for the authenticated user."""
|
||||
service = get_referral_service()
|
||||
return service.get_dashboard_data(auth.user_email)
|
||||
|
||||
|
||||
@router.put("/me")
|
||||
async def update_my_link(
|
||||
def update_my_link(
|
||||
updates: UpdateReferralLinkRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
@@ -108,7 +108,7 @@ async def update_my_link(
|
||||
|
||||
|
||||
@router.post("/me/connect")
|
||||
async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
def start_stripe_connect(auth=Depends(require_auth)):
|
||||
"""Start Stripe Connect onboarding for the authenticated user."""
|
||||
# Check if user already has a Connect account
|
||||
from backend.services.user_service import get_user_service
|
||||
@@ -129,7 +129,7 @@ async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
|
||||
|
||||
@router.post("/me/connect/dashboard-link")
|
||||
async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
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)
|
||||
@@ -145,7 +145,7 @@ async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
|
||||
|
||||
@router.post("/me/connect/update-link")
|
||||
async def get_connect_update_link(auth=Depends(require_auth)):
|
||||
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)
|
||||
@@ -165,7 +165,7 @@ class VanityRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/me/vanity-request")
|
||||
async def request_vanity_url(
|
||||
def request_vanity_url(
|
||||
request: VanityRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
@@ -215,7 +215,7 @@ async def request_vanity_url(
|
||||
|
||||
|
||||
@router.post("/me/flyer")
|
||||
async def generate_flyer(
|
||||
def generate_flyer(
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
@@ -249,7 +249,7 @@ async def generate_flyer(
|
||||
|
||||
|
||||
@router.post("/admin/vanity")
|
||||
async def create_vanity_link(
|
||||
def create_vanity_link(
|
||||
request: CreateReferralLinkRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -276,7 +276,7 @@ async def create_vanity_link(
|
||||
|
||||
|
||||
@router.get("/admin/vanity-requests")
|
||||
async def list_vanity_requests(
|
||||
def list_vanity_requests(
|
||||
status: str = Query("pending", pattern="^(pending|approved|denied)$"),
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -293,7 +293,7 @@ async def list_vanity_requests(
|
||||
|
||||
|
||||
@router.post("/admin/vanity-requests/{request_id}/approve")
|
||||
async def approve_vanity_request(
|
||||
def approve_vanity_request(
|
||||
request_id: str,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -332,7 +332,7 @@ async def approve_vanity_request(
|
||||
|
||||
|
||||
@router.post("/admin/vanity-requests/{request_id}/deny")
|
||||
async def deny_vanity_request(
|
||||
def deny_vanity_request(
|
||||
request_id: str,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
@@ -346,7 +346,7 @@ async def deny_vanity_request(
|
||||
|
||||
|
||||
@router.get("/admin/links")
|
||||
async def list_links(
|
||||
def list_links(
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
auth=Depends(require_admin),
|
||||
@@ -406,7 +406,7 @@ async def admin_apply_discount(
|
||||
|
||||
|
||||
@router.put("/admin/links/{code}")
|
||||
async def update_link(
|
||||
def update_link(
|
||||
code: str,
|
||||
updates: UpdateReferralLinkRequest,
|
||||
auth=Depends(require_admin),
|
||||
@@ -429,7 +429,7 @@ async def update_link(
|
||||
|
||||
|
||||
@router.post("/admin/links/{code}/flyer")
|
||||
async def admin_generate_flyer(
|
||||
def admin_generate_flyer(
|
||||
code: str,
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_admin),
|
||||
|
||||
@@ -79,7 +79,7 @@ def _to_public(req: SongRequest, your_vote: Optional[int] = None) -> SongRequest
|
||||
|
||||
|
||||
@router.get("/requests", response_model=BoardResponse)
|
||||
async def list_requests(
|
||||
def list_requests(
|
||||
viewer_email: Optional[str] = Depends(optional_user_email),
|
||||
):
|
||||
"""The ranked board: active requests + recently published, with the caller's vote."""
|
||||
@@ -134,7 +134,7 @@ async def submit_request(
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/vote", response_model=SongRequestPublic)
|
||||
async def vote(
|
||||
def vote(
|
||||
request_id: str,
|
||||
body: VoteBody,
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
@@ -158,7 +158,7 @@ async def vote(
|
||||
|
||||
|
||||
@router.get("/me", response_model=DailyVoteStatus)
|
||||
async def my_daily_status(
|
||||
def my_daily_status(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""The caller's daily-vote status (has today's vote been used, and on what)."""
|
||||
|
||||
+487
-105
File diff suppressed because it is too large.
Load diff
@@ -20,7 +20,7 @@ router = APIRouter(prefix="/api/tenant", tags=["tenant"])
|
||||
|
||||
|
||||
@router.get("/config", response_model=TenantConfigResponse)
|
||||
async def get_tenant_config(
|
||||
def get_tenant_config(
|
||||
request: Request,
|
||||
tenant: Optional[str] = Query(
|
||||
None,
|
||||
@@ -81,7 +81,7 @@ async def get_tenant_config(
|
||||
|
||||
|
||||
@router.get("/config/{tenant_id}", response_model=TenantConfigResponse)
|
||||
async def get_tenant_config_by_id(tenant_id: str):
|
||||
def get_tenant_config_by_id(tenant_id: str):
|
||||
"""
|
||||
Get tenant configuration by explicit tenant ID.
|
||||
|
||||
@@ -102,7 +102,7 @@ async def get_tenant_config_by_id(tenant_id: str):
|
||||
|
||||
|
||||
@router.get("/asset/{tenant_id}/{asset_name}")
|
||||
async def get_tenant_asset(tenant_id: str, asset_name: str):
|
||||
def get_tenant_asset(tenant_id: str, asset_name: str):
|
||||
"""
|
||||
Get a signed URL for a tenant asset (logo, favicon, etc.).
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
@@ -23,11 +24,15 @@ from backend.services.tenant_admin_service import (
|
||||
IMAGE_CONTENT_TYPES,
|
||||
TenantConflictError,
|
||||
TenantNotFoundError,
|
||||
TenantProvisioningError,
|
||||
TenantValidationError,
|
||||
create_tenant,
|
||||
delete_tenant,
|
||||
get_default_style_params,
|
||||
get_tenant_detail,
|
||||
get_tenant_domain_status,
|
||||
list_tenants,
|
||||
provision_tenant_domain,
|
||||
update_tenant,
|
||||
)
|
||||
|
||||
@@ -48,7 +53,9 @@ class TenantSummary(BaseModel):
|
||||
subdomain: Optional[str] = None
|
||||
is_active: bool = True
|
||||
locked_theme: Optional[str] = None
|
||||
theme_id: Optional[str] = None
|
||||
dropbox_path: Optional[str] = None
|
||||
brand_prefix: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
|
||||
|
||||
@@ -60,6 +67,9 @@ class TenantCreateResponse(BaseModel):
|
||||
tenant: TenantPublicConfig
|
||||
preview_url: str
|
||||
subdomain_url: str
|
||||
# Cloudflare state of the portal subdomain: {hostname, state, dns_ok, pages_status}.
|
||||
# state is "active" once the certificate is issued (usually within ~1 min).
|
||||
domain: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class TenantDetailResponse(BaseModel):
|
||||
@@ -68,6 +78,11 @@ class TenantDetailResponse(BaseModel):
|
||||
style_params: Dict[str, Any]
|
||||
assets: List[str]
|
||||
preview_url: str
|
||||
domain: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
class TenantDomainResponse(BaseModel):
|
||||
domain: Dict[str, Any]
|
||||
|
||||
|
||||
class TenantTemplateResponse(BaseModel):
|
||||
@@ -154,13 +169,13 @@ async def _read_asset(upload: Optional[UploadFile], label: str) -> Optional[Tupl
|
||||
|
||||
|
||||
@router.get("", response_model=TenantListResponse)
|
||||
async def admin_list_tenants(auth_data: AuthResult = Depends(require_admin)):
|
||||
def admin_list_tenants(auth_data: AuthResult = Depends(require_admin)):
|
||||
"""List all white-label tenants."""
|
||||
return TenantListResponse(tenants=[TenantSummary(**t) for t in list_tenants()])
|
||||
|
||||
|
||||
@router.get("/_template", response_model=TenantTemplateResponse)
|
||||
async def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_admin)):
|
||||
def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_admin)):
|
||||
"""Return the default Nomad theme's full style_params as an editing starting point."""
|
||||
try:
|
||||
return TenantTemplateResponse(style_params=get_default_style_params())
|
||||
@@ -168,14 +183,47 @@ async def admin_tenant_theme_template(auth_data: AuthResult = Depends(require_ad
|
||||
raise HTTPException(status_code=500, detail=str(exc))
|
||||
|
||||
|
||||
# Sync handlers: FastAPI runs them in its threadpool, so the blocking GCS and
|
||||
# Cloudflare calls don't stall the event loop (the admin UI polls this).
|
||||
@router.get("/{tenant_id}", response_model=TenantDetailResponse)
|
||||
async def admin_get_tenant(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
|
||||
def admin_get_tenant(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
|
||||
"""Return a tenant's full config, theme style_params, and asset list for editing."""
|
||||
try:
|
||||
detail = get_tenant_detail(tenant_id)
|
||||
except TenantNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
return TenantDetailResponse(preview_url=_preview_url(tenant_id), **detail)
|
||||
return TenantDetailResponse(
|
||||
preview_url=_preview_url(tenant_id),
|
||||
domain=get_tenant_domain_status(tenant_id),
|
||||
**detail,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{tenant_id}/domain", response_model=TenantDomainResponse)
|
||||
def admin_provision_tenant_domain(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
|
||||
"""(Re)provision the tenant's {id}.nomadkaraoke.com subdomain (idempotent)."""
|
||||
try:
|
||||
domain = provision_tenant_domain(tenant_id)
|
||||
except TenantNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
except TenantConflictError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
except TenantProvisioningError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
logger.info(f"Admin {auth_data.user_email or 'admin:unknown'} provisioned domain for tenant '{tenant_id}'")
|
||||
return TenantDomainResponse(domain=domain)
|
||||
|
||||
|
||||
@router.delete("/{tenant_id}", status_code=204)
|
||||
def admin_delete_tenant(tenant_id: str, auth_data: AuthResult = Depends(require_admin)):
|
||||
"""Delete a tenant: subdomain (Cloudflare), theme, and config. Jobs are kept."""
|
||||
try:
|
||||
delete_tenant(tenant_id)
|
||||
except TenantNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
except TenantProvisioningError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
logger.info(f"Admin {auth_data.user_email or 'admin:unknown'} deleted tenant '{tenant_id}'")
|
||||
|
||||
|
||||
@router.put("/{tenant_id}", response_model=TenantUpdateResponse)
|
||||
@@ -205,7 +253,8 @@ async def admin_update_tenant(
|
||||
logo_image = await _read_image(logo, "logo")
|
||||
|
||||
try:
|
||||
updated = update_tenant(
|
||||
updated = await run_in_threadpool(
|
||||
update_tenant,
|
||||
tenant_id,
|
||||
config_updates=config_updates,
|
||||
style_params=style,
|
||||
@@ -214,8 +263,12 @@ async def admin_update_tenant(
|
||||
)
|
||||
except TenantNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
except TenantConflictError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
except TenantValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except TenantProvisioningError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid config: {exc}")
|
||||
except ValueError as exc:
|
||||
@@ -236,6 +289,7 @@ async def admin_create_tenant(
|
||||
tenant_id: Optional[str] = Form(None),
|
||||
subdomain: Optional[str] = Form(None),
|
||||
allowed_email_domains: Optional[str] = Form(None),
|
||||
allowed_emails: Optional[str] = Form(None),
|
||||
artist_color: Optional[str] = Form(None),
|
||||
title_color: Optional[str] = Form(None),
|
||||
sung_lyrics_color: Optional[str] = Form(None),
|
||||
@@ -282,11 +336,13 @@ async def admin_create_tenant(
|
||||
raise HTTPException(status_code=400, detail="style_params must be a JSON object.")
|
||||
|
||||
try:
|
||||
config = create_tenant(
|
||||
config = await run_in_threadpool(
|
||||
create_tenant,
|
||||
name=name,
|
||||
tenant_id=_clean(tenant_id),
|
||||
subdomain=_clean(subdomain),
|
||||
allowed_email_domains=_parse_domains(allowed_email_domains),
|
||||
allowed_emails=_parse_domains(allowed_emails),
|
||||
colors=colors,
|
||||
style_params_override=style_override,
|
||||
tagline=_clean(tagline),
|
||||
@@ -300,6 +356,8 @@ async def admin_create_tenant(
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
except TenantValidationError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except TenantProvisioningError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
@@ -313,4 +371,5 @@ async def admin_create_tenant(
|
||||
tenant=TenantPublicConfig.from_config(config),
|
||||
preview_url=_preview_url(config.id),
|
||||
subdomain_url=config.get_frontend_url(),
|
||||
domain=await run_in_threadpool(get_tenant_domain_status, config.id),
|
||||
)
|
||||
@@ -0,0 +1,273 @@
|
||||
"""
|
||||
Tenant self-service theme editor API (``/api/tenant/theme``).
|
||||
|
||||
Any user allowed on a tenant's portal can view, preview and save that tenant's
|
||||
theme. Tenant context comes from the request (subdomain or the client-controlled
|
||||
``X-Tenant-ID`` header), so every endpoint re-checks membership against the
|
||||
tenant's allowlist (admins always pass) — a header alone grants nothing.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from pydantic import BaseModel, Field, constr
|
||||
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.middleware.tenant import get_tenant_config_from_request
|
||||
from backend.models.tenant import TenantConfig
|
||||
from backend.services.auth_service import AuthResult
|
||||
from backend.services.tenant_admin_service import TenantValidationError
|
||||
from backend.services.tenant_theme_service import (
|
||||
ThemeNotEditableError,
|
||||
ThemeNotFoundError,
|
||||
get_theme_for_editor,
|
||||
prepare_preview_styles,
|
||||
save_tenant_theme,
|
||||
store_uploaded_asset,
|
||||
)
|
||||
from backend.services.theme_change_service import outdated_jobs, refresh_inflight_jobs
|
||||
from backend.services.theme_preview_service import ThemePreviewError, render_theme_preview
|
||||
from backend.services.tenant_admin_service import _theme_id_for
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/tenant/theme", tags=["tenant-theme"])
|
||||
|
||||
MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
||||
|
||||
# Previews run ffmpeg/PIL on the API instance — bound concurrency like the review
|
||||
# preview path so a burst of edits can't starve request handling.
|
||||
_PREVIEW_SEMAPHORE = asyncio.Semaphore(2)
|
||||
_PREVIEW_EXECUTOR = ThreadPoolExecutor(max_workers=2, thread_name_prefix="theme-preview")
|
||||
PREVIEW_TIMEOUT_S = 45
|
||||
|
||||
|
||||
def require_tenant_member(
|
||||
request: Request, auth_result: AuthResult = Depends(require_auth)
|
||||
) -> TenantConfig:
|
||||
"""The request's tenant, iff the authenticated user is allowed on it."""
|
||||
config = get_tenant_config_from_request(request)
|
||||
if config is None or not config.is_active:
|
||||
raise HTTPException(status_code=404, detail="Theme editing is only available on a tenant portal.")
|
||||
if auth_result.tenant_id and auth_result.tenant_id != config.id:
|
||||
raise HTTPException(status_code=403, detail="Your sign-in belongs to a different portal.")
|
||||
if not auth_result.user_email or not config.is_email_allowed(auth_result.user_email):
|
||||
raise HTTPException(status_code=403, detail="You don't have access to this portal's theme.")
|
||||
return config
|
||||
|
||||
|
||||
def _raise_http(exc: TenantValidationError) -> None:
|
||||
if isinstance(exc, ThemeNotFoundError):
|
||||
raise HTTPException(status_code=404, detail=str(exc))
|
||||
if isinstance(exc, ThemeNotEditableError):
|
||||
raise HTTPException(status_code=403, detail=str(exc))
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
class ThemeResponse(BaseModel):
|
||||
theme_id: str
|
||||
style_params: Dict[str, Any]
|
||||
images: List[str]
|
||||
fonts: List[str]
|
||||
|
||||
|
||||
class PreviewSample(BaseModel):
|
||||
artist: str = Field("Artist Name", max_length=80)
|
||||
title: str = Field("Song Title", max_length=80)
|
||||
lyrics: Optional[List[constr(max_length=120)]] = Field(None, max_length=4)
|
||||
|
||||
|
||||
class PreviewRequest(BaseModel):
|
||||
style_params: Dict[str, Any]
|
||||
sample: PreviewSample = Field(default_factory=PreviewSample)
|
||||
|
||||
|
||||
class PreviewResponse(BaseModel):
|
||||
# data:image/jpeg;base64,... — null for a screen the theme leaves out of videos.
|
||||
title_card: Optional[str] = None
|
||||
karaoke_frame: str
|
||||
end_screen: Optional[str] = None
|
||||
|
||||
|
||||
class SaveRequest(BaseModel):
|
||||
style_params: Dict[str, Any]
|
||||
|
||||
|
||||
class AssetResponse(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
@router.get("", response_model=ThemeResponse)
|
||||
def get_theme(config: TenantConfig = Depends(require_tenant_member)):
|
||||
try:
|
||||
return ThemeResponse(**get_theme_for_editor(config))
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
|
||||
|
||||
@router.post("/assets", response_model=AssetResponse)
|
||||
async def upload_asset(file: UploadFile = File(...), config: TenantConfig = Depends(require_tenant_member)):
|
||||
# Read in chunks and stop as soon as the limit is exceeded, so an oversized
|
||||
# upload never gets materialised in memory in full.
|
||||
chunks, size = [], 0
|
||||
while True:
|
||||
chunk = await file.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
if size > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=400, detail="The file is too large (max 15 MB).")
|
||||
chunks.append(chunk)
|
||||
data = b"".join(chunks)
|
||||
if not data:
|
||||
raise HTTPException(status_code=400, detail="The file is empty.")
|
||||
try:
|
||||
name = await run_in_threadpool(store_uploaded_asset, config, file.filename or "asset", data)
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
return AssetResponse(name=name)
|
||||
|
||||
|
||||
@router.post("/preview", response_model=PreviewResponse)
|
||||
async def preview_theme(body: PreviewRequest, config: TenantConfig = Depends(require_tenant_member)):
|
||||
try:
|
||||
styles = await run_in_threadpool(prepare_preview_styles, config, body.style_params)
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
await _PREVIEW_SEMAPHORE.acquire()
|
||||
future = loop.run_in_executor(
|
||||
_PREVIEW_EXECUTOR,
|
||||
lambda: render_theme_preview(
|
||||
_theme_id_for(config),
|
||||
styles,
|
||||
artist=body.sample.artist,
|
||||
title=body.sample.title,
|
||||
lyrics=body.sample.lyrics,
|
||||
),
|
||||
)
|
||||
# The slot is released only when the render really finishes — a timed-out
|
||||
# render keeps running in its thread, so releasing early would let a burst
|
||||
# queue unbounded work behind it.
|
||||
future.add_done_callback(lambda _f: _PREVIEW_SEMAPHORE.release())
|
||||
try:
|
||||
images = await asyncio.wait_for(asyncio.shield(future), timeout=PREVIEW_TIMEOUT_S)
|
||||
except ThemePreviewError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc))
|
||||
except asyncio.TimeoutError:
|
||||
raise HTTPException(status_code=504, detail="The preview took too long to render. Try again.")
|
||||
return PreviewResponse(**images.as_data_urls())
|
||||
|
||||
|
||||
class SaveResponse(ThemeResponse):
|
||||
# In-progress tracks switched to the new theme by this save.
|
||||
refreshed_jobs: int = 0
|
||||
# The caller's finished tracks made with an older theme (re-render to update).
|
||||
outdated_job_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OutdatedJobsResponse(BaseModel):
|
||||
theme_updated_at: Optional[str] = None
|
||||
job_ids: List[str]
|
||||
|
||||
|
||||
class RerenderOutdatedResponse(BaseModel):
|
||||
started: List[str]
|
||||
failed: Dict[str, str]
|
||||
# Outdated tracks beyond this call's cap (ask again to start them).
|
||||
remaining: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
# Tracks started per bulk call: bounds the request time and the burst of
|
||||
# render/encode work it queues. The UI offers the remainder again.
|
||||
MAX_BULK_RERENDER = 20
|
||||
|
||||
|
||||
def _owner_scope(auth_result: AuthResult) -> Optional[str]:
|
||||
"""Admins act on all the portal's tracks; members only on their own."""
|
||||
return None if auth_result.is_admin else auth_result.user_email
|
||||
|
||||
|
||||
@router.put("", response_model=SaveResponse)
|
||||
def save_theme(
|
||||
body: SaveRequest,
|
||||
config: TenantConfig = Depends(require_tenant_member),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
try:
|
||||
save_tenant_theme(config, body.style_params)
|
||||
theme = get_theme_for_editor(config)
|
||||
except TenantValidationError as exc:
|
||||
_raise_http(exc)
|
||||
theme_id = _theme_id_for(config)
|
||||
# Never fail the save over the follow-up work: the theme is already stored.
|
||||
refreshed = 0
|
||||
try:
|
||||
refreshed = refresh_inflight_jobs(config.id, theme_id)["updated"]
|
||||
except Exception:
|
||||
logger.exception(f"Tenant '{config.id}': refreshing in-progress tracks after theme save failed")
|
||||
outdated: List[str] = []
|
||||
try:
|
||||
outdated = outdated_jobs(config.id, theme_id, _owner_scope(auth_result))["job_ids"]
|
||||
except Exception:
|
||||
logger.exception(f"Tenant '{config.id}': listing outdated tracks after theme save failed")
|
||||
return SaveResponse(**theme, refreshed_jobs=refreshed, outdated_job_ids=outdated)
|
||||
|
||||
|
||||
@router.get("/outdated-jobs", response_model=OutdatedJobsResponse)
|
||||
def get_outdated_jobs(
|
||||
config: TenantConfig = Depends(require_tenant_member),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Finished tracks made with an older version of the theme (re-render to update)."""
|
||||
return OutdatedJobsResponse(**outdated_jobs(config.id, _theme_id_for(config), _owner_scope(auth_result)))
|
||||
|
||||
|
||||
@router.post("/rerender-outdated", response_model=RerenderOutdatedResponse)
|
||||
async def rerender_outdated(
|
||||
config: TenantConfig = Depends(require_tenant_member),
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
):
|
||||
"""Re-render every outdated finished track with the current theme.
|
||||
|
||||
Quiet: no per-track "your video is ready" email/push (one per track would
|
||||
flood the inbox); the portal shows progress on each track.
|
||||
"""
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
|
||||
|
||||
theme_id = _theme_id_for(config)
|
||||
job_ids = (await run_in_threadpool(
|
||||
outdated_jobs, config.id, theme_id, _owner_scope(auth_result)
|
||||
))["job_ids"]
|
||||
batch, remaining = job_ids[:MAX_BULK_RERENDER], job_ids[MAX_BULK_RERENDER:]
|
||||
job_manager = JobManager()
|
||||
service = ThemeRerenderService(job_manager)
|
||||
started: List[str] = []
|
||||
failed: Dict[str, str] = {}
|
||||
for job_id in batch:
|
||||
job = await run_in_threadpool(job_manager.get_job, job_id)
|
||||
if job is None:
|
||||
continue
|
||||
try:
|
||||
await service.start(
|
||||
job, theme_id=theme_id,
|
||||
requested_by=auth_result.user_email or "unknown",
|
||||
notify_customer=False,
|
||||
)
|
||||
started.append(job_id)
|
||||
except RerenderError as e:
|
||||
failed[job_id] = str(e)
|
||||
except Exception as e:
|
||||
logger.exception(f"[job:{job_id}] Bulk theme re-render failed to start")
|
||||
failed[job_id] = "Couldn't start the re-render."
|
||||
logger.info(
|
||||
f"Tenant '{config.id}': bulk re-render started {len(started)}, failed {len(failed)}, "
|
||||
f"remaining {len(remaining)}"
|
||||
)
|
||||
return RerenderOutdatedResponse(started=started, failed=failed, remaining=remaining)
|
||||
@@ -6,6 +6,7 @@ These endpoints are public (no authentication required) to allow theme selection
|
||||
before job creation.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
@@ -21,7 +22,7 @@ router = APIRouter(prefix="/themes", tags=["themes"])
|
||||
|
||||
|
||||
@router.get("", response_model=ThemesListResponse)
|
||||
async def list_themes(request: Request) -> ThemesListResponse:
|
||||
def list_themes(request: Request) -> ThemesListResponse:
|
||||
"""
|
||||
List all available themes.
|
||||
|
||||
@@ -43,8 +44,37 @@ async def list_themes(request: Request) -> ThemesListResponse:
|
||||
)
|
||||
|
||||
|
||||
@router.get("/translation-preview")
|
||||
async def get_translation_preview(language: str, request: Request) -> dict:
|
||||
"""
|
||||
Preview frame of a translated-lyrics karaoke video in ``language``.
|
||||
|
||||
Renders the default theme's karaoke frame with sample lyrics and their
|
||||
(pre-generated) translation beneath each line, so users can see the option
|
||||
before enabling it at job creation. Public, like the other theme endpoints.
|
||||
|
||||
Returns:
|
||||
Object with ``image`` (JPEG data URL)
|
||||
|
||||
Raises:
|
||||
400: Unsupported language
|
||||
"""
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
from backend.services.translation_preview import render_translation_preview
|
||||
|
||||
code = normalize_language(language)
|
||||
if code is None:
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported language: {language}")
|
||||
try:
|
||||
image = await asyncio.to_thread(render_translation_preview, code)
|
||||
except Exception as e:
|
||||
logger.error(f"Error rendering translation preview for {code}: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail="Could not render the translation preview")
|
||||
return {"image": image}
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
"""
|
||||
Get detailed information about a specific theme.
|
||||
|
||||
@@ -83,7 +113,7 @@ async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse:
|
||||
|
||||
|
||||
@router.get("/{theme_id}/preview")
|
||||
async def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get a signed URL for the theme's preview image.
|
||||
|
||||
@@ -128,7 +158,7 @@ async def get_theme_preview(theme_id: str, request: Request) -> dict:
|
||||
|
||||
|
||||
@router.get("/{theme_id}/youtube-description")
|
||||
async def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
|
||||
def get_theme_youtube_description(theme_id: str, request: Request) -> dict:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
|
||||
+275
-92
@@ -12,7 +12,8 @@ import hashlib
|
||||
import html
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Tuple
|
||||
|
||||
|
||||
@@ -100,6 +101,10 @@ def _build_user_public(user, role_override=None, feedback_eligible=False):
|
||||
except Exception:
|
||||
discount_percent = 10 # default fallback
|
||||
|
||||
from backend.services.conversion_emails import active_promo
|
||||
|
||||
promo = active_promo(user)
|
||||
|
||||
return UserPublic(
|
||||
email=user.email,
|
||||
role=role_override or user.role,
|
||||
@@ -114,6 +119,8 @@ def _build_user_public(user, role_override=None, feedback_eligible=False):
|
||||
has_active_referral_discount=has_discount,
|
||||
referral_discount_percent=discount_percent,
|
||||
referral_discount_expires_at=discount_expires,
|
||||
promo_discount_percent=promo[0] if promo else None,
|
||||
promo_discount_expires_at=promo[1].isoformat() if promo else None,
|
||||
referred_by_code=user.referred_by_code,
|
||||
)
|
||||
from backend.services.youtube_download_service import (
|
||||
@@ -187,12 +194,13 @@ class LogoutResponse(BaseModel):
|
||||
# =============================================================================
|
||||
|
||||
|
||||
def _precompute_credit_eval(token: str, email: str) -> None:
|
||||
"""Run credit evaluation in background and store result on magic link doc.
|
||||
def _precompute_credit_eval(token: str, email: str, collection: Optional[str] = None) -> None:
|
||||
"""Run credit evaluation in background and store result on the sign-in doc.
|
||||
|
||||
Called in a background thread after sending a magic link for new users.
|
||||
If the user clicks the link before this finishes, verify_magic_link falls
|
||||
back to inline evaluation (same as before this optimization).
|
||||
Called in a background thread after sending a magic link (or a kjbox emailed
|
||||
code — pass ``collection`` + that doc's id as ``token``) for new users. If the
|
||||
user verifies before this finishes, verification falls back to inline
|
||||
evaluation (same as before this optimization).
|
||||
"""
|
||||
try:
|
||||
from backend.services.credit_evaluation_service import get_credit_evaluation_service
|
||||
@@ -202,7 +210,7 @@ def _precompute_credit_eval(token: str, email: str) -> None:
|
||||
evaluation = eval_service.evaluate(email, "welcome")
|
||||
|
||||
user_service = get_user_service()
|
||||
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
user_service.db.collection(collection or MAGIC_LINKS_COLLECTION).document(token).update({
|
||||
"credit_eval_decision": evaluation.decision,
|
||||
"credit_eval_reasoning": evaluation.reasoning,
|
||||
"credit_eval_error": evaluation.error,
|
||||
@@ -213,7 +221,7 @@ def _precompute_credit_eval(token: str, email: str) -> None:
|
||||
|
||||
|
||||
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
|
||||
async def send_magic_link(
|
||||
def send_magic_link(
|
||||
request: SendMagicLinkRequest,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -237,7 +245,15 @@ async def send_magic_link(
|
||||
|
||||
locale = get_locale_from_request(http_request)
|
||||
|
||||
if email_validation.is_disposable_domain(email):
|
||||
# On a tenant portal, an address the tenant explicitly allowlisted (by email
|
||||
# or domain) was vouched for by an admin — don't second-guess it with the
|
||||
# disposable-domain heuristics (external APIs have false positives).
|
||||
request_tenant_config = get_tenant_config_from_request(http_request)
|
||||
tenant_vouched = bool(
|
||||
request_tenant_config and request_tenant_config.is_explicitly_allowlisted(email)
|
||||
)
|
||||
|
||||
if not tenant_vouched and email_validation.is_disposable_domain(email):
|
||||
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
@@ -296,9 +312,9 @@ async def send_magic_link(
|
||||
tenant_config = get_tenant_config_from_request(http_request)
|
||||
|
||||
# Validate email domain for tenant if configured
|
||||
if tenant_config and tenant_config.auth.allowed_email_domains:
|
||||
if tenant_config:
|
||||
if not tenant_config.is_email_allowed(email):
|
||||
logger.warning(f"Email domain not allowed for tenant {tenant_id}: {_mask_email(email)}")
|
||||
logger.warning(f"Email not allowed for tenant {tenant_id}: {_mask_email(email)}")
|
||||
# Return success anyway to prevent email enumeration
|
||||
return SendMagicLinkResponse(
|
||||
status="success",
|
||||
@@ -317,6 +333,7 @@ async def send_magic_link(
|
||||
device_fingerprint=device_fingerprint,
|
||||
referral_code=request.referral_code,
|
||||
purpose=request.purpose,
|
||||
attribution=request.attribution,
|
||||
)
|
||||
|
||||
# Get tenant-specific email configuration
|
||||
@@ -355,7 +372,9 @@ async def send_magic_link(
|
||||
# will be ready and verification will be instant.
|
||||
# Skip for test emails — they get auto-granted without evaluation.
|
||||
# Skip for board sign-in — it never grants a welcome credit, so there's nothing to eval.
|
||||
if existing_user is None and not is_test_email(email) and not is_board_signin:
|
||||
# Skip for tenant portals — tenant users are billed under a separate agreement and
|
||||
# never get consumer welcome credits.
|
||||
if existing_user is None and not is_test_email(email) and not is_board_signin and not tenant_id:
|
||||
thread = threading.Thread(
|
||||
target=_precompute_credit_eval,
|
||||
args=(magic_link.token, email),
|
||||
@@ -386,8 +405,113 @@ def _magic_link_redirect_path(purpose) -> "Optional[str]":
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class VerifiedLogin:
|
||||
"""Outcome of the shared post-verification login steps."""
|
||||
user: object
|
||||
session: object
|
||||
credits_granted: int = 0
|
||||
credit_status: str = "not_applicable"
|
||||
|
||||
|
||||
def complete_verified_login(
|
||||
user,
|
||||
*,
|
||||
user_service: UserService,
|
||||
email_service: EmailService,
|
||||
is_first_login: bool,
|
||||
precomputed_eval: Optional[dict],
|
||||
grant_welcome_credit: bool,
|
||||
referral_code: Optional[str],
|
||||
locale: Optional[str],
|
||||
ui_locale: Optional[str],
|
||||
ip_address: Optional[str],
|
||||
user_agent: Optional[str],
|
||||
tenant_id: Optional[str],
|
||||
device_fingerprint: Optional[str],
|
||||
email_locale: str = "en",
|
||||
) -> VerifiedLogin:
|
||||
"""Everything that happens after an identity proof (magic link click or kjbox
|
||||
emailed code) succeeds: welcome-credit grant (with the precomputed AI eval),
|
||||
referral attribution, locale persistence, session creation and the first-login
|
||||
welcome email.
|
||||
|
||||
``user`` must already be marked verified (email_verified / last_login_at) by
|
||||
the caller's verification step.
|
||||
|
||||
Args:
|
||||
locale: Narrowed email locale (en/es/de) to persist on the user, or None
|
||||
to leave the stored value untouched (e.g. no Accept-Language header).
|
||||
ui_locale: Full UI language subtag to persist, or None.
|
||||
email_locale: Locale used to render the welcome email.
|
||||
"""
|
||||
credits_granted = 0
|
||||
credit_status = "not_applicable" # returning user, not first login
|
||||
granted = False
|
||||
if grant_welcome_credit:
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
if granted:
|
||||
credits_granted = user_service.NEW_USER_FREE_CREDITS
|
||||
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
|
||||
# Refresh user to get updated credit balance
|
||||
user = user_service.get_user(user.email)
|
||||
elif credit_status == "denied":
|
||||
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
|
||||
|
||||
if referral_code and not user.referred_by_code:
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
attr_success, attr_msg = referral_svc.attribute_referral(
|
||||
referred_email=user.email,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
if attr_success:
|
||||
attr_data = referral_svc.get_attribution_data(referral_code)
|
||||
if attr_data:
|
||||
user_service.update_user(user.email, **attr_data)
|
||||
user = user_service.get_user(user.email) # Refresh to include referral data
|
||||
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
|
||||
|
||||
# `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.
|
||||
locale_updates = {}
|
||||
if 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:
|
||||
try:
|
||||
user_service.update_user(user.email, **locale_updates)
|
||||
except Exception:
|
||||
pass # Non-critical — don't block login
|
||||
|
||||
session = user_service.create_session(
|
||||
user.email,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=tenant_id,
|
||||
device_fingerprint=device_fingerprint,
|
||||
)
|
||||
|
||||
# Send welcome email to first-time users (not when the welcome credit is
|
||||
# skipped, e.g. board sign-in — the credit-centric copy would be confusing
|
||||
# with a 0 balance).
|
||||
if is_first_login and grant_welcome_credit:
|
||||
email_service.send_welcome_email(user.email, user.credits, locale=email_locale)
|
||||
|
||||
return VerifiedLogin(
|
||||
user=user, session=session,
|
||||
credits_granted=credits_granted, credit_status=credit_status,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/auth/verify", response_model=VerifyMagicLinkResponse)
|
||||
async def verify_magic_link(
|
||||
def verify_magic_link(
|
||||
token: str,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -431,7 +555,6 @@ async def verify_magic_link(
|
||||
if not success or not user:
|
||||
raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message))
|
||||
|
||||
# Grant welcome credits on first verification (with AI abuse evaluation)
|
||||
# Use pre-computed evaluation from magic link if available (computed at send time)
|
||||
precomputed_eval = None
|
||||
if magic_link_doc.exists:
|
||||
@@ -441,80 +564,44 @@ async def verify_magic_link(
|
||||
if magic_link_data.get(k) is not None
|
||||
} or None
|
||||
|
||||
credits_granted = 0
|
||||
credit_status = "not_applicable" # returning user, not first login
|
||||
# Board sign-in grants NO welcome credit — it's identity only. The credit is granted
|
||||
# later, when the user converts via the "make it yourself now" flow (claim endpoint),
|
||||
# or when their requested track gets picked (Phase 2).
|
||||
is_board_signin = magic_link_purpose == "requests_board"
|
||||
granted = False
|
||||
if not is_board_signin:
|
||||
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
|
||||
user.email, precomputed_eval=precomputed_eval,
|
||||
)
|
||||
if granted:
|
||||
credits_granted = user_service.NEW_USER_FREE_CREDITS
|
||||
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
|
||||
# Refresh user to get updated credit balance
|
||||
user = user_service.get_user(user.email)
|
||||
elif credit_status == "denied":
|
||||
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
|
||||
|
||||
# Referral attribution: try header first (cookie path), then magic link token (email path), then URL param
|
||||
# Referral attribution: try header first (cookie path), then magic link token (email path)
|
||||
referral_code = (
|
||||
http_request.headers.get("x-referral-code")
|
||||
or (magic_link_data.get("referral_code") if magic_link_doc.exists else None)
|
||||
)
|
||||
if referral_code and not user.referred_by_code:
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
attr_success, attr_msg = referral_svc.attribute_referral(
|
||||
referred_email=user.email,
|
||||
referral_code=referral_code,
|
||||
)
|
||||
if attr_success:
|
||||
attr_data = referral_svc.get_attribution_data(referral_code)
|
||||
if attr_data:
|
||||
user_service.update_user(user.email, **attr_data)
|
||||
user = user_service.get_user(user.email) # Refresh to include referral data
|
||||
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
|
||||
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:
|
||||
try:
|
||||
user_service.update_user(user.email, **locale_updates)
|
||||
except Exception:
|
||||
pass # Non-critical — don't block login
|
||||
has_accept_language = bool(http_request.headers.get("accept-language"))
|
||||
|
||||
# Create session with tenant context and device fingerprint from the magic link
|
||||
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
|
||||
session = user_service.create_session(
|
||||
user.email,
|
||||
# Board sign-in grants NO welcome credit — it's identity only. The credit is granted
|
||||
# later, when the user converts via the "make it yourself now" flow (claim endpoint),
|
||||
# or when their requested track gets picked (Phase 2).
|
||||
# Tenant portal sign-ins never touch consumer credits (no eval, no denial/welcome
|
||||
# emails, no credit interstitial) — tenants have a separate commercial agreement.
|
||||
result = complete_verified_login(
|
||||
user,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
is_first_login=is_first_login,
|
||||
precomputed_eval=precomputed_eval,
|
||||
grant_welcome_credit=magic_link_purpose != "requests_board" and not magic_link_tenant_id,
|
||||
referral_code=referral_code if not magic_link_tenant_id else None,
|
||||
locale=locale if has_accept_language else None,
|
||||
ui_locale=get_full_locale_from_request(http_request),
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
tenant_id=magic_link_tenant_id,
|
||||
device_fingerprint=magic_link_fingerprint,
|
||||
email_locale=locale,
|
||||
)
|
||||
|
||||
# Send welcome email to first-time users (not for board sign-in — no credit granted,
|
||||
# and the credit-centric welcome copy would be confusing with a 0 balance).
|
||||
if is_first_login and not is_board_signin:
|
||||
email_service.send_welcome_email(user.email, user.credits, locale=locale)
|
||||
user = result.user
|
||||
session = result.session
|
||||
credits_granted = result.credits_granted
|
||||
credit_status = result.credit_status
|
||||
|
||||
# Return user info with tenant_id
|
||||
user_public = _build_user_public(user)
|
||||
@@ -548,7 +635,7 @@ class ClaimWelcomeCreditResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/claim-welcome-credit", response_model=ClaimWelcomeCreditResponse)
|
||||
async def claim_welcome_credit(
|
||||
def claim_welcome_credit(
|
||||
auth_result: AuthResult = Depends(require_auth),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -578,7 +665,7 @@ class MagicLinkStatusResponse(BaseModel):
|
||||
|
||||
|
||||
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
|
||||
async def magic_link_status(
|
||||
def magic_link_status(
|
||||
token: str,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -600,7 +687,7 @@ async def magic_link_status(
|
||||
|
||||
|
||||
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
|
||||
async def resend_magic_link_from_token(
|
||||
def resend_magic_link_from_token(
|
||||
request: ResendFromTokenRequest,
|
||||
http_request: Request,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -751,7 +838,7 @@ async def resend_magic_link_from_token(
|
||||
|
||||
|
||||
@router.post("/auth/logout", response_model=LogoutResponse)
|
||||
async def logout(
|
||||
def logout(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -776,7 +863,7 @@ async def logout(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/me", response_model=UserProfileResponse)
|
||||
async def get_current_user(
|
||||
def get_current_user(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -833,7 +920,7 @@ async def get_current_user(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/credits/packages", response_model=CreditPackagesResponse)
|
||||
async def list_credit_packages():
|
||||
def list_credit_packages():
|
||||
"""
|
||||
List available credit packages for purchase.
|
||||
|
||||
@@ -854,7 +941,7 @@ async def list_credit_packages():
|
||||
|
||||
|
||||
@router.post("/credits/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_checkout(
|
||||
def create_checkout(
|
||||
request: CreateCheckoutRequest,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
):
|
||||
@@ -869,15 +956,26 @@ async def create_checkout(
|
||||
|
||||
# Check for referral discount
|
||||
referral_coupon_id = None
|
||||
referral_percent = 0
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
discount_info = referral_svc.get_discount_for_checkout(request.email)
|
||||
if discount_info:
|
||||
referral_coupon_id = discount_info["coupon_id"]
|
||||
referral_percent = discount_info.get("discount_percent") or 0
|
||||
except Exception as ref_err:
|
||||
logger.warning(f"Referral discount lookup failed: {ref_err}")
|
||||
|
||||
# A time-limited conversion-email offer wins when it's the bigger discount
|
||||
try:
|
||||
from backend.services.conversion_emails import promo_coupon_for_checkout
|
||||
promo_coupon = promo_coupon_for_checkout(request.email, better_than_percent=referral_percent)
|
||||
if promo_coupon:
|
||||
referral_coupon_id = promo_coupon
|
||||
except Exception as promo_err:
|
||||
logger.warning(f"Promo discount lookup failed: {promo_err}")
|
||||
|
||||
success, checkout_url, message = stripe_service.create_checkout_session(
|
||||
package_id=request.package_id,
|
||||
user_email=request.email,
|
||||
@@ -895,7 +993,7 @@ async def create_checkout(
|
||||
|
||||
|
||||
@router.post("/made-for-you/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_made_for_you_checkout(
|
||||
def create_made_for_you_checkout(
|
||||
request: MadeForYouCheckoutRequest,
|
||||
http_request: Request,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
@@ -1464,7 +1562,8 @@ async def stripe_webhook(
|
||||
try:
|
||||
from backend.services.referral_service import get_referral_service
|
||||
referral_svc = get_referral_service()
|
||||
amount_charged = session.get("amount_total", 0)
|
||||
# Referrers earn on the credit purchase, not on a tip
|
||||
amount_charged = stripe_service.referral_base_cents(session)
|
||||
if amount_charged > 0:
|
||||
earning_result = referral_svc.record_earning(
|
||||
referred_email=user_email,
|
||||
@@ -1499,7 +1598,7 @@ async def stripe_webhook(
|
||||
import stripe as stripe_lib
|
||||
expanded_session = stripe_lib.checkout.Session.retrieve(
|
||||
session_id,
|
||||
expand=["payment_intent.latest_charge.balance_transaction"],
|
||||
expand=["payment_intent.latest_charge.balance_transaction", "line_items"],
|
||||
)
|
||||
admin_service.store_payment(dict(expanded_session))
|
||||
except Exception as store_err:
|
||||
@@ -1621,7 +1720,7 @@ async def stripe_webhook(
|
||||
# =============================================================================
|
||||
|
||||
@router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse)
|
||||
async def check_feedback_eligibility(
|
||||
def check_feedback_eligibility(
|
||||
request: Request,
|
||||
authorization: Optional[str] = Header(None),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -1661,7 +1760,7 @@ async def check_feedback_eligibility(
|
||||
|
||||
|
||||
@router.post("/feedback", response_model=UserFeedbackResponse)
|
||||
async def submit_user_feedback(
|
||||
def submit_user_feedback(
|
||||
http_request: Request,
|
||||
request: UserFeedbackRequest,
|
||||
authorization: Optional[str] = Header(None),
|
||||
@@ -1880,12 +1979,93 @@ class UserDetailResponse(BaseModel):
|
||||
referred_by_code: Optional[str] = None
|
||||
referral_discount_expires_at: Optional[str] = None
|
||||
referral_code: Optional[str] = None
|
||||
# Acquisition: channel label + first-touch UTM/referrer detail
|
||||
signup_source: Optional[str] = None
|
||||
signup_venue: Optional[str] = None
|
||||
signup_attribution: Optional[dict] = None
|
||||
# Recent session details (IP, user agent, fingerprint)
|
||||
recent_sessions: list[dict] = []
|
||||
|
||||
|
||||
class AttributionSourceRow(BaseModel):
|
||||
"""Funnel counts for one acquisition channel."""
|
||||
source: str
|
||||
signups: int = 0
|
||||
verified: int = 0
|
||||
made_job: int = 0
|
||||
paid: int = 0
|
||||
revenue_cents: int = 0
|
||||
|
||||
|
||||
class AttributionSummaryResponse(BaseModel):
|
||||
days: int
|
||||
total_signups: int
|
||||
sources: list[AttributionSourceRow]
|
||||
|
||||
|
||||
def _as_datetime(value) -> Optional[datetime]:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
parsed = value
|
||||
else:
|
||||
try:
|
||||
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
# Compare as naive UTC (model_dump stores utcnow() ISO strings without an offset)
|
||||
if parsed.tzinfo:
|
||||
parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
return parsed
|
||||
|
||||
|
||||
@router.get("/admin/attribution-summary", response_model=AttributionSummaryResponse)
|
||||
def attribution_summary(
|
||||
days: int = 90,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Signups -> verified -> made a job -> paid, grouped by signup_source (admin only).
|
||||
|
||||
Covers consumer accounts created in the last ``days`` (test and tenant users
|
||||
excluded). Users without a recorded source show as "direct / unknown"; all
|
||||
accounts created before attribution capture shipped (2026-10) land there.
|
||||
"""
|
||||
from datetime import timedelta
|
||||
|
||||
days = max(1, min(days, 3650))
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
fields = [
|
||||
"email", "created_at", "signup_source", "email_verified",
|
||||
"total_jobs_created", "total_spent", "tenant_id",
|
||||
]
|
||||
rows: dict[str, AttributionSourceRow] = {}
|
||||
total = 0
|
||||
for doc in user_service.db.collection(USERS_COLLECTION).select(fields).stream():
|
||||
data = doc.to_dict() or {}
|
||||
if data.get("tenant_id") or is_test_email(data.get("email", "")):
|
||||
continue
|
||||
created = _as_datetime(data.get("created_at"))
|
||||
if not created or created < cutoff:
|
||||
continue
|
||||
source = data.get("signup_source") or "direct / unknown"
|
||||
row = rows.setdefault(source, AttributionSourceRow(source=source))
|
||||
row.signups += 1
|
||||
total += 1
|
||||
if data.get("email_verified"):
|
||||
row.verified += 1
|
||||
if (data.get("total_jobs_created") or 0) > 0:
|
||||
row.made_job += 1
|
||||
spent = data.get("total_spent") or 0
|
||||
if spent > 0:
|
||||
row.paid += 1
|
||||
row.revenue_cents += spent
|
||||
sources = sorted(rows.values(), key=lambda r: (-r.paid, -r.signups, r.source))
|
||||
return AttributionSummaryResponse(days=days, total_signups=total, sources=sources)
|
||||
|
||||
|
||||
@router.get("/admin/users", response_model=UserListResponsePaginated)
|
||||
async def list_users(
|
||||
def list_users(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
search: Optional[str] = None,
|
||||
@@ -1983,7 +2163,7 @@ async def list_users(
|
||||
|
||||
|
||||
@router.get("/admin/users/{email}/detail", response_model=UserDetailResponse)
|
||||
async def get_user_detail(
|
||||
def get_user_detail(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
@@ -2081,12 +2261,15 @@ async def get_user_detail(
|
||||
referred_by_code=user.referred_by_code,
|
||||
referral_discount_expires_at=user.referral_discount_expires_at.isoformat() if user.referral_discount_expires_at and hasattr(user.referral_discount_expires_at, 'isoformat') else str(user.referral_discount_expires_at) if user.referral_discount_expires_at else None,
|
||||
referral_code=user.referral_code,
|
||||
signup_source=user.signup_source,
|
||||
signup_venue=user.signup_venue,
|
||||
signup_attribution=user.signup_attribution,
|
||||
recent_sessions=active_sessions,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/admin/users", response_model=AdminCreateUserResponse, status_code=201)
|
||||
async def admin_create_user(
|
||||
def admin_create_user(
|
||||
request: AdminCreateUserRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -2148,7 +2331,7 @@ async def admin_create_user(
|
||||
|
||||
|
||||
@router.post("/admin/credits", response_model=AddCreditsResponse)
|
||||
async def add_credits_to_user(
|
||||
def add_credits_to_user(
|
||||
request: AddCreditsRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
@@ -2185,7 +2368,7 @@ async def add_credits_to_user(
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/disable")
|
||||
async def disable_user(
|
||||
def disable_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2206,7 +2389,7 @@ async def disable_user(
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/enable")
|
||||
async def enable_user(
|
||||
def enable_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2227,7 +2410,7 @@ async def enable_user(
|
||||
|
||||
|
||||
@router.delete("/admin/users/{email}")
|
||||
async def delete_user(
|
||||
def delete_user(
|
||||
email: str,
|
||||
request: Request,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
@@ -2253,7 +2436,7 @@ async def delete_user(
|
||||
|
||||
|
||||
@router.post("/admin/users/{email}/role")
|
||||
async def set_user_role(
|
||||
def set_user_role(
|
||||
email: str,
|
||||
role: UserRole,
|
||||
request: Request,
|
||||
|
||||
@@ -15,9 +15,9 @@ steps:
|
||||
- '-f'
|
||||
- 'backend/Dockerfile.gpu-base'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
|
||||
- '-t'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- '--build-arg'
|
||||
- 'BUILD_DATE=$_BUILD_DATE'
|
||||
- '--build-arg'
|
||||
@@ -25,8 +25,8 @@ steps:
|
||||
- '.'
|
||||
|
||||
images:
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
|
||||
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:latest'
|
||||
- 'us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-gpu-base:$BUILD_ID'
|
||||
|
||||
timeout: '3600s'
|
||||
|
||||
|
||||
+113
-10
@@ -6,7 +6,10 @@ import logging
|
||||
from typing import Optional, Dict
|
||||
from dotenv import load_dotenv
|
||||
from pydantic_settings import BaseSettings
|
||||
from google.cloud import secretmanager
|
||||
|
||||
# google.cloud.secretmanager is imported lazily in get_secret() — importing it
|
||||
# (and the google.api_core/grpc graph behind it) costs ~1.7s and config is
|
||||
# imported by every backend entrypoint (cold-start work, 2026-09-22).
|
||||
|
||||
# Load .env for local development (no-op when absent, e.g. in Cloud Run).
|
||||
# Must run before the Settings class body below, which reads os.getenv at
|
||||
@@ -64,6 +67,10 @@ class Settings(BaseSettings):
|
||||
|
||||
# Application
|
||||
environment: str = os.getenv("ENVIRONMENT", "development")
|
||||
# Event-loop stall watchdog (backend/services/loop_watchdog.py): logs the
|
||||
# blocking stack when the single uvicorn loop stops ticking for >1s, and
|
||||
# records stalls >=5s to Firestore client_events (production only).
|
||||
loop_watchdog_enabled: bool = os.getenv("LOOP_WATCHDOG_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
log_level: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
|
||||
# Processing
|
||||
@@ -79,9 +86,9 @@ class Settings(BaseSettings):
|
||||
|
||||
# Agentic AI Correction (for lyrics correction via LLM)
|
||||
# Only used when skip_correction=false
|
||||
# When enabled, uses Gemini via Vertex AI for intelligent lyrics correction
|
||||
# When enabled, uses Gemini (Developer API, key GEMINI_API_KEY) for intelligent lyrics correction
|
||||
use_agentic_ai: bool = os.getenv("USE_AGENTIC_AI", "true").lower() in ("true", "1", "yes")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "vertexai/gemini-3-flash-preview")
|
||||
agentic_ai_model: str = os.getenv("AGENTIC_AI_MODEL", "gemini/gemini-3.8-flash")
|
||||
# Timeout for agentic correction in seconds. If correction takes longer, abort and
|
||||
# use uncorrected transcription - human review will fix any issues.
|
||||
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
|
||||
@@ -102,22 +109,26 @@ class Settings(BaseSettings):
|
||||
# before granting. Fail-CLOSED: if evaluation fails, the decision becomes
|
||||
# "pending_review" (no auto-grant; an admin is notified to decide).
|
||||
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
|
||||
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.8-flash")
|
||||
|
||||
# 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_model: str = os.getenv("CUSTOM_LYRICS_MODEL", "gemini-3.8-flash")
|
||||
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"))
|
||||
|
||||
# Translated lyrics — per-job opt-in (Job.translation_language): the reviewed
|
||||
# lyrics are translated line-by-line just before the karaoke video renders.
|
||||
lyrics_translation_model: str = os.getenv("LYRICS_TRANSLATION_MODEL", "gemini-3.8-flash")
|
||||
|
||||
# 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")
|
||||
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.8-flash")
|
||||
# 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", "")
|
||||
@@ -172,7 +183,7 @@ class Settings(BaseSettings):
|
||||
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")
|
||||
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.8-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
|
||||
@@ -184,7 +195,7 @@ class Settings(BaseSettings):
|
||||
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_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.8-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
|
||||
@@ -202,6 +213,16 @@ class Settings(BaseSettings):
|
||||
# must still enqueue to the real queue location — building queue paths from
|
||||
# gcp_region 404s from those workers ("Queue does not exist").
|
||||
cloud_tasks_region: str = os.getenv("CLOUD_TASKS_REGION", "us-central1")
|
||||
# Region of the latency-critical CPU Cloud Run Jobs (audio-download-job,
|
||||
# lyrics-transcription-job, bulk-search-job, video-encoding-job). Cloud Run
|
||||
# Jobs in us-central1 queue 2-5 min before the container starts (measured
|
||||
# 2026-09-28 with a tiny sample image: us-central1 4-5 min vs us-east4 8-19s),
|
||||
# independent of image size or CPU. video-encoding-job reads ~0.3 GB/run from
|
||||
# the us-central1 bucket cross-region (~$1.60/mo, 2026-09-29 model). Rollback:
|
||||
# recreate the jobs in us-central1 via Pulumi, then set CPU_JOBS_REGION on the
|
||||
# service AND the jobs (see docs/TROUBLESHOOTING.md). Deliberately separate from gcp_region,
|
||||
# which these workers use for other resources (queues, encoding VM zones).
|
||||
cpu_jobs_region: str = os.getenv("CPU_JOBS_REGION", "us-east4")
|
||||
|
||||
# Cloud Run Jobs (for long-running video encoding)
|
||||
# When enabled AND enable_cloud_tasks is true, video worker uses Cloud Run Jobs
|
||||
@@ -263,6 +284,16 @@ class Settings(BaseSettings):
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
|
||||
# Search retry settings are much lighter than the download defaults above:
|
||||
# search is called synchronously from user-facing requests that sit behind
|
||||
# Cloudflare's ~100s edge timeout, so there's only room for one quick retry
|
||||
# (worst case: 60s timeout + 1s wait + fast cache-hit retry).
|
||||
flacfetch_search_retry_max_attempts: int = int(os.getenv("FLACFETCH_SEARCH_RETRY_MAX_ATTEMPTS", "2"))
|
||||
flacfetch_search_retry_wait: float = float(os.getenv("FLACFETCH_SEARCH_RETRY_WAIT", "1.0")) # seconds
|
||||
# Total budget across all search attempts, kept under Cloudflare's ~100s edge
|
||||
# deadline so callers get a clean FlacfetchServiceError instead of an edge 524.
|
||||
flacfetch_search_total_timeout: float = float(os.getenv("FLACFETCH_SEARCH_TOTAL_TIMEOUT", "95.0")) # seconds
|
||||
|
||||
# Default distribution settings (can be overridden per-request)
|
||||
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
|
||||
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
|
||||
@@ -288,10 +319,44 @@ class Settings(BaseSettings):
|
||||
# When a flagged pick is "kept on board", how long before it can be re-flagged.
|
||||
community_review_snooze_days: int = int(os.getenv("COMMUNITY_REVIEW_SNOOZE_DAYS", "30"))
|
||||
|
||||
# KaraokeHunt retired-app request interceptor (POST /api/karaokehunt/request).
|
||||
# Shared secret set by the Cloudflare Worker on create.karaokehunt.com; the
|
||||
# endpoint 503s while this is empty, so deploys are dark until the secret is
|
||||
# wired (Secret Manager: karaokehunt-forwarder-secret).
|
||||
karaokehunt_forwarder_secret: str = os.getenv("KARAOKEHUNT_FORWARDER_SECRET", "")
|
||||
# Max conversion jobs per UTC day (bounds unattended generation spend);
|
||||
# over-cap requests fall through to the free community requests board.
|
||||
karaokehunt_daily_job_cap: int = int(os.getenv("KARAOKEHUNT_DAILY_JOB_CAP", "3"))
|
||||
|
||||
# kjbox partner API (/api/kjbox/*): singer email-code sign-in + show credits
|
||||
# for the karaoke-night "make it" flow. Every endpoint 503s while the secret is
|
||||
# empty, so deploys are dark until it's wired (Secret Manager: kjbox-partner-secret).
|
||||
kjbox_partner_secret: str = os.getenv("KJBOX_PARTNER_SECRET", "")
|
||||
# Partner-wide cap on NEW gen accounts created via kjbox per rolling 24h (a venue
|
||||
# shares one IP, so gen's per-IP signup cap is bypassed for kjbox; this bounds it).
|
||||
kjbox_signup_cap_per_24h: int = int(os.getenv("KJBOX_SIGNUP_CAP_PER_24H", "100"))
|
||||
# Max emailed sign-in codes per address per rolling hour.
|
||||
kjbox_codes_per_email_per_hour: int = int(os.getenv("KJBOX_CODES_PER_EMAIL_PER_HOUR", "5"))
|
||||
# Max "free at the show" credits kjbox may grant one user per rolling 24h.
|
||||
kjbox_show_credits_per_user_per_24h: int = int(os.getenv("KJBOX_SHOW_CREDITS_PER_USER_PER_24H", "5"))
|
||||
|
||||
# Private (non-published) track distribution settings
|
||||
default_private_dropbox_path: Optional[str] = os.getenv("DEFAULT_PRIVATE_DROPBOX_PATH")
|
||||
default_private_brand_prefix: Optional[str] = os.getenv("DEFAULT_PRIVATE_BRAND_PREFIX", "NOMADNP")
|
||||
|
||||
# Output files NOT uploaded to Nomad's own Dropbox folders (DEFAULT_DROPBOX_PATH /
|
||||
# DEFAULT_PRIVATE_DROPBOX_PATH), as "|"-separated filename suffixes. They stay in
|
||||
# GCS (job-page downloads, YouTube upload, AWS backup) — this only saves the
|
||||
# multi-GB internet egress + upload time. Tenant Dropbox folders are exempt
|
||||
# (B2B tenants expect the full set). Default skips only the lossless 4K MP4,
|
||||
# which no customer-facing text promises in Dropbox. The lossless MKV IS promised
|
||||
# there (completion email + the Fiverr bot), so add
|
||||
# " (Final Karaoke Lossless 4k).mkv" only after updating those.
|
||||
# See docs/archive/2026-09-26-encoding-cost-cuts.md.
|
||||
dropbox_skip_output_suffixes: str = os.getenv(
|
||||
"DROPBOX_SKIP_OUTPUT_SUFFIXES", " (Final Karaoke Lossless 4k).mp4"
|
||||
)
|
||||
|
||||
# YouTube Data API v3 Quota Configuration
|
||||
# Daily quota limit (YouTube grants 10,000 units/day by default)
|
||||
youtube_quota_daily_limit: int = int(os.getenv("YOUTUBE_QUOTA_DAILY_LIMIT", "10000"))
|
||||
@@ -315,10 +380,10 @@ class Settings(BaseSettings):
|
||||
"Vote for the songs you want us to make next — the most-upvoted requests get "
|
||||
"made into karaoke videos and published free, right here on this channel. "
|
||||
"Nothing to buy, no password needed:\n"
|
||||
"👉 https://requests.nomadkaraoke.com\n\n"
|
||||
"👉 https://requests.nomadkaraoke.com/?utm_source=youtube&utm_medium=description&utm_campaign=requests\n\n"
|
||||
"▶️ MAKE A VIDEO LIKE THIS FOR ANY SONG\n"
|
||||
"Create studio-quality karaoke videos of ANY song, ready in under an hour:\n"
|
||||
"👉 https://nomadkaraoke.com/r/youtube\n"
|
||||
"👉 https://nomadkaraoke.com/r/youtube?utm_source=youtube&utm_medium=description&utm_campaign=make_cta\n"
|
||||
"Follow that link for 50% off all credit purchases for your first 30 days.\n\n"
|
||||
"🎶 KARAOKE LOVER LINKS\n"
|
||||
"• Nomad Karaoke Community Discord: https://discord.nomadkaraoke.com\n"
|
||||
@@ -335,6 +400,25 @@ class Settings(BaseSettings):
|
||||
"Brand Code: {brand_code}"
|
||||
)
|
||||
|
||||
# Offer an opt-in "tip the creator" optional item on gen Stripe Checkout pages
|
||||
# (credits + Made For You). Kill switch: CHECKOUT_TIP_ENABLED=false.
|
||||
checkout_tip_enabled: bool = os.getenv("CHECKOUT_TIP_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
# Free-to-paid conversion emails (backend/services/conversion_emails.py).
|
||||
# OFF until Andrew approves the copy: CONVERSION_EMAILS_ENABLED=true sends E1
|
||||
# ("your next song" + time-limited discount) and E2 (offer ending) on Postmark's
|
||||
# broadcast stream; REVIEW_LAST_CHANCE_ENABLED=true adds the 42h review nudge.
|
||||
conversion_emails_enabled: bool = os.getenv("CONVERSION_EMAILS_ENABLED", "false").lower() in ("true", "1", "yes")
|
||||
review_last_chance_enabled: bool = os.getenv("REVIEW_LAST_CHANCE_ENABLED", "false").lower() in ("true", "1", "yes")
|
||||
conversion_offer_percent: int = int(os.getenv("CONVERSION_OFFER_PERCENT", "25"))
|
||||
conversion_offer_hours: int = int(os.getenv("CONVERSION_OFFER_HOURS", "48"))
|
||||
conversion_e1_delay_hours: float = float(os.getenv("CONVERSION_E1_DELAY_HOURS", "2"))
|
||||
conversion_e2_hours_before_expiry: float = float(os.getenv("CONVERSION_E2_HOURS_BEFORE_EXPIRY", "8"))
|
||||
# CAN-SPAM: commercial email must carry a physical postal address.
|
||||
# Default = the business address already published on nomadkaraoke.com.
|
||||
commercial_email_postal_address: str = os.getenv(
|
||||
"COMMERCIAL_EMAIL_POSTAL_ADDRESS", "Nomad Karaoke, 612 Joan St, Columbia, SC 29203, USA"
|
||||
)
|
||||
|
||||
# YouTube description back-catalogue rewrite (scheduled daily drain worker).
|
||||
# Rewrites existing channel videos to match `default_youtube_description`.
|
||||
# Reusable: whenever the template changes, the worker re-drains the channel.
|
||||
@@ -348,6 +432,23 @@ class Settings(BaseSettings):
|
||||
# Where the daily progress + completion emails are sent.
|
||||
youtube_backfill_report_email: str = os.getenv("YOUTUBE_BACKFILL_REPORT_EMAIL", "andrew@nomadkaraoke.com")
|
||||
|
||||
# Storage retention (backend/services/storage_retention.py): a daily job purges
|
||||
# regenerable files (big finals, rendered videos, stems, ...) from jobs
|
||||
# completed more than `storage_retention_min_age_days` ago. DRY-RUN BY DEFAULT:
|
||||
# it only writes a report until STORAGE_RETENTION_DRY_RUN=false is set after a
|
||||
# human has reviewed one.
|
||||
storage_retention_enabled: bool = os.getenv("STORAGE_RETENTION_ENABLED", "true").lower() in ("true", "1", "yes")
|
||||
storage_retention_dry_run: bool = os.getenv("STORAGE_RETENTION_DRY_RUN", "true").lower() not in ("false", "0", "no")
|
||||
storage_retention_min_age_days: int = int(os.getenv("STORAGE_RETENTION_MIN_AGE_DAYS", "30"))
|
||||
# Real (non-dry) runs purge at most this many jobs per run, resuming from a cursor.
|
||||
storage_retention_max_jobs_per_run: int = int(os.getenv("STORAGE_RETENTION_MAX_JOBS_PER_RUN", "50"))
|
||||
# Comma-separated tenant ids whose jobs are never purged.
|
||||
storage_retention_excluded_tenants: str = os.getenv("STORAGE_RETENTION_EXCLUDED_TENANTS", "")
|
||||
|
||||
# Customer "Regenerate video" limits (per job / per user, rolling 24h).
|
||||
regenerate_max_per_job_per_day: int = int(os.getenv("REGENERATE_MAX_PER_JOB_PER_DAY", "3"))
|
||||
regenerate_max_per_user_per_day: int = int(os.getenv("REGENERATE_MAX_PER_USER_PER_DAY", "10"))
|
||||
|
||||
# Default CDG/TXT generation settings
|
||||
# When True, CDG and TXT packages are generated by default (when a theme is set)
|
||||
# These can be overridden per-request via explicit enable_cdg/enable_txt parameters
|
||||
@@ -400,6 +501,8 @@ class Settings(BaseSettings):
|
||||
return None
|
||||
|
||||
try:
|
||||
from google.cloud import secretmanager
|
||||
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
name = f"projects/{self.google_cloud_project}/secrets/{secret_id}/versions/latest"
|
||||
response = client.access_secret_version(request={"name": name})
|
||||
|
||||
+139
-19
@@ -4,13 +4,16 @@ 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 asyncio
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
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, tenant_admin, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_admin, tenant_bulk, tenant_theme, rate_limits, push, catalog, encoding_worker, client_errors, client_events, bulk, parse_titles
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -38,7 +41,7 @@ tracing_enabled = setup_tracing(
|
||||
)
|
||||
|
||||
|
||||
async def validate_credentials_on_startup():
|
||||
def validate_credentials_on_startup():
|
||||
"""Validate OAuth credentials on startup and send alerts if needed."""
|
||||
try:
|
||||
from backend.services.credential_manager import get_credential_manager, CredentialStatus
|
||||
@@ -68,22 +71,49 @@ async def validate_credentials_on_startup():
|
||||
logger.error(f"Failed to validate credentials on startup: {e}")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Lifespan event handler for startup and shutdown."""
|
||||
# Startup
|
||||
logger.info("Starting karaoke generation backend")
|
||||
logger.info(f"Environment: {settings.environment}")
|
||||
logger.info(f"GCS Bucket: {settings.gcs_bucket_name}")
|
||||
logger.info(f"Tracing enabled: {tracing_enabled}")
|
||||
# Modules that route handlers import lazily. On a fresh instance the first such
|
||||
# import ran ON the event loop: httpx/httpcore (via flacfetch_client /
|
||||
# worker_service) froze it 3-15s on cold disk reads (EVENT_LOOP_STALL in
|
||||
# importlib, 2026-10-08). Lifespan startup imports them in a worker thread before
|
||||
# readiness — a background thread alone would still race the first request.
|
||||
_LAZY_ROUTE_IMPORTS = (
|
||||
"httpx",
|
||||
"backend.services.worker_service",
|
||||
"backend.services.flacfetch_client",
|
||||
"backend.services.catalog_proxy_service",
|
||||
"backend.services.ip_geolocation_service",
|
||||
"backend.services.email_validation_service",
|
||||
"backend.services.musicbrainz_service",
|
||||
)
|
||||
|
||||
# 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
|
||||
LAZY_ROUTE_IMPORT_TIMEOUT_S = 30
|
||||
|
||||
|
||||
def _import_lazy_route_modules() -> None:
|
||||
import importlib
|
||||
|
||||
for module in _LAZY_ROUTE_IMPORTS:
|
||||
try:
|
||||
importlib.import_module(module)
|
||||
except Exception as e:
|
||||
logger.warning(f"Startup import of {module} failed (will import lazily): {e}")
|
||||
|
||||
|
||||
def _run_background_warmup():
|
||||
"""Warm caches that used to block startup (runs in a daemon thread).
|
||||
|
||||
Historically these preloads ran inline in lifespan startup, which meant
|
||||
Cloud Run held every routed request for the full ~7.5s they take (spaCy
|
||||
~1s, NLTK ~2.5s, Langfuse ~3s, credential checks ~1.5s) on top of import
|
||||
time. None of them are needed to serve HTTP: they exist to make the FIRST
|
||||
lyrics-processing job fast (see docs/archive/2026-01-08-performance-
|
||||
investigation.md). Running them in a background thread right after boot
|
||||
keeps that warm-cache property (they finish within seconds, long before
|
||||
any real job runs) without gating readiness. Workers that race the warmup
|
||||
simply fall back to the preloaders' lazy paths.
|
||||
"""
|
||||
warmup_start = time.time()
|
||||
|
||||
# 1. SpaCy model (60+ second delay without preload)
|
||||
try:
|
||||
@@ -103,14 +133,92 @@ async def lifespan(app: FastAPI):
|
||||
except Exception as e:
|
||||
logger.warning(f"Langfuse preload failed (will initialize lazily): {e}")
|
||||
|
||||
# Validate OAuth credentials (non-blocking)
|
||||
# 4. Encoding service singleton — its first construction imports
|
||||
# google.cloud.compute_v1 (~10s on a fresh instance). Build it here, off the
|
||||
# event loop, before /api/health/detailed or a preview encode needs it.
|
||||
try:
|
||||
await validate_credentials_on_startup()
|
||||
from backend.services.encoding_service import get_encoding_service
|
||||
|
||||
get_encoding_service()
|
||||
except Exception as e:
|
||||
logger.warning(f"Encoding service warmup failed (will build lazily): {e}")
|
||||
|
||||
# Validate OAuth credentials (alerting only, nothing depends on it)
|
||||
try:
|
||||
validate_credentials_on_startup()
|
||||
except Exception as e:
|
||||
logger.error(f"Credential validation failed: {e}")
|
||||
|
||||
|
||||
logger.info(f"Background warmup complete in {time.time() - warmup_start:.2f}s")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Lifespan event handler for startup and shutdown."""
|
||||
# Startup
|
||||
logger.info("Starting karaoke generation backend")
|
||||
logger.info(f"Environment: {settings.environment}")
|
||||
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()
|
||||
|
||||
# Off the loop, but before readiness (Cloud Run holds requests meanwhile).
|
||||
# Bounded so a hung cold-disk read can't keep the instance from ever going
|
||||
# ready; the import keeps running in its thread and routes fall back to it.
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(_import_lazy_route_modules), timeout=LAZY_ROUTE_IMPORT_TIMEOUT_S
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.error(
|
||||
f"Startup import of lazy route modules exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; "
|
||||
"continuing startup (first requests may import them on the event loop)"
|
||||
)
|
||||
|
||||
# NLP model / credential warmup runs in the background so it doesn't gate
|
||||
# readiness — Cloud Run holds all routed requests until lifespan startup
|
||||
# returns, and these preloads were ~7.5s of the ~16s cold start.
|
||||
threading.Thread(
|
||||
target=_run_background_warmup, name="startup-warmup", daemon=True
|
||||
).start()
|
||||
|
||||
# asyncio.to_thread's default executor is min(32, cpu+4) ≈ 6 threads on our
|
||||
# 2 vCPUs. The screens worker, stale-review cron, auto-correct and many
|
||||
# review endpoints all offload into it (mostly I/O-bound), so size it up —
|
||||
# otherwise review-page requests queue behind a few long-running jobs.
|
||||
import concurrent.futures
|
||||
|
||||
asyncio.get_running_loop().set_default_executor(
|
||||
concurrent.futures.ThreadPoolExecutor(max_workers=48, thread_name_prefix="to-thread")
|
||||
)
|
||||
|
||||
# Event-loop stall watchdog: makes "every request froze for 30s" episodes
|
||||
# self-diagnosing (logs the blocking stack; records >=5s stalls in prod).
|
||||
watchdog = None
|
||||
if settings.loop_watchdog_enabled:
|
||||
from backend.services.loop_watchdog import (
|
||||
LoopWatchdog,
|
||||
firestore_stall_recorder,
|
||||
request_tracker,
|
||||
)
|
||||
|
||||
watchdog = LoopWatchdog(
|
||||
recorder=firestore_stall_recorder if settings.environment == "production" else None,
|
||||
# Stalls nobody waited on (idle, CPU-throttled autoscaled instances)
|
||||
# stay WARNING so they don't trip the >=10s stall alert.
|
||||
request_tracker=request_tracker,
|
||||
)
|
||||
watchdog.start()
|
||||
|
||||
yield
|
||||
|
||||
if watchdog is not None:
|
||||
await watchdog.stop()
|
||||
|
||||
# Shutdown - best-effort parking of any still-registered workers.
|
||||
#
|
||||
# Reality check (incident 2026-09-13, job 41e06b90): Cloud Run services
|
||||
@@ -191,6 +299,12 @@ app.add_middleware(TenantMiddleware)
|
||||
# backend/middleware/edge_auth.py.
|
||||
app.add_middleware(EdgeAuthMiddleware)
|
||||
|
||||
# Counts in-flight requests for the loop watchdog (outermost, so every request that
|
||||
# waited on a stalled loop counts — even ones the edge lock rejects).
|
||||
from backend.services.loop_watchdog import RequestTrackingMiddleware # noqa: E402
|
||||
|
||||
app.add_middleware(RequestTrackingMiddleware)
|
||||
|
||||
# Include routers
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(jobs.router, prefix="/api")
|
||||
@@ -213,9 +327,15 @@ app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submissio
|
||||
from backend.api.routes import requests_board
|
||||
app.include_router(requests_board.router, prefix="/api") # Public song-request voting board
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(client_events.router, prefix="/api") # Frontend degradation telemetry (banner/unavailable/waveform events)
|
||||
from backend.api.routes import karaokehunt
|
||||
app.include_router(karaokehunt.router, prefix="/api") # Retired KaraokeHunt app request interceptor
|
||||
from backend.api.routes import kjbox
|
||||
app.include_router(kjbox.router, prefix="/api") # kjbox partner API: singer email-code sign-in + show credits
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
app.include_router(tenant_admin.router) # Admin tenant provisioning (router has /api prefix)
|
||||
app.include_router(tenant_bulk.router) # Tenant bulk-upload filename analysis (router has /api prefix)
|
||||
app.include_router(tenant_theme.router) # Tenant self-service theme editor (router has /api prefix)
|
||||
|
||||
|
||||
# Exception handlers
|
||||
|
||||
@@ -203,6 +203,7 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
JobStatus.AWAITING_REVIEW, # Retry from combined review
|
||||
JobStatus.RENDER_PENDING_CAPACITY, # Operator parks a stale-failed job for auto-retry
|
||||
JobStatus.AWAITING_AUDIO_SELECTION, # Choose different audio after a failed download
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
@@ -289,6 +290,11 @@ class Job(BaseModel):
|
||||
# instrumental. Consumed by the auto-approval instrumental decision.
|
||||
backing_preference: str = "auto"
|
||||
|
||||
# Translated lyrics: language code (one of the UI locales, e.g. "en", "es") whose
|
||||
# LLM translation of each reviewed line is drawn in smaller text beneath it in the
|
||||
# karaoke videos. None = no translation row. See backend/services/lyrics_translation.py.
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
# Multi-tenant support ("" = consumer portal, "vocalstar"/etc = tenant portal)
|
||||
tenant_id: str = "" # Tenant ID for white-label portal scoping
|
||||
|
||||
@@ -300,6 +306,9 @@ class Job(BaseModel):
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
# When the theme was last re-snapshotted onto the job after creation (theme
|
||||
# edit refresh, re-render, Edit). None = the creation-time snapshot (created_at).
|
||||
theme_applied_at: Optional[datetime] = None
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
User color overrides applied on top of theme. Keys:
|
||||
@@ -385,12 +394,25 @@ class Job(BaseModel):
|
||||
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
|
||||
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
|
||||
|
||||
# Storage retention (backend/services/storage_retention.py): set when the
|
||||
# daily purge deleted this job's regenerable renders / separated stems.
|
||||
# Cleared when they're rebuilt (regenerate / re-render / stems restore).
|
||||
renders_purged_at: Optional[datetime] = None
|
||||
stems_purged_at: Optional[datetime] = None
|
||||
renders_regenerated_at: Optional[datetime] = None # last GCS-only regenerate
|
||||
storage_purge: Optional[Dict[str, Any]] = None # manifest of the last purge
|
||||
|
||||
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
|
||||
credit_refunded: bool = False
|
||||
|
||||
# Edit tracking (how many times a completed track has been re-edited)
|
||||
edit_count: int = 0
|
||||
|
||||
# Whole-track tempo change applied in the audio editor (1.0 / None = original
|
||||
# speed). When set, job.title carries a "(90% Tempo)" label so every published
|
||||
# output says so; see backend/services/tempo_label.py.
|
||||
tempo_factor: Optional[float] = None
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
@@ -580,6 +602,8 @@ class JobCreate(BaseModel):
|
||||
# "auto" (default) = retain backing vocals where confidently safe; "clean" =
|
||||
# always strip backing vocals; "review" = always let a human pick the instrumental.
|
||||
backing_preference: str = "auto"
|
||||
# Translated lyrics language (see Job.translation_language); None = off
|
||||
translation_language: Optional[str] = None
|
||||
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
@@ -678,6 +702,16 @@ class JobCreate(BaseModel):
|
||||
executor already treats any non-"auto" value as an enforcement blocker."""
|
||||
return v if v in ("auto", "always_review") else "always_review"
|
||||
|
||||
@validator('translation_language')
|
||||
def _normalize_translation_language(cls, v):
|
||||
"""Supported language code; empty or unsupported values turn the feature off
|
||||
(every creation route passes the client value straight through)."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
from backend.services.lyrics_translation import normalize_language
|
||||
|
||||
return normalize_language(v)
|
||||
|
||||
@validator('backing_preference')
|
||||
def _normalize_backing_preference(cls, v):
|
||||
"""Coerce an out-of-set value to the default. Every creation route passes
|
||||
|
||||
@@ -117,6 +117,10 @@ class TenantAuth(BaseModel):
|
||||
default_factory=list,
|
||||
description="Email domains allowed for magic link auth (e.g., ['vocal-star.com'])"
|
||||
)
|
||||
allowed_emails: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="Individual email addresses allowed for magic link auth (e.g. a client's gmail)"
|
||||
)
|
||||
require_email_domain: bool = Field(
|
||||
True,
|
||||
description="If true, only allowed domains can sign up. If false, domains get auto-approved."
|
||||
@@ -160,18 +164,41 @@ class TenantConfig(BaseModel):
|
||||
# Default pattern: {tenant_id}@nomadkaraoke.com
|
||||
return f"{self.id}@nomadkaraoke.com"
|
||||
|
||||
def is_explicitly_allowlisted(self, email: str) -> bool:
|
||||
"""True if the email is named in allowed_emails or matches an allowed domain."""
|
||||
email_lower = (email or "").strip().lower()
|
||||
if email_lower in [e.strip().lower() for e in self.auth.allowed_emails]:
|
||||
return True
|
||||
return any(email_lower.endswith(f"@{d.lower()}") for d in self.auth.allowed_email_domains)
|
||||
|
||||
def is_email_allowed(self, email: str) -> bool:
|
||||
"""Check if an email address is allowed for this tenant."""
|
||||
if not self.auth.allowed_email_domains:
|
||||
# No domain restrictions
|
||||
"""Check if an email address may sign in to this tenant's portal.
|
||||
|
||||
- Nomad Karaoke admins (admin email domain) can always sign in.
|
||||
- No allowlist at all (no domains, no emails) = admins only. Tenant jobs
|
||||
are free of consumer credits, so a portal must never be open to anyone.
|
||||
- Otherwise only an ``allowed_emails`` entry or a matching domain is
|
||||
allowed. (``require_email_domain`` is vestigial: any non-empty
|
||||
allowlist is always enforced.)
|
||||
"""
|
||||
from backend.services.auth_service import is_admin_email # avoid import cycle
|
||||
|
||||
email_lower = (email or "").strip().lower()
|
||||
if is_admin_email(email_lower):
|
||||
return True
|
||||
|
||||
email_lower = email.lower()
|
||||
for domain in self.auth.allowed_email_domains:
|
||||
allowed_emails = [e.strip().lower() for e in self.auth.allowed_emails]
|
||||
domains = self.auth.allowed_email_domains
|
||||
if not allowed_emails and not domains:
|
||||
return False
|
||||
|
||||
if email_lower in allowed_emails:
|
||||
return True
|
||||
for domain in domains:
|
||||
if email_lower.endswith(f"@{domain.lower()}"):
|
||||
return True
|
||||
|
||||
return not self.auth.require_email_domain
|
||||
return False
|
||||
|
||||
|
||||
class TenantPublicConfig(BaseModel):
|
||||
|
||||
+34
-2
@@ -9,8 +9,8 @@ Supports:
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from typing import Optional, List, Dict
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Annotated, Optional, List, Dict
|
||||
from pydantic import BaseModel, EmailStr, Field, StringConstraints
|
||||
|
||||
|
||||
class UserRole(str, Enum):
|
||||
@@ -115,6 +115,30 @@ class User(BaseModel):
|
||||
# Flag to prevent duplicate welcome credit grants (idempotency)
|
||||
welcome_credits_granted: bool = False
|
||||
|
||||
# Acquisition channel for accounts created outside the gen website, e.g.
|
||||
# "kjbox" (signed up via an emailed code on a karaoke-night singer page).
|
||||
# None = normal gen website signup (all pre-existing docs).
|
||||
# Gen website signups record their first-touch marketing source here too:
|
||||
# utm_source when the landing URL carried one, else the referring site's domain
|
||||
# (e.g. "youtube", "google.com"). Full detail lives in signup_attribution.
|
||||
signup_source: Optional[str] = None
|
||||
signup_venue: Optional[str] = None # Venue name reported by the partner (kjbox)
|
||||
# First-touch attribution captured by the frontend before signup (see
|
||||
# backend/services/signup_attribution.py): utm_* params, external referrer
|
||||
# domain, landing path and when it was captured.
|
||||
signup_attribution: Optional[Dict[str, str]] = None
|
||||
|
||||
# Free-to-paid conversion emails (backend/services/conversion_emails.py)
|
||||
conversion_e1_due_at: Optional[datetime] = None # set when the first video completes unpaid
|
||||
conversion_e1_sent_at: Optional[datetime] = None
|
||||
conversion_e1_skipped: bool = False # due but not sent (already paid / too late)
|
||||
first_video_artist: Optional[str] = None # named in the E1 email
|
||||
first_video_title: Optional[str] = None
|
||||
conversion_e2_sent_at: Optional[datetime] = None
|
||||
# Time-limited discount granted by the E1 offer, applied automatically at checkout
|
||||
promo_discount_percent: Optional[int] = None
|
||||
promo_discount_expires_at: Optional[datetime] = None
|
||||
|
||||
# Referral system
|
||||
referral_code: Optional[str] = None # User's own referral code
|
||||
referred_by_code: Optional[str] = None # Code used when this user signed up
|
||||
@@ -190,6 +214,11 @@ class SendMagicLinkRequest(BaseModel):
|
||||
email: str
|
||||
device_fingerprint: Optional[str] = None
|
||||
referral_code: Optional[str] = None # From referral interstitial
|
||||
# First-touch marketing attribution (utm_*, referrer, landing_path), recorded on
|
||||
# the user only when this request creates the account.
|
||||
attribution: Optional[
|
||||
Dict[Annotated[str, StringConstraints(max_length=32)], Optional[Annotated[str, StringConstraints(max_length=500)]]]
|
||||
] = Field(default=None, max_length=16)
|
||||
# "requests_board" = board sign-in (identity only; no welcome credit / no IP limit).
|
||||
purpose: Optional[str] = None
|
||||
|
||||
@@ -245,6 +274,9 @@ class UserPublic(BaseModel):
|
||||
has_active_referral_discount: bool = False
|
||||
referral_discount_percent: Optional[int] = None
|
||||
referral_discount_expires_at: Optional[str] = None # ISO string
|
||||
# Active time-limited promo (conversion email offer), applied at checkout
|
||||
promo_discount_percent: Optional[int] = None
|
||||
promo_discount_expires_at: Optional[str] = None # ISO string
|
||||
referred_by_code: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
last_login_at: Optional[str] = None
|
||||
|
||||
@@ -18,6 +18,10 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# Presets to bake into the GPU image
|
||||
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
|
||||
# Individual models baked in addition to the presets.
|
||||
# UVR-MDX-NET-Inst_HQ_4.onnx: the kjbox make-it "quick version" separation
|
||||
# (backend/services/quick_version/service.py).
|
||||
EXTRA_MODELS = ["UVR-MDX-NET-Inst_HQ_4.onnx"]
|
||||
|
||||
|
||||
def download_preset_models(model_dir: str) -> None:
|
||||
@@ -34,7 +38,9 @@ def download_preset_models(model_dir: str) -> None:
|
||||
for preset_name in PRESETS_TO_DOWNLOAD:
|
||||
models_to_download.update(presets[preset_name]["models"])
|
||||
|
||||
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
|
||||
models_to_download.update(EXTRA_MODELS)
|
||||
|
||||
logger.info(f"Downloading {len(models_to_download)} models for presets {PRESETS_TO_DOWNLOAD} + {EXTRA_MODELS}")
|
||||
for model in sorted(models_to_download):
|
||||
logger.info(f" Downloading: {model}")
|
||||
sep = Separator(model_file_dir=model_dir)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Regenerate backend/services/translation_preview_samples.py.
|
||||
|
||||
The job-creation "translated lyrics" preview renders sample lyrics with their
|
||||
translation beneath. Translations are generated once with the production
|
||||
translation service and committed, so the preview never calls the LLM.
|
||||
|
||||
GOOGLE_CLOUD_PROJECT=nomadkaraoke python backend/scripts/generate_translation_preview_samples.py
|
||||
"""
|
||||
import os
|
||||
import pprint
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||
|
||||
from backend.services.lyrics_translation import TRANSLATION_LANGUAGES, LyricsTranslationService # noqa: E402
|
||||
from backend.services.theme_preview_service import DEFAULT_SAMPLE_LYRICS # noqa: E402
|
||||
|
||||
# Shown instead of the English sample when the target language is English
|
||||
SPANISH_SAMPLE_LYRICS = [
|
||||
"Cada noche canto sin parar",
|
||||
"Se apagan las luces, es mi lugar",
|
||||
"Tomo el micrófono y subo al escenario",
|
||||
"Doy la vuelta a la página otra vez",
|
||||
]
|
||||
|
||||
|
||||
class _NoCache:
|
||||
def file_exists(self, path):
|
||||
return False
|
||||
|
||||
def upload_json(self, path, data):
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
service = LyricsTranslationService(storage=_NoCache())
|
||||
samples = {}
|
||||
for code in TRANSLATION_LANGUAGES:
|
||||
source = SPANISH_SAMPLE_LYRICS if code == "en" else DEFAULT_SAMPLE_LYRICS
|
||||
samples[code] = {"lyrics": source, "translations": service.translate_lines(source, code)}
|
||||
print(code, samples[code]["translations"][0], file=sys.stderr)
|
||||
out = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "services", "translation_preview_samples.py")
|
||||
with open(out, "w", encoding="utf-8") as f:
|
||||
f.write('"""Sample lyrics + translations for the translated-lyrics preview.\n\n')
|
||||
f.write("Generated by backend/scripts/generate_translation_preview_samples.py; don't edit by hand.\n")
|
||||
f.write('"""\n\n')
|
||||
f.write("SAMPLES = " + pprint.pformat(samples, width=110, sort_dicts=False) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,564 @@
|
||||
"""
|
||||
Admin re-render: rebuild ANY finished job end to end without a review step.
|
||||
|
||||
Use case: a renderer fix (e.g. RTL/Hebrew lyrics, v0.255.0) needs videos that
|
||||
were already delivered regenerated. Unlike the tenant "Re-render with current
|
||||
theme" (theme_rerender_service), this:
|
||||
|
||||
- works for every job (consumer or tenant, public or private);
|
||||
- keeps the job's EXISTING style snapshot (``jobs/{id}/style/...``,
|
||||
``style_params_gcs_path``, ``style_assets``) — no theme re-snapshot;
|
||||
- deletes the published outputs (YouTube video, Google Drive files, Dropbox
|
||||
folder) up front, like Edit — but only for destinations the re-render will
|
||||
re-publish to (see ``plan_republish``); others are left in place with a
|
||||
warning. The brand code is KEPT (never recycled): the video worker
|
||||
re-publishes under the same code via ``rerender_brand_code``. YouTube gets a
|
||||
new upload, so the YouTube URL changes;
|
||||
- doesn't email/push the customer (or Discord / community voters) on
|
||||
completion unless the admin opted in (``notify_customer``) — see
|
||||
``suppress_customer_notifications``.
|
||||
|
||||
Mechanism (shared with the theme re-render and the private->public visibility
|
||||
flow): atomically move the job COMPLETE -> LYRICS_COMPLETE with
|
||||
``state_data.regen_restore_status = "review_complete"`` and trigger the screens
|
||||
worker. The screens worker regenerates the screens, restores REVIEW_COMPLETE and
|
||||
triggers the render worker, which renders from the existing
|
||||
corrections_updated.json; the video worker then encodes, distributes and
|
||||
completes using ``state_data.instrumental_selection``.
|
||||
|
||||
``state_data.admin_rerender`` is the in-progress marker. The video worker clears
|
||||
it on success; a FAILED admin re-render keeps it, which lets an admin
|
||||
``POST /api/jobs/{id}/retry`` (or another admin re-render) resume it. The marker
|
||||
only applies to its own run: it records the job's ``review_token`` at claim
|
||||
(a new token is minted whenever the job goes back through review), and the
|
||||
admin reset/restart, Edit, visibility and delete-outputs flows clear it.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.published_outputs_cleanup import (
|
||||
delete_dropbox_folder,
|
||||
delete_gdrive_files,
|
||||
delete_youtube_video,
|
||||
snapshot_published_outputs,
|
||||
)
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderConflictError,
|
||||
RerenderError,
|
||||
delete_regenerated_artifacts,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ADMIN_RERENDER_MARKER = "admin_rerender"
|
||||
_LOG_SOURCE = "admin-rerender"
|
||||
|
||||
# destination -> state_data keys that reference its published output
|
||||
_DESTINATION_KEYS = {
|
||||
"youtube": ("youtube_url", "youtube_video_id", "youtube_upload_queued"),
|
||||
"dropbox": ("dropbox_link",),
|
||||
"gdrive": ("gdrive_files",),
|
||||
}
|
||||
# state_data link a destination's output is recorded under (kept_outputs keys)
|
||||
_DESTINATION_LINK = {"youtube": "youtube_url", "dropbox": "dropbox_link", "gdrive": "gdrive_files"}
|
||||
|
||||
|
||||
# --- Marker helpers ------------------------------------------------------------
|
||||
|
||||
def raw_admin_rerender_marker(job) -> Dict[str, Any]:
|
||||
"""The stored marker, regardless of whether it belongs to the current run."""
|
||||
state_data = getattr(job, "state_data", None)
|
||||
marker = state_data.get(ADMIN_RERENDER_MARKER) if isinstance(state_data, dict) else None
|
||||
return marker if isinstance(marker, dict) else {}
|
||||
|
||||
|
||||
def active_admin_rerender(job) -> Dict[str, Any]:
|
||||
"""The marker if it belongs to the job's current run, else ``{}``.
|
||||
|
||||
A job that has since gone back through review (admin reset, Edit, ...) has a
|
||||
new ``review_token``, so a stale marker from a failed admin re-render no
|
||||
longer suppresses notifications or forces the brand code.
|
||||
"""
|
||||
marker = raw_admin_rerender_marker(job)
|
||||
if marker and "review_token" in marker:
|
||||
if marker["review_token"] != getattr(job, "review_token", None):
|
||||
return {}
|
||||
return marker
|
||||
|
||||
|
||||
def admin_rerender_blocks_upload(job_data: Dict[str, Any]) -> bool:
|
||||
"""True if a queued YouTube upload must not start for this job (raw job doc).
|
||||
|
||||
An ACTIVE (review_token-scoped) admin re-render on a job that isn't complete
|
||||
is rebuilding (or failed while rebuilding) the finals. Used inside the
|
||||
queue's claim transaction, which reads the job doc.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
view = SimpleNamespace(
|
||||
state_data=job_data.get("state_data") or {},
|
||||
review_token=job_data.get("review_token"),
|
||||
)
|
||||
return bool(active_admin_rerender(view)) and job_data.get("status") != JobStatus.COMPLETE.value
|
||||
|
||||
|
||||
UPLOAD_IN_PROGRESS_MESSAGE = (
|
||||
"A YouTube upload for this track is in progress — try again in a few minutes."
|
||||
)
|
||||
|
||||
|
||||
def claim_with_youtube_queue(
|
||||
db, job_id: str, update: Dict[str, Any], allowed_statuses: set,
|
||||
cancel_deferred_upload: bool, keep_reason: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Atomically claim the job for an admin re-render, reading its YouTube queue doc too.
|
||||
|
||||
- job status not claimable → RerenderConflictError (409);
|
||||
- a deferred upload is ``processing`` → RerenderConflictError (409): an
|
||||
upload of the old finals must never overlap the re-render;
|
||||
- a ``queued``/``failed`` entry is cancelled in the same transaction when
|
||||
the re-render will re-publish YouTube, otherwise left in place (warning).
|
||||
|
||||
The queue's ``mark_processing`` transaction reads the job doc and refuses
|
||||
while an admin re-render is active, so the two can never interleave.
|
||||
Returns the queue outcome, e.g. ``{"status": "cancelled", "previous_status": "queued"}``.
|
||||
"""
|
||||
from backend.services.youtube_upload_queue_service import (
|
||||
PACIFIC_TZ,
|
||||
YOUTUBE_UPLOAD_QUEUE_COLLECTION,
|
||||
)
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
# Same collection the YouTube queue's mark_processing transaction reads, so
|
||||
# the two claims always contend on the same job document.
|
||||
job_ref = db.collection(get_settings().firestore_collection).document(job_id)
|
||||
queue_ref = db.collection(YOUTUBE_UPLOAD_QUEUE_COLLECTION).document(job_id)
|
||||
marker_key = f"state_data.{ADMIN_RERENDER_MARKER}"
|
||||
|
||||
@firestore.transactional
|
||||
def claim(transaction):
|
||||
snapshot = job_ref.get(transaction=transaction)
|
||||
queue_snapshot = queue_ref.get(transaction=transaction)
|
||||
status = (snapshot.to_dict() or {}).get("status") if snapshot.exists else None
|
||||
if status not in allowed_statuses:
|
||||
return "not_claimable", None
|
||||
queue_status = (queue_snapshot.to_dict() or {}).get("status") if queue_snapshot.exists else None
|
||||
if queue_status == "processing":
|
||||
return "uploading", None
|
||||
|
||||
payload = dict(update) # fresh copy per transaction attempt
|
||||
if queue_status in ("queued", "failed"):
|
||||
if cancel_deferred_upload:
|
||||
transaction.update(queue_ref, {
|
||||
"status": "cancelled",
|
||||
"last_error": "Cancelled: admin re-render will re-upload",
|
||||
"updated_at": datetime.now(PACIFIC_TZ),
|
||||
})
|
||||
outcome = {"status": "cancelled", "previous_status": queue_status}
|
||||
else:
|
||||
warning = f"pending deferred YouTube upload left queued (YouTube not re-published: {keep_reason})"
|
||||
marker = dict(payload[marker_key])
|
||||
marker["warnings"] = [*marker.get("warnings", []), warning]
|
||||
payload[marker_key] = marker
|
||||
outcome = {"status": "kept", "previous_status": queue_status, "reason": keep_reason,
|
||||
"warning": warning}
|
||||
else:
|
||||
outcome = {"status": "skipped",
|
||||
"reason": "no queue entry" if queue_status is None else f"entry is {queue_status}"}
|
||||
transaction.update(job_ref, payload)
|
||||
return "ok", outcome
|
||||
|
||||
result, outcome = claim(db.transaction())
|
||||
if result == "uploading":
|
||||
raise RerenderConflictError(UPLOAD_IN_PROGRESS_MESSAGE)
|
||||
if result != "ok":
|
||||
raise RerenderConflictError("This track is already being re-rendered or is no longer finished.")
|
||||
return outcome
|
||||
|
||||
|
||||
def clear_admin_rerender_update(job) -> Dict[str, Any]:
|
||||
"""Firestore update that drops the marker (empty if there is none).
|
||||
|
||||
Also drops a storage-retention regenerate marker: every caller (admin
|
||||
reset/restart, Edit, visibility change, delete outputs) starts a new run.
|
||||
"""
|
||||
update: Dict[str, Any] = {}
|
||||
if raw_admin_rerender_marker(job):
|
||||
update[f"state_data.{ADMIN_RERENDER_MARKER}"] = DELETE_FIELD
|
||||
from backend.services.regenerate_service import clear_regenerate_update
|
||||
update.update(clear_regenerate_update(job))
|
||||
return update
|
||||
|
||||
|
||||
def suppress_customer_notifications(job) -> bool:
|
||||
"""True if this run's customer-facing notifications must be skipped.
|
||||
|
||||
Only an active admin re-render the admin didn't opt into announcing
|
||||
suppresses them; normal jobs and a single tenant theme re-render notify.
|
||||
"""
|
||||
marker = active_admin_rerender(job)
|
||||
if marker:
|
||||
return not marker.get("notify_customer", False)
|
||||
# A bulk "re-render all outdated tracks" theme re-render is started quietly.
|
||||
theme_marker = (getattr(job, "state_data", None) or {}).get("theme_rerender") or {}
|
||||
if theme_marker.get("notify_customer") is False:
|
||||
return True
|
||||
# A storage-retention regenerate notifies unless it was started quietly.
|
||||
from backend.services.regenerate_service import regenerate_suppresses_notifications
|
||||
return regenerate_suppresses_notifications(job)
|
||||
|
||||
|
||||
def admin_rerender_brand_code(job) -> Optional[str]:
|
||||
return active_admin_rerender(job).get("brand_code") or None
|
||||
|
||||
|
||||
def admin_rerender_kept_outputs(job) -> Dict[str, Any]:
|
||||
"""Published outputs left in place (not re-published) by the active re-render."""
|
||||
return active_admin_rerender(job).get("kept_outputs") or {}
|
||||
|
||||
|
||||
# --- Validation / planning -----------------------------------------------------
|
||||
|
||||
def _claimable_statuses(job) -> set:
|
||||
"""COMPLETE, plus FAILED/CANCELLED when that was an admin re-render (resume)."""
|
||||
statuses = {JobStatus.COMPLETE.value}
|
||||
if active_admin_rerender(job):
|
||||
statuses.update({JobStatus.FAILED.value, JobStatus.CANCELLED.value})
|
||||
return statuses
|
||||
|
||||
|
||||
def validate_admin_rerender(job) -> Optional[str]:
|
||||
"""Return a reason the job can't be re-rendered, or None if it can."""
|
||||
if job.status not in _claimable_statuses(job):
|
||||
return f"Only completed jobs can be re-rendered (current status: {job.status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This job's outputs were deleted, so it can't be re-rendered."
|
||||
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
|
||||
if purge_in_progress(job):
|
||||
return PURGE_IN_PROGRESS_MESSAGE
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "Prep-only / finalise-only jobs can't be re-rendered."
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get("visibility_change_in_progress"):
|
||||
return "A visibility change is in progress for this job."
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "This job has no instrumental selection to re-render with."
|
||||
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "This job has no reviewed lyrics to re-render with."
|
||||
return None
|
||||
|
||||
|
||||
def plan_republish(job) -> Dict[str, Tuple[bool, Optional[str]]]:
|
||||
"""Which destinations the re-render's distribution step will publish to.
|
||||
|
||||
Mirrors the video worker: YouTube needs ``enable_youtube_upload`` on a
|
||||
non-private job (effective distribution) and configured YouTube credentials;
|
||||
Dropbox needs an effective ``dropbox_path`` and ``brand_prefix``; Google
|
||||
Drive needs an effective ``gdrive_folder_id``. Returns
|
||||
``{destination: (will_republish, reason_if_not)}``. Does blocking I/O
|
||||
(YouTube credential lookup) — call off the event loop.
|
||||
"""
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
dist = get_effective_distribution_for_job(job)
|
||||
plan: Dict[str, Tuple[bool, Optional[str]]] = {}
|
||||
|
||||
if getattr(job, "is_private", False) or not dist.enable_youtube_upload:
|
||||
plan["youtube"] = (False, "YouTube upload is disabled for this job")
|
||||
else:
|
||||
try:
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
configured = get_youtube_service().is_configured
|
||||
reason = "YouTube credentials are not configured"
|
||||
except Exception as e:
|
||||
# Can't plan → don't delete or cancel anything YouTube; warn instead.
|
||||
logger.warning(f"[job:{job.job_id}] YouTube credential check failed: {e}")
|
||||
configured = False
|
||||
reason = f"couldn't verify YouTube credentials ({e})"
|
||||
plan["youtube"] = (True, None) if configured else (False, reason)
|
||||
|
||||
if dist.dropbox_path and dist.brand_prefix:
|
||||
plan["dropbox"] = (True, None)
|
||||
else:
|
||||
plan["dropbox"] = (False, "Dropbox upload is not configured for this job")
|
||||
|
||||
if dist.gdrive_folder_id:
|
||||
plan["gdrive"] = (True, None)
|
||||
else:
|
||||
plan["gdrive"] = (False, "Google Drive upload is not configured for this job")
|
||||
return plan
|
||||
|
||||
|
||||
def _has_output(state_data: dict, destination: str) -> bool:
|
||||
return bool(state_data.get(_DESTINATION_LINK[destination]))
|
||||
|
||||
|
||||
# --- Service ---------------------------------------------------------------------
|
||||
|
||||
class AdminRerenderService:
|
||||
def __init__(
|
||||
self,
|
||||
job_manager: Optional[JobManager] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
self.storage = storage or StorageService()
|
||||
|
||||
async def start(self, job, requested_by: str, notify_customer: bool = False) -> Dict[str, Any]:
|
||||
"""Claim the job, delete its re-publishable outputs and kick off the re-render.
|
||||
|
||||
Blocking Firestore/GCS/YouTube/Dropbox/GDrive work runs in worker
|
||||
threads. Any failure after the claim marks the job FAILED with the
|
||||
marker kept (so it can be retried) and raises RerenderError.
|
||||
|
||||
Returns ``{"brand_code", "previous_outputs", "cleanup_results", "warnings"}``.
|
||||
Raises RerenderError (400/500/503) or RerenderConflictError (409).
|
||||
"""
|
||||
reason = validate_admin_rerender(job)
|
||||
if reason:
|
||||
raise RerenderError(reason)
|
||||
|
||||
plan = await asyncio.to_thread(plan_republish, job)
|
||||
update, context = self._build_claim(job, requested_by, notify_customer, plan)
|
||||
queue_outcome = await asyncio.to_thread(
|
||||
claim_with_youtube_queue, self.job_manager.firestore.db, job.job_id, update,
|
||||
_claimable_statuses(job), plan["youtube"][0], plan["youtube"][1],
|
||||
)
|
||||
context["youtube_queue"] = queue_outcome
|
||||
if queue_outcome.get("warning"):
|
||||
context["warnings"].append(queue_outcome["warning"])
|
||||
|
||||
job_id = job.job_id
|
||||
try:
|
||||
cleanup_results = await asyncio.to_thread(self._after_claim, job, context, plan)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
except Exception as e:
|
||||
logger.exception(f"[job:{job_id}] Admin re-render failed after claim")
|
||||
await asyncio.to_thread(self._fail_run, job_id, f"Admin re-render failed to start: {e}", "start_error")
|
||||
raise RerenderError(
|
||||
f"The re-render failed to start ({e}). The job was marked failed; retry it to continue.",
|
||||
status_code=500,
|
||||
) from e
|
||||
|
||||
if not triggered:
|
||||
await asyncio.to_thread(
|
||||
self._fail_run, job_id,
|
||||
"Admin re-render couldn't start the screens worker. Retry the job to continue.",
|
||||
"screens_trigger_failed",
|
||||
)
|
||||
raise RerenderError("Couldn't start the re-render. Please retry the job.", status_code=503)
|
||||
|
||||
await asyncio.to_thread(log_to_job, job_id, _LOG_SOURCE, "INFO",
|
||||
"Re-render started (screens worker triggered)",
|
||||
{"cleanup_results": cleanup_results})
|
||||
return {
|
||||
"brand_code": context["brand_code"],
|
||||
"previous_outputs": context["previous_outputs"],
|
||||
"cleanup_results": cleanup_results,
|
||||
"warnings": context["warnings"],
|
||||
}
|
||||
|
||||
def _build_claim(self, job, requested_by: str, notify_customer: bool, plan) -> Tuple[dict, dict]:
|
||||
state_data = job.state_data or {}
|
||||
# Only the ACTIVE (same-run) marker carries over: a stale one from an
|
||||
# earlier run must not leak its brand code / history into this run.
|
||||
previous_marker = active_admin_rerender(job)
|
||||
# On a retry the re-published outputs were already removed (and cleared
|
||||
# from state_data) by the first attempt — keep that attempt's record.
|
||||
previous_outputs = {
|
||||
**(previous_marker.get("previous_outputs") or {}),
|
||||
**snapshot_published_outputs(state_data),
|
||||
}
|
||||
brand_code = state_data.get("brand_code") or previous_marker.get("brand_code")
|
||||
is_retry = bool(previous_marker)
|
||||
|
||||
warnings: List[str] = []
|
||||
kept_outputs: Dict[str, Any] = {}
|
||||
for destination, (republish, why) in plan.items():
|
||||
if not republish and _has_output(state_data, destination):
|
||||
link_key = _DESTINATION_LINK[destination]
|
||||
kept_outputs[link_key] = state_data[link_key]
|
||||
warnings.append(f"{destination} output left in place (not re-published): {why}")
|
||||
republish_youtube = plan["youtube"][0]
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
message = (
|
||||
f"Admin re-render requested by {requested_by} "
|
||||
f"(existing style, no review; brand code {brand_code or 'n/a'} kept; "
|
||||
f"customer notification {'on' if notify_customer else 'off'})"
|
||||
)
|
||||
update: Dict[str, Any] = {
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"progress": 50,
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"state_data.distribution_warnings": DELETE_FIELD,
|
||||
f"state_data.{ADMIN_RERENDER_MARKER}": {
|
||||
"requested_by": requested_by,
|
||||
"requested_at": now.isoformat(),
|
||||
"notify_customer": bool(notify_customer),
|
||||
"brand_code": brand_code,
|
||||
"previous_outputs": previous_outputs,
|
||||
"kept_outputs": kept_outputs,
|
||||
"warnings": warnings,
|
||||
"republish_youtube": republish_youtube,
|
||||
# Run identity: a later trip through review mints a new token,
|
||||
# which retires this marker (see active_admin_rerender).
|
||||
"review_token": getattr(job, "review_token", None),
|
||||
},
|
||||
# Old screens are deleted after the claim; drop their file_urls so
|
||||
# nothing (e.g. a later retry) reuses them.
|
||||
"file_urls.screens": DELETE_FIELD,
|
||||
"file_urls.videos.with_vocals": DELETE_FIELD,
|
||||
"updated_at": now,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": message,
|
||||
"metadata": {
|
||||
"action": "admin_rerender_initiated",
|
||||
"initiated_by": requested_by,
|
||||
"notify_customer": bool(notify_customer),
|
||||
"brand_code": brand_code,
|
||||
"previous_outputs": previous_outputs,
|
||||
"kept_outputs": kept_outputs,
|
||||
"warnings": warnings,
|
||||
"retry": is_retry,
|
||||
},
|
||||
}]),
|
||||
}
|
||||
# Drop the links of outputs about to be deleted and re-published (dead
|
||||
# links otherwise). brand_code stays — it's reused.
|
||||
for destination, (republish, _) in plan.items():
|
||||
if republish:
|
||||
for key in _DESTINATION_KEYS[destination]:
|
||||
update[f"state_data.{key}"] = DELETE_FIELD
|
||||
# youtube_upload_queued is only cleared (and the deferred upload
|
||||
# cancelled) when YouTube will be re-published — it's in
|
||||
# _DESTINATION_KEYS["youtube"] above.
|
||||
|
||||
context = {
|
||||
"message": message,
|
||||
"brand_code": brand_code,
|
||||
"previous_outputs": previous_outputs,
|
||||
"warnings": warnings,
|
||||
"notify_customer": bool(notify_customer),
|
||||
"is_retry": is_retry,
|
||||
"republish_youtube": republish_youtube,
|
||||
}
|
||||
return update, context
|
||||
|
||||
def _after_claim(self, job, context: dict, plan) -> Dict[str, Any]:
|
||||
"""Blocking post-claim work: audit log, stale artifacts, published outputs."""
|
||||
job_id = job.job_id
|
||||
logger.info(
|
||||
f"[job:{job_id}] Admin re-render claimed: brand_code={context['brand_code']} "
|
||||
f"notify_customer={context['notify_customer']} retry={context['is_retry']} "
|
||||
f"previous_outputs={sorted(context['previous_outputs'])} warnings={context['warnings']}"
|
||||
)
|
||||
log_to_job(job_id, _LOG_SOURCE, "INFO", context["message"], {
|
||||
"previous_outputs": context["previous_outputs"],
|
||||
"notify_customer": context["notify_customer"],
|
||||
"retry": context["is_retry"],
|
||||
})
|
||||
for warning in context["warnings"]:
|
||||
log_to_job(job_id, _LOG_SOURCE, "WARNING", warning)
|
||||
|
||||
delete_regenerated_artifacts(self.storage, job_id)
|
||||
return self._delete_published_outputs(
|
||||
job, job.state_data or {}, context["brand_code"], plan, context.get("youtube_queue")
|
||||
)
|
||||
|
||||
def _fail_run(self, job_id: str, error: str, reason: str) -> None:
|
||||
"""Mark the run FAILED, keeping the marker so it can be retried."""
|
||||
logger.error(f"[job:{job_id}] {error}")
|
||||
try:
|
||||
self.job_manager.update_job(job_id, {
|
||||
"status": JobStatus.FAILED.value,
|
||||
"error_message": error,
|
||||
"error_details": {"stage": "admin_rerender", "reason": reason},
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
log_to_job(job_id, _LOG_SOURCE, "ERROR", error)
|
||||
except Exception:
|
||||
logger.exception(f"[job:{job_id}] Failed to mark admin re-render as failed")
|
||||
|
||||
def _delete_published_outputs(
|
||||
self, job, state_data: dict, brand_code: Optional[str], plan,
|
||||
youtube_queue: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete outputs the re-render will re-publish; keep the rest. Best-effort.
|
||||
|
||||
Failures don't abort the re-render: the re-publish targets the same
|
||||
names (same brand code), and the server-side YouTube upload and GDrive
|
||||
upload both replace a same-named leftover, while Dropbox uploads overwrite.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
from backend.services.job_defaults_service import get_effective_distribution_for_job
|
||||
|
||||
def kept(destination):
|
||||
return {"status": "kept", "reason": plan[destination][1]}
|
||||
|
||||
results: Dict[str, Any] = {}
|
||||
results["youtube"] = (
|
||||
delete_youtube_video(job_id, state_data.get("youtube_url"))
|
||||
if plan["youtube"][0] else kept("youtube")
|
||||
)
|
||||
# Private jobs publish to the private Dropbox path, not job.dropbox_path.
|
||||
results["dropbox"] = (
|
||||
delete_dropbox_folder(
|
||||
job_id, get_effective_distribution_for_job(job).dropbox_path,
|
||||
brand_code, job.artist, job.title,
|
||||
)
|
||||
if plan["dropbox"][0] else kept("dropbox")
|
||||
)
|
||||
# Same brand code is re-published, so the kjbox GCS mirror copy is
|
||||
# overwritten in place rather than removed.
|
||||
results["gdrive"] = (
|
||||
delete_gdrive_files(job_id, state_data.get("gdrive_files"), brand_code, cleanup_mirror=False)
|
||||
if plan["gdrive"][0] else kept("gdrive")
|
||||
)
|
||||
# Handled atomically by the claim transaction (claim_with_youtube_queue).
|
||||
results["youtube_queue"] = youtube_queue or {"status": "skipped", "reason": "no queue entry"}
|
||||
results["brand_code"] = {"status": "kept", "code": brand_code}
|
||||
|
||||
for service in ("youtube", "dropbox", "gdrive", "youtube_queue"):
|
||||
status = results[service].get("status")
|
||||
level = "WARNING" if status in ("failed", "partial", "error", "kept", "processing") else "INFO"
|
||||
log_to_job(job_id, _LOG_SOURCE, level, f"{service} cleanup: {status}", results[service])
|
||||
logger.info(
|
||||
f"[job:{job_id}] Admin re-render cleanup: "
|
||||
+ ", ".join(f"{k}={v.get('status')}" for k, v in results.items())
|
||||
)
|
||||
try:
|
||||
now = datetime.now(timezone.utc)
|
||||
self.job_manager.update_job(job_id, {
|
||||
f"state_data.{ADMIN_RERENDER_MARKER}.cleanup_results": results,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": "Admin re-render: previous published outputs removed",
|
||||
"metadata": {"action": "admin_rerender_cleanup", "cleanup_results": results},
|
||||
}]),
|
||||
})
|
||||
except Exception as e: # audit only — never block the re-render
|
||||
logger.warning(f"[job:{job_id}] Failed to record admin re-render cleanup results: {e}")
|
||||
return results
|
||||
@@ -243,6 +243,171 @@ class AudioAnalysisService:
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
@staticmethod
|
||||
def review_waveform_cache_path(job_id: str, num_points: int) -> str:
|
||||
"""GCS path of the cached review-page waveform JSON for a job."""
|
||||
return f"jobs/{job_id}/review-audio/waveform_review_{num_points}.json"
|
||||
|
||||
def get_review_waveform(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
num_points: int = 1000,
|
||||
transcoding_service=None,
|
||||
) -> tuple[list[float], float]:
|
||||
"""
|
||||
Waveform data for the review page, cached persistently in GCS.
|
||||
|
||||
Decoding a full stem (pydub -> ffmpeg + a pure-Python RMS loop) takes
|
||||
seconds of CPU, so it must only ever happen once per job: results are
|
||||
cached at ``review_waveform_cache_path`` and validated against the
|
||||
source path + num_points (a replaced stem or different resolution
|
||||
recomputes). On a miss, decode the small transcoded review OGG when it
|
||||
exists (~3 MB) instead of the raw stem (~35 MB FLAC).
|
||||
|
||||
The cache upload is best-effort — a failed write still returns the
|
||||
computed data.
|
||||
"""
|
||||
cache_path = self.review_waveform_cache_path(job_id, num_points)
|
||||
cached = self._load_review_waveform_cache(cache_path, gcs_audio_path, num_points)
|
||||
if cached is not None:
|
||||
logger.info(f"[{job_id}] Review waveform cache hit: {cache_path}")
|
||||
return cached
|
||||
|
||||
decode_path = gcs_audio_path
|
||||
if transcoding_service is not None:
|
||||
try:
|
||||
ogg_path = transcoding_service.get_transcoded_cache_path(gcs_audio_path)
|
||||
if self.storage_service.file_exists(ogg_path):
|
||||
decode_path = ogg_path
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Could not resolve transcoded OGG for waveform: {e}")
|
||||
|
||||
amplitudes, duration = self.get_waveform_data(
|
||||
gcs_audio_path=decode_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
|
||||
try:
|
||||
self.storage_service.upload_json(cache_path, {
|
||||
"amplitudes": list(amplitudes),
|
||||
"duration_seconds": duration,
|
||||
"num_points": num_points,
|
||||
# Keyed to the LOGICAL source (the stem path), not decode_path,
|
||||
# so swapping in/out the OGG shortcut never invalidates the cache
|
||||
# but a regenerated stem at a new path does.
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
})
|
||||
logger.info(f"[{job_id}] Review waveform cached at {cache_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to cache review waveform (non-fatal): {e}")
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
def _load_review_waveform_cache(
|
||||
self,
|
||||
cache_gcs_path: str,
|
||||
source_gcs_path: str,
|
||||
num_points: int,
|
||||
) -> Optional[tuple[list[float], float]]:
|
||||
"""Load + validate the review waveform cache; None on any mismatch/error."""
|
||||
try:
|
||||
if not self.storage_service.file_exists(cache_gcs_path):
|
||||
return None
|
||||
data = self.storage_service.download_json(cache_gcs_path)
|
||||
if data.get("source_gcs_path") != source_gcs_path:
|
||||
return None
|
||||
if data.get("num_points") != num_points:
|
||||
return None
|
||||
amplitudes = data.get("amplitudes") or []
|
||||
if not amplitudes:
|
||||
return None
|
||||
return amplitudes, float(data.get("duration_seconds", 0.0))
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load review waveform cache {cache_gcs_path}: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def vocals_peaks_cache_path(job_id: str, peaks_per_second: int) -> str:
|
||||
"""GCS path of the cached vocals peak-envelope JSON for a job."""
|
||||
return f"jobs/{job_id}/review-audio/vocals_peaks_{peaks_per_second}.json"
|
||||
|
||||
def get_vocals_peaks(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
peaks_per_second: int = 400,
|
||||
transcoding_service=None,
|
||||
) -> dict:
|
||||
"""
|
||||
Pre-computed peak envelope of the vocal stem for the review page's
|
||||
Waveforms mode, cached persistently in GCS.
|
||||
|
||||
Returns the serve-ready payload::
|
||||
|
||||
{peaks_b64, encoding: "u8", peaks_per_second, duration_seconds,
|
||||
source_gcs_path}
|
||||
|
||||
``peaks_b64`` is base64 of one uint8 per bucket (max-abs amplitude
|
||||
quantized to 0-255) — ~150 KB for a 5-minute track vs the ~7 MB OGG
|
||||
the frontend previously downloaded and decoded client-side. On a cache
|
||||
miss, decode the small transcoded review OGG when it exists.
|
||||
The cache upload is best-effort.
|
||||
"""
|
||||
import base64
|
||||
|
||||
cache_path = self.vocals_peaks_cache_path(job_id, peaks_per_second)
|
||||
try:
|
||||
if self.storage_service.file_exists(cache_path):
|
||||
data = self.storage_service.download_json(cache_path)
|
||||
if (
|
||||
data.get("source_gcs_path") == gcs_audio_path
|
||||
and data.get("peaks_per_second") == peaks_per_second
|
||||
and data.get("peaks_b64")
|
||||
):
|
||||
logger.info(f"[{job_id}] Vocals peaks cache hit: {cache_path}")
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to load vocals peaks cache: {e}")
|
||||
|
||||
decode_path = gcs_audio_path
|
||||
if transcoding_service is not None:
|
||||
try:
|
||||
ogg_path = transcoding_service.get_transcoded_cache_path(gcs_audio_path)
|
||||
if self.storage_service.file_exists(ogg_path):
|
||||
decode_path = ogg_path
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Could not resolve transcoded OGG for peaks: {e}")
|
||||
|
||||
import numpy as np
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(decode_path, "vocals"))
|
||||
self.storage_service.download_file(decode_path, local_audio_path)
|
||||
peaks, duration = self.waveform_generator.generate_peaks(
|
||||
local_audio_path, peaks_per_second=peaks_per_second
|
||||
)
|
||||
|
||||
quantized = np.clip(np.round(peaks * 255.0), 0, 255).astype(np.uint8)
|
||||
payload = {
|
||||
"peaks_b64": base64.b64encode(quantized.tobytes()).decode("ascii"),
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": peaks_per_second,
|
||||
"duration_seconds": duration,
|
||||
# Keyed to the LOGICAL source (the stem path) so a regenerated stem
|
||||
# at a new path invalidates, while the OGG decode shortcut doesn't.
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
}
|
||||
|
||||
try:
|
||||
self.storage_service.upload_json(cache_path, payload)
|
||||
logger.info(f"[{job_id}] Vocals peaks cached at {cache_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to cache vocals peaks (non-fatal): {e}")
|
||||
|
||||
return payload
|
||||
|
||||
def cache_waveform_data(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Time budgets for the audio-download Cloud Run Job (torrent stall handling).
|
||||
|
||||
A torrent whose only seeder is intermittently offline can sit at 0 peers for a
|
||||
while and then complete in seconds. flacfetch aborts a download after
|
||||
``max_stall_seconds`` with no progress; the worker then fails the job with
|
||||
error code ``audio_download_stalled`` and the user chooses "Keep trying" (a
|
||||
longer stall budget) or different audio — there is no silent auto-retry.
|
||||
|
||||
The worker's wait and the Cloud Run execution timeout are derived from the stall
|
||||
budget so they always leave room for the download itself plus the GCS upload.
|
||||
"""
|
||||
|
||||
# First attempt: wait this long with no progress before asking the user.
|
||||
STALL_SECONDS_DEFAULT = 20 * 60
|
||||
# "Keep trying": wait up to another hour (flacfetch caps a request at 3600s).
|
||||
STALL_SECONDS_KEEP_TRYING = 60 * 60
|
||||
|
||||
# Once data flows the stall clock resets; allow this much active download time
|
||||
# on top of the stall budget before the worker gives up waiting.
|
||||
_ACTIVE_DOWNLOAD_ALLOWANCE_SECONDS = 20 * 60
|
||||
# Headroom between the worker's wait and the Cloud Run task timeout, for the GCS
|
||||
# upload + state transition (so the worker fails gracefully, never SIGKILLed).
|
||||
_TASK_HEADROOM_SECONDS = 5 * 60
|
||||
|
||||
# While waiting on a torrent, the worker writes progress to the job this often.
|
||||
# Must stay well under the recover-stuck-jobs "no update for 10 min" threshold
|
||||
# (job_health_service: downloading_audio_stuck), or a live wait gets parked.
|
||||
HEARTBEAT_INTERVAL_SECONDS = 2 * 60
|
||||
|
||||
# Firestore state_data flag set by /retry {keep_trying: true}.
|
||||
KEEP_TRYING_STATE_KEY = "audio_download_keep_trying"
|
||||
|
||||
# error_details.code for a stalled download (read by the job card).
|
||||
STALLED_ERROR_CODE = "audio_download_stalled"
|
||||
|
||||
|
||||
def stall_seconds(keep_trying: bool) -> int:
|
||||
return STALL_SECONDS_KEEP_TRYING if keep_trying else STALL_SECONDS_DEFAULT
|
||||
|
||||
|
||||
def torrent_wait_timeout_seconds(keep_trying: bool) -> int:
|
||||
return stall_seconds(keep_trying) + _ACTIVE_DOWNLOAD_ALLOWANCE_SECONDS
|
||||
|
||||
|
||||
def task_timeout_seconds(keep_trying: bool) -> int:
|
||||
"""Cloud Run execution timeout override for audio-download-job."""
|
||||
return torrent_wait_timeout_seconds(keep_trying) + _TASK_HEADROOM_SECONDS
|
||||
@@ -106,23 +106,23 @@ 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
|
||||
# Fade selections within this distance of a clip edge snap to it, matching the
|
||||
# editor UI's edge tolerance ("fade in from ~the start" means from 0).
|
||||
FADE_EDGE_SNAP_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).
|
||||
"""Fade in or out across [start, end] only (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].
|
||||
Like Audacity's selection fades: direction='in' ramps silence -> full across
|
||||
the selection, direction='out' ramps full -> silence. Audio outside the
|
||||
selection is untouched, so fades work mid-track (e.g. fade out + mute +
|
||||
fade in to drop out a section). A selection starting within 1s of the clip
|
||||
start snaps to 0, and one ending within 1s of the end snaps to the 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.
|
||||
Implemented as trim -> afade -> concat, because afade applied to the whole
|
||||
stream silences everything before a fade-in / after a fade-out.
|
||||
"""
|
||||
if direction not in ("in", "out"):
|
||||
raise ValueError(f"Invalid fade direction: {direction}")
|
||||
@@ -130,25 +130,85 @@ class AudioEditService:
|
||||
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:
|
||||
snap = self.FADE_EDGE_SNAP_SECONDS
|
||||
if end > total + snap:
|
||||
raise ValueError(f"Fade region exceeds clip duration ({end} > {total})")
|
||||
if start <= snap:
|
||||
start = 0.0
|
||||
reaches_end = end >= total - snap
|
||||
if reaches_end:
|
||||
end = total
|
||||
if end - start <= 0:
|
||||
raise ValueError(f"Fade region must have positive duration (got {end - start})")
|
||||
|
||||
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})")
|
||||
fade = f"afade=t={direction}:st=0:d={end - start}"
|
||||
chains = []
|
||||
if start > 0:
|
||||
chains.append(f"[0]atrim=start=0:end={start},asetpts=PTS-STARTPTS[pre]")
|
||||
fade_trim = f"atrim=start={start}" if reaches_end else f"atrim=start={start}:end={end}"
|
||||
chains.append(f"[0]{fade_trim},asetpts=PTS-STARTPTS,{fade}[fade]")
|
||||
if not reaches_end:
|
||||
chains.append(f"[0]atrim=start={end},asetpts=PTS-STARTPTS[post]")
|
||||
labels = "".join(c[c.rindex("["):] for c in chains)
|
||||
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-af", f"afade=t={direction}:st={fade_start}:d={fade_duration}",
|
||||
"-filter_complex",
|
||||
";".join(chains) + f";{labels}concat=n={len(chains)}:v=0:a=1[out]",
|
||||
"-map", "[out]",
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
return self.get_metadata(output_path)
|
||||
|
||||
# Tempo factors outside this range sound badly artefacted and are almost
|
||||
# certainly a mistake for a sing-along track. The editor UI uses the same bounds.
|
||||
MIN_TEMPO_FACTOR = 0.5
|
||||
MAX_TEMPO_FACTOR = 1.5
|
||||
|
||||
_rubberband_available: bool | None = None
|
||||
|
||||
@classmethod
|
||||
def _has_rubberband(cls) -> bool:
|
||||
"""Whether this ffmpeg build includes the librubberband filter (cached)."""
|
||||
if cls._rubberband_available is None:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ffmpeg", "-hide_banner", "-filters"],
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
cls._rubberband_available = result.returncode == 0 and " rubberband " in result.stdout
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
cls._rubberband_available = False
|
||||
if not cls._rubberband_available:
|
||||
logger.warning(
|
||||
"ffmpeg has no rubberband filter; tempo changes will use the "
|
||||
"lower-quality atempo filter"
|
||||
)
|
||||
return cls._rubberband_available
|
||||
|
||||
def change_tempo(self, input_path: str, factor: float, output_path: str) -> AudioMetadata:
|
||||
"""Speed up (factor > 1) or slow down (factor < 1) the whole track, preserving pitch.
|
||||
|
||||
Uses Rubber Band (high-quality, pitch-preserving time-stretch) when the
|
||||
ffmpeg build has it — the production static build does — else atempo.
|
||||
"""
|
||||
if not (self.MIN_TEMPO_FACTOR <= factor <= self.MAX_TEMPO_FACTOR):
|
||||
raise ValueError(
|
||||
f"Tempo factor must be between {self.MIN_TEMPO_FACTOR} and "
|
||||
f"{self.MAX_TEMPO_FACTOR} (got {factor})"
|
||||
)
|
||||
if abs(factor - 1.0) < 1e-6:
|
||||
raise ValueError("Tempo factor of 1.0 would not change the audio")
|
||||
|
||||
if self._has_rubberband():
|
||||
audio_filter = f"rubberband=tempo={factor}:pitchq=quality:channels=together"
|
||||
else:
|
||||
audio_filter = f"atempo={factor}"
|
||||
|
||||
self._run_ffmpeg([
|
||||
"-i", input_path,
|
||||
"-af", audio_filter,
|
||||
"-c:a", "flac",
|
||||
output_path,
|
||||
])
|
||||
@@ -209,6 +269,8 @@ class AudioEditService:
|
||||
metadata = self.fade_region(
|
||||
local_input, params["start_seconds"], params["end_seconds"], direction, local_output
|
||||
)
|
||||
elif operation == "tempo":
|
||||
metadata = self.change_tempo(local_input, float(params["factor"]), local_output)
|
||||
elif operation in ("join_start", "join_end"):
|
||||
# Download the upload file
|
||||
upload_gcs_path = params["upload_gcs_path"]
|
||||
|
||||
@@ -56,6 +56,10 @@ class AudioTranscodingService:
|
||||
filename = Path(source_gcs_path).stem + ".ogg"
|
||||
return f"jobs/{job_id}/review-audio/{filename}"
|
||||
|
||||
def get_transcoded_cache_path(self, source_gcs_path: str) -> str:
|
||||
"""Public accessor for the transcoded-OGG cache path of a source file."""
|
||||
return self._get_cache_path(source_gcs_path)
|
||||
|
||||
def _transcode_and_upload(self, source_gcs_path: str, cache_path: str) -> str:
|
||||
"""
|
||||
Download FLAC from GCS, transcode to OGG Opus, upload to cache path.
|
||||
@@ -91,6 +95,14 @@ class AudioTranscodingService:
|
||||
|
||||
return cache_path
|
||||
|
||||
def invalidate_cache(self, source_gcs_path: str) -> None:
|
||||
"""Drop the cached OGG for a source that was overwritten in place (cache is
|
||||
keyed only on the source path, so a stale transcode would otherwise be served)."""
|
||||
try:
|
||||
self.storage.delete_file(self._get_cache_path(source_gcs_path), ignore_missing=True)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not invalidate review-audio cache for {source_gcs_path}: {e}")
|
||||
|
||||
def transcode_if_needed(self, source_gcs_path: str) -> str:
|
||||
"""
|
||||
Return the GCS path of the transcoded OGG file, transcoding if not cached.
|
||||
@@ -171,6 +183,44 @@ class AudioTranscodingService:
|
||||
"""Async wrapper around get_review_audio_bytes via asyncio.to_thread."""
|
||||
return await asyncio.to_thread(self.get_review_audio_bytes, source_gcs_path)
|
||||
|
||||
# Stems the review UI plays (instrumental options + the backing-vocals waveform).
|
||||
REVIEW_STEM_KEYS = ("instrumental_clean", "instrumental_with_backing", "backing_vocals")
|
||||
|
||||
def transcode_review_stems(self, job, force: bool = True) -> list[str]:
|
||||
"""
|
||||
Transcode the review-playable stems right after audio separation uploads them.
|
||||
|
||||
screens_worker's eager pass runs on LYRICS completion, which often precedes
|
||||
separation — so without this the stems' OGGs were only made on demand when the
|
||||
reviewer first played them (a 7-15 s ffmpeg run blocking the preview modal's
|
||||
instrumental audio). ``force`` (default) re-transcodes even if a cached OGG
|
||||
exists, since freshly uploaded stems supersede any OGG from an earlier run.
|
||||
Stems are transcoded in parallel; failures are logged, not raised.
|
||||
|
||||
Returns list of cache paths that were written.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
stems = (job.file_urls or {}).get("stems", {})
|
||||
sources = [(k, stems[k]) for k in self.REVIEW_STEM_KEYS if stems.get(k)]
|
||||
if not sources:
|
||||
return []
|
||||
|
||||
def _one(item):
|
||||
label, source_path = item
|
||||
try:
|
||||
if force:
|
||||
return self._transcode_and_upload(source_path, self._get_cache_path(source_path))
|
||||
return self.transcode_if_needed(source_path)
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job.job_id}] Failed to transcode review stem {label}: {e}")
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(sources)) as pool:
|
||||
results = [r for r in pool.map(_one, sources) if r]
|
||||
logger.info(f"[{job.job_id}] Review stems transcoded: {len(results)}/{len(sources)}")
|
||||
return results
|
||||
|
||||
def prepare_review_audio_for_job(self, job) -> list[str]:
|
||||
"""
|
||||
Transcode all review audio files for a job (eager transcoding).
|
||||
|
||||
@@ -33,9 +33,12 @@ review. Auto-approval must never be the reason a job fails.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.auto_approval.instrumental import (
|
||||
@@ -125,7 +128,16 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
audio_complete = bool(state_data.get("audio_complete", False))
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
|
||||
verdict = score_job(corrections, backing_analysis, ai_suggestions)
|
||||
# Missing-lyrics gate input: sung stretches the transcription has no words
|
||||
# for. Gates only when reference lyrics put lines in the gap ("evidenced");
|
||||
# fail-OPEN on pending audio / analysis errors (recorded below). Stem
|
||||
# download + decode: keep it off the event loop.
|
||||
vocal_gaps_info, vocal_gaps = await asyncio.to_thread(
|
||||
_vocal_gaps_shadow,
|
||||
job_id, job, corrections, ai_suggestions, stems, audio_complete, storage, job_manager,
|
||||
)
|
||||
|
||||
verdict = score_job(corrections, backing_analysis, ai_suggestions, vocal_gaps=vocal_gaps)
|
||||
|
||||
# Timing-plausibility gate: word timing vs the lead-vocal stem. Audio
|
||||
# IO (~15MB stem + a few seconds of numpy), so it runs only when the
|
||||
@@ -142,8 +154,9 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
elif not audio_complete:
|
||||
timing_info = {"status": "pending_audio"}
|
||||
else:
|
||||
signals = _compute_timing_signals(
|
||||
job_id, corrections, ai_suggestions, stems, storage
|
||||
signals = await asyncio.to_thread(
|
||||
_compute_timing_signals,
|
||||
job_id, corrections, ai_suggestions, stems, storage,
|
||||
)
|
||||
if signals is None:
|
||||
timing_info = {"status": "no_lead_stem"}
|
||||
@@ -154,7 +167,7 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
if signals.fired:
|
||||
verdict = score_job(
|
||||
corrections, backing_analysis, ai_suggestions,
|
||||
timing_signals=signals,
|
||||
timing_signals=signals, vocal_gaps=vocal_gaps,
|
||||
)
|
||||
|
||||
blockers = _enforcement_blockers(job, settings)
|
||||
@@ -216,6 +229,7 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
"trigger": trigger,
|
||||
"enforcement_blockers": blockers,
|
||||
"timing": timing_info,
|
||||
"vocal_gaps": vocal_gaps_info,
|
||||
"audio_complete_at_scoring": audio_complete,
|
||||
"backing_analysis_available": backing_analysis is not None,
|
||||
"ai_suggestions_available": ai_suggestions is not None,
|
||||
@@ -324,6 +338,136 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
|
||||
return {"outcome": "error", "error": str(e)}
|
||||
|
||||
|
||||
def _published_segments(corrections, ai_suggestions):
|
||||
"""The segments auto-ship would publish: raw + auto-applied AI suggestions."""
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if ai_suggestions:
|
||||
applied = build_applied_segments(corrections, ai_suggestions)
|
||||
if not applied.get("aborted"):
|
||||
segments = applied["segments"]
|
||||
return segments
|
||||
|
||||
|
||||
def analyze_vocal_gaps(job_id, corrections, segments, stems, storage):
|
||||
"""Download the lead-vocal stem and find sung stretches with no transcribed words.
|
||||
|
||||
Returns ``None`` when no lead/vocals stem is registered, else a
|
||||
``VocalGapsResult`` (``.error`` set on analysis failure). Never raises.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from backend.services.auto_approval.vocal_gaps import VocalGapsResult, compute_vocal_gaps
|
||||
|
||||
stem_path = stems.get("lead_vocals") or stems.get("vocals_clean")
|
||||
if not stem_path:
|
||||
return None
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
storage.download_file(stem_path, local)
|
||||
result = compute_vocal_gaps(segments, local, corrections)
|
||||
logger.info(
|
||||
f"[job:{job_id}] vocal gaps: {len(result.gaps)} gap(s), "
|
||||
f"suspect={result.suspect_count} max_run={result.max_suspect_run_s}s error={result.error}"
|
||||
)
|
||||
return result
|
||||
except Exception as e: # noqa: BLE001 — shadow analysis is best-effort
|
||||
logger.warning(f"[job:{job_id}] vocal gap analysis failed non-fatally: {e}")
|
||||
return VocalGapsResult(error=str(e))
|
||||
|
||||
|
||||
def vocal_gaps_input_key(segments, stems) -> str:
|
||||
"""Fingerprint of what a vocal-gap analysis looked at: word timings, stem, detector
|
||||
version. A reset, re-transcription, audio edit or new AI suggestions changes it."""
|
||||
from backend.services.auto_approval.vocal_gaps import VOCAL_GAPS_VERSION
|
||||
|
||||
words = [(w.get("id"), round(w.get("start_time") or 0, 2), round(w.get("end_time") or 0, 2))
|
||||
for seg in segments for w in (seg.get("words") or [])]
|
||||
stem = stems.get("lead_vocals") or stems.get("vocals_clean")
|
||||
blob = json.dumps([VOCAL_GAPS_VERSION, stem, words], ensure_ascii=False)
|
||||
return hashlib.sha1(blob.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _vocal_gaps_shadow(job_id, job, corrections, ai_suggestions, stems, audio_complete,
|
||||
storage, job_manager) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]:
|
||||
"""Analyze when stems exist and store ``state_data.vocal_gaps``; reuse a stored
|
||||
result only if it was computed from the same lyrics + stem (``input_key``).
|
||||
|
||||
Returns ``(summary for the payload, full vocal-gaps dict or None)``. Never raises.
|
||||
Blocking (stem download + decode): call via ``asyncio.to_thread``.
|
||||
"""
|
||||
try:
|
||||
if not audio_complete:
|
||||
return {"status": "pending_audio"}, None
|
||||
segments = _published_segments(corrections, ai_suggestions)
|
||||
input_key = vocal_gaps_input_key(segments, stems)
|
||||
existing = (job.state_data or {}).get("vocal_gaps")
|
||||
if existing and existing.get("input_key") == input_key:
|
||||
return {"status": "cached", "suspect_count": existing.get("suspect_count"),
|
||||
"evidenced_count": existing.get("evidenced_count", 0),
|
||||
"max_suspect_run_s": existing.get("max_suspect_run_s")}, existing
|
||||
result = analyze_vocal_gaps(job_id, corrections, segments, stems, storage)
|
||||
if result is None:
|
||||
return {"status": "no_lead_stem"}, None
|
||||
if result.error:
|
||||
return {"status": "error", "error": result.error}, None
|
||||
stored = {**result.to_dict(), "analyzed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"source": "auto_approval", "input_key": input_key}
|
||||
job_manager.update_state_data(job_id, "vocal_gaps", stored)
|
||||
return {"status": "checked", "suspect_count": result.suspect_count,
|
||||
"evidenced_count": result.evidenced_count,
|
||||
"max_suspect_run_s": result.max_suspect_run_s}, stored
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] vocal gap analysis failed non-fatally: {e}")
|
||||
return {"status": "error", "error": str(e)}, None
|
||||
|
||||
|
||||
def analyze_job_vocal_gaps(job_id: str, store: bool = True) -> Dict[str, Any]:
|
||||
"""Backfill/inspect: vocal gaps for the lyrics a job actually has now.
|
||||
|
||||
Uses the reviewed ``corrections_updated.json`` segments when present (what was
|
||||
rendered), with reference lyrics + anchors from ``corrections.json``. Runs
|
||||
synchronously (stem download + numpy, a few seconds). Never raises.
|
||||
"""
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
try:
|
||||
job_manager, storage = JobManager(), StorageService()
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
return {"status": "no_job"}
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
return {"status": "no_corrections"}
|
||||
corrections = storage.download_json(corrections_path)
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
lyrics_source = "corrections"
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
if storage.file_exists(updated_path):
|
||||
updated = storage.download_json(updated_path)
|
||||
if updated.get("corrected_segments"):
|
||||
segments, lyrics_source = updated["corrected_segments"], "corrections_updated"
|
||||
stems = (job.file_urls or {}).get("stems", {}) if job.file_urls else {}
|
||||
result = analyze_vocal_gaps(job_id, corrections, segments, stems, storage)
|
||||
if result is None:
|
||||
return {"status": "no_lead_stem"}
|
||||
if result.error:
|
||||
return {"status": "error", "error": result.error}
|
||||
payload = {**result.to_dict(), "analyzed_at": datetime.now(timezone.utc).isoformat(),
|
||||
"source": "backfill", "lyrics_source": lyrics_source,
|
||||
"input_key": vocal_gaps_input_key(segments, stems)}
|
||||
if store:
|
||||
job_manager.update_state_data(job_id, "vocal_gaps", payload)
|
||||
return {"status": "checked", "stored": store, "vocal_gaps": payload}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"[job:{job_id}] vocal gap backfill failed: {e}")
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
|
||||
def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage):
|
||||
"""Download the lead-vocal stem and run the timing-plausibility analysis
|
||||
on the POST-AI word stream (the state auto-ship would publish).
|
||||
@@ -335,7 +479,6 @@ def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage)
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from backend.services.auto_approval.apply import build_applied_segments
|
||||
from backend.services.auto_approval.timing_check import (
|
||||
TimingSignals,
|
||||
compute_timing_signals,
|
||||
@@ -348,11 +491,7 @@ def _compute_timing_signals(job_id, corrections, ai_suggestions, stems, storage)
|
||||
# The published state is raw + auto-applied suggestions; on an apply
|
||||
# abort the executor falls back to human review anyway, so analyzing
|
||||
# the raw segments there is only shadow data.
|
||||
segments = corrections.get("corrected_segments") or []
|
||||
if ai_suggestions:
|
||||
applied = build_applied_segments(corrections, ai_suggestions)
|
||||
if not applied.get("aborted"):
|
||||
segments = applied["segments"]
|
||||
segments = _published_segments(corrections, ai_suggestions)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
storage.download_file(stem_path, local)
|
||||
|
||||
@@ -19,6 +19,7 @@ its existing client-side on-load auto-apply. Auto-approval must never strand a j
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
@@ -51,32 +52,33 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
storage = StorageService()
|
||||
|
||||
corrections_path = CORRECTIONS_PATH.format(job_id=job_id)
|
||||
if not storage.file_exists(corrections_path):
|
||||
# All GCS/Firestore calls below are sync — run them off the event loop.
|
||||
if not await asyncio.to_thread(storage.file_exists, corrections_path):
|
||||
return {"outcome": "skipped", "reason": "no_corrections"}
|
||||
|
||||
updated_path = CORRECTIONS_UPDATED_PATH.format(job_id=job_id)
|
||||
if storage.file_exists(updated_path):
|
||||
if await asyncio.to_thread(storage.file_exists, updated_path):
|
||||
# Already applied once (executor auto-complete, a prior pre-apply run,
|
||||
# or a human edit). Never clobber existing corrections_updated.json.
|
||||
try:
|
||||
existing = storage.download_json(updated_path)
|
||||
existing = await asyncio.to_thread(storage.download_json, updated_path)
|
||||
if ((existing.get("metadata") or {}).get("auto_approval")):
|
||||
return {"outcome": "skipped", "reason": "already_applied"}
|
||||
except Exception:
|
||||
pass
|
||||
return {"outcome": "skipped", "reason": "corrections_updated_exists"}
|
||||
|
||||
corrections = storage.download_json(corrections_path)
|
||||
corrections = await asyncio.to_thread(storage.download_json, corrections_path)
|
||||
|
||||
# 1) Ensure the proactive suggestion cache exists (generate on miss, unless
|
||||
# the caller — e.g. the load-time path — asked to only apply an existing
|
||||
# cache so the request doesn't block on an LLM call).
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
ai_suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
|
||||
if ai_suggestions is None and generate_on_miss and settings.auto_correct_proactive_enabled:
|
||||
logger.info(f"[job:{job_id}] pre-apply: cache miss, generating suggestions synchronously")
|
||||
from backend.workers.auto_correct_worker import process_proactive_auto_correct
|
||||
await process_proactive_auto_correct(job_id) # bounded (180s) + best-effort
|
||||
ai_suggestions = _load_ai_suggestions(storage, job_id)
|
||||
ai_suggestions = await asyncio.to_thread(_load_ai_suggestions, storage, job_id)
|
||||
|
||||
if ai_suggestions is None:
|
||||
# Unknown suggestion set (proactive disabled or generation failed) —
|
||||
@@ -84,7 +86,7 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
return {"outcome": "skipped", "reason": "no_suggestions_cache"}
|
||||
|
||||
# 2) Apply with the executor's sanity gates.
|
||||
result = build_applied_segments(corrections, ai_suggestions)
|
||||
result = await asyncio.to_thread(build_applied_segments, corrections, ai_suggestions)
|
||||
if result.get("aborted"):
|
||||
logger.info(f"[job:{job_id}] pre-apply aborted ({result['aborted']}) — UI will apply client-side")
|
||||
return {"outcome": "skipped", "reason": result["aborted"]}
|
||||
@@ -115,11 +117,13 @@ async def ensure_and_pre_apply(job_id: str, *, generate_on_miss: bool = True) ->
|
||||
except Exception: # pragma: no cover - google libs always present in prod
|
||||
PreconditionFailed = () # type: ignore[assignment]
|
||||
try:
|
||||
storage.upload_json(updated_path, updated, if_generation_match=0)
|
||||
await asyncio.to_thread(storage.upload_json, updated_path, updated, if_generation_match=0)
|
||||
except PreconditionFailed:
|
||||
logger.info(f"[job:{job_id}] pre-apply raced a concurrent write — theirs wins")
|
||||
return {"outcome": "skipped", "reason": "raced_concurrent_write"}
|
||||
JobManager().update_file_url(job_id, "lyrics", "corrections_updated", updated_path)
|
||||
await asyncio.to_thread(
|
||||
JobManager().update_file_url, job_id, "lyrics", "corrections_updated", updated_path
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"[job:{job_id}] pre-apply saved corrections_updated.json "
|
||||
|
||||
@@ -41,7 +41,7 @@ from backend.services.auto_approval.models import (
|
||||
LyricsVerdict,
|
||||
)
|
||||
|
||||
SCORER_VERSION = "0.4.0"
|
||||
SCORER_VERSION = "0.5.0"
|
||||
|
||||
# --- Lyrics thresholds (deliberately conservative; the safe intersection first) ---
|
||||
# The AUTO tier requires a synced reference the transcription matches with ZERO
|
||||
@@ -373,13 +373,43 @@ def extract_lyrics_signals(
|
||||
)
|
||||
|
||||
|
||||
def _fmt_time(seconds: float) -> str:
|
||||
return f"{int(seconds // 60)}:{int(seconds % 60):02d}"
|
||||
|
||||
|
||||
def missing_lyrics_reasons(vocal_gaps: Optional[Dict[str, Any]]) -> List[str]:
|
||||
"""Human-readable reasons for each evidenced vocal gap (sung, no lyrics, and the
|
||||
reference lyrics put lines there). Empty when there's nothing to flag."""
|
||||
reasons = []
|
||||
for gap in (vocal_gaps or {}).get("gaps") or []:
|
||||
if not gap.get("evidenced"):
|
||||
continue
|
||||
lines = max(
|
||||
[len(v) for v in (gap.get("synced_reference_lines") or {}).values()]
|
||||
+ [len(v) for v in (gap.get("reference_lines") or {}).values()] + [0]
|
||||
)
|
||||
reasons.append(
|
||||
f"possible missing lyrics: ~{gap['longest_run_s']:.0f}s of singing at "
|
||||
f"{_fmt_time(gap['start'])}-{_fmt_time(gap['end'])} has no transcribed words, and the "
|
||||
f"reference lyrics have {lines} line(s) there"
|
||||
)
|
||||
return reasons
|
||||
|
||||
|
||||
def score_lyrics(
|
||||
correction_data: Dict[str, Any],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
timing_signals: Optional[Any] = None,
|
||||
vocal_gaps: Optional[Dict[str, Any]] = None,
|
||||
) -> LyricsResult:
|
||||
"""Decide whether the lyrics look safe to auto-approve.
|
||||
|
||||
``vocal_gaps`` (a stored ``VocalGapsResult`` dict) is a never-auto gate when any
|
||||
gap is *evidenced*: the lead vocal sings for >=3s with no transcribed words AND
|
||||
the reference lyrics place lines there (transcription dropped them — anchor
|
||||
coverage can't see omissions). Audio-only gaps don't gate (2026-10 audit:
|
||||
~25% precision without reference evidence).
|
||||
|
||||
``timing_signals`` (a ``timing_check.TimingSignals``) is optional because
|
||||
computing it needs the lead-vocal stem (audio IO the executor performs only
|
||||
when the text signals would otherwise be AUTO). When provided and fired,
|
||||
@@ -416,6 +446,11 @@ def score_lyrics(
|
||||
)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "phantom-gate", s, reasons)
|
||||
|
||||
missing = missing_lyrics_reasons(vocal_gaps)
|
||||
if missing:
|
||||
reasons.extend(missing)
|
||||
return LyricsResult(LyricsVerdict.REVIEW, "missing-lyrics-gate", s, reasons)
|
||||
|
||||
if timing_signals is not None and getattr(timing_signals, "fired", None):
|
||||
sig = timing_signals
|
||||
reasons.append(
|
||||
@@ -635,13 +670,14 @@ def score_job(
|
||||
backing_analysis: Optional[Dict[str, Any]],
|
||||
ai_suggestions: Optional[List[Dict[str, Any]]] = None,
|
||||
timing_signals: Optional[Any] = None,
|
||||
vocal_gaps: Optional[Dict[str, Any]] = None,
|
||||
) -> AutoApprovabilityVerdict:
|
||||
"""Produce the combined shadow verdict for a job.
|
||||
|
||||
``overall_auto`` is the narrow safe intersection: confident lyrics AND a
|
||||
non-subjective (no-audible-backing) backing decision.
|
||||
"""
|
||||
lyrics = score_lyrics(correction_data, ai_suggestions, timing_signals)
|
||||
lyrics = score_lyrics(correction_data, ai_suggestions, timing_signals, vocal_gaps)
|
||||
backing = score_backing(backing_analysis)
|
||||
overall_auto = lyrics.verdict == LyricsVerdict.AUTO and backing.non_subjective
|
||||
return AutoApprovabilityVerdict(
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
"""Vocal gaps: stretches where the lead vocal is singing but the transcription has no words.
|
||||
|
||||
Transcription can silently drop whole sung lines (job 5710831e: 11.7s of a Hebrew
|
||||
pre-chorus, three lines, no words at all). Nothing downstream notices:
|
||||
|
||||
- the scorer's anchor coverage is the fraction of *transcribed* words that match the
|
||||
reference, so omitted lines don't lower it;
|
||||
- ``SectionDetector`` labels any >=10s gap between segments "INSTRUMENTAL" without
|
||||
looking at the audio, so the video shows "♪ INSTRUMENTAL ♪" over singing;
|
||||
- a reviewer who doesn't read the language can't see that lines are missing.
|
||||
|
||||
For every transcription gap of at least ``MIN_GAP_S`` this measures how much of it the
|
||||
lead-vocal stem is active (short breaths bridged), and which reference lyrics sit
|
||||
between the reference positions of the words either side of the gap. Lines in the
|
||||
reference there are the strongest evidence that lyrics were dropped rather than the gap
|
||||
being ad-libs or a vocal sample.
|
||||
|
||||
Shadow-only for now: results are stored on the job (``state_data.vocal_gaps``) for
|
||||
calibration before anything gates on them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
from backend.services.auto_approval.timing_check import _load_mono, _rms_activity
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VOCAL_GAPS_VERSION = "0.2.0"
|
||||
|
||||
MIN_GAP_S = 3.0 # shorter gaps are normal phrasing
|
||||
BREATH_BRIDGE_S = 0.5 # silences this short inside singing don't end a vocal run
|
||||
# Shadow "suspect" threshold — calibrate on the backfill audit. Keyed on the longest
|
||||
# continuous (breath-bridged) vocal run, NOT the gap's active fraction: dropped lines
|
||||
# followed by an instrumental inside one transcription gap dilute the fraction (a 4s
|
||||
# dropped line in a 20s gap is only 20% active). On job 5710831e genuine
|
||||
# instrumentals peaked at 0.16s runs vs 11.76s for the dropped lines.
|
||||
SUSPECT_MIN_RUN_S = 3.0
|
||||
# A vocal run that starts at the gap's first frame is usually the previous word's held
|
||||
# note (transcribed end_time under-extended — a known AudioShake failure). Don't count
|
||||
# its first seconds as "unlyricked"; dropped lines run far longer (11.76s on 5710831e).
|
||||
# Held notes up to ALLOWANCE + SUSPECT_MIN_RUN_S (4.5s) past the word's end are tolerated.
|
||||
HELD_NOTE_ALLOWANCE_S = 1.5 # calibrate with the audit; 2.0 hid a single 4s dropped line
|
||||
MAX_REFERENCE_LINES = 12 # more than this between anchors = misaligned anchors, not a gap
|
||||
|
||||
|
||||
@dataclass
|
||||
class VocalGap:
|
||||
start: float
|
||||
end: float
|
||||
duration: float
|
||||
active_fraction: float # share of the gap where the lead vocal is active
|
||||
longest_run_s: float # longest vocal run inside the gap, breaths bridged
|
||||
reference_lines: Dict[str, List[str]] = field(default_factory=dict) # source -> lines
|
||||
# Synced reference lines (e.g. LRCLIB) whose timestamp falls inside the gap
|
||||
synced_reference_lines: Dict[str, List[str]] = field(default_factory=dict)
|
||||
suspect: bool = False # sung run long enough to be dropped lyrics (audio only)
|
||||
evidenced: bool = False # suspect AND reference lyrics place lines in this gap
|
||||
|
||||
|
||||
@dataclass
|
||||
class VocalGapsResult:
|
||||
version: str = VOCAL_GAPS_VERSION
|
||||
gaps: List[VocalGap] = field(default_factory=list)
|
||||
suspect_count: int = 0
|
||||
evidenced_count: int = 0
|
||||
max_suspect_run_s: float = 0.0
|
||||
error: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
# ---- transcription gaps ---------------------------------------------------------
|
||||
|
||||
def _words(segments: List[dict]) -> List[dict]:
|
||||
words = [w for seg in segments for w in (seg.get("words") or [])
|
||||
if w.get("start_time") is not None and w.get("end_time") is not None]
|
||||
return sorted(words, key=lambda w: w["start_time"])
|
||||
|
||||
|
||||
def transcription_gaps(segments: List[dict], audio_duration: float,
|
||||
min_gap_s: float = MIN_GAP_S) -> List[Tuple[float, float, Optional[dict], Optional[dict]]]:
|
||||
"""(start, end, word_before, word_after) for every gap >= ``min_gap_s``.
|
||||
|
||||
Includes the stretch before the first word and after the last one.
|
||||
"""
|
||||
words = _words(segments)
|
||||
gaps = []
|
||||
cursor, prev = 0.0, None
|
||||
for w in words:
|
||||
if w["start_time"] - cursor >= min_gap_s:
|
||||
gaps.append((cursor, w["start_time"], prev, w))
|
||||
cursor = max(cursor, w["end_time"])
|
||||
prev = w
|
||||
if audio_duration - cursor >= min_gap_s:
|
||||
gaps.append((cursor, audio_duration, prev, None))
|
||||
return gaps
|
||||
|
||||
|
||||
# ---- vocal activity -------------------------------------------------------------
|
||||
|
||||
def _bridge(active: np.ndarray, max_gap_frames: int) -> np.ndarray:
|
||||
"""Fill inactive runs of <= ``max_gap_frames`` that sit between active frames."""
|
||||
out = active.copy()
|
||||
idx = np.flatnonzero(active)
|
||||
if len(idx) < 2:
|
||||
return out
|
||||
for a, b in zip(idx[:-1], idx[1:]):
|
||||
if 1 < b - a <= max_gap_frames + 1:
|
||||
out[a:b] = True
|
||||
return out
|
||||
|
||||
|
||||
def _longest_run(mask: np.ndarray) -> int:
|
||||
best = run = 0
|
||||
for v in mask:
|
||||
run = run + 1 if v else 0
|
||||
best = max(best, run)
|
||||
return best
|
||||
|
||||
|
||||
# ---- reference lines in a gap ---------------------------------------------------
|
||||
|
||||
def _reference_index(correction_data: Dict[str, Any]) -> Dict[str, Dict[str, Tuple[int, int, int]]]:
|
||||
"""source -> reference word id -> (line index, word index within line, line length)."""
|
||||
index: Dict[str, Dict[str, Tuple[int, int, int]]] = {}
|
||||
for source, ref in (correction_data.get("reference_lyrics") or {}).items():
|
||||
ids: Dict[str, Tuple[int, int, int]] = {}
|
||||
for li, seg in enumerate((ref or {}).get("segments") or []):
|
||||
seg_words = seg.get("words") or []
|
||||
for wi, w in enumerate(seg_words):
|
||||
if w.get("id"):
|
||||
ids[w["id"]] = (li, wi, len(seg_words))
|
||||
index[source] = ids
|
||||
return index
|
||||
|
||||
|
||||
def _transcribed_to_reference(correction_data: Dict[str, Any]) -> Dict[str, Dict[str, List[str]]]:
|
||||
"""transcribed word id -> source -> reference word ids (anchors + gap sequences)."""
|
||||
mapping: Dict[str, Dict[str, List[str]]] = {}
|
||||
for seq in (correction_data.get("anchor_sequences") or []) + (correction_data.get("gap_sequences") or []):
|
||||
t_ids = seq.get("transcribed_word_ids") or []
|
||||
r_ids = seq.get("reference_word_ids") or {}
|
||||
for source, refs in r_ids.items():
|
||||
if len(refs) == len(t_ids): # anchors: 1:1 by position
|
||||
for t, r in zip(t_ids, refs):
|
||||
mapping.setdefault(t, {})[source] = [r]
|
||||
else: # gap sequences: not aligned word-for-word
|
||||
for t in t_ids:
|
||||
mapping.setdefault(t, {})[source] = list(refs)
|
||||
return mapping
|
||||
|
||||
|
||||
def reference_lines_between(correction_data: Dict[str, Any], word_before: Optional[dict],
|
||||
word_after: Optional[dict], _indexes=None) -> Dict[str, List[str]]:
|
||||
"""Reference lines strictly between the reference positions of the words around a gap.
|
||||
|
||||
Only whole reference lines are returned, and only when both neighbours map to the
|
||||
same source in increasing order (repeated choruses can anchor to a different
|
||||
occurrence; those cases return nothing rather than a misleading span).
|
||||
"""
|
||||
if not word_before or not word_after:
|
||||
return {}
|
||||
ref_index, t2r = _indexes or (_reference_index(correction_data), _transcribed_to_reference(correction_data))
|
||||
before = t2r.get(word_before.get("id"), {})
|
||||
after = t2r.get(word_after.get("id"), {})
|
||||
out: Dict[str, List[str]] = {}
|
||||
for source in set(before) & set(after):
|
||||
ids = ref_index.get(source, {})
|
||||
b = [ids[r] for r in before[source] if r in ids]
|
||||
a = [ids[r] for r in after[source] if r in ids]
|
||||
if not b or not a:
|
||||
continue
|
||||
b_line, b_word, _ = max(b, key=lambda x: (x[0], x[1]))
|
||||
a_line, a_word, a_len = min(a, key=lambda x: (x[0], x[1]))
|
||||
# Anchor reference ids can be off by one word at line boundaries (section
|
||||
# headers like "[Chorus]" tokenised differently): a gap's preceding word
|
||||
# "landing" on the first word of a line really ended the previous line, and
|
||||
# a following word landing on the last word of a line starts the next one.
|
||||
b_len = len(correction_data["reference_lyrics"][source]["segments"][b_line].get("words") or [])
|
||||
if b_word == 0 and b_len > 1:
|
||||
b_line -= 1
|
||||
if a_word == a_len - 1 and a_len > 1:
|
||||
a_line += 1
|
||||
# Whole lines only: after the line holding word_before, before the line of word_after
|
||||
first, last = b_line + 1, a_line - 1
|
||||
if first > last or last - first + 1 > MAX_REFERENCE_LINES:
|
||||
continue
|
||||
segs = correction_data["reference_lyrics"][source]["segments"]
|
||||
lines = [(segs[i].get("text") or "").strip() for i in range(first, last + 1)]
|
||||
lines = [l for l in lines if l and not (l.startswith("[") and l.endswith("]"))] # drop [Chorus] headers
|
||||
if lines:
|
||||
out[source] = lines
|
||||
return out
|
||||
|
||||
|
||||
# ---- synced reference lines in a gap ---------------------------------------------
|
||||
|
||||
SYNCED_EDGE_S = 0.5 # line must start this far inside the gap (tolerates small offsets)
|
||||
|
||||
|
||||
def _synced_reference_lines(correction_data: Dict[str, Any]) -> Dict[str, List[Tuple[float, str]]]:
|
||||
"""source -> [(line start time, text)] for reference sources with word timings."""
|
||||
out: Dict[str, List[Tuple[float, str]]] = {}
|
||||
for source, ref in (correction_data.get("reference_lyrics") or {}).items():
|
||||
lines = []
|
||||
for seg in (ref or {}).get("segments") or []:
|
||||
starts = [w.get("start_time") for w in seg.get("words") or [] if w.get("start_time") is not None]
|
||||
text = (seg.get("text") or "").strip()
|
||||
if starts and text and not (text.startswith("[") and text.endswith("]")):
|
||||
lines.append((float(starts[0]), text))
|
||||
if lines:
|
||||
out[source] = lines
|
||||
return out
|
||||
|
||||
|
||||
def synced_lines_in_gap(synced: Dict[str, List[Tuple[float, str]]], start: float, end: float) -> Dict[str, List[str]]:
|
||||
"""Synced reference lines that start inside (start, end), with an edge tolerance.
|
||||
|
||||
On the 2026-10 audit this was the most reliable evidence of dropped lyrics: only ~25%
|
||||
of audio-only suspect gaps had a synced reference line inside them.
|
||||
"""
|
||||
found = {src: [t for ts, t in lines if start + SYNCED_EDGE_S <= ts <= end - SYNCED_EDGE_S]
|
||||
for src, lines in synced.items()}
|
||||
return {src: lines for src, lines in found.items() if lines}
|
||||
|
||||
|
||||
# ---- entry point ----------------------------------------------------------------
|
||||
|
||||
def compute_vocal_gaps(segments: List[dict], lead_vocals_path: str,
|
||||
correction_data: Optional[Dict[str, Any]] = None) -> VocalGapsResult:
|
||||
"""Never raises: failures return ``VocalGapsResult(error=...)``."""
|
||||
try:
|
||||
samples, sr = _load_mono(lead_vocals_path)
|
||||
active, frame_s = _rms_activity(samples, sr)
|
||||
if len(active) == 0 or not active.any():
|
||||
# A failed separation must not be recorded as a clean "no gaps" pass
|
||||
return VocalGapsResult(error="empty or silent lead-vocal audio")
|
||||
bridged = _bridge(active, int(round(BREATH_BRIDGE_S / frame_s)))
|
||||
duration = len(active) * frame_s
|
||||
allowance = int(round(HELD_NOTE_ALLOWANCE_S / frame_s))
|
||||
|
||||
correction_data = correction_data or {}
|
||||
try:
|
||||
indexes = (_reference_index(correction_data), _transcribed_to_reference(correction_data))
|
||||
except Exception as e: # noqa: BLE001 — reference evidence is secondary
|
||||
logger.warning("vocal gaps: reference index failed: %s", e)
|
||||
indexes = None
|
||||
try:
|
||||
synced = _synced_reference_lines(correction_data)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("vocal gaps: synced reference parse failed: %s", e)
|
||||
synced = {}
|
||||
|
||||
result = VocalGapsResult()
|
||||
for start, end, before, after in transcription_gaps(segments, duration):
|
||||
i0, i1 = int(start / frame_s), min(len(active), int(np.ceil(end / frame_s)))
|
||||
if i1 <= i0:
|
||||
continue
|
||||
frac = float(active[i0:i1].mean())
|
||||
window = bridged[i0:i1].copy()
|
||||
# Discount a held note carried over from the word before the gap
|
||||
if before is not None and window[0]:
|
||||
window[:allowance] = False
|
||||
run_s = _longest_run(window) * frame_s
|
||||
try:
|
||||
refs = reference_lines_between(correction_data, before, after, indexes) if indexes else {}
|
||||
except Exception as e: # noqa: BLE001 — never lose the audio result to bad reference data
|
||||
logger.warning("vocal gaps: reference lookup failed: %s", e)
|
||||
refs = {}
|
||||
gap = VocalGap(
|
||||
start=round(start, 2), end=round(end, 2), duration=round(end - start, 2),
|
||||
active_fraction=round(frac, 3), longest_run_s=round(run_s, 2),
|
||||
reference_lines=refs,
|
||||
)
|
||||
gap.synced_reference_lines = synced_lines_in_gap(synced, start, end)
|
||||
gap.suspect = run_s >= SUSPECT_MIN_RUN_S
|
||||
gap.evidenced = gap.suspect and bool(gap.reference_lines or gap.synced_reference_lines)
|
||||
result.gaps.append(gap)
|
||||
|
||||
suspects = [g for g in result.gaps if g.suspect]
|
||||
result.suspect_count = len(suspects)
|
||||
result.evidenced_count = sum(1 for g in suspects if g.evidenced)
|
||||
result.max_suspect_run_s = max((g.longest_run_s for g in suspects), default=0.0)
|
||||
return result
|
||||
except Exception as e: # noqa: BLE001 — shadow analysis is best-effort
|
||||
logger.warning("vocal gap analysis failed: %s", e, exc_info=True)
|
||||
return VocalGapsResult(error=str(e))
|
||||
@@ -22,6 +22,7 @@ logged tokens rather than trusting the historical USD value.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
@@ -49,27 +50,49 @@ class _Rate(TypedDict):
|
||||
MODEL_PRICING: dict[str, _Rate] = {
|
||||
# --- Anthropic (authoritative) ---
|
||||
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
|
||||
"claude-opus-5-5": {"input": 4.0, "output": 20.0, "cache_read": 0.2},
|
||||
"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 (ESTIMATE — 3.x Pro preview, <=200K-token context tier;
|
||||
# confirm against current Google pricing before trusting USD). Calls go
|
||||
# via the Gemini Developer API (paid tier), assumed at Vertex list-price
|
||||
# parity. ---
|
||||
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
|
||||
# Promo rate through 2026-12-31; see _RATE_CHANGES for the standard rate.
|
||||
"gemini-3.8-flash": {"input": 0.75, "output": 3.75, "cache_read": 0.075},
|
||||
}
|
||||
|
||||
# Scheduled price changes: model -> [(effective_date, rate)], oldest first.
|
||||
# The latest entry whose date has arrived overrides MODEL_PRICING.
|
||||
_RATE_CHANGES: dict[str, list[tuple[date, _Rate]]] = {
|
||||
"gemini-3.8-flash": [
|
||||
(date(2027, 1, 1), {"input": 1.5, "output": 7.5, "cache_read": 0.15}),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def get_rate(model: str) -> Optional[_Rate]:
|
||||
def _effective(model: str, rate: _Rate, on: Optional[date]) -> _Rate:
|
||||
on = on or datetime.now(timezone.utc).date()
|
||||
for effective, changed in _RATE_CHANGES.get(model, []):
|
||||
if on >= effective:
|
||||
rate = changed
|
||||
return rate
|
||||
|
||||
|
||||
def get_rate(model: str, on: Optional[date] = None) -> 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.
|
||||
so a minor model-id change doesn't silently drop cost tracking. ``on``
|
||||
(default: today, UTC) selects any scheduled price change.
|
||||
"""
|
||||
if model in MODEL_PRICING:
|
||||
return MODEL_PRICING[model]
|
||||
return _effective(model, MODEL_PRICING[model], on)
|
||||
for known, rate in MODEL_PRICING.items():
|
||||
if model.startswith(known):
|
||||
return rate
|
||||
return _effective(known, rate, on)
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@ import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
# google.genai is imported lazily in _call_gemini() — it costs ~0.6s at import
|
||||
# time and this service sits on the backend's startup path via the review routes
|
||||
# (cold-start work, 2026-09-22).
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.auto_correct.deterministic import deterministic_suggestions
|
||||
@@ -673,7 +674,11 @@ class AutoCorrectService:
|
||||
system=system_prompt,
|
||||
messages=[{"role": "user", "content": user_prompt}],
|
||||
thinking={"type": "adaptive"},
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
# Pin effort: Opus 5.5 defaults to "medium" (4.8 defaulted to "high").
|
||||
output_config={
|
||||
"effort": "high",
|
||||
"format": {"type": "json_schema", "schema": strict_schema},
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
if _is_transient_model_error(exc):
|
||||
@@ -705,19 +710,19 @@ class AutoCorrectService:
|
||||
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),
|
||||
)
|
||||
from google.genai import types
|
||||
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
|
||||
# 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:
|
||||
# Gemini Developer API (API key). Timeout in milliseconds bounds the
|
||||
# call so a hung model never strands the UI.
|
||||
client = get_genai_client(timeout_ms=120_000)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -728,6 +733,15 @@ class AutoCorrectService:
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if note_gemini_failure("auto_correct", exc):
|
||||
# Quota / prepaid credit / key problem: retrying won't help.
|
||||
# Non-retryable so compare mode drops the Gemini leg at once
|
||||
# and keeps the other model's (Opus) suggestions.
|
||||
raise AutoCorrectServiceError(
|
||||
"Gemini is unavailable (quota/billing/key) — skipped",
|
||||
status_code=503,
|
||||
retryable=False,
|
||||
) from exc
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
|
||||
@@ -217,6 +217,18 @@ class BrandCodeService:
|
||||
return match.group(1), int(match.group(2))
|
||||
|
||||
|
||||
def is_preserved_brand_code(job, brand_code: Optional[str]) -> bool:
|
||||
"""True when ``brand_code`` came from the job itself (``keep_brand_code`` — e.g. a
|
||||
tenant's own catalogue code like "VS6588"), not from the allocator.
|
||||
|
||||
Such codes must never be recycled into a counter: a tenant code that happens to
|
||||
look like an allocated one (e.g. "VSTAR-0005") would otherwise put that number
|
||||
back in the pool and cause a duplicate later.
|
||||
"""
|
||||
kept = getattr(job, "keep_brand_code", None)
|
||||
return bool(kept) and kept == brand_code
|
||||
|
||||
|
||||
def get_brand_code_service() -> BrandCodeService:
|
||||
"""Get or create the singleton BrandCodeService instance."""
|
||||
global _brand_code_service
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
Free-to-paid conversion emails for gen consumers.
|
||||
|
||||
Funnel data (2026-10 business review): 44% of signups finish a free video but
|
||||
only 6% ever pay, and buyers decide fast (median ~5h after signup). So:
|
||||
|
||||
- When a never-paid user's FIRST video completes, ``on_job_completed`` marks
|
||||
``conversion_e1_due_at`` (now + CONVERSION_E1_DELAY_HOURS).
|
||||
- The hourly stale-review cron calls ``process_conversion_emails``:
|
||||
E1 ("your next song" + CONVERSION_OFFER_PERCENT% off for CONVERSION_OFFER_HOURS)
|
||||
once due, which also grants the time-limited ``promo_discount_*`` that
|
||||
checkout applies automatically; E2 ("ends in N hours") once, near the end.
|
||||
- Both are promotional, so they go out on Postmark's broadcast stream (Postmark
|
||||
adds the unsubscribe link and suppresses unsubscribed recipients).
|
||||
|
||||
Everything is gated by CONVERSION_EMAILS_ENABLED (off until Andrew approves the
|
||||
copy). Due times older than STALE_DUE_HOURS are skipped, so enabling the flag
|
||||
later never emails a backlog.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
USERS_COLLECTION = "gen_users"
|
||||
STALE_DUE_HOURS = 24
|
||||
UTM = "utm_source=email&utm_medium=email"
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _aware(value: Any) -> Optional[datetime]:
|
||||
"""Firestore timestamps / ISO strings / naive UTC datetimes -> aware UTC datetime."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(value, datetime):
|
||||
return None
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def active_promo(user: Any) -> Optional[Tuple[int, datetime]]:
|
||||
"""(percent, expires_at) of the user's unexpired promo discount, else None."""
|
||||
percent = getattr(user, "promo_discount_percent", None)
|
||||
expires = _aware(getattr(user, "promo_discount_expires_at", None))
|
||||
if not percent or not expires or expires <= _now():
|
||||
return None
|
||||
return int(percent), expires
|
||||
|
||||
|
||||
def promo_coupon_for_checkout(email: str, better_than_percent: int = 0) -> Optional[str]:
|
||||
"""Stripe coupon id for the user's active promo if it beats ``better_than_percent``."""
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
user = get_user_service().get_user(email)
|
||||
promo = active_promo(user) if user else None
|
||||
if not promo or promo[0] <= better_than_percent:
|
||||
return None
|
||||
return get_stripe_service().get_or_create_promo_coupon(promo[0])
|
||||
|
||||
|
||||
def on_job_completed(job: Any, user_service: Any) -> bool:
|
||||
"""Mark a never-paid consumer's first completed video for the E1 email.
|
||||
|
||||
Called (best-effort) right after ``total_jobs_completed`` is incremented.
|
||||
Returns True when the user was marked.
|
||||
"""
|
||||
if getattr(job, "made_for_you", False) or getattr(job, "tenant_id", None):
|
||||
return False
|
||||
email = getattr(job, "user_email", None)
|
||||
if not email or is_test_email(email):
|
||||
return False
|
||||
user = user_service.get_user(email)
|
||||
if not user or getattr(user, "tenant_id", None):
|
||||
return False
|
||||
if (user.total_spent or 0) > 0 or user.total_jobs_completed != 1:
|
||||
return False
|
||||
if user.conversion_e1_due_at or user.conversion_e1_sent_at:
|
||||
return False
|
||||
due = _now() + timedelta(hours=get_settings().conversion_e1_delay_hours)
|
||||
user_service.update_user(
|
||||
email,
|
||||
conversion_e1_due_at=due,
|
||||
first_video_artist=getattr(job, "artist", None),
|
||||
first_video_title=getattr(job, "title", None),
|
||||
)
|
||||
logger.info(f"Conversion E1 scheduled for {email.split('@')[-1]} user at {due.isoformat()}")
|
||||
return True
|
||||
|
||||
|
||||
def _links(frontend_url: str, locale: str, campaign: str) -> Tuple[str, str]:
|
||||
from backend.i18n import get_locale_prefix
|
||||
|
||||
base = f"{frontend_url}{get_locale_prefix(locale)}"
|
||||
utm = f"{UTM}&utm_campaign={campaign}"
|
||||
return f"{base}/app?buy=1&{utm}", f"{base}/order?{utm}"
|
||||
|
||||
|
||||
def process_conversion_emails(db: Any = None, email_service: Any = None, user_service: Any = None) -> Dict[str, Any]:
|
||||
"""Send due E1/E2 conversion emails. Safe to run every hour (idempotent per user)."""
|
||||
settings = get_settings()
|
||||
if not settings.conversion_emails_enabled:
|
||||
return {"status": "disabled", "e1_sent": 0, "e2_sent": 0, "errors": []}
|
||||
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.user_service import get_user_service
|
||||
|
||||
user_service = user_service or get_user_service()
|
||||
email_service = email_service or get_email_service()
|
||||
db = db or user_service.db
|
||||
now = _now()
|
||||
e1_sent = e2_sent = 0
|
||||
errors = []
|
||||
|
||||
# --- E1: offer, once due ---
|
||||
for doc in db.collection(USERS_COLLECTION).where("conversion_e1_due_at", "<=", now).stream():
|
||||
data = doc.to_dict() or {}
|
||||
email = data.get("email") or doc.id
|
||||
try:
|
||||
due = _aware(data.get("conversion_e1_due_at"))
|
||||
if data.get("conversion_e1_sent_at") or not due:
|
||||
continue
|
||||
if (data.get("total_spent") or 0) > 0 or (now - due) > timedelta(hours=STALE_DUE_HOURS):
|
||||
# Bought already, or too late to be timely: never send
|
||||
user_service.update_user(email, conversion_e1_sent_at=now, conversion_e1_skipped=True)
|
||||
continue
|
||||
percent = settings.conversion_offer_percent
|
||||
expires = now + timedelta(hours=settings.conversion_offer_hours)
|
||||
# Mark first so a crash mid-send can't produce a duplicate next hour
|
||||
user_service.update_user(
|
||||
email,
|
||||
conversion_e1_sent_at=now,
|
||||
promo_discount_percent=percent,
|
||||
promo_discount_expires_at=expires,
|
||||
)
|
||||
locale = data.get("locale") or "en"
|
||||
buy_url, mfy_url = _links(email_service.frontend_url, locale, "conv_e1")
|
||||
email_service.send_conversion_offer(
|
||||
to_email=email,
|
||||
artist=data.get("first_video_artist"),
|
||||
title=data.get("first_video_title"),
|
||||
percent=percent,
|
||||
offer_hours=settings.conversion_offer_hours,
|
||||
buy_url=buy_url,
|
||||
made_for_you_url=mfy_url,
|
||||
locale=locale,
|
||||
)
|
||||
e1_sent += 1
|
||||
except Exception as e:
|
||||
logger.exception(f"Conversion E1 failed for a user: {e}")
|
||||
errors.append(str(e))
|
||||
|
||||
# --- E2: offer ending soon, once ---
|
||||
window_end = now + timedelta(hours=settings.conversion_e2_hours_before_expiry)
|
||||
for doc in db.collection(USERS_COLLECTION).where("promo_discount_expires_at", ">", now).stream():
|
||||
data = doc.to_dict() or {}
|
||||
email = data.get("email") or doc.id
|
||||
try:
|
||||
expires = _aware(data.get("promo_discount_expires_at"))
|
||||
if not expires or expires > window_end or data.get("conversion_e2_sent_at"):
|
||||
continue
|
||||
if not data.get("conversion_e1_sent_at") or (data.get("total_spent") or 0) > 0:
|
||||
continue
|
||||
user_service.update_user(email, conversion_e2_sent_at=now)
|
||||
locale = data.get("locale") or "en"
|
||||
buy_url, _ = _links(email_service.frontend_url, locale, "conv_e2")
|
||||
hours_left = max(1, round((expires - now).total_seconds() / 3600))
|
||||
email_service.send_conversion_offer_reminder(
|
||||
to_email=email,
|
||||
percent=int(data.get("promo_discount_percent") or settings.conversion_offer_percent),
|
||||
hours_left=hours_left,
|
||||
buy_url=buy_url,
|
||||
locale=locale,
|
||||
)
|
||||
e2_sent += 1
|
||||
except Exception as e:
|
||||
logger.exception(f"Conversion E2 failed for a user: {e}")
|
||||
errors.append(str(e))
|
||||
|
||||
logger.info(f"Conversion emails: {e1_sent} E1, {e2_sent} E2, {len(errors)} errors")
|
||||
return {"status": "completed", "e1_sent": e1_sent, "e2_sent": e2_sent, "errors": errors}
|
||||
@@ -295,16 +295,17 @@ class CreditEvaluationService:
|
||||
"""Call Gemini and return the response text."""
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=60_000)
|
||||
response = client.models.generate_content(
|
||||
model=self.settings.credit_eval_model,
|
||||
contents=prompt,
|
||||
config=genai.types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
# Grant/deny classification over a short signal list: low
|
||||
# thinking is ample (Gemini 3 Flash defaults to high).
|
||||
thinking_config=genai.types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
@@ -402,7 +403,13 @@ class CreditEvaluationService:
|
||||
feedback_content=feedback_content,
|
||||
)
|
||||
|
||||
response_text = self._call_gemini(prompt)
|
||||
try:
|
||||
response_text = self._call_gemini(prompt)
|
||||
except Exception as gemini_exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("credit_evaluation", gemini_exc)
|
||||
raise
|
||||
evaluation = _parse_gemini_response(response_text)
|
||||
evaluation.signals = signals
|
||||
|
||||
|
||||
@@ -7,8 +7,11 @@ import logging
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
# google.genai is imported lazily in _call_gemini() — it costs ~0.6s at import
|
||||
# time and this service sits on the backend's startup path via the review routes
|
||||
# (cold-start work, 2026-09-22). Module attributes `genai`/`types` still resolve
|
||||
# via __getattr__ below so tests can keep patching
|
||||
# "backend.services.custom_lyrics.service.genai.Client".
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.custom_lyrics.prompts import (
|
||||
@@ -34,6 +37,19 @@ from karaoke_gen.lyrics_transcriber.utils.syllable_counter import SyllableCounte
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
"""Lazy module attributes so `service.genai` / `service.types` stay patchable."""
|
||||
if name == "genai":
|
||||
from google import genai
|
||||
|
||||
return genai
|
||||
if name == "types":
|
||||
from google.genai import types
|
||||
|
||||
return types
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
|
||||
SUPPORTED_MIMES = {
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
||||
"application/pdf": "pdf",
|
||||
@@ -546,33 +562,43 @@ class CustomLyricsService:
|
||||
pdf_bytes: Optional[bytes],
|
||||
settings: GenerationSettings,
|
||||
) -> list[str]:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=self.settings.google_cloud_project,
|
||||
location="global",
|
||||
)
|
||||
from google.genai import types
|
||||
|
||||
from backend.services.gemini_client import get_genai_client, note_gemini_failure
|
||||
|
||||
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"}}
|
||||
try:
|
||||
# Bounded so a stalled call can't hang the request (Gemini Developer API).
|
||||
client = get_genai_client(timeout_ms=300_000)
|
||||
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"],
|
||||
},
|
||||
"required": ["lines"],
|
||||
},
|
||||
),
|
||||
)
|
||||
),
|
||||
)
|
||||
except Exception as exc:
|
||||
if note_gemini_failure("custom_lyrics", exc):
|
||||
raise CustomLyricsServiceError(
|
||||
"The AI lyrics service is temporarily unavailable. Please try "
|
||||
"again later, or edit the lyrics manually.",
|
||||
status_code=503,
|
||||
) from exc
|
||||
raise
|
||||
# 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
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
Approximate vocals for jobs where the user supplied their own instrumental.
|
||||
|
||||
Those jobs skip GPU separation, so there is no vocals stem and the lyrics review
|
||||
"Waveforms" mode had nothing to draw. The waveform only needs a peak envelope,
|
||||
so a cheap CPU estimate is enough: vocals ≈ mix − gain × instrumental, after
|
||||
aligning the instrumental to the mix by cross-correlation.
|
||||
|
||||
The result is registered as ``stems.vocals_derived`` — used ONLY for the review
|
||||
waveform (see backend/utils/stems.py). It is never shipped as a deliverable stem
|
||||
or used for the original-vocals guide, since it can contain residue when the
|
||||
instrumental isn't from the same master as the mix.
|
||||
|
||||
Runs inside the lyrics worker (4Gi, shared with transcription), so memory is
|
||||
bounded: alignment correlates a fixed-length excerpt, not the whole track, and
|
||||
very long inputs are skipped.
|
||||
"""
|
||||
import logging
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Waveform-only use: mono at 22.05 kHz keeps a 5-minute song ~26 MB as float32.
|
||||
SAMPLE_RATE = 22050
|
||||
# Encoder delay / leading silence differences are small; search ±2s.
|
||||
MAX_LAG_SECONDS = 2.0
|
||||
# Alignment excerpt length — plenty to lock onto, and keeps the FFT tiny.
|
||||
ALIGN_WINDOW_SECONDS = 60.0
|
||||
# Bound memory on the shared worker: skip absurdly long inputs (mashups, DJ sets).
|
||||
MAX_DURATION_SECONDS = 20 * 60
|
||||
# Minimum usable decode.
|
||||
MIN_DURATION_SECONDS = 1.0
|
||||
# residual energy / mix energy above this = the instrumental didn't cancel
|
||||
# (different master, big offset, edited mix). Showing that as "vocals" would
|
||||
# just be the full-mix envelope and mislead timing edits, so don't register it.
|
||||
MAX_USEFUL_RESIDUAL_RATIO = 0.85
|
||||
FFMPEG_TIMEOUT_SECONDS = 120
|
||||
|
||||
|
||||
class DerivedVocalsError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class DerivationResult:
|
||||
offset_samples: int
|
||||
gain: float
|
||||
# residual energy / mix energy. With a same-master instrumental this is
|
||||
# roughly the vocals' share of the mix; near 1.0 means the subtraction
|
||||
# removed little (the waveform is then ≈ the mix).
|
||||
residual_ratio: float
|
||||
|
||||
@property
|
||||
def useful(self) -> bool:
|
||||
return self.residual_ratio <= MAX_USEFUL_RESIDUAL_RATIO
|
||||
|
||||
|
||||
def _run_ffmpeg(args: list, input_bytes: Optional[bytes] = None) -> bytes:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["ffmpeg", "-nostdin", "-v", "error", *args],
|
||||
input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
timeout=FFMPEG_TIMEOUT_SECONDS, check=True,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
stderr = (e.stderr or b"").decode(errors="replace").strip()[-500:]
|
||||
raise DerivedVocalsError(f"ffmpeg failed (exit {e.returncode}): {stderr}") from e
|
||||
except subprocess.TimeoutExpired as e:
|
||||
raise DerivedVocalsError(f"ffmpeg timed out after {FFMPEG_TIMEOUT_SECONDS}s") from e
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def _decode_mono(path: str, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
|
||||
"""Decode any audio file to mono float32 at sample_rate via ffmpeg."""
|
||||
raw = _run_ffmpeg(["-i", path, "-t", str(MAX_DURATION_SECONDS + 1), "-ac", "1",
|
||||
"-ar", str(sample_rate), "-f", "f32le", "-"])
|
||||
samples = np.frombuffer(raw, dtype=np.float32).copy()
|
||||
seconds = len(samples) / sample_rate
|
||||
if seconds < MIN_DURATION_SECONDS:
|
||||
raise DerivedVocalsError(f"decoded only {seconds:.2f}s of audio from {path}")
|
||||
if seconds > MAX_DURATION_SECONDS:
|
||||
raise DerivedVocalsError(f"audio longer than {MAX_DURATION_SECONDS // 60} min; skipping")
|
||||
return samples
|
||||
|
||||
|
||||
def _encode_flac(samples: np.ndarray, out_path: str, sample_rate: int = SAMPLE_RATE) -> None:
|
||||
peak = float(np.max(np.abs(samples))) if samples.size else 0.0
|
||||
if peak > 1.0:
|
||||
samples = samples / peak
|
||||
_run_ffmpeg(["-y", "-f", "f32le", "-ar", str(sample_rate), "-ac", "1", "-i", "-",
|
||||
"-c:a", "flac", out_path], input_bytes=samples.astype(np.float32).tobytes())
|
||||
|
||||
|
||||
def find_offset(mix: np.ndarray, inst: np.ndarray, max_lag: int,
|
||||
window: int = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE),
|
||||
start_fraction: float = 0.25) -> int:
|
||||
"""Lag (samples) that best aligns inst to mix: mix[n] ≈ inst[n - lag].
|
||||
|
||||
Correlates a `window`-sample excerpt of the mix (by default from a quarter
|
||||
of the way in, past intros) against the matching instrumental span
|
||||
±max_lag, so memory and time are independent of track length.
|
||||
"""
|
||||
window = max(1, min(window, len(mix)))
|
||||
start = min(int(len(mix) * start_fraction), len(mix) - window)
|
||||
excerpt = mix[start: start + window].astype(np.float64)
|
||||
|
||||
# Instrumental span covering every candidate lag, zero-padded where it runs
|
||||
# off either end: seg[j] = inst[start - max_lag + j].
|
||||
seg = np.zeros(window + 2 * max_lag, dtype=np.float64)
|
||||
lo = start - max_lag
|
||||
src_lo, src_hi = max(0, lo), min(len(inst), lo + len(seg))
|
||||
if src_hi > src_lo:
|
||||
seg[src_lo - lo: src_hi - lo] = inst[src_lo:src_hi]
|
||||
|
||||
# c[k] = Σ_j excerpt[j] · seg[j + k] for k in [0, 2·max_lag] ⇒ lag = max_lag − k
|
||||
size = 1 << (len(seg) + window - 1).bit_length()
|
||||
corr = np.fft.irfft(np.conj(np.fft.rfft(excerpt, size)) * np.fft.rfft(seg, size), size)
|
||||
k = int(np.argmax(corr[: 2 * max_lag + 1]))
|
||||
return max_lag - k
|
||||
|
||||
|
||||
def subtract_instrumental(mix: np.ndarray, inst: np.ndarray, sample_rate: int = SAMPLE_RATE):
|
||||
"""Return (residual, DerivationResult) with inst aligned + gain-matched to mix."""
|
||||
lag = find_offset(mix, inst, int(MAX_LAG_SECONDS * sample_rate), int(ALIGN_WINDOW_SECONDS * sample_rate))
|
||||
aligned = np.zeros_like(mix)
|
||||
if lag >= 0:
|
||||
src = inst[: max(0, len(mix) - lag)]
|
||||
aligned[lag: lag + len(src)] = src
|
||||
else:
|
||||
src = inst[-lag: -lag + len(mix)]
|
||||
aligned[: len(src)] = src
|
||||
denom = float(np.dot(aligned, aligned))
|
||||
gain = float(np.dot(mix, aligned) / denom) if denom > 0 else 0.0
|
||||
residual = mix - gain * aligned
|
||||
mix_energy = float(np.dot(mix, mix))
|
||||
ratio = float(np.dot(residual, residual) / mix_energy) if mix_energy > 0 else 1.0
|
||||
return residual, DerivationResult(offset_samples=lag, gain=gain, residual_ratio=ratio)
|
||||
|
||||
|
||||
def derive_vocals_file(mix_path: str, instrumental_path: str, out_path: str) -> DerivationResult:
|
||||
"""Compute approximate vocals; write a FLAC (mono, 22.05 kHz) only if useful.
|
||||
|
||||
Raises DerivedVocalsError on decode/encode problems. Check ``result.useful``
|
||||
before registering the output — nothing is written when it's False.
|
||||
"""
|
||||
mix = _decode_mono(mix_path)
|
||||
inst = _decode_mono(instrumental_path)
|
||||
residual, result = subtract_instrumental(mix, inst)
|
||||
logger.info(
|
||||
"Derived vocals: offset=%d samples (%.1f ms) gain=%.3f residual_ratio=%.3f useful=%s",
|
||||
result.offset_samples, 1000 * result.offset_samples / SAMPLE_RATE, result.gain,
|
||||
result.residual_ratio, result.useful,
|
||||
)
|
||||
if result.useful:
|
||||
_encode_flac(residual, out_path)
|
||||
return result
|
||||
@@ -8,17 +8,57 @@ replacing rclone for server-side operations. It handles:
|
||||
|
||||
Credentials are loaded from Google Cloud Secret Manager.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from typing import Optional
|
||||
import tempfile
|
||||
import zipfile
|
||||
from typing import Optional, Sequence, Tuple
|
||||
|
||||
from google.cloud import secretmanager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def prefix_zip_entries(src_zip: str, dst_zip: str, prefix: str) -> None:
|
||||
"""Copy a zip, prepending ``prefix`` to every entry's file name (not its folders).
|
||||
|
||||
Entries are streamed (never fully loaded into memory) and keep their original
|
||||
timestamps/compression, so re-packing the same zip is deterministic.
|
||||
"""
|
||||
import shutil
|
||||
|
||||
with zipfile.ZipFile(src_zip) as zin, zipfile.ZipFile(dst_zip, "w") as zout:
|
||||
for info in zin.infolist():
|
||||
folder, _, name = info.filename.rpartition("/")
|
||||
if info.is_dir() or not name:
|
||||
zout.writestr(info, b"")
|
||||
continue
|
||||
new_info = zipfile.ZipInfo(f"{folder}/{prefix}{name}" if folder else f"{prefix}{name}", info.date_time)
|
||||
new_info.compress_type = info.compress_type
|
||||
new_info.external_attr = info.external_attr
|
||||
with zin.open(info) as src, zout.open(new_info, "w") as dst:
|
||||
shutil.copyfileobj(src, dst, 1024 * 1024)
|
||||
|
||||
|
||||
_DROPBOX_HASH_BLOCK = 4 * 1024 * 1024
|
||||
|
||||
|
||||
def dropbox_content_hash(path: str) -> str:
|
||||
"""Dropbox ``content_hash`` of a local file: SHA-256 of the concatenated
|
||||
SHA-256 digests of each 4 MiB block (https://www.dropbox.com/developers/reference/content-hash)."""
|
||||
overall = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while True:
|
||||
block = f.read(_DROPBOX_HASH_BLOCK)
|
||||
if not block:
|
||||
break
|
||||
overall.update(hashlib.sha256(block).digest())
|
||||
return overall.hexdigest()
|
||||
|
||||
|
||||
class DropboxService:
|
||||
"""Dropbox operations using native Python SDK."""
|
||||
|
||||
@@ -86,8 +126,10 @@ class DropboxService:
|
||||
path: Dropbox path to list (e.g., "/Karaoke/Tracks-Organized")
|
||||
|
||||
Returns:
|
||||
List of folder names in the path
|
||||
List of folder names in the path (empty if the path doesn't exist yet,
|
||||
e.g. a brand-new tenant folder — the upload creates it)
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
from dropbox.files import FolderMetadata
|
||||
|
||||
# Ensure path starts with /
|
||||
@@ -96,7 +138,14 @@ class DropboxService:
|
||||
|
||||
logger.info(f"Listing folders at Dropbox path: {path}")
|
||||
|
||||
result = self.client.files_list_folder(path)
|
||||
try:
|
||||
result = self.client.files_list_folder(path)
|
||||
except ApiError as e:
|
||||
err = e.error
|
||||
if err.is_path() and err.get_path().is_not_found():
|
||||
logger.info(f"Dropbox path {path} does not exist yet; treating as empty")
|
||||
return []
|
||||
raise
|
||||
folders = []
|
||||
|
||||
# Get all entries (handling pagination)
|
||||
@@ -112,6 +161,32 @@ class DropboxService:
|
||||
logger.info(f"Found {len(folders)} folders in {path}")
|
||||
return folders
|
||||
|
||||
def ensure_folder(self, path: str) -> bool:
|
||||
"""
|
||||
Create a Dropbox folder (and any missing parents) if it doesn't exist.
|
||||
|
||||
Args:
|
||||
path: Dropbox folder path (e.g., "/MediaUnsynced/Karaoke/Tracks-RandyVild")
|
||||
|
||||
Returns:
|
||||
True if the folder was created, False if it already existed
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
|
||||
if not path.startswith("/"):
|
||||
path = f"/{path}"
|
||||
|
||||
try:
|
||||
self.client.files_create_folder_v2(path)
|
||||
except ApiError as e:
|
||||
err = e.error
|
||||
write_err = err.get_path() if err.is_path() else None
|
||||
if write_err is not None and write_err.is_conflict() and write_err.get_conflict().is_folder():
|
||||
return False
|
||||
raise
|
||||
logger.info(f"Created Dropbox folder {path}")
|
||||
return True
|
||||
|
||||
def get_next_brand_code(self, path: str, brand_prefix: str) -> str:
|
||||
"""
|
||||
Calculate next brand code from existing folders, filling gaps in the sequence.
|
||||
@@ -249,13 +324,62 @@ class DropboxService:
|
||||
)
|
||||
cursor.offset = file_obj.tell()
|
||||
|
||||
def upload_folder(self, local_dir: str, remote_path: str) -> None:
|
||||
def _remote_content_hashes(self, remote_path: str) -> dict:
|
||||
"""``{path_lower: content_hash}`` for every file under ``remote_path``.
|
||||
|
||||
Best-effort: a missing folder is empty, and any other error returns ``{}``
|
||||
(the caller then uploads everything, as before).
|
||||
"""
|
||||
from dropbox.exceptions import ApiError
|
||||
from dropbox.files import FileMetadata
|
||||
|
||||
try:
|
||||
result = self.client.files_list_folder(remote_path, recursive=True)
|
||||
except ApiError as e:
|
||||
err = e.error
|
||||
if err.is_path() and err.get_path().is_not_found():
|
||||
return {}
|
||||
logger.warning(f"Couldn't list {remote_path} to skip unchanged files: {e}")
|
||||
return {}
|
||||
except Exception as e:
|
||||
logger.warning(f"Couldn't list {remote_path} to skip unchanged files: {e}")
|
||||
return {}
|
||||
hashes = {}
|
||||
try:
|
||||
while True:
|
||||
for entry in result.entries:
|
||||
if isinstance(entry, FileMetadata) and entry.content_hash:
|
||||
hashes[entry.path_lower] = entry.content_hash
|
||||
if not result.has_more:
|
||||
break
|
||||
result = self.client.files_list_folder_continue(result.cursor)
|
||||
except Exception as e:
|
||||
logger.warning(f"Couldn't finish listing {remote_path} to skip unchanged files: {e}")
|
||||
return {}
|
||||
return hashes
|
||||
|
||||
def upload_folder(
|
||||
self,
|
||||
local_dir: str,
|
||||
remote_path: str,
|
||||
exclude_suffixes: Sequence[str] = (),
|
||||
skip_unchanged: bool = False,
|
||||
filename_prefix: str = "",
|
||||
) -> None:
|
||||
"""
|
||||
Recursively upload all files and subdirectories to Dropbox folder.
|
||||
|
||||
Args:
|
||||
local_dir: Local directory to upload
|
||||
remote_path: Dropbox destination folder path
|
||||
exclude_suffixes: Filename suffixes to skip (see
|
||||
dropbox_skip_suffixes_for). Skipped files stay on local disk / GCS.
|
||||
skip_unchanged: Don't re-upload files already in the folder with the
|
||||
same Dropbox content hash (one recursive listing up front). Used
|
||||
when a second pass adds files to a folder that was just uploaded.
|
||||
filename_prefix: Prepended to every uploaded file's name (e.g. a
|
||||
tenant's "VS6588 - " catalogue code). Entries inside .zip packages
|
||||
(CDG/TXT) are renamed too, so CDG+MP3 pairs keep matching names.
|
||||
"""
|
||||
# Ensure remote path starts with /
|
||||
if not remote_path.startswith("/"):
|
||||
@@ -263,7 +387,11 @@ class DropboxService:
|
||||
|
||||
logger.info(f"Uploading folder {local_dir} to {remote_path}")
|
||||
|
||||
remote_hashes = self._remote_content_hashes(remote_path) if skip_unchanged else {}
|
||||
|
||||
uploaded_count = 0
|
||||
skipped_count = 0
|
||||
unchanged_count = 0
|
||||
for root, _dirs, files in os.walk(local_dir):
|
||||
# Calculate the relative path from local_dir to current root
|
||||
rel_root = os.path.relpath(root, local_dir)
|
||||
@@ -273,12 +401,35 @@ class DropboxService:
|
||||
current_remote = f"{remote_path}/{rel_root}"
|
||||
|
||||
for filename in files:
|
||||
if exclude_suffixes and filename.endswith(tuple(exclude_suffixes)):
|
||||
logger.info(f"Skipping {filename} (excluded from Dropbox upload)")
|
||||
skipped_count += 1
|
||||
continue
|
||||
local_file = os.path.join(root, filename)
|
||||
remote_file = f"{current_remote}/{filename}"
|
||||
remote_file = f"{current_remote}/{filename_prefix}{filename}"
|
||||
if filename_prefix and filename.lower().endswith(".zip"):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
prefixed_zip = os.path.join(tmp, filename)
|
||||
prefix_zip_entries(local_file, prefixed_zip, filename_prefix)
|
||||
remote_hash = remote_hashes.get(remote_file.lower())
|
||||
if remote_hash and remote_hash == dropbox_content_hash(prefixed_zip):
|
||||
unchanged_count += 1
|
||||
continue
|
||||
self.upload_file(prefixed_zip, remote_file)
|
||||
uploaded_count += 1
|
||||
continue
|
||||
remote_hash = remote_hashes.get(remote_file.lower())
|
||||
if remote_hash and remote_hash == dropbox_content_hash(local_file):
|
||||
unchanged_count += 1
|
||||
continue
|
||||
self.upload_file(local_file, remote_file)
|
||||
uploaded_count += 1
|
||||
|
||||
logger.info(f"Uploaded {uploaded_count} files to {remote_path}")
|
||||
logger.info(
|
||||
f"Uploaded {uploaded_count} files to {remote_path}"
|
||||
+ (f" (skipped {skipped_count} excluded)" if skipped_count else "")
|
||||
+ (f" ({unchanged_count} already up to date)" if unchanged_count else "")
|
||||
)
|
||||
|
||||
def create_shared_link(self, path: str) -> str:
|
||||
"""
|
||||
@@ -351,3 +502,27 @@ class DropboxService:
|
||||
def get_dropbox_service() -> DropboxService:
|
||||
"""Factory function to get a DropboxService instance."""
|
||||
return DropboxService()
|
||||
|
||||
|
||||
def dropbox_skip_suffixes_for(dropbox_path: Optional[str]) -> Tuple[str, ...]:
|
||||
"""Filename suffixes to leave out of a Dropbox upload to ``dropbox_path``.
|
||||
|
||||
Only Nomad's own folders (DEFAULT_DROPBOX_PATH / DEFAULT_PRIVATE_DROPBOX_PATH)
|
||||
skip anything — tenant folders get the full output set. The suffix list comes
|
||||
from settings.dropbox_skip_output_suffixes ("|"-separated). Skipped files are
|
||||
still in GCS, so job-page downloads and YouTube uploads are unaffected.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not dropbox_path:
|
||||
return ()
|
||||
own_paths = {
|
||||
p.rstrip("/")
|
||||
for p in (settings.default_dropbox_path, settings.default_private_dropbox_path)
|
||||
if p
|
||||
}
|
||||
if dropbox_path.rstrip("/") not in own_paths:
|
||||
return ()
|
||||
raw = settings.dropbox_skip_output_suffixes or ""
|
||||
return tuple(s for s in raw.split("|") if s.strip())
|
||||
@@ -11,10 +11,15 @@ import html
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import smtplib
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from email.message import EmailMessage
|
||||
from email.utils import formataddr
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import NamedTuple, Optional, List
|
||||
from typing import NamedTuple, Optional, List, Tuple
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
@@ -174,6 +179,76 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
|
||||
API_URL = "https://api.postmarkapp.com/email"
|
||||
|
||||
# SMTP fallback for when Postmark's API edge blocks us. Since 2026-09-30 the
|
||||
# edge has answered us-central1 Cloud Run egress IPs with a bare nginx HTML
|
||||
# 403 for hours at a time, so retrying the API doesn't help; SMTP is served
|
||||
# by separate infrastructure. Auth = server token as username and password.
|
||||
SMTP_HOST = "smtp.postmarkapp.com"
|
||||
SMTP_PORT = 587
|
||||
SMTP_TIMEOUT = 15
|
||||
MESSAGE_STREAM = "outbound"
|
||||
|
||||
# Seconds to sleep before each retry of a transient failure (429 / 5xx /
|
||||
# connect timeout). Kept short: magic-link sends block the request.
|
||||
RETRY_DELAYS = (1.0, 3.0)
|
||||
|
||||
@staticmethod
|
||||
def _is_transient_failure(response: requests.Response) -> bool:
|
||||
"""True for failures worth retrying against the API: 429 or 5xx."""
|
||||
status = response.status_code
|
||||
return status == 429 or status >= 500
|
||||
|
||||
@staticmethod
|
||||
def _is_edge_block(response: requests.Response) -> bool:
|
||||
"""True for a 403 without a JSON body: an IP-level block at Postmark's edge.
|
||||
|
||||
Postmark's own API errors (bad token, invalid payload, suppressed
|
||||
recipient) come back as JSON and are verdicts on the request itself; a
|
||||
bare HTML 403 never reached the API, so the message was not accepted and
|
||||
it's safe to resend it over SMTP.
|
||||
"""
|
||||
if response.status_code != 403:
|
||||
return False
|
||||
try:
|
||||
response.json()
|
||||
except ValueError:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _post_with_retry(self, payload: dict) -> requests.Response:
|
||||
"""POST to Postmark, retrying transient failures with backoff.
|
||||
|
||||
Only connect-phase errors are retried among exceptions: a read timeout
|
||||
may mean Postmark already accepted the message, and it has no
|
||||
idempotency key, so retrying could send a duplicate.
|
||||
"""
|
||||
attempts = len(self.RETRY_DELAYS) + 1
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
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,
|
||||
)
|
||||
except requests.ConnectTimeout:
|
||||
if attempt == attempts:
|
||||
raise
|
||||
logger.warning(f"Postmark connect timeout (attempt {attempt}/{attempts}); retrying")
|
||||
else:
|
||||
if attempt == attempts or not self._is_transient_failure(response):
|
||||
return response
|
||||
logger.warning(
|
||||
f"Postmark returned transient status {response.status_code} "
|
||||
f"(attempt {attempt}/{attempts}); retrying"
|
||||
)
|
||||
time.sleep(self.RETRY_DELAYS[attempt - 1])
|
||||
raise AssertionError("unreachable") # pragma: no cover
|
||||
|
||||
def __init__(self, server_token: str, from_email: str, from_name: str = "Nomad Karaoke"):
|
||||
self.server_token = server_token
|
||||
self.from_email = from_email
|
||||
@@ -196,6 +271,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
cc_emails: Optional[List[str]] = None,
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
message_stream: Optional[str] = None,
|
||||
) -> bool:
|
||||
return self.send_email_detailed(
|
||||
to_email=to_email,
|
||||
@@ -205,6 +281,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
from_email_override=from_email_override,
|
||||
message_stream=message_stream,
|
||||
).success
|
||||
|
||||
def send_email_detailed(
|
||||
@@ -216,8 +293,16 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
cc_emails: Optional[List[str]] = None,
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
message_stream: Optional[str] = None,
|
||||
) -> SendResult:
|
||||
"""Send via the Postmark API (SMTP fallback on edge blocks).
|
||||
|
||||
``message_stream`` defaults to the transactional stream; promotional mail
|
||||
passes "broadcast" (Postmark appends the unsubscribe link and suppresses
|
||||
unsubscribed recipients on that stream).
|
||||
"""
|
||||
self.last_suppressed = False
|
||||
stream = message_stream or self.MESSAGE_STREAM
|
||||
try:
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
@@ -225,7 +310,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
"To": to_email,
|
||||
"Subject": subject,
|
||||
"HtmlBody": html_content,
|
||||
"MessageStream": "outbound",
|
||||
"MessageStream": stream,
|
||||
}
|
||||
if text_content:
|
||||
payload["TextBody"] = text_content
|
||||
@@ -235,16 +320,20 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
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,
|
||||
)
|
||||
try:
|
||||
response = self._post_with_retry(payload)
|
||||
except requests.ConnectTimeout:
|
||||
# Never connected, so Postmark didn't accept it: safe to resend.
|
||||
logger.warning("Postmark API connect timed out on every attempt; falling back to SMTP")
|
||||
return self._send_via_smtp(to_email, subject, html_content, text_content,
|
||||
cc_emails, bcc_emails, sender_email, stream)
|
||||
|
||||
if self._is_edge_block(response):
|
||||
logger.warning(
|
||||
f"Postmark API edge returned HTML 403 for {to_email}; falling back to SMTP"
|
||||
)
|
||||
return self._send_via_smtp(to_email, subject, html_content, text_content,
|
||||
cc_emails, bcc_emails, sender_email, stream)
|
||||
|
||||
if 200 <= response.status_code < 300:
|
||||
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
|
||||
@@ -287,6 +376,59 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
logger.exception("Failed to send email via Postmark")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
def _send_via_smtp(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str],
|
||||
cc_emails: Optional[List[str]],
|
||||
bcc_emails: Optional[List[str]],
|
||||
sender_email: str,
|
||||
message_stream: Optional[str] = None,
|
||||
) -> SendResult:
|
||||
"""Send through Postmark's SMTP endpoint (used when the API is unreachable).
|
||||
|
||||
SMTP returns no Postmark MessageID and can't report suppressed
|
||||
recipients synchronously (Postmark logs those as bounces instead).
|
||||
"""
|
||||
cc = _dedupe_emails(cc_emails) if cc_emails else []
|
||||
bcc = _dedupe_emails(bcc_emails) if bcc_emails else []
|
||||
try:
|
||||
msg = EmailMessage()
|
||||
msg["From"] = formataddr((self.from_name, sender_email))
|
||||
msg["To"] = to_email
|
||||
msg["Subject"] = subject
|
||||
msg["X-PM-Message-Stream"] = message_stream or self.MESSAGE_STREAM
|
||||
if cc:
|
||||
msg["Cc"] = ", ".join(cc)
|
||||
if text_content:
|
||||
msg.set_content(text_content)
|
||||
msg.add_alternative(html_content, subtype="html")
|
||||
else:
|
||||
msg.set_content(html_content, subtype="html")
|
||||
|
||||
smtp = smtplib.SMTP(self.SMTP_HOST, self.SMTP_PORT, timeout=self.SMTP_TIMEOUT)
|
||||
try:
|
||||
smtp.starttls(context=ssl.create_default_context())
|
||||
smtp.login(self.server_token, self.server_token)
|
||||
smtp.send_message(msg, to_addrs=[to_email, *cc, *bcc])
|
||||
finally:
|
||||
# A failed QUIT after an accepted send must not fail the send
|
||||
# (a caller retry would then duplicate the email).
|
||||
try:
|
||||
smtp.quit()
|
||||
except (smtplib.SMTPException, OSError):
|
||||
smtp.close()
|
||||
except (smtplib.SMTPException, OSError, ValueError):
|
||||
# ValueError: EmailMessage rejects CR/LF in header values.
|
||||
logger.exception(f"Failed to send email to {to_email} via Postmark SMTP fallback")
|
||||
return SendResult(success=False, message_id=None)
|
||||
|
||||
logger.info(f"Email sent to {to_email} via Postmark SMTP fallback")
|
||||
self.last_message_id = None
|
||||
return SendResult(success=True, 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
|
||||
@@ -407,6 +549,7 @@ class EmailService:
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
email_type: Optional[str] = None,
|
||||
message_stream: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""Single send chokepoint: dispatch via the provider, then persist a
|
||||
record of the send for the admin email-history view.
|
||||
@@ -430,6 +573,12 @@ class EmailService:
|
||||
# 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.
|
||||
# Only Postmark knows about message streams; dev providers ignore them.
|
||||
stream_kwargs = (
|
||||
{"message_stream": message_stream}
|
||||
if message_stream and isinstance(self.provider, PostmarkEmailProvider)
|
||||
else {}
|
||||
)
|
||||
success = self.provider.send_email(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
@@ -438,6 +587,7 @@ class EmailService:
|
||||
cc_emails=cc_emails,
|
||||
bcc_emails=bcc_emails,
|
||||
from_email_override=from_email_override,
|
||||
**stream_kwargs,
|
||||
)
|
||||
|
||||
# Mirror the provider's suppression flag so route handlers can tell a
|
||||
@@ -460,6 +610,7 @@ class EmailService:
|
||||
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),
|
||||
message_stream=message_stream or "outbound",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
@@ -480,6 +631,7 @@ class EmailService:
|
||||
from_email: Optional[str],
|
||||
email_type: Optional[str],
|
||||
message_id: Optional[str],
|
||||
message_stream: str = "outbound",
|
||||
) -> None:
|
||||
"""Write one Firestore ``email_log`` doc mirroring a sent email.
|
||||
|
||||
@@ -501,7 +653,7 @@ class EmailService:
|
||||
"html_content": _redact_sensitive_tokens(html_content),
|
||||
"text_content": _redact_sensitive_tokens(text_content),
|
||||
"email_type": email_type,
|
||||
"message_stream": "outbound",
|
||||
"message_stream": message_stream,
|
||||
"postmark_message_id": message_id,
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
@@ -608,6 +760,76 @@ class EmailService:
|
||||
email, subject, html_content, text_content, from_email_override=sender_email
|
||||
)
|
||||
|
||||
def send_kjbox_login_code(
|
||||
self,
|
||||
email: str,
|
||||
code: str,
|
||||
expiry_minutes: int,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""
|
||||
Send a 6-digit sign-in code for the kjbox karaoke-night singer page.
|
||||
|
||||
The singer types the code into the venue's singer page (they never visit
|
||||
the gen website), so the email carries no link — just the code.
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
subject = t(locale, "emails.kjboxLoginCode.subject", code=code)
|
||||
safe_code = html.escape(code)
|
||||
|
||||
extra_styles = f"""
|
||||
.code-box {{
|
||||
background-color: #fdf2f8;
|
||||
border: 2px solid {self.BRAND_PRIMARY};
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
margin: 24px 0;
|
||||
}}
|
||||
.code {{
|
||||
font-size: 40px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 10px;
|
||||
font-family: 'SF Mono', Menlo, Consolas, monospace;
|
||||
color: #111827;
|
||||
}}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>{t(locale, "emails.kjboxLoginCode.greeting")}</p>
|
||||
|
||||
<p>{t(locale, "emails.kjboxLoginCode.intro")}</p>
|
||||
|
||||
<div class="code-box">
|
||||
<div class="code">{safe_code}</div>
|
||||
</div>
|
||||
|
||||
<p>{t(locale, "emails.kjboxLoginCode.expiry", minutes=expiry_minutes)}</p>
|
||||
|
||||
<p>{t(locale, "emails.kjboxLoginCode.ignoreNote")}</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles, locale=locale)
|
||||
|
||||
text_content = f"""
|
||||
{t(locale, "emails.kjboxLoginCode.greeting")}
|
||||
|
||||
{t(locale, "emails.kjboxLoginCode.intro")}
|
||||
|
||||
{code}
|
||||
|
||||
{t(locale, "emails.kjboxLoginCode.expiry", minutes=expiry_minutes)}
|
||||
|
||||
{t(locale, "emails.kjboxLoginCode.ignoreNote")}
|
||||
|
||||
---
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self._log_and_send(email, subject, html_content, text_content)
|
||||
|
||||
def send_credits_added(self, email: str, credits: int, total_credits: int, locale: str = "en") -> bool:
|
||||
"""
|
||||
Send notification when credits are added to account.
|
||||
@@ -679,6 +901,171 @@ class EmailService:
|
||||
|
||||
return self._log_and_send(email, subject, html_content, text_content)
|
||||
|
||||
def send_karaokehunt_conversion(
|
||||
self,
|
||||
email: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
variant: str,
|
||||
login_url: str,
|
||||
community_url: Optional[str] = None,
|
||||
used_existing_credit: bool = False,
|
||||
locale: str = "en",
|
||||
is_new_user: bool = False,
|
||||
) -> bool:
|
||||
"""The email the retired KaraokeHunt app has promised its users for years
|
||||
("you should receive an email in 5-10 minutes"). One template, four
|
||||
variants matching the conversion outcome:
|
||||
|
||||
- "job": their track is being generated right now
|
||||
- "job_parked": we need them to pick the audio recording first
|
||||
- "board": no credits, so the song went to the community requests board
|
||||
- "community": a community karaoke version already exists — no job was
|
||||
made; the main button IS the YouTube link
|
||||
- "uninstall": they already used their one-time freebie — nothing was
|
||||
processed; tell them to uninstall the app and use Gen directly
|
||||
|
||||
All first-time variants also carry the "uninstall the app, use
|
||||
gen.nomadkaraoke.com from now on" note — the conversion is one-per-email.
|
||||
"""
|
||||
esc_artist = html.escape(artist)
|
||||
esc_title = html.escape(title)
|
||||
subject = t(locale, "emails.karaokehuntConversion.subject",
|
||||
artist=artist, title=title)
|
||||
|
||||
intro = t(
|
||||
locale,
|
||||
"emails.karaokehuntConversion.uninstallIntro" if variant == "uninstall"
|
||||
else "emails.karaokehuntConversion.intro",
|
||||
)
|
||||
|
||||
if variant == "uninstall":
|
||||
headline = t(locale, "emails.karaokehuntConversion.uninstallHeadline")
|
||||
detail = t(locale, "emails.karaokehuntConversion.uninstallDetail",
|
||||
artist=esc_artist, title=esc_title)
|
||||
detail_key = "uninstallDetail"
|
||||
button_label = t(locale, "emails.karaokehuntConversion.signInLink")
|
||||
button_url = login_url
|
||||
elif variant == "community":
|
||||
headline = t(locale, "emails.karaokehuntConversion.communityIntro")
|
||||
detail = t(locale, "emails.karaokehuntConversion.communityDetail",
|
||||
artist=esc_artist, title=esc_title)
|
||||
detail_key = "communityDetail"
|
||||
button_label = t(locale, "emails.karaokehuntConversion.communityLinkText")
|
||||
button_url = community_url or "https://gen.nomadkaraoke.com"
|
||||
elif variant == "job_parked":
|
||||
headline = t(locale, "emails.karaokehuntConversion.parkedIntro")
|
||||
detail = t(locale, "emails.karaokehuntConversion.parkedDetail",
|
||||
artist=esc_artist, title=esc_title)
|
||||
detail_key = "parkedDetail"
|
||||
button_label = t(locale, "emails.karaokehuntConversion.pickButton")
|
||||
button_url = login_url
|
||||
elif variant == "board":
|
||||
headline = t(locale, "emails.karaokehuntConversion.boardIntro")
|
||||
detail = t(locale, "emails.karaokehuntConversion.boardDetail",
|
||||
artist=esc_artist, title=esc_title)
|
||||
detail_key = "boardDetail"
|
||||
button_label = t(locale, "emails.karaokehuntConversion.boardButton")
|
||||
button_url = "https://requests.nomadkaraoke.com"
|
||||
else: # "job"
|
||||
headline = t(locale, "emails.karaokehuntConversion.jobStarted")
|
||||
detail = t(locale, "emails.karaokehuntConversion.jobDetail",
|
||||
artist=esc_artist, title=esc_title)
|
||||
detail_key = "jobDetail"
|
||||
button_label = t(locale, "emails.karaokehuntConversion.trackButton")
|
||||
button_url = login_url
|
||||
|
||||
account_note = ""
|
||||
if variant in ("job", "job_parked"):
|
||||
if used_existing_credit:
|
||||
account_note = t(locale, "emails.karaokehuntConversion.usedCreditNote")
|
||||
else:
|
||||
account_note = t(locale, "emails.karaokehuntConversion.newAccountNote")
|
||||
elif variant == "community":
|
||||
account_note = t(
|
||||
locale,
|
||||
"emails.karaokehuntConversion.communityCreditNoteNew" if is_new_user
|
||||
else "emails.karaokehuntConversion.communityCreditNoteExisting",
|
||||
)
|
||||
|
||||
community_block = ""
|
||||
community_text = ""
|
||||
if community_url and variant != "community":
|
||||
community_block = f"""
|
||||
<p>{t(locale, "emails.karaokehuntConversion.communityBonus")}<br>
|
||||
<a href="{html.escape(community_url)}">{t(locale, "emails.karaokehuntConversion.communityLinkText")}</a></p>
|
||||
"""
|
||||
community_text = (
|
||||
f"\n{t(locale, 'emails.karaokehuntConversion.communityBonus')}\n"
|
||||
f"{community_url}\n"
|
||||
)
|
||||
|
||||
sign_in_line = ""
|
||||
sign_in_text = ""
|
||||
if variant in ("board", "community"):
|
||||
# Board voting / using their credit both need them signed in.
|
||||
sign_in_label = t(
|
||||
locale,
|
||||
"emails.karaokehuntConversion.trackButton" if variant == "board"
|
||||
else "emails.karaokehuntConversion.signInLink",
|
||||
)
|
||||
sign_in_line = f"""
|
||||
<p style="text-align: center;">
|
||||
<a href="{login_url}">{sign_in_label}</a>
|
||||
</p>
|
||||
"""
|
||||
sign_in_text = f"\n{sign_in_label}: {login_url}\n"
|
||||
|
||||
# First-time variants carry the uninstall instruction; the "uninstall"
|
||||
# variant IS that instruction, so it doesn't repeat it.
|
||||
uninstall_note = ""
|
||||
if variant != "uninstall":
|
||||
uninstall_note = t(locale, "emails.karaokehuntConversion.uninstallNote")
|
||||
|
||||
content = f"""
|
||||
<p>{intro}</p>
|
||||
|
||||
<p><strong>{headline}</strong></p>
|
||||
|
||||
<p>{detail}</p>
|
||||
|
||||
{f'<p>{account_note}</p>' if account_note else ''}
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{button_url}" class="button">{button_label}</a>
|
||||
</p>
|
||||
{sign_in_line}{community_block}
|
||||
{f'<p><strong>{uninstall_note}</strong></p>' if uninstall_note else ''}
|
||||
|
||||
<p style="font-size: 13px; color: #6b7280;">{t(locale, "emails.karaokehuntConversion.whyEmail")}</p>
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, locale=locale)
|
||||
|
||||
text_content = f"""
|
||||
{intro}
|
||||
|
||||
{headline}
|
||||
|
||||
{t(locale, f"emails.karaokehuntConversion.{detail_key}", artist=artist, title=title)}
|
||||
|
||||
{account_note}
|
||||
|
||||
{button_label}: {button_url}
|
||||
{sign_in_text}{community_text}
|
||||
{uninstall_note}
|
||||
|
||||
---
|
||||
{t(locale, "emails.karaokehuntConversion.whyEmail")}
|
||||
|
||||
© {self._get_year()} Nomad Karaoke
|
||||
"""
|
||||
|
||||
return self._log_and_send(
|
||||
email, subject, html_content, text_content,
|
||||
email_type="karaokehunt_conversion",
|
||||
)
|
||||
|
||||
def send_welcome_email(self, email: str, credits: int = 0, locale: str = "en") -> bool:
|
||||
"""
|
||||
Send welcome email to new users.
|
||||
@@ -885,7 +1272,7 @@ class EmailService:
|
||||
}}
|
||||
"""
|
||||
|
||||
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "", locale: str = "en") -> str:
|
||||
def _build_email_html(self, content: str, extra_styles: str = "", extra_header_content: str = "", locale: str = "en", trailing_content: str = "") -> str:
|
||||
"""Build a complete HTML email with standard header, footer, and styles.
|
||||
|
||||
Args:
|
||||
@@ -912,6 +1299,7 @@ class EmailService:
|
||||
{content}
|
||||
|
||||
{self._get_email_footer(locale)}
|
||||
{trailing_content}
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
@@ -1290,6 +1678,7 @@ class EmailService:
|
||||
title: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
locale: str = "en",
|
||||
review_url: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send 24h review reminder email with expiry warning.
|
||||
@@ -1302,6 +1691,8 @@ class EmailService:
|
||||
artist: Artist name for subject line
|
||||
title: Song title for subject line
|
||||
job_id: Job ID for constructing the review link
|
||||
review_url: Override link (e.g. a one-click sign-in link to the review
|
||||
for kjbox jobs); defaults to the bare review URL
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
@@ -1312,7 +1703,8 @@ class EmailService:
|
||||
subject = t(locale, "emails.reviewReminder.subjectFallback")
|
||||
|
||||
locale_prefix = get_locale_prefix(locale)
|
||||
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
|
||||
if not review_url:
|
||||
review_url = f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}{locale_prefix}/app"
|
||||
|
||||
extra_styles = """
|
||||
.alert {
|
||||
@@ -1383,6 +1775,165 @@ class EmailService:
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Free-to-paid conversion emails (backend/services/conversion_emails.py)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
_CONVERSION_STYLES = """
|
||||
.offer {
|
||||
background-color: #fdf2f8;
|
||||
border: 1px solid #ff7acc;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
}
|
||||
.cta-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;
|
||||
}
|
||||
.legal {
|
||||
margin-top: 24px;
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
"""
|
||||
|
||||
def _commercial_footer(self, locale: str) -> Tuple[str, str]:
|
||||
"""(html, text) legal footer for promotional mail on the broadcast stream.
|
||||
|
||||
Postmark appends the unsubscribe link itself on the broadcast stream.
|
||||
"""
|
||||
why = t(locale, "emails.conversion.whyReceiving")
|
||||
address = self.settings.commercial_email_postal_address
|
||||
return (
|
||||
f'<p class="legal">{html.escape(why)}<br>{html.escape(address)}</p>',
|
||||
f"{why}\n{address}",
|
||||
)
|
||||
|
||||
def send_conversion_offer(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
percent: int,
|
||||
offer_hours: int,
|
||||
buy_url: str,
|
||||
made_for_you_url: str,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""E1: first free video is done, here's a time-limited discount on credits."""
|
||||
subject = t(locale, "emails.conversion.offerSubject")
|
||||
song = f"{artist} - {title}" if artist and title else ""
|
||||
intro_key = "emails.conversion.offerIntro" if song else "emails.conversion.offerIntroNoSong"
|
||||
intro_html = t(locale, intro_key, song=f"<strong>{html.escape(song)}</strong>")
|
||||
intro_text = t(locale, intro_key, song=song)
|
||||
offer = t(locale, "emails.conversion.offerLine", percent=percent, hours=offer_hours)
|
||||
legal_html, legal_text = self._commercial_footer(locale)
|
||||
|
||||
content = f"""
|
||||
<p>{intro_html}</p>
|
||||
<p>{t(locale, "emails.conversion.offerLead")}</p>
|
||||
<div class="offer"><strong>{html.escape(offer)}</strong><br>
|
||||
<span style="font-size: 14px;">{t(locale, "emails.conversion.offerAutoApplied")}</span></div>
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(buy_url)}" class="cta-btn">{t(locale, "emails.conversion.offerButton")}</a>
|
||||
</p>
|
||||
<p>{t(locale, "emails.conversion.madeForYouLine")} <a href="{html.escape(made_for_you_url)}">{t(locale, "emails.conversion.madeForYouLink")}</a></p>
|
||||
"""
|
||||
text_content = (
|
||||
f"{intro_text}\n\n{t(locale, 'emails.conversion.offerLead')}\n\n"
|
||||
f"{offer}\n{t(locale, 'emails.conversion.offerAutoApplied')}\n\n"
|
||||
f"{t(locale, 'emails.conversion.offerButton')}: {buy_url}\n\n"
|
||||
f"{t(locale, 'emails.conversion.madeForYouLine')} {made_for_you_url}\n\n{legal_text}"
|
||||
)
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=self._build_email_html(
|
||||
content, self._CONVERSION_STYLES, locale=locale, trailing_content=legal_html
|
||||
),
|
||||
text_content=text_content,
|
||||
message_stream="broadcast",
|
||||
)
|
||||
|
||||
def send_conversion_offer_reminder(
|
||||
self,
|
||||
to_email: str,
|
||||
percent: int,
|
||||
hours_left: int,
|
||||
buy_url: str,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""E2: the E1 discount ends soon."""
|
||||
subject = t(locale, "emails.conversion.reminderSubject", percent=percent, hours=hours_left)
|
||||
body = t(locale, "emails.conversion.reminderBody", percent=percent, hours=hours_left)
|
||||
legal_html, legal_text = self._commercial_footer(locale)
|
||||
content = f"""
|
||||
<p>{html.escape(body)}</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(buy_url)}" class="cta-btn">{t(locale, "emails.conversion.reminderButton")}</a>
|
||||
</p>
|
||||
<p>{t(locale, "emails.conversion.reminderNoPressure")}</p>
|
||||
"""
|
||||
text_content = (
|
||||
f"{body}\n\n{t(locale, 'emails.conversion.reminderButton')}: {buy_url}\n\n"
|
||||
f"{t(locale, 'emails.conversion.reminderNoPressure')}\n\n{legal_text}"
|
||||
)
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=self._build_email_html(
|
||||
content, self._CONVERSION_STYLES, locale=locale, trailing_content=legal_html
|
||||
),
|
||||
text_content=text_content,
|
||||
message_stream="broadcast",
|
||||
)
|
||||
|
||||
def send_review_last_chance(
|
||||
self,
|
||||
to_email: str,
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
review_url: str,
|
||||
hours_left: int,
|
||||
locale: str = "en",
|
||||
) -> bool:
|
||||
"""R2: final nudge a few hours before an unreviewed job auto-expires (transactional)."""
|
||||
song = f"{artist} - {title}" if artist and title else ""
|
||||
if song:
|
||||
subject = t(locale, "emails.reviewLastChance.subject", hours=hours_left, song=song)
|
||||
intro_html = t(locale, "emails.reviewLastChance.intro", hours=hours_left, song=f"<strong>{html.escape(song)}</strong>")
|
||||
intro_text = t(locale, "emails.reviewLastChance.intro", hours=hours_left, song=song)
|
||||
else:
|
||||
subject = t(locale, "emails.reviewLastChance.subjectFallback", hours=hours_left)
|
||||
intro_html = intro_text = t(locale, "emails.reviewLastChance.introNoSong", hours=hours_left)
|
||||
content = f"""
|
||||
<p>{intro_html}</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="{html.escape(review_url)}" class="cta-btn">{t(locale, "emails.reviewLastChance.button")}</a>
|
||||
</p>
|
||||
<p>{t(locale, "emails.reviewLastChance.howLong")}</p>
|
||||
<p>{t(locale, "emails.reviewLastChance.refundNote")}</p>
|
||||
"""
|
||||
text_content = (
|
||||
f"{intro_text}\n\n{t(locale, 'emails.reviewLastChance.button')}: {review_url}\n\n"
|
||||
f"{t(locale, 'emails.reviewLastChance.howLong')}\n\n{t(locale, 'emails.reviewLastChance.refundNote')}"
|
||||
)
|
||||
return self._log_and_send(
|
||||
to_email=to_email,
|
||||
subject=subject,
|
||||
html_content=self._build_email_html(content, self._CONVERSION_STYLES, locale=locale),
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
def send_duration_confirm_reminder(
|
||||
self,
|
||||
to_email: str,
|
||||
|
||||
@@ -71,6 +71,11 @@ GMAIL_LIKE_DOMAINS = {
|
||||
|
||||
# Well-known email providers that are never disposable.
|
||||
# These skip all external API checks for zero-latency validation.
|
||||
# Our own domains are never disposable. External disposable-email APIs have
|
||||
# flagged nomadkaraoke.com (auto-learned into manual_domains), which blocked
|
||||
# every admin magic-link sign-in.
|
||||
NEVER_DISPOSABLE_DOMAINS = {"nomadkaraoke.com"}
|
||||
|
||||
WELL_KNOWN_PROVIDERS = {
|
||||
"gmail.com",
|
||||
"googlemail.com",
|
||||
@@ -261,8 +266,8 @@ class EmailValidationService:
|
||||
|
||||
domain = email.lower().split("@")[-1]
|
||||
|
||||
# Tier 0: Well-known providers — skip everything
|
||||
if domain in WELL_KNOWN_PROVIDERS:
|
||||
# Tier 0: Well-known providers and our own domains — skip everything
|
||||
if domain in WELL_KNOWN_PROVIDERS or domain in NEVER_DISPOSABLE_DOMAINS:
|
||||
return False
|
||||
|
||||
# Tier 1: Static blocklist (instant, always available)
|
||||
@@ -394,6 +399,9 @@ class EmailValidationService:
|
||||
This persists the result so future checks don't need the API call.
|
||||
Fire-and-forget: errors are logged but don't affect the caller.
|
||||
"""
|
||||
if domain in NEVER_DISPOSABLE_DOMAINS or domain in WELL_KNOWN_PROVIDERS:
|
||||
logger.warning(f"Refusing to auto-learn protected domain as disposable: {domain}")
|
||||
return
|
||||
try:
|
||||
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
|
||||
BLOCKLIST_CONFIG_DOC
|
||||
|
||||
@@ -137,7 +137,7 @@ class EncodingInput:
|
||||
Contains all the paths and metadata needed to encode a karaoke video.
|
||||
"""
|
||||
# Required input files
|
||||
title_video_path: str # Title card video (MOV)
|
||||
title_video_path: Optional[str] # Title card video (MOV); None = theme omits it
|
||||
karaoke_video_path: str # Main karaoke video with vocals (MOV/MKV)
|
||||
instrumental_audio_path: str # Instrumental audio track (FLAC)
|
||||
|
||||
@@ -459,6 +459,18 @@ class GCEEncodingBackend(EncodingBackend):
|
||||
}
|
||||
|
||||
# Add countdown padding if present (for audio sync with countdown-padded vocals)
|
||||
# User-supplied instrumental: the encoder downloads it from uploads/
|
||||
# and matches it by name regardless of extension (wav, m4a, ...).
|
||||
existing_instrumental = input_config.options.get("existing_instrumental")
|
||||
if existing_instrumental:
|
||||
encoding_config["existing_instrumental"] = existing_instrumental
|
||||
|
||||
# Screens the theme leaves out: the encoder must skip them rather than
|
||||
# rebuild them from whatever matching PNG it finds in the job folder.
|
||||
for flag in ("include_title_screen", "include_end_screen"):
|
||||
if input_config.options.get(flag) is False:
|
||||
encoding_config[flag] = False
|
||||
|
||||
countdown_padding = input_config.options.get("countdown_padding_seconds")
|
||||
if countdown_padding:
|
||||
encoding_config["countdown_padding_seconds"] = countdown_padding
|
||||
|
||||
@@ -17,6 +17,7 @@ Usage:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
@@ -116,6 +117,26 @@ def _parse_resubmit_max() -> int:
|
||||
return 2
|
||||
|
||||
|
||||
# GCE statuses meaning the worker VM is not running (idle-stop, deploy stop, or —
|
||||
# since the a/b pair moved to Spot on 2026-09-26 — a Spot preemption, which STOPs
|
||||
# the VM). A job submitted to a VM in one of these states can never complete:
|
||||
# its in-memory job registry and ffmpeg process are gone.
|
||||
# PROVISIONING/STAGING/REPAIRING are included too: the job was accepted by a
|
||||
# RUNNING VM, so seeing the VM in a (re)start state means it went down and came
|
||||
# back (e.g. another request restarted a preempted worker) — the job is gone.
|
||||
_STOPPED_VM_STATUSES = frozenset({
|
||||
"STOPPING", "STOPPED", "TERMINATED", "SUSPENDING", "SUSPENDED",
|
||||
"PROVISIONING", "STAGING", "REPAIRING",
|
||||
})
|
||||
|
||||
# While polling a job, refresh config/encoding-worker.last_activity_at at most
|
||||
# this often. The idle-shutdown function keeps the routed VM alive only while
|
||||
# last_activity_at is < IDLE_TIMEOUT_MINUTES (5) old, and its /health
|
||||
# active_jobs counts only RUNNING jobs — so without this, a VM whose encode ran
|
||||
# longer than the idle window could be stopped in the seconds between the job
|
||||
# finishing and our next poll collecting the result.
|
||||
ACTIVITY_TOUCH_INTERVAL_SECONDS = 60.0
|
||||
|
||||
QUEUE_TIMEOUT_SECONDS = _parse_queue_timeout()
|
||||
ENCODING_RESUBMIT_MAX = _parse_resubmit_max()
|
||||
|
||||
@@ -272,6 +293,104 @@ class EncodingService:
|
||||
async with sem:
|
||||
yield
|
||||
|
||||
def _fallback_entries(self) -> list:
|
||||
"""Parse ENCODING_WORKER_FALLBACK_VMS into candidate dicts.
|
||||
|
||||
Schema: '[{"vm":"encoding-worker-fallback-c2df","zone":"us-central1-f",
|
||||
"ip":"34.x.x.x","machine_type":"c2d-highcpu-16"}, ...]'. machine_type is
|
||||
optional (inferred from the VM name for legacy entries). Malformed input
|
||||
degrades to fewer/no fallbacks — this runs during connection recovery and
|
||||
must never raise.
|
||||
"""
|
||||
import json as _json
|
||||
raw = self.settings.encoding_worker_fallback_vms
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
parsed = _json.loads(raw)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
|
||||
return []
|
||||
# A non-list root (null, dict, scalar) parses fine but would blow up
|
||||
# `for item in parsed` and escape 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")
|
||||
return []
|
||||
entries = []
|
||||
for item in parsed:
|
||||
try:
|
||||
entries.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
|
||||
return entries
|
||||
|
||||
def _vm_for_worker_url(self, worker_url: Optional[str]) -> Optional[tuple]:
|
||||
"""Map a worker base URL (http://<ip>:8080) back to its (vm_name, zone).
|
||||
|
||||
Looks at the blue-green primary/secondary, the active override, and the
|
||||
configured fallbacks. Returns None when unknown (no manager, unparseable
|
||||
URL, or an IP no longer in the fleet). BLOCKING (Firestore read).
|
||||
"""
|
||||
if not self._worker_manager or not worker_url:
|
||||
return None
|
||||
from urllib.parse import urlparse
|
||||
|
||||
host = urlparse(worker_url).hostname
|
||||
if not host:
|
||||
return None
|
||||
config = self._worker_manager.get_config()
|
||||
default_zone = self._worker_manager._zone
|
||||
known = [
|
||||
(config.primary_ip, config.primary_vm, default_zone),
|
||||
(config.secondary_ip, config.secondary_vm, default_zone),
|
||||
(config.active_override_ip, config.active_override_vm,
|
||||
config.active_override_zone or default_zone),
|
||||
]
|
||||
known.extend((fb["ip"], fb["vm"], fb["zone"]) for fb in self._fallback_entries())
|
||||
for ip, vm, zone in known:
|
||||
if ip and vm and ip == host:
|
||||
return vm, zone
|
||||
return None
|
||||
|
||||
async def _touch_worker_activity(self, job_id: str) -> None:
|
||||
"""Best-effort refresh of last_activity_at (keeps the VM from idle-stop)."""
|
||||
try:
|
||||
await asyncio.to_thread(self._worker_manager.update_activity)
|
||||
except Exception as e: # noqa: BLE001 — keep-alive only, never fail the poll
|
||||
logger.debug(f"[job:{job_id}] Could not refresh worker activity: {_format_exception(e)}")
|
||||
|
||||
async def _stopped_worker_status(self, worker_url: Optional[str]) -> Optional[str]:
|
||||
"""If the VM behind ``worker_url`` is stopped/preempted, return its GCE status.
|
||||
|
||||
Returns None when the VM is running, unknown, or the lookup fails — the
|
||||
caller then falls back to the ordinary poll-failure tolerance. Blocking
|
||||
Firestore/Compute calls run off the event loop.
|
||||
"""
|
||||
if not self._worker_manager:
|
||||
return None
|
||||
try:
|
||||
# Unpinned (legacy) polls target the current active URL.
|
||||
url = worker_url or await asyncio.to_thread(self._get_worker_url)
|
||||
found = await asyncio.to_thread(self._vm_for_worker_url, url)
|
||||
if not found:
|
||||
return None
|
||||
vm_name, zone = found
|
||||
status = await asyncio.to_thread(self._worker_manager.get_vm_status, vm_name, zone)
|
||||
except Exception as e: # noqa: BLE001 — best-effort diagnosis only
|
||||
logger.debug(f"Could not check worker VM status for {worker_url}: {_format_exception(e)}")
|
||||
return None
|
||||
if status in _STOPPED_VM_STATUSES:
|
||||
return f"{vm_name} is {status}"
|
||||
return None
|
||||
|
||||
def _build_worker_candidates(self) -> list:
|
||||
"""Build the ranked candidate list for ensure_any_running.
|
||||
|
||||
@@ -310,37 +429,9 @@ class EncodingService:
|
||||
"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
|
||||
# Optional capacity-fallback VMs in alternate zones/families (see
|
||||
# _fallback_entries). Empty when unconfigured.
|
||||
pool.extend(self._fallback_entries())
|
||||
|
||||
# Rank fastest-first, demoting types that recently stocked out. Keeps the
|
||||
# primary (c4d) at the top whenever it has capacity.
|
||||
@@ -413,17 +504,24 @@ class EncodingService:
|
||||
return
|
||||
|
||||
candidates = self._build_worker_candidates()
|
||||
# ensure_*_running are BLOCKING (Compute API get/start + wait for the
|
||||
# start operation — 10-20 s for a stopped VM). This coroutine runs on the
|
||||
# API service's event loop (preview encodes), so they MUST go through
|
||||
# to_thread: inline they froze every in-flight request on the instance
|
||||
# for the whole VM start (incident 2026-09-23).
|
||||
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)
|
||||
result = await asyncio.to_thread(
|
||||
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()
|
||||
else:
|
||||
result = self._worker_manager.ensure_primary_running()
|
||||
result = await asyncio.to_thread(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
|
||||
@@ -771,6 +869,7 @@ class EncodingService:
|
||||
# counts from here; time spent "pending" in the worker's serialized
|
||||
# heavy queue counts against `queue_timeout` instead.
|
||||
run_started_at: Optional[float] = None
|
||||
last_activity_touch: Optional[float] = None
|
||||
|
||||
while True:
|
||||
now = asyncio.get_event_loop().time()
|
||||
@@ -802,6 +901,25 @@ class EncodingService:
|
||||
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
|
||||
job_id=job_id,
|
||||
) from e
|
||||
# The worker VM itself went away (Spot preemption, idle/deploy
|
||||
# stop). Nothing on that VM can finish this job, so waiting out the
|
||||
# remaining poll tolerance (several minutes of retries) only delays
|
||||
# recovery — and "lost contact" is NOT resubmitted. Surface it as a
|
||||
# lost job so run_with_lost_job_resubmit re-submits it; the
|
||||
# resubmit's connection failure then restarts a worker (the Spot
|
||||
# VM, or the on-demand fallback if Spot capacity is gone).
|
||||
stopped = await self._stopped_worker_status(worker_url)
|
||||
if stopped:
|
||||
logger.warning(
|
||||
f"[job:{job_id}] Encoding worker VM stopped mid-job ({stopped}) — "
|
||||
f"likely Spot preemption; treating job as lost for resubmission"
|
||||
)
|
||||
self._invalidate_cached_url()
|
||||
raise EncodingJobLostError(
|
||||
f"Encoding job {job_id} was lost: worker VM {stopped} "
|
||||
f"(Spot preemption or stop)",
|
||||
job_id=job_id,
|
||||
) from e
|
||||
consecutive_failures += 1
|
||||
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
|
||||
logger.error(
|
||||
@@ -827,6 +945,12 @@ class EncodingService:
|
||||
status = {}
|
||||
|
||||
job_seen = True
|
||||
if self._worker_manager and (
|
||||
last_activity_touch is None
|
||||
or now - last_activity_touch >= ACTIVITY_TOUCH_INTERVAL_SECONDS
|
||||
):
|
||||
last_activity_touch = now
|
||||
await self._touch_worker_activity(job_id)
|
||||
job_status = status.get("status", "unknown")
|
||||
progress = status.get("progress", 0)
|
||||
if run_started_at is None and (job_status == "running" or progress):
|
||||
@@ -1258,25 +1382,49 @@ class EncodingService:
|
||||
_encoding_service: Optional[EncodingService] = None
|
||||
|
||||
|
||||
_encoding_service_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_encoding_service() -> EncodingService:
|
||||
"""Get the singleton encoding service instance."""
|
||||
"""Get the singleton encoding service instance.
|
||||
|
||||
First construction imports ``google.cloud.compute_v1`` (a ~10s import on a
|
||||
fresh Cloud Run instance) — the startup warmup thread builds it in the
|
||||
background, and async callers should use ``asyncio.to_thread`` so a cold
|
||||
call can't freeze the event loop (watchdog caught a 9.9s stall here in
|
||||
/api/health/detailed, 2026-10-03).
|
||||
"""
|
||||
global _encoding_service
|
||||
if _encoding_service is None:
|
||||
_encoding_service = EncodingService()
|
||||
# Wire up worker manager for dynamic URL resolution
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
settings = get_settings()
|
||||
db = firestore.Client(project=settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=settings.google_cloud_project,
|
||||
)
|
||||
_encoding_service.set_worker_manager(manager)
|
||||
except Exception:
|
||||
# Fallback to static URL if worker manager setup fails
|
||||
pass
|
||||
if _encoding_service is not None:
|
||||
return _encoding_service
|
||||
with _encoding_service_lock:
|
||||
if _encoding_service is not None:
|
||||
return _encoding_service
|
||||
_build_encoding_service()
|
||||
return _encoding_service
|
||||
|
||||
|
||||
def _build_encoding_service() -> None:
|
||||
"""Construct + wire the singleton; publish it only once fully wired, so the
|
||||
lock-free fast path in get_encoding_service never sees a half-built one."""
|
||||
global _encoding_service
|
||||
if _encoding_service is not None:
|
||||
return
|
||||
service = EncodingService()
|
||||
# Wire up worker manager for dynamic URL resolution
|
||||
try:
|
||||
from backend.services.encoding_worker_manager import EncodingWorkerManager
|
||||
from google.cloud import compute_v1, firestore
|
||||
settings = get_settings()
|
||||
db = firestore.Client(project=settings.google_cloud_project)
|
||||
compute_client = compute_v1.InstancesClient()
|
||||
manager = EncodingWorkerManager(
|
||||
db=db,
|
||||
compute_client=compute_client,
|
||||
project_id=settings.google_cloud_project,
|
||||
)
|
||||
service.set_worker_manager(manager)
|
||||
except Exception:
|
||||
# Fallback to static URL if worker manager setup fails
|
||||
pass
|
||||
_encoding_service = service
|
||||
@@ -34,6 +34,7 @@ from typing import Any, Optional
|
||||
|
||||
import aiohttp
|
||||
|
||||
from google.api_core import exceptions as gcp_exceptions
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.services.encoding_errors import (
|
||||
@@ -126,7 +127,7 @@ class EncodingWorkerConfig:
|
||||
|
||||
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
|
||||
temporarily out of c4d (Spot) capacity without rewriting the
|
||||
blue-green primary/secondary tracking.
|
||||
"""
|
||||
if self.active_override_ip:
|
||||
@@ -141,7 +142,7 @@ class EncodingWorkerCandidate:
|
||||
Carries everything needed to talk to the worker: VM name + zone (so the
|
||||
GCE compute client targets the right zone) and external IP (so successful
|
||||
starts can be persisted as the active URL override). ``machine_type`` (e.g.
|
||||
"c4d-highcpu-32") lets the manager record/clear per-(type,zone) capacity
|
||||
"c4d-highcpu-16") lets the manager record/clear per-(type,zone) capacity
|
||||
state so the shared preference logic can demote a stocked-out type.
|
||||
"""
|
||||
|
||||
@@ -444,7 +445,20 @@ class EncodingWorkerManager:
|
||||
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)
|
||||
try:
|
||||
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
|
||||
except gcp_exceptions.NotFound as nf:
|
||||
# A candidate that no longer exists (e.g. a fallback VM removed
|
||||
# from the fleet while an instance still holds the old
|
||||
# ENCODING_WORKER_FALLBACK_VMS list) must be SKIPPED, not
|
||||
# abort the whole failover — otherwise one stale entry blocks
|
||||
# every later (real) candidate.
|
||||
raise EncodingWorkerStartError(
|
||||
f"VM {candidate.vm_name} not found in {candidate.zone}: {nf}",
|
||||
vm_name=candidate.vm_name,
|
||||
zone=candidate.zone,
|
||||
code="NOT_FOUND",
|
||||
) from nf
|
||||
started = False
|
||||
if status not in ("RUNNING", "STAGING"):
|
||||
logger.info(
|
||||
@@ -613,7 +627,11 @@ class EncodingWorkerManager:
|
||||
zone = config.active_override_zone
|
||||
if not vm:
|
||||
# Primary pair was serving — see docstring; leave selection untouched.
|
||||
logger.warning(
|
||||
# Logged at ERROR so it alerts: on 2026-10-06 a primary that booted
|
||||
# without its env failed every job for an hour while this was a WARNING.
|
||||
# The worker now restarts itself (gce_encoding/self_heal.py); if this
|
||||
# keeps firing, that self-heal isn't working.
|
||||
logger.error(
|
||||
"Active encoding worker hit an infra failure while the primary was "
|
||||
"serving; leaving selection unchanged for bounded retry: %s", reason,
|
||||
)
|
||||
@@ -728,7 +746,9 @@ class EncodingWorkerManager:
|
||||
last_status = None
|
||||
last_log = 0.0
|
||||
while loop.time() < deadline:
|
||||
last_status = self.get_vm_status(vm_name, zone=zone)
|
||||
# Compute API call — keep it off the event loop (this runs inside
|
||||
# the API service for preview cold starts).
|
||||
last_status = await asyncio.to_thread(self.get_vm_status, vm_name, zone=zone)
|
||||
if last_status == "RUNNING":
|
||||
logger.info("VM %s reached RUNNING", vm_name)
|
||||
break
|
||||
|
||||
@@ -33,21 +33,24 @@ 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
|
||||
# Lower rank = faster = preferred. Keyed by machine FAMILY (the prefix before the
|
||||
# first "-"), so the ranking is independent of the vCPU size — the fleet moved
|
||||
# from *-highcpu-32 to *-highcpu-16 on 2026-09-26 and could move again. Seeded
|
||||
# from CPU architecture; refine with the measured medians from
|
||||
# infrastructure/encoding-worker/benchmark_types.py.
|
||||
# c4d AMD EPYC Turin (Zen5) — Spot blue-green primary pair, 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)
|
||||
# c2d AMD Milan (Zen3) — mature, deep pool (current on-demand fallback)
|
||||
# n2d AMD Rome/Milan — deep pool
|
||||
# n2 Intel Cascade/Ice Lake — deep pool
|
||||
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,
|
||||
"c4d": 10,
|
||||
"c4": 20,
|
||||
"n4d": 30,
|
||||
"c2d": 50,
|
||||
"n2d": 60,
|
||||
"n2": 70,
|
||||
}
|
||||
|
||||
# Rank for a candidate whose machine type is unknown and cannot be inferred:
|
||||
@@ -58,20 +61,26 @@ UNKNOWN_RANK = 1000
|
||||
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"
|
||||
# They are always c4d (Spot); used when a candidate carries no explicit
|
||||
# machine_type. Keep in sync with infrastructure/config.py MachineTypes.ENCODING_WORKER.
|
||||
PRIMARY_MACHINE_TYPE = "c4d-highcpu-16"
|
||||
|
||||
# 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"),
|
||||
)
|
||||
# Current vCPU size of the fleet — used only to turn a family inferred from a VM
|
||||
# name into a full machine type (for display + cooldown keys).
|
||||
_FLEET_SIZE_SUFFIX = "-highcpu-16"
|
||||
|
||||
# vm-name substring → machine family, 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_FAMILY = ("c4d", "n4d", "n2d", "c2d", "c4", "n2")
|
||||
|
||||
|
||||
def machine_family(machine_type: Optional[str]) -> Optional[str]:
|
||||
"""``"c4d-highcpu-16"`` → ``"c4d"``; None/empty → None."""
|
||||
if not machine_type:
|
||||
return None
|
||||
return machine_type.split("-", 1)[0].lower()
|
||||
|
||||
|
||||
def _candidate_name(candidate: Dict[str, Any]) -> str:
|
||||
@@ -83,21 +92,22 @@ 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).
|
||||
vm/zone/ip; the VM-name family token (…-fallback-c2df) is the only hint and
|
||||
is expanded to the current fleet size. 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
|
||||
for family in _NAME_TOKEN_TO_FAMILY:
|
||||
if family in name:
|
||||
return f"{family}{_FLEET_SIZE_SUFFIX}"
|
||||
return None
|
||||
|
||||
|
||||
def _speed_rank(candidate: Dict[str, Any]) -> int:
|
||||
return SPEED_RANK.get(infer_machine_type(candidate), UNKNOWN_RANK)
|
||||
return SPEED_RANK.get(machine_family(infer_machine_type(candidate)), UNKNOWN_RANK)
|
||||
|
||||
|
||||
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
|
||||
|
||||
@@ -17,11 +17,18 @@ 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
|
||||
#: How far back to look for errors on each run (minutes). Must equal the
|
||||
#: scheduler interval (ErrorMonitorConfig.MONITOR_SCHEDULE, hourly since
|
||||
#: 2026-09-26) so consecutive windows tile without gaps or double counting.
|
||||
LOOKBACK_MINUTES: int = 60
|
||||
|
||||
#: Maximum number of log entries to fetch per service per run.
|
||||
MAX_LOG_ENTRIES: int = 500
|
||||
#: Window (minutes) assumed for ``rolling_counts`` entries written before
|
||||
#: entries recorded their own ``window_minutes`` (i.e. the 15-min era).
|
||||
LEGACY_ROLLING_WINDOW_MINUTES: int = 15
|
||||
|
||||
#: Maximum number of log entries to fetch per resource type per run (scaled
|
||||
#: 4x with the 15 -> 60 min window to keep the same per-minute capacity).
|
||||
MAX_LOG_ENTRIES: int = 2000
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monitored services
|
||||
@@ -46,6 +53,10 @@ MONITORED_CLOUD_RUN_JOBS: list[str] = [
|
||||
"lyrics-transcription-job",
|
||||
"audio-separation-job",
|
||||
"audio-download-job",
|
||||
# karaoke-decide weekly MusicBrainz dump -> BigQuery refresh
|
||||
"mb-refresh",
|
||||
# karaoke-decide ListenBrainz statistics dump -> BigQuery refresh
|
||||
"lb-refresh",
|
||||
]
|
||||
|
||||
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
|
||||
@@ -98,8 +109,7 @@ Shared infrastructure:
|
||||
# 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")
|
||||
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-3.8-flash")
|
||||
|
||||
#: Minimum number of active error patterns required before triggering LLM analysis.
|
||||
MIN_PATTERNS_FOR_ANALYSIS: int = 3
|
||||
|
||||
@@ -19,6 +19,7 @@ from backend.services.error_monitor.config import (
|
||||
AUTO_RESOLVE_MIN_HOURS,
|
||||
AUTO_RESOLVE_MULTIPLIER,
|
||||
ROLLING_WINDOW_DAYS,
|
||||
LOOKBACK_MINUTES,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -174,7 +175,9 @@ class ErrorPatternsAdapter:
|
||||
snap = doc_ref.get()
|
||||
ts_iso = _iso(data.timestamp)
|
||||
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count}
|
||||
# window_minutes lets spike detection normalise counts across a change
|
||||
# of monitor cadence (15 -> 60 min on 2026-09-26).
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count, "window_minutes": LOOKBACK_MINUTES}
|
||||
|
||||
if not snap.exists:
|
||||
# ── brand new pattern ──────────────────────────────────────────
|
||||
|
||||
@@ -19,6 +19,10 @@ from backend.services.error_monitor.normalizer import (
|
||||
|
||||
MAX_SAMPLE_MESSAGE_CHARS = 4000
|
||||
MAX_URL_CHARS = 512
|
||||
# Stack goes LAST in the sample and is trimmed: Discord shows only the head of
|
||||
# the sample, and a long stack used to push URL/UA/build/diagnostics off the end.
|
||||
MAX_SAMPLE_STACK_LINES = 15
|
||||
MAX_SAMPLE_BREADCRUMBS = 10
|
||||
|
||||
# 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
|
||||
@@ -50,6 +54,26 @@ def is_bot_user_agent(user_agent: str | None) -> bool:
|
||||
return bool(_BOT_UA_RE.search(user_agent))
|
||||
|
||||
|
||||
# Browsers mask errors from cross-origin scripts (third-party tags, in-app
|
||||
# browser/extension injections) as a bare "Script error." with no error object,
|
||||
# file or line — nothing actionable. The frontend drops these at the source; this
|
||||
# also covers older cached bundles that still report them (as "Error: Script
|
||||
# error." whose stack is only our own window.onerror handler's frame, so the stack
|
||||
# can't be used to tell them apart). The discriminator is the ErrorEvent's own
|
||||
# filename/lineno, which browsers blank for opaque errors — a genuine
|
||||
# `throw new Error("Script error.")` from our code keeps its file/line and is kept.
|
||||
_OPAQUE_SCRIPT_ERROR_RE = re.compile(r"^(?:Error:\s*)?Script error\.?$", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_opaque_script_error(message: str | None, source: str | None = None, extra: dict | None = None) -> bool:
|
||||
"""Return True for the browser's opaque cross-origin "Script error." report."""
|
||||
if not message or not _OPAQUE_SCRIPT_ERROR_RE.match(message.strip()):
|
||||
return False
|
||||
if source != "window.onerror" or not isinstance(extra, dict):
|
||||
return False
|
||||
return not extra.get("filename") and not extra.get("lineno")
|
||||
|
||||
|
||||
@dataclass
|
||||
class FrontendErrorReport:
|
||||
"""In-memory representation of an inbound crash report."""
|
||||
@@ -79,17 +103,49 @@ def sanitize_url(url: str) -> str:
|
||||
return url[:MAX_URL_CHARS]
|
||||
|
||||
|
||||
def _error_location(extra: dict | None) -> str | None:
|
||||
"""`file:line:col` from a window.onerror report's extra, if present."""
|
||||
if not isinstance(extra, dict) or not extra.get("filename"):
|
||||
return None
|
||||
return f"{extra.get('filename')}:{extra.get('lineno', '?')}:{extra.get('colno', '?')}"
|
||||
|
||||
|
||||
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.
|
||||
has interpolated values). Errors with no real stack (the browser gave no
|
||||
Error object, e.g. Firefox "out of memory") hash on message + location.
|
||||
"""
|
||||
if report.stack:
|
||||
return report.stack
|
||||
location = _error_location(report.extra)
|
||||
if location:
|
||||
return f"{report.message} @ {location}"
|
||||
return report.message
|
||||
|
||||
|
||||
def _format_diagnostics(extra: dict | None) -> str | None:
|
||||
"""One compact line from the client's diagnostics snapshot."""
|
||||
diag = extra.get("diagnostics") if isinstance(extra, dict) else None
|
||||
if not isinstance(diag, dict) or not diag:
|
||||
return None
|
||||
parts = [f"{k}={v}" for k, v in diag.items() if isinstance(v, (int, float, str, bool)) and v != ""]
|
||||
return "Diag: " + " ".join(parts) if parts else None
|
||||
|
||||
|
||||
def _format_breadcrumbs(extra: dict | None) -> str | None:
|
||||
"""The last few client breadcrumbs (what the page was doing before the error)."""
|
||||
crumbs = extra.get("breadcrumbs") if isinstance(extra, dict) else None
|
||||
if not isinstance(crumbs, list) or not crumbs:
|
||||
return None
|
||||
lines = []
|
||||
for c in crumbs[-MAX_SAMPLE_BREADCRUMBS:]:
|
||||
if isinstance(c, dict):
|
||||
lines.append(f" {c.get('t', '?')}s [{c.get('category', '?')}] {str(c.get('message', ''))[:120]}")
|
||||
return "Trail:\n" + "\n".join(lines) if lines else None
|
||||
|
||||
|
||||
def build_pattern_data(
|
||||
report: FrontendErrorReport, now: datetime | None = None
|
||||
) -> PatternData:
|
||||
@@ -106,8 +162,10 @@ def build_pattern_data(
|
||||
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())
|
||||
if not report.stack:
|
||||
location = _error_location(report.extra)
|
||||
if location:
|
||||
sample_parts.append(f"At: {location} (no stack from browser)")
|
||||
clean_url = sanitize_url(report.url)
|
||||
if clean_url:
|
||||
sample_parts.append(f"URL: {clean_url}")
|
||||
@@ -115,6 +173,15 @@ def build_pattern_data(
|
||||
sample_parts.append(f"UA: {report.user_agent[:200]}")
|
||||
if report.release:
|
||||
sample_parts.append(f"Build: {report.release}")
|
||||
for line in (_format_diagnostics(report.extra), _format_breadcrumbs(report.extra)):
|
||||
if line:
|
||||
sample_parts.append(line)
|
||||
if report.stack and report.stack.strip() != (report.message or "").strip():
|
||||
stack_lines = report.stack.strip().splitlines()
|
||||
trimmed = "\n".join(stack_lines[:MAX_SAMPLE_STACK_LINES])
|
||||
if len(stack_lines) > MAX_SAMPLE_STACK_LINES:
|
||||
trimmed += f"\n … {len(stack_lines) - MAX_SAMPLE_STACK_LINES} more frames"
|
||||
sample_parts.append("Stack:\n" + trimmed)
|
||||
sample_message = "\n".join(sample_parts)[:MAX_SAMPLE_MESSAGE_CHARS]
|
||||
|
||||
return PatternData(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""LLM-powered incident analysis and duplicate detection for the error monitor.
|
||||
|
||||
Uses Gemini Flash via the google-generativeai library to:
|
||||
Uses Gemini Flash via the Gemini Developer API (backend.services.gemini_client) to:
|
||||
1. Group related error patterns into incidents with root-cause analysis.
|
||||
2. Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
@@ -17,13 +17,11 @@ 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.gemini_client import get_genai_client, note_gemini_failure
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LLM_ANALYSIS_MODEL,
|
||||
LLM_VERTEX_LOCATION,
|
||||
MIN_PATTERNS_FOR_ANALYSIS,
|
||||
SERVICE_DEPENDENCY_MAP,
|
||||
)
|
||||
@@ -96,11 +94,7 @@ def _call_llm(
|
||||
|
||||
for attempt in range(_RETRY_ATTEMPTS):
|
||||
try:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=GCP_PROJECT,
|
||||
location=LLM_VERTEX_LOCATION,
|
||||
)
|
||||
client = get_genai_client(timeout_ms=120_000)
|
||||
response = client.models.generate_content(
|
||||
model=LLM_ANALYSIS_MODEL,
|
||||
contents=user_prompt,
|
||||
@@ -111,6 +105,10 @@ def _call_llm(
|
||||
)
|
||||
return response.text
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if note_gemini_failure("error_monitor", exc):
|
||||
# Quota/credit/key problem: don't retry — callers fall back to
|
||||
# alerts without the AI summary.
|
||||
raise
|
||||
last_exc = exc
|
||||
delay = _RETRY_BASE_DELAY * (2**attempt)
|
||||
logger.warning(
|
||||
|
||||
@@ -23,6 +23,7 @@ from google.cloud import secretmanager
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LEGACY_ROLLING_WINDOW_MINUTES,
|
||||
LOOKBACK_MINUTES,
|
||||
MAX_LOG_ENTRIES,
|
||||
MONITORED_CLOUD_FUNCTIONS,
|
||||
@@ -214,15 +215,22 @@ def _group_by_pattern(entries: list[dict]) -> dict[str, dict]:
|
||||
def _rolling_average(rolling_counts: list[dict]) -> float:
|
||||
"""Compute the mean count from a list of rolling_count dicts.
|
||||
|
||||
Each entry's count is scaled to the current ``LOOKBACK_MINUTES`` window
|
||||
(entries without ``window_minutes`` predate it and were 15-minute counts),
|
||||
so a change of monitor cadence doesn't read as a spike.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"count": int, ...}`` dicts.
|
||||
rolling_counts: List of ``{"count": int, "window_minutes"?: int, ...}`` dicts.
|
||||
|
||||
Returns:
|
||||
The arithmetic mean as a float, or ``0.0`` for an empty list.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return 0.0
|
||||
total = sum(entry.get("count", 0) for entry in rolling_counts)
|
||||
total = 0.0
|
||||
for entry in rolling_counts:
|
||||
window = entry.get("window_minutes") or LEGACY_ROLLING_WINDOW_MINUTES
|
||||
total += entry.get("count", 0) * LOOKBACK_MINUTES / window
|
||||
return total / len(rolling_counts)
|
||||
|
||||
|
||||
@@ -258,7 +266,7 @@ def _is_spike(current_count: int, rolling_counts: list[dict]) -> bool:
|
||||
class ErrorMonitor:
|
||||
"""Orchestrates the full production error monitoring pipeline.
|
||||
|
||||
On each run (typically every 15 minutes via Cloud Scheduler), it:
|
||||
On each run (hourly via Cloud Scheduler), it:
|
||||
|
||||
1. Queries Cloud Logging for recent errors across all monitored services.
|
||||
2. Groups errors into patterns using normalisation + hashing.
|
||||
|
||||
@@ -253,8 +253,11 @@ class FirestoreService:
|
||||
|
||||
# Fields needed by the dashboard summary view
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'job_id', 'status', 'progress', 'created_at', 'updated_at', 'artist', 'title',
|
||||
'error_message', 'error_details.code', 'error_details.stage',
|
||||
'error_details.stall_minutes', 'error_details.keep_trying', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'renders_purged_at', 'stems_purged_at', 'finalise_only', 'prep_only',
|
||||
'state_data.regenerate', 'state_data.stems_restore', 'state_data.instrumental_selection',
|
||||
'made_for_you', 'customer_email', 'locale',
|
||||
'url', 'filename', 'existing_instrumental_gcs_path',
|
||||
'audio_search_artist', 'audio_search_title',
|
||||
@@ -271,6 +274,7 @@ class FirestoreService:
|
||||
'state_data.duration_confirm_reason',
|
||||
'state_data.batch_id',
|
||||
'state_data.bulk_auto_selected',
|
||||
'state_data.awaiting_upload',
|
||||
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
|
||||
'processing_metadata',
|
||||
]
|
||||
|
||||
@@ -44,6 +44,21 @@ class FlacfetchServiceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FlacfetchDownloadStalledError(FlacfetchServiceError):
|
||||
"""A torrent made no progress for the whole stall ceiling (typically its only
|
||||
seeder is offline). Recoverable by waiting longer or picking other audio, so
|
||||
callers surface it to the user instead of auto-retrying the same torrent."""
|
||||
pass
|
||||
|
||||
|
||||
def _is_stall_failure(status: Dict[str, Any]) -> bool:
|
||||
"""flacfetch >= 0.31 reports error_code='torrent_stalled'; older versions only
|
||||
the message ("Torrent download stalled for 600s ...")."""
|
||||
if status.get("error_code") == "torrent_stalled":
|
||||
return True
|
||||
return "download stalled for" in str(status.get("error") or "").lower()
|
||||
|
||||
|
||||
def _format_httpx_error(e: Exception) -> str:
|
||||
"""
|
||||
Format an httpx exception into a descriptive error string.
|
||||
@@ -92,17 +107,21 @@ def should_retry_flacfetch_error(exception: Exception) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
async def with_retry(func, *args, **kwargs):
|
||||
async def with_retry(func, *args, retry_max_attempts=None, retry_min_wait=None, retry_max_wait=None, **kwargs):
|
||||
"""
|
||||
Execute an async function with retry logic using exponential backoff.
|
||||
|
||||
This implementation uses manual retry logic instead of tenacity decorators
|
||||
for better testability and runtime configuration.
|
||||
|
||||
The retry_* keyword-only arguments override the FLACFETCH_RETRY_* settings
|
||||
for callers that need a different retry profile (e.g. search, which sits on
|
||||
a latency-sensitive user-facing path).
|
||||
"""
|
||||
settings = get_settings()
|
||||
max_attempts = settings.flacfetch_retry_max_attempts
|
||||
min_wait = settings.flacfetch_retry_min_wait
|
||||
max_wait = settings.flacfetch_retry_max_wait
|
||||
max_attempts = retry_max_attempts if retry_max_attempts is not None else settings.flacfetch_retry_max_attempts
|
||||
min_wait = retry_min_wait if retry_min_wait is not None else settings.flacfetch_retry_min_wait
|
||||
max_wait = retry_max_wait if retry_max_wait is not None else settings.flacfetch_retry_max_wait
|
||||
|
||||
last_exception = None
|
||||
|
||||
@@ -218,43 +237,72 @@ class FlacfetchClient:
|
||||
|
||||
Returns:
|
||||
Search response dict with search_id and results list
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On search failure
|
||||
FlacfetchServiceError: On search failure (after all retries exhausted)
|
||||
|
||||
Search is idempotent, so transient network errors (e.g. a ReadTimeout
|
||||
while the flacfetch server is busy with an uncached provider sweep) are
|
||||
retried once with a short wait. The retry usually hits the server-side
|
||||
search cache warmed by the first attempt and returns in seconds.
|
||||
|
||||
All attempts share a total time budget kept below Cloudflare's ~100s
|
||||
edge deadline, so a slow retry surfaces as FlacfetchServiceError rather
|
||||
than an opaque edge 524.
|
||||
"""
|
||||
settings = get_settings()
|
||||
total_timeout = settings.flacfetch_search_total_timeout
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "title": title},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
|
||||
if resp.status_code == 404:
|
||||
# No results found - return empty results
|
||||
return {
|
||||
"search_id": None,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"results": [],
|
||||
"results_count": 0,
|
||||
}
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
return await asyncio.wait_for(
|
||||
with_retry(
|
||||
self._search_impl,
|
||||
artist,
|
||||
title,
|
||||
retry_max_attempts=settings.flacfetch_search_retry_max_attempts,
|
||||
retry_min_wait=settings.flacfetch_search_retry_wait,
|
||||
retry_max_wait=settings.flacfetch_search_retry_wait,
|
||||
),
|
||||
timeout=total_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
raise FlacfetchServiceError(
|
||||
f"Search timed out after {total_timeout:.0f}s total (including retries)"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _search_impl(self, artist: str, title: str) -> Dict[str, Any]:
|
||||
"""Implementation of search without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "title": title},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
|
||||
if resp.status_code == 404:
|
||||
# No results found - return empty results
|
||||
return {
|
||||
"search_id": None,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"results": [],
|
||||
"results_count": 0,
|
||||
}
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def download(
|
||||
self,
|
||||
search_id: str,
|
||||
result_index: int,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading an audio file.
|
||||
@@ -267,6 +315,8 @@ class FlacfetchClient:
|
||||
result_index: Index of result to download
|
||||
output_filename: Optional custom filename (without extension)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
max_stall_seconds: Torrents only — abort after this long with no progress
|
||||
(overrides flacfetch's default ceiling)
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
@@ -275,7 +325,9 @@ class FlacfetchClient:
|
||||
FlacfetchServiceError: On download start failure (after all retries exhausted)
|
||||
"""
|
||||
try:
|
||||
return await with_retry(self._download_impl, search_id, result_index, output_filename, gcs_path)
|
||||
return await with_retry(
|
||||
self._download_impl, search_id, result_index, output_filename, gcs_path, max_stall_seconds
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
@@ -287,6 +339,7 @@ class FlacfetchClient:
|
||||
result_index: int,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Implementation of download without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -299,6 +352,8 @@ class FlacfetchClient:
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
if max_stall_seconds:
|
||||
payload["max_stall_seconds"] = max_stall_seconds
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download",
|
||||
@@ -319,6 +374,7 @@ class FlacfetchClient:
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading directly by source ID (no prior search required).
|
||||
@@ -336,6 +392,8 @@ class FlacfetchClient:
|
||||
target_file: For torrents, specific file to extract
|
||||
download_url: For YouTube/Spotify, direct URL (optional)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
max_stall_seconds: Torrents only — abort after this long with no progress
|
||||
(overrides flacfetch's default ceiling)
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
@@ -346,7 +404,8 @@ class FlacfetchClient:
|
||||
try:
|
||||
return await with_retry(
|
||||
self._download_by_id_impl,
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path
|
||||
source_name, source_id, output_filename, target_file, download_url, gcs_path,
|
||||
max_stall_seconds,
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {_format_httpx_error(e)}")
|
||||
@@ -361,6 +420,7 @@ class FlacfetchClient:
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
max_stall_seconds: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Implementation of download_by_id without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
@@ -377,6 +437,8 @@ class FlacfetchClient:
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
if max_stall_seconds:
|
||||
payload["max_stall_seconds"] = max_stall_seconds
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
@@ -486,6 +548,8 @@ class FlacfetchClient:
|
||||
return status
|
||||
elif download_status == "failed":
|
||||
error = status.get("error", "Unknown error")
|
||||
if _is_stall_failure(status):
|
||||
raise FlacfetchDownloadStalledError(f"Download failed: {error}")
|
||||
raise FlacfetchServiceError(f"Download failed: {error}")
|
||||
elif download_status == "cancelled":
|
||||
raise FlacfetchServiceError("Download was cancelled")
|
||||
|
||||
@@ -15,11 +15,21 @@ from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Force google-auth to reach the metadata server over plain HTTP. google-auth
|
||||
# >=2.40 switches to mTLS over HTTPS when /run/google-mds-mtls/ certs exist, and
|
||||
# that handshake fails with CERTIFICATE_VERIFY_FAILED on our images. startup.sh
|
||||
# sets this in the systemd env file, but the Packer-baked startup-fallback.sh
|
||||
# (used when GCS is unreachable at boot) does not, which broke every job on
|
||||
# 2026-10-06. Defaulting it here covers every boot path. Must run before any
|
||||
# google library is imported.
|
||||
os.environ.setdefault("GCE_METADATA_MTLS_MODE", "none")
|
||||
|
||||
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
|
||||
from google.cloud import storage
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
|
||||
from . import self_heal
|
||||
from .persistence import JobStatePersister
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
|
||||
@@ -88,8 +98,28 @@ def _persist(job_id: str) -> None:
|
||||
persister.save(state)
|
||||
|
||||
|
||||
def _has_active_jobs() -> bool:
|
||||
return any(j.get("status") in ("running", "pending") for j in jobs.values())
|
||||
|
||||
|
||||
def _self_heal_after_failure(error: Exception) -> None:
|
||||
"""Restart the worker if a job failed because the VM itself can't reach GCP."""
|
||||
try:
|
||||
self_heal.schedule_restart_if_unhealthy(str(error), _has_active_jobs)
|
||||
except Exception as exc: # noqa: BLE001 — must never mask the job failure
|
||||
logger.warning("Self-heal scheduling failed: %r", exc)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Refuse to serve if this boot came up broken (no API key / no GCP
|
||||
# credentials, e.g. bootstrap fell back because the network wasn't up yet).
|
||||
# Failing startup makes uvicorn exit; systemd then re-runs the bootstrap.
|
||||
problem = await asyncio.to_thread(self_heal.boot_health_problem)
|
||||
if problem:
|
||||
logger.critical("Encoding worker booted unhealthy, exiting for systemd restart: %s", problem)
|
||||
raise RuntimeError(f"Encoding worker booted unhealthy: {problem}")
|
||||
|
||||
# Startup: read back any in-progress jobs from Firestore. They were
|
||||
# interrupted by the restart that brought us here — their work_dir is
|
||||
# gone, so mark them failed with the restart code so polls return a
|
||||
@@ -155,6 +185,8 @@ class RenderVideoRequest(BaseModel):
|
||||
# Multi-singer / duet rendering. When True, OutputConfig is_duet is set
|
||||
# so the SubtitlesGenerator and CDGGenerator emit per-singer styles.
|
||||
is_duet: bool = False
|
||||
# Translated lyrics (lyrics/translations.json) drawn beneath each line.
|
||||
translations_gcs_path: Optional[str] = None
|
||||
|
||||
|
||||
class JobStatus(BaseModel):
|
||||
@@ -452,6 +484,17 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
# 2b. Translated lyrics (shown beneath each line)
|
||||
if request.translations_gcs_path:
|
||||
from karaoke_gen.lyrics_transcriber.output.translations import load_and_apply_translations
|
||||
|
||||
translations_path = work_dir / "translations.json"
|
||||
try:
|
||||
download_single_file_from_gcs(request.translations_gcs_path, translations_path)
|
||||
load_and_apply_translations(correction_result.corrected_segments, str(translations_path))
|
||||
except Exception as e: # translations are best-effort: never fail the render
|
||||
logger.error(f"[job:{job_id}] Translated lyrics unavailable, rendering without: {e}")
|
||||
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
@@ -812,6 +855,61 @@ def find_file(work_dir: Path, *patterns):
|
||||
return None
|
||||
|
||||
|
||||
def resolve_instrumental(work_dir: Path, config: dict):
|
||||
"""Pick the instrumental track in work_dir for this encode (user-supplied >
|
||||
custom > with_backing > clean). Returns a Path or None."""
|
||||
# Instrumental audio - respect user's selection from encoding config
|
||||
instrumental_selection = config.get("instrumental_selection", "clean")
|
||||
existing_instrumental = config.get("existing_instrumental")
|
||||
logger.info(f"Instrumental selection from config: {instrumental_selection}")
|
||||
if existing_instrumental:
|
||||
logger.info(f"Existing instrumental from config: {existing_instrumental}")
|
||||
|
||||
if existing_instrumental:
|
||||
# User-provided instrumental uploaded at job creation
|
||||
# Downloaded to work_dir by process_job before run_encoding is called.
|
||||
# Prefer that top-level copy (it's exactly config["existing_instrumental"]):
|
||||
# the job folder also holds persisted inputs (input/audio/existing_instrumental.*
|
||||
# = the raw upload, input/conformed/... = its aligned copy), which the
|
||||
# recursive glob below could return instead.
|
||||
top_level = sorted(work_dir.glob("existing_instrumental.*"))
|
||||
instrumental = top_level[0] if top_level else find_file(
|
||||
work_dir,
|
||||
"*existing_instrumental*", "*Instrumental User*",
|
||||
)
|
||||
elif instrumental_selection == "custom":
|
||||
# Custom instrumental created via mute-region editing in review UI
|
||||
# FLAC first (mute-region edits + review uploads are converted to FLAC),
|
||||
# then any extension: staged user instrumentals keep their original
|
||||
# extension (.wav, .m4a, ...) and used to fall through to
|
||||
# "No instrumental audio found".
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*custom_instrumental*.flac", "*Instrumental Custom*.flac",
|
||||
"*custom_instrumental*.mp3", "*custom_instrumental*.wav",
|
||||
"*custom_instrumental*.m4a", "*custom_instrumental*.ogg",
|
||||
"*custom_instrumental*.aac", "*Instrumental Custom*",
|
||||
)
|
||||
elif instrumental_selection == "with_backing":
|
||||
# User selected instrumental with backing vocals. NO generic fallback:
|
||||
# "*instrumental*.flac" used to match instrumental_clean.flac (or a kept
|
||||
# custom_instrumental.flac) whenever the with-backing stem was missing,
|
||||
# silently shipping the wrong instrumental. Missing => fail loudly.
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*instrumental_with_backing*.flac", "*Instrumental Backing*.flac",
|
||||
)
|
||||
else:
|
||||
# Default to clean instrumental — never fall back to a with-backing or
|
||||
# custom/user instrumental (same silent-wrong-instrumental risk).
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*instrumental_clean*.flac", "*Instrumental Clean*.flac",
|
||||
)
|
||||
|
||||
return instrumental
|
||||
|
||||
|
||||
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
|
||||
"""Generate a MOV video from a static PNG image using FFmpeg.
|
||||
|
||||
@@ -914,6 +1012,13 @@ def render_portrait_into_outputs(
|
||||
with open(corrections_file, "r", encoding="utf-8") as f:
|
||||
correction_result = CorrectionResult.from_dict(json.load(f))
|
||||
|
||||
# Translated lyrics, if the job has them (downloaded with the job's lyrics/)
|
||||
translations_file = work_dir / "lyrics" / "translations.json"
|
||||
if translations_file.is_file():
|
||||
from karaoke_gen.lyrics_transcriber.output.translations import load_and_apply_translations
|
||||
|
||||
load_and_apply_translations(correction_result.corrected_segments, str(translations_file))
|
||||
|
||||
# Theme styles (optional — renderer fills defaults).
|
||||
styles = {}
|
||||
style_params = work_dir / "style" / "style_params.json"
|
||||
@@ -986,15 +1091,20 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
# Title/end screens: look for MOV first, fall back to generating from PNG.
|
||||
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
|
||||
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
|
||||
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
|
||||
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
|
||||
# A theme may leave a screen out. Don't look for it at all then: the loose globs
|
||||
# below also match theme assets (style/cdg_title_background.png,
|
||||
# style/end_background.png) and old finals, which would bring it back.
|
||||
include_title = config.get("include_title_screen", True) is not False
|
||||
include_end = config.get("include_end_screen", True) is not False
|
||||
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov") if include_title else None
|
||||
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov") if include_end else None
|
||||
|
||||
# Get intro/end video durations from style config (default 5s)
|
||||
intro_duration = config.get("intro_video_duration", 5)
|
||||
end_duration = config.get("end_video_duration", 5)
|
||||
|
||||
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
|
||||
if not title_video or title_video.stat().st_size < 1024:
|
||||
if include_title and (not title_video or title_video.stat().st_size < 1024):
|
||||
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
|
||||
if title_png:
|
||||
title_mov_path = title_png.parent / "title.mov"
|
||||
@@ -1004,7 +1114,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
|
||||
|
||||
# Generate end MOV from PNG if missing or invalid
|
||||
if not end_video or (end_video and end_video.stat().st_size < 1024):
|
||||
if include_end and (not end_video or end_video.stat().st_size < 1024):
|
||||
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
|
||||
if end_png:
|
||||
end_mov_path = end_png.parent / "end.mov"
|
||||
@@ -1044,44 +1154,8 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
"videos/*vocals*.mkv", "videos/*vocals*.mov"
|
||||
)
|
||||
|
||||
# Instrumental audio - respect user's selection from encoding config
|
||||
instrumental_selection = config.get("instrumental_selection", "clean")
|
||||
existing_instrumental = config.get("existing_instrumental")
|
||||
logger.info(f"Instrumental selection from config: {instrumental_selection}")
|
||||
if existing_instrumental:
|
||||
logger.info(f"Existing instrumental from config: {existing_instrumental}")
|
||||
|
||||
if existing_instrumental:
|
||||
# User-provided instrumental uploaded at job creation
|
||||
# Downloaded to work_dir by process_job before run_encoding is called
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*existing_instrumental*", "*Instrumental User*",
|
||||
)
|
||||
elif instrumental_selection == "custom":
|
||||
# Custom instrumental created via mute-region editing in review UI
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*custom_instrumental*.flac", "*Instrumental Custom*.flac",
|
||||
"*custom_instrumental*.mp3",
|
||||
)
|
||||
elif instrumental_selection == "with_backing":
|
||||
# User selected instrumental with backing vocals
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*instrumental_with_backing*.flac", "*Instrumental Backing*.flac",
|
||||
"*with_backing*.flac", "*Backing*.flac",
|
||||
"*instrumental*.flac", "*Instrumental*.flac",
|
||||
"*instrumental*.wav"
|
||||
)
|
||||
else:
|
||||
# Default to clean instrumental
|
||||
instrumental = find_file(
|
||||
work_dir,
|
||||
"*instrumental_clean*.flac", "*Instrumental Clean*.flac",
|
||||
"*instrumental*.flac", "*Instrumental*.flac",
|
||||
"*instrumental*.wav"
|
||||
)
|
||||
instrumental = resolve_instrumental(work_dir, config)
|
||||
|
||||
logger.info(f"Found files:")
|
||||
logger.info(f" Title video: {title_video}")
|
||||
@@ -1095,8 +1169,10 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
logger.info(f" Countdown padding: {countdown_padding_seconds}s - will be handled by LocalEncodingService")
|
||||
|
||||
# Validate required files
|
||||
if not title_video:
|
||||
if include_title and not title_video:
|
||||
raise ValueError(f"No title video found in {work_dir}. Check screens/ subdirectory.")
|
||||
if not include_title or not include_end:
|
||||
logger.info(f" Theme omits screens: title={'kept' if include_title else 'omitted'}, end={'kept' if include_end else 'omitted'}")
|
||||
if not karaoke_video:
|
||||
raise ValueError(f"No karaoke video found in {work_dir}")
|
||||
if not instrumental:
|
||||
@@ -1110,7 +1186,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
|
||||
# Build encoding config with proper file names
|
||||
# Note: countdown_padding_seconds is passed to LocalEncodingService which handles padding
|
||||
encoding_config = EncodingConfig(
|
||||
title_video=str(title_video),
|
||||
title_video=str(title_video) if title_video else None,
|
||||
karaoke_video=str(karaoke_video),
|
||||
instrumental_audio=str(instrumental),
|
||||
end_video=str(end_video) if end_video else None,
|
||||
@@ -1263,6 +1339,7 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
_self_heal_after_failure(e)
|
||||
|
||||
|
||||
async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
@@ -1293,6 +1370,7 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
_self_heal_after_failure(e)
|
||||
|
||||
|
||||
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
@@ -1335,6 +1413,7 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
jobs[job_id]["status"] = "failed"
|
||||
jobs[job_id]["error"] = str(e)
|
||||
_persist(job_id)
|
||||
_self_heal_after_failure(e)
|
||||
|
||||
|
||||
@app.post("/encode-preview")
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Self-healing for an encoding worker that booted into a broken state.
|
||||
|
||||
Incident 2026-10-06 (job ebfe4344): the primary VM booted before its network was
|
||||
up, so ``bootstrap.sh`` could not download the CI-managed ``startup.sh`` from GCS
|
||||
and fell back to the Packer-baked ``startup-fallback.sh``. That fallback wrote an
|
||||
env file with no ``ENCODING_API_KEY`` and no ``GCE_METADATA_MTLS_MODE=none``, so
|
||||
google-auth talked mTLS to the metadata server and every job failed with
|
||||
``CERTIFICATE_VERIFY_FAILED``. The worker still answered /health, and the backend
|
||||
deliberately keeps retrying the primary on infra errors, so customer renders
|
||||
looped for an hour until someone ran ``systemctl restart encoding-worker``.
|
||||
|
||||
This module performs that restart automatically. Exiting the process makes
|
||||
systemd (``Restart=always``) re-run ``ExecStartPre=bootstrap.sh``, which, now that
|
||||
the network is up, downloads the real ``startup.sh`` and rewrites the env file.
|
||||
|
||||
Only active on an encoding-worker VM running under systemd (``INVOCATION_ID`` is
|
||||
set by systemd for every service process, and the Packer image installs
|
||||
``/opt/encoding-worker/bootstrap.sh``), so local runs, CI and tests never exit.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable, Optional
|
||||
|
||||
from backend.services.encoding_errors import is_worker_infra_error
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Credential probe: a few attempts so a single metadata-server blip doesn't
|
||||
# restart a healthy worker.
|
||||
PROBE_ATTEMPTS = 3
|
||||
PROBE_RETRY_SECONDS = 5.0
|
||||
|
||||
# After an infra-failed job, wait before checking/restarting so the backend's
|
||||
# status poll (every ~10s) sees the "failed" status first and parks the job for
|
||||
# retry rather than hitting a vanished worker.
|
||||
RESTART_DELAY_SECONDS = 30.0
|
||||
|
||||
_restart_lock = threading.Lock()
|
||||
_restart_pending = False
|
||||
|
||||
|
||||
BOOTSTRAP_PATH = "/opt/encoding-worker/bootstrap.sh"
|
||||
|
||||
|
||||
def running_on_worker_vm() -> bool:
|
||||
"""True only for the encoding-worker systemd service on a worker VM."""
|
||||
return bool(os.environ.get("INVOCATION_ID")) and os.path.exists(BOOTSTRAP_PATH)
|
||||
|
||||
|
||||
def _refresh_default_credentials() -> None:
|
||||
import google.auth
|
||||
import google.auth.transport.requests
|
||||
|
||||
credentials, _ = google.auth.default(
|
||||
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
||||
)
|
||||
credentials.refresh(google.auth.transport.requests.Request())
|
||||
|
||||
|
||||
def probe_credentials(
|
||||
attempts: int = PROBE_ATTEMPTS,
|
||||
retry_seconds: float = PROBE_RETRY_SECONDS,
|
||||
refresh: Callable[[], None] = _refresh_default_credentials,
|
||||
) -> Optional[str]:
|
||||
"""Try to fetch a service-account token. Returns None if healthy, else the last error."""
|
||||
last_error = ""
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
refresh()
|
||||
return None
|
||||
except Exception as e: # noqa: BLE001 — any failure means "can't authenticate"
|
||||
last_error = str(e) or repr(e)
|
||||
logger.warning(
|
||||
"Credential probe failed (attempt %d/%d): %s", attempt, attempts, last_error
|
||||
)
|
||||
if attempt < attempts:
|
||||
time.sleep(retry_seconds)
|
||||
return last_error
|
||||
|
||||
|
||||
def boot_health_problem(probe: Callable[[], Optional[str]] = probe_credentials) -> Optional[str]:
|
||||
"""Describe why this worker booted broken, or None if it is fine to serve.
|
||||
|
||||
Returns None outside systemd so local/dev runs are unaffected.
|
||||
"""
|
||||
if not running_on_worker_vm():
|
||||
return None
|
||||
problems = []
|
||||
if not os.environ.get("ENCODING_API_KEY"):
|
||||
problems.append("ENCODING_API_KEY is not set (startup fell back without the real env)")
|
||||
probe_error = probe()
|
||||
if probe_error:
|
||||
problems.append(f"cannot obtain GCP credentials: {probe_error}")
|
||||
return "; ".join(problems) or None
|
||||
|
||||
|
||||
def schedule_restart_if_unhealthy(
|
||||
error_text: str,
|
||||
has_active_jobs: Callable[[], bool],
|
||||
*,
|
||||
delay_seconds: float = RESTART_DELAY_SECONDS,
|
||||
probe: Callable[[], Optional[str]] = probe_credentials,
|
||||
exit_process: Callable[[int], None] = os._exit,
|
||||
) -> bool:
|
||||
"""After a job failed with a VM infra/auth error, restart the worker if it is still broken.
|
||||
|
||||
Runs in a daemon thread: waits ``delay_seconds``, re-probes credentials, and if
|
||||
they still fail, waits for in-flight jobs to drain and exits so systemd
|
||||
re-bootstraps the service. Returns True if a check was scheduled.
|
||||
"""
|
||||
global _restart_pending
|
||||
if not running_on_worker_vm() or not is_worker_infra_error(error_text):
|
||||
return False
|
||||
with _restart_lock:
|
||||
if _restart_pending:
|
||||
return False
|
||||
_restart_pending = True
|
||||
|
||||
def _run() -> None:
|
||||
global _restart_pending
|
||||
try:
|
||||
while True:
|
||||
time.sleep(delay_seconds)
|
||||
probe_error = probe()
|
||||
if not probe_error:
|
||||
logger.info("Credentials healthy again after infra failure; not restarting")
|
||||
return
|
||||
if has_active_jobs():
|
||||
logger.warning(
|
||||
"Credentials still failing but jobs are in flight; "
|
||||
"re-checking before restarting: %s", probe_error,
|
||||
)
|
||||
continue
|
||||
logger.critical(
|
||||
"Encoding worker cannot authenticate to GCP (%s); exiting so systemd "
|
||||
"re-runs the bootstrap", probe_error,
|
||||
)
|
||||
exit_process(1)
|
||||
return
|
||||
finally:
|
||||
with _restart_lock:
|
||||
_restart_pending = False
|
||||
|
||||
threading.Thread(target=_run, name="encoding-worker-self-heal", daemon=True).start()
|
||||
return True
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Shared Gemini client for the backend: Gemini Developer API (API key), not Vertex.
|
||||
|
||||
Every backend Gemini call goes through :func:`get_genai_client`. Vertex AI is
|
||||
disabled in the nomadkaraoke GCP project so AI spend never lands on it; calls are
|
||||
billed to whichever AI Studio key is stored in Secret Manager ``gemini-api-key``.
|
||||
|
||||
Key resolution (via :meth:`backend.config.Settings.get_secret`):
|
||||
1. ``GEMINI_API_KEY`` env var — injected on Cloud Run from
|
||||
``gemini-api-key:latest`` (CI ``--set-secrets`` for the service, Pulumi
|
||||
for the jobs).
|
||||
2. Secret Manager ``gemini-api-key`` (latest) — read directly with the
|
||||
runtime service account / your ADC when the env var isn't set.
|
||||
|
||||
Rotating the key: add a new version of ``gemini-api-key``. New instances / job
|
||||
executions pick it up; no code change.
|
||||
|
||||
Degradation: when the key's quota or prepaid credit is exhausted (or the key is
|
||||
rejected), callers must degrade rather than fail jobs. Use
|
||||
:func:`is_quota_or_billing_error` to classify and :func:`note_gemini_failure`
|
||||
from the caller's ``except`` block — it also sends a Discord ops alert at most
|
||||
once per ``GEMINI_QUOTA_ALERT_HOURS`` (default 6h) across all instances.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SECRET_NAME = "gemini-api-key"
|
||||
|
||||
QUOTA_EXHAUSTED_MESSAGE = (
|
||||
"Gemini quota/credit exhausted — top up AI Studio or rotate gemini-api-key "
|
||||
"(add a new version of Secret Manager secret 'gemini-api-key' in project nomadkaraoke)."
|
||||
)
|
||||
|
||||
# Firestore dedup doc id (in ops_alerts' collection) shared by every instance/job.
|
||||
_ALERT_KEY = "gemini-quota-exhausted"
|
||||
_DEFAULT_ALERT_HOURS = 6.0
|
||||
|
||||
|
||||
class GeminiKeyUnavailableError(RuntimeError):
|
||||
"""No Gemini API key could be resolved (env var unset and Secret Manager failed)."""
|
||||
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Return the Gemini Developer API key or raise GeminiKeyUnavailableError."""
|
||||
env_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
||||
if env_key:
|
||||
return env_key
|
||||
from backend.config import get_settings
|
||||
|
||||
key = (get_settings().get_secret(SECRET_NAME) or "").strip()
|
||||
if not key:
|
||||
raise GeminiKeyUnavailableError(
|
||||
"GEMINI_API_KEY is not set and Secret Manager secret 'gemini-api-key' "
|
||||
"could not be read"
|
||||
)
|
||||
return key
|
||||
|
||||
|
||||
def get_genai_client(timeout_ms: Optional[int] = None) -> Any:
|
||||
"""Build a google-genai client for the Gemini Developer API.
|
||||
|
||||
``timeout_ms`` bounds each HTTP request (milliseconds). No project/location:
|
||||
those only apply to Vertex AI.
|
||||
"""
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
http_options = types.HttpOptions(timeout=int(timeout_ms)) if timeout_ms else None
|
||||
# vertexai=False pins the Developer API even if GOOGLE_GENAI_USE_VERTEXAI is set.
|
||||
return genai.Client(vertexai=False, api_key=get_api_key(), http_options=http_options)
|
||||
|
||||
|
||||
# Message fragments that mean "the key/account can't pay or isn't valid" — a
|
||||
# retry won't help; a human must top up credit or rotate the key.
|
||||
_QUOTA_PATTERNS = re.compile(
|
||||
r"RESOURCE_EXHAUSTED|exceeded your current quota|quota exceeded|"
|
||||
r"billing (details|account)|prepa(id|yment)|credits? (are |is |have been )?"
|
||||
r"(exhausted|depleted|used up)|insufficient (credit|funds|balance)|"
|
||||
r"API_KEY_INVALID|API key not valid|API key expired|API_KEY_SERVICE_BLOCKED|"
|
||||
r"\b429 Too Many Requests",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# A 429 that names a per-minute quota / carries a retry delay is an ordinary
|
||||
# rate limit (transient — retry with backoff), not exhausted credit.
|
||||
_RATE_LIMIT_PATTERNS = re.compile(r"PerMinute|retryDelay|retry in \d", re.IGNORECASE)
|
||||
# ...unless it names a per-day quota: that won't clear for hours — treat as exhausted.
|
||||
_DAILY_QUOTA_PATTERN = re.compile(r"PerDay", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_rate_limit(text: str) -> bool:
|
||||
return bool(_RATE_LIMIT_PATTERNS.search(text)) and not _DAILY_QUOTA_PATTERN.search(text)
|
||||
|
||||
|
||||
def is_quota_or_billing_error(exc: Optional[BaseException]) -> bool:
|
||||
"""True if ``exc`` (or anything in its ``__cause__`` chain) is a Gemini quota,
|
||||
prepaid-credit, billing or API-key error — i.e. needs a top-up/key rotation,
|
||||
not a retry.
|
||||
|
||||
Matches google-genai ``APIError`` (``.code`` 429 / 403 or status
|
||||
RESOURCE_EXHAUSTED / PERMISSION_DENIED, or a billing/key message on a 400),
|
||||
a missing key, and wrapped/stringified errors from other layers (LangChain).
|
||||
Per-minute rate limits (429 naming a ``PerMinute`` quota or a retry delay)
|
||||
are NOT matched — those are transient; retry them.
|
||||
"""
|
||||
seen: set[int] = set()
|
||||
while exc is not None and id(exc) not in seen:
|
||||
seen.add(id(exc))
|
||||
if isinstance(exc, GeminiKeyUnavailableError):
|
||||
return True
|
||||
code = getattr(exc, "code", None)
|
||||
if code is None:
|
||||
code = getattr(exc, "status_code", None)
|
||||
status = str(getattr(exc, "status", "") or "")
|
||||
if code == 429 or status == "RESOURCE_EXHAUSTED":
|
||||
return not _is_rate_limit(str(exc))
|
||||
if code == 403 or status == "PERMISSION_DENIED":
|
||||
return True
|
||||
text = str(exc)
|
||||
if _QUOTA_PATTERNS.search(text) and not _is_rate_limit(text):
|
||||
return True
|
||||
# Only explicit chaining (`raise X from e`): implicit __context__ could
|
||||
# attribute an unrelated earlier error (e.g. a Firestore 403) to Gemini.
|
||||
exc = exc.__cause__
|
||||
return False
|
||||
|
||||
|
||||
def _alert_hours() -> float:
|
||||
try:
|
||||
return float(os.environ.get("GEMINI_QUOTA_ALERT_HOURS", _DEFAULT_ALERT_HOURS))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_ALERT_HOURS
|
||||
|
||||
|
||||
# In-process throttle so a burst of failures in one instance doesn't hit
|
||||
# Firestore on every call; the Firestore doc throttles across instances/jobs.
|
||||
_last_alert_attempt: float = 0.0
|
||||
_alert_lock = threading.Lock()
|
||||
# Alert I/O (Firestore + Secret Manager + Discord) runs on a daemon thread so it
|
||||
# never blocks the caller — several callers are on the asyncio event loop.
|
||||
# Tests flip this off to run it inline.
|
||||
_ALERT_IN_BACKGROUND = True
|
||||
|
||||
|
||||
def note_gemini_failure(caller: str, exc: BaseException) -> bool:
|
||||
"""Classify a Gemini failure; on quota/billing/key errors log + alert.
|
||||
|
||||
Call from a caller's ``except`` block. Returns True when the error is a
|
||||
quota/billing/key error (caller should skip retries and degrade). Never raises.
|
||||
"""
|
||||
try:
|
||||
if not is_quota_or_billing_error(exc):
|
||||
return False
|
||||
logger.error("Gemini unavailable (quota/billing/key) in %s: %s", caller, exc)
|
||||
_maybe_alert(caller, exc)
|
||||
return True
|
||||
except Exception: # noqa: BLE001 - classification/alerting must never raise
|
||||
logger.warning("note_gemini_failure failed", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def _maybe_alert(caller: str, exc: BaseException) -> None:
|
||||
global _last_alert_attempt
|
||||
window = _alert_hours() * 3600
|
||||
now = time.monotonic()
|
||||
with _alert_lock:
|
||||
if _last_alert_attempt and now - _last_alert_attempt < window:
|
||||
return
|
||||
_last_alert_attempt = now
|
||||
if _ALERT_IN_BACKGROUND:
|
||||
threading.Thread(
|
||||
target=_send_alert, args=(caller, exc, window), name="gemini-quota-alert", daemon=True
|
||||
).start()
|
||||
else:
|
||||
_send_alert(caller, exc, window)
|
||||
|
||||
|
||||
def _send_alert(caller: str, exc: BaseException, window: float) -> None:
|
||||
global _last_alert_attempt
|
||||
from backend.services import ops_alerts
|
||||
|
||||
err = str(exc).strip()
|
||||
if len(err) > 800:
|
||||
err = err[:800] + " …[truncated]"
|
||||
message = (
|
||||
"🟠 **Gemini API unavailable — quota / prepaid credit / key problem**\n"
|
||||
f"**First seen in:** `{caller}`\n"
|
||||
"Callers are degrading (auto-correct keeps Opus only, match-judge/parse-titles "
|
||||
"return no suggestion, credit evals go to manual review, translations are "
|
||||
"skipped).\n"
|
||||
f"**Fix:** {QUOTA_EXHAUSTED_MESSAGE}\n"
|
||||
f"**Error:** ```{err}```"
|
||||
)
|
||||
try:
|
||||
ops_alerts.send_throttled_ops_alert(_ALERT_KEY, message, throttle_minutes=int(window / 60))
|
||||
except Exception: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("Gemini quota alert failed", exc_info=True)
|
||||
# Let the next failure in this instance try again.
|
||||
with _alert_lock:
|
||||
_last_alert_attempt = 0.0
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
Keep user-uploaded inputs forever: copy ``uploads/{job_id}/**`` into ``jobs/{job_id}/input/``.
|
||||
|
||||
Uploads land under ``uploads/{job_id}/`` (signed-URL / multipart / downloader
|
||||
destinations). That prefix has a bucket lifecycle delete, and user inputs (the
|
||||
mix, a bring-your-own instrumental and its conformed copy, a lyrics file, style
|
||||
uploads) are irreplaceable: re-renders, regenerations after the storage-retention
|
||||
purge and late reviews all need them again. Losing them made tenant re-renders
|
||||
fail (2026-10-08: every randy-vild job left in review for >7 days had lost its
|
||||
mix and instrumental).
|
||||
|
||||
``persist_job_inputs`` server-side copies every object under ``uploads/{job_id}/``
|
||||
to ``jobs/{job_id}/input/<same relative path>`` (``input/`` is KEEP-forever in
|
||||
``storage_retention``) and repoints every job field that referenced the
|
||||
``uploads/`` copy. It is idempotent and cheap when there's nothing new, so each
|
||||
worker calls it on entry: inputs uploaded later in a job's life (conformed
|
||||
instrumentals, style uploads, review-time uploads) are caught by the next worker.
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
UPLOADS_PREFIX = "uploads/"
|
||||
|
||||
|
||||
def uploads_prefix(job_id: str) -> str:
|
||||
return f"{UPLOADS_PREFIX}{job_id}/"
|
||||
|
||||
|
||||
def persisted_path(job_id: str, path: str) -> Optional[str]:
|
||||
"""``uploads/{job_id}/a/b.wav`` -> ``jobs/{job_id}/input/a/b.wav`` (None if not this job's upload)."""
|
||||
prefix = uploads_prefix(job_id)
|
||||
if not isinstance(path, str) or not path.startswith(prefix) or path == prefix:
|
||||
return None
|
||||
return f"jobs/{job_id}/input/{path[len(prefix):]}"
|
||||
|
||||
|
||||
def _rewrites(value: Any, mapping: Dict[str, str], path: str, out: Dict[str, str]) -> None:
|
||||
"""Collect dotted Firestore field paths whose string value is a mapped upload path."""
|
||||
if isinstance(value, str):
|
||||
if value in mapping:
|
||||
out[path] = mapping[value]
|
||||
elif isinstance(value, dict):
|
||||
for key, child in value.items():
|
||||
if isinstance(key, str) and "." not in key and "`" not in key:
|
||||
_rewrites(child, mapping, f"{path}.{key}" if path else key, out)
|
||||
|
||||
|
||||
# Job fields that can hold an input path (top-level, plus everything under these maps).
|
||||
_SCALAR_FIELDS = (
|
||||
"input_media_gcs_path", "existing_instrumental_gcs_path", "lyrics_file_gcs_path", "style_params_gcs_path",
|
||||
)
|
||||
_MAP_FIELDS = ("file_urls", "state_data", "style_assets")
|
||||
|
||||
|
||||
def persist_job_inputs(job, storage, job_manager) -> Tuple[int, Dict[str, str]]:
|
||||
"""Copy this job's uploads into ``jobs/{id}/input/`` and repoint the job.
|
||||
|
||||
Returns ``(objects_copied, field_updates)``. Raises on storage/Firestore errors.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
copied = 0
|
||||
mapping: Dict[str, str] = {}
|
||||
for blob in storage.bucket.list_blobs(prefix=uploads_prefix(job_id)):
|
||||
dest = persisted_path(job_id, blob.name)
|
||||
if not dest:
|
||||
continue
|
||||
mapping[blob.name] = dest
|
||||
existing = storage.bucket.get_blob(dest)
|
||||
if existing is not None and existing.md5_hash == blob.md5_hash and existing.size == blob.size:
|
||||
continue
|
||||
storage.bucket.copy_blob(blob, storage.bucket, dest)
|
||||
copied += 1
|
||||
|
||||
updates: Dict[str, str] = {}
|
||||
for field in _SCALAR_FIELDS:
|
||||
value = getattr(job, field, None)
|
||||
if value in mapping:
|
||||
updates[field] = mapping[value]
|
||||
for field in _MAP_FIELDS:
|
||||
_rewrites(getattr(job, field, None) or {}, mapping, field, updates)
|
||||
|
||||
if updates:
|
||||
job_manager.update_job(job_id, dict(updates))
|
||||
# Keep the in-memory job consistent for the caller.
|
||||
for field in _SCALAR_FIELDS:
|
||||
if field in updates:
|
||||
setattr(job, field, updates[field])
|
||||
if copied or updates:
|
||||
logger.info(f"Job {job_id}: persisted {copied} upload(s) to jobs/{job_id}/input/; repointed {sorted(updates)}")
|
||||
return copied, updates
|
||||
|
||||
|
||||
def ensure_job_inputs_persisted(job, storage, job_manager, worker: str = "") -> None:
|
||||
"""Worker-entry wrapper: never fails the job, but logs an ERROR (alerts) on failure.
|
||||
|
||||
The ``uploads/`` lifecycle gives months to retry, and every later worker retries.
|
||||
"""
|
||||
try:
|
||||
persist_job_inputs(job, storage, job_manager)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(
|
||||
f"Job {getattr(job, 'job_id', '?')}: failed to persist uploaded inputs to jobs/ "
|
||||
f"({worker or 'worker'}): {e}"
|
||||
)
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Line a user-supplied instrumental up with its mix when their lengths differ.
|
||||
|
||||
Artists often export the instrumental with a different edit from the mix: extra
|
||||
count-in, a longer or shorter outro. Lyrics are timed against the mix, so the
|
||||
instrumental must start at the same moment and run the same length. Rather than
|
||||
reject the job, we find the start offset by cross-correlation (the same method
|
||||
as derived_vocals), then trim/pad the start and trim (with a fade) or pad the
|
||||
end so it matches the mix exactly. Files that don't correlate at all are almost
|
||||
certainly the wrong pairing and are still rejected, as are files whose offset
|
||||
changes between early and late in the song (an edit in the middle).
|
||||
|
||||
Runs in the API request (uploads-complete), so it decodes a bounded mono copy
|
||||
for alignment and does the actual edit with one ffmpeg pass on the original.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
from dataclasses import dataclass, asdict
|
||||
|
||||
import numpy as np
|
||||
|
||||
from backend.services.derived_vocals import (
|
||||
SAMPLE_RATE,
|
||||
DerivedVocalsError,
|
||||
_decode_mono,
|
||||
find_offset,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Count-ins / intros can add several seconds; search well past that.
|
||||
MAX_LAG_SECONDS = 15.0
|
||||
ALIGN_WINDOW_SECONDS = 60.0
|
||||
# Pearson correlation of mix vs aligned instrumental. Same-master pairs score
|
||||
# ~0.75-0.85 (the vocals are the only difference); unrelated files score ~0.01.
|
||||
MIN_CORRELATION = 0.3
|
||||
# Fade applied when the instrumental's extra outro is cut at the mix's end.
|
||||
END_FADE_SECONDS = 2.0
|
||||
# Offsets measured early and late in the song must agree this closely; a bigger
|
||||
# difference means an edit in the middle (removed bar, longer bridge), which a
|
||||
# single start/end fix can't correct.
|
||||
MAX_OFFSET_DRIFT_SECONDS = 0.02
|
||||
# Where the two alignment excerpts start, as a fraction of the mix length.
|
||||
ALIGN_POINTS = (0.25, 0.75)
|
||||
# How close the conformed file must land to the mix length.
|
||||
LENGTH_TOLERANCE_SECONDS = 0.05
|
||||
FFMPEG_TIMEOUT_SECONDS = 180
|
||||
|
||||
|
||||
class InstrumentalConformError(RuntimeError):
|
||||
"""Conforming failed. ``mismatch`` is True when the files themselves don't
|
||||
line up (wrong file / mid-song edit) — a reason to reject the upload — and
|
||||
False for processing failures (ffmpeg crash/timeout), which are retryable."""
|
||||
|
||||
def __init__(self, message: str, mismatch: bool = False):
|
||||
super().__init__(message)
|
||||
self.mismatch = mismatch
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConformResult:
|
||||
mix_duration: float
|
||||
original_duration: float
|
||||
# > 0: instrumental had this much extra audio at the start (trimmed).
|
||||
# < 0: instrumental started late by this much (silence added).
|
||||
start_trimmed_seconds: float
|
||||
# > 0: extra outro cut (with a fade). < 0: silence padded at the end.
|
||||
end_trimmed_seconds: float
|
||||
correlation: float
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {k: round(v, 3) + 0.0 for k, v in asdict(self).items()}
|
||||
|
||||
|
||||
def _probe_duration(path: str) -> float:
|
||||
out = subprocess.run(
|
||||
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", path],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60, check=True,
|
||||
).stdout
|
||||
return float(json.loads(out)["format"]["duration"])
|
||||
|
||||
|
||||
def _aligned_correlation(mix: np.ndarray, inst: np.ndarray, lag: int, window: int,
|
||||
start_fraction: float = 0.25) -> float:
|
||||
"""Pearson correlation of a mix excerpt vs the instrumental shifted by lag."""
|
||||
window = max(1, min(window, len(mix)))
|
||||
start = min(int(len(mix) * start_fraction), len(mix) - window)
|
||||
excerpt = mix[start: start + window].astype(np.float64)
|
||||
shifted = np.zeros(window, dtype=np.float64)
|
||||
lo = start - lag
|
||||
src_lo, src_hi = max(0, lo), min(len(inst), lo + window)
|
||||
if src_hi > src_lo:
|
||||
shifted[src_lo - lo: src_hi - lo] = inst[src_lo:src_hi]
|
||||
if not excerpt.std() or not shifted.std():
|
||||
return 0.0
|
||||
return float(np.corrcoef(excerpt, shifted)[0, 1])
|
||||
|
||||
|
||||
def build_filter(lag_seconds: float, original_duration: float, mix_duration: float) -> str:
|
||||
"""ffmpeg -af chain moving the instrumental by lag and fitting it to mix_duration.
|
||||
|
||||
lag follows find_offset: mix[t] ≈ inst[t - lag], so a negative lag means the
|
||||
instrumental has extra audio at the start.
|
||||
"""
|
||||
filters = []
|
||||
if lag_seconds < 0:
|
||||
filters.append(f"atrim=start={-lag_seconds:.6f},asetpts=PTS-STARTPTS")
|
||||
elif lag_seconds > 0:
|
||||
filters.append(f"adelay=delays={lag_seconds * 1000:.3f}:all=1")
|
||||
shifted_duration = original_duration + lag_seconds
|
||||
if shifted_duration > mix_duration + LENGTH_TOLERANCE_SECONDS:
|
||||
fade = min(END_FADE_SECONDS, mix_duration / 10)
|
||||
filters.append(f"afade=t=out:st={mix_duration - fade:.6f}:d={fade:.6f}")
|
||||
else:
|
||||
filters.append(f"apad=whole_dur={mix_duration:.6f}")
|
||||
filters.append(f"atrim=end={mix_duration:.6f}")
|
||||
return ",".join(filters)
|
||||
|
||||
|
||||
def conform_instrumental(mix_path: str, instrumental_path: str, out_path: str) -> ConformResult:
|
||||
"""Write an instrumental aligned to, and exactly as long as, the mix (FLAC).
|
||||
|
||||
Raises InstrumentalConformError when the files don't line up.
|
||||
"""
|
||||
try:
|
||||
mix = _decode_mono(mix_path)
|
||||
inst = _decode_mono(instrumental_path)
|
||||
except DerivedVocalsError as e:
|
||||
# Too long / undecodable input fails the same way every time: reject it
|
||||
# rather than hand back a retryable error.
|
||||
raise InstrumentalConformError(str(e), mismatch=True) from e
|
||||
|
||||
# Measure the offset early and late in the song. One constant shift is all
|
||||
# this can fix, so the two must agree and both must be a genuine match.
|
||||
window = int(ALIGN_WINDOW_SECONDS * SAMPLE_RATE)
|
||||
max_lag = int(MAX_LAG_SECONDS * SAMPLE_RATE)
|
||||
lags, correlations = [], []
|
||||
for fraction in ALIGN_POINTS:
|
||||
point_lag = find_offset(mix, inst, max_lag, window, start_fraction=fraction)
|
||||
lags.append(point_lag)
|
||||
correlations.append(_aligned_correlation(mix, inst, point_lag, window, start_fraction=fraction))
|
||||
correlation = min(correlations)
|
||||
if correlation < MIN_CORRELATION:
|
||||
raise InstrumentalConformError(
|
||||
f"instrumental doesn't match the mix (correlation {correlation:.2f})", mismatch=True
|
||||
)
|
||||
drift = abs(lags[1] - lags[0]) / SAMPLE_RATE
|
||||
if drift > MAX_OFFSET_DRIFT_SECONDS:
|
||||
raise InstrumentalConformError(
|
||||
f"instrumental is edited differently mid-song (offset {lags[0] / SAMPLE_RATE:+.3f}s early "
|
||||
f"vs {lags[1] / SAMPLE_RATE:+.3f}s late)", mismatch=True
|
||||
)
|
||||
lag = lags[0]
|
||||
|
||||
mix_duration = _probe_duration(mix_path)
|
||||
original_duration = _probe_duration(instrumental_path)
|
||||
lag_seconds = lag / SAMPLE_RATE
|
||||
af = build_filter(lag_seconds, original_duration, mix_duration)
|
||||
try:
|
||||
subprocess.run(
|
||||
["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", instrumental_path,
|
||||
"-af", af, "-c:a", "flac", out_path],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
timeout=FFMPEG_TIMEOUT_SECONDS, check=True,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
stderr = (e.stderr or b"").decode(errors="replace").strip()[-500:]
|
||||
raise InstrumentalConformError(f"ffmpeg failed: {stderr}") from e
|
||||
except subprocess.TimeoutExpired as e:
|
||||
raise InstrumentalConformError("ffmpeg timed out conforming instrumental") from e
|
||||
|
||||
result_duration = _probe_duration(out_path)
|
||||
if abs(result_duration - mix_duration) > LENGTH_TOLERANCE_SECONDS:
|
||||
raise InstrumentalConformError(
|
||||
f"conformed instrumental is {result_duration:.2f}s, expected {mix_duration:.2f}s"
|
||||
)
|
||||
|
||||
result = ConformResult(
|
||||
mix_duration=mix_duration,
|
||||
original_duration=original_duration,
|
||||
start_trimmed_seconds=-lag_seconds,
|
||||
end_trimmed_seconds=(original_duration + lag_seconds) - mix_duration,
|
||||
correlation=correlation,
|
||||
)
|
||||
logger.info(f"Conformed instrumental: {result.to_dict()} (filter: {af})")
|
||||
return result
|
||||
+169
-15
@@ -20,11 +20,23 @@ from backend.models.worker_log import WorkerLogEntry
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.utils.keyed_lock import job_lock
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Statuses a job sits in while its prep workers (audio separation + lyrics) run,
|
||||
# i.e. the states from which the lyrics→screens handoff may fire. Normal jobs
|
||||
# prep at DOWNLOADING; jobs that went through the audio editor prep at
|
||||
# AUDIO_EDIT_COMPLETE (the edit-submit endpoint triggers the workers without
|
||||
# passing back through DOWNLOADING).
|
||||
PREP_PHASE_STATUSES = frozenset({
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
})
|
||||
|
||||
|
||||
def _mask_email(email: str) -> str:
|
||||
"""Mask email for logging to protect PII. Shows first char + domain."""
|
||||
if not email or "@" not in email:
|
||||
@@ -43,6 +55,26 @@ class JobManager:
|
||||
self.firestore = FirestoreService()
|
||||
self.storage = StorageService()
|
||||
|
||||
@staticmethod
|
||||
def _is_tenant_billed(tenant_id: Optional[str], user_email: Optional[str]) -> bool:
|
||||
"""True if this job is billed to a tenant (not consumer credits).
|
||||
|
||||
The tenant context can come from the client-controlled X-Tenant-ID
|
||||
header, so a tenant id alone is NOT proof of membership: the user must
|
||||
be allowed on that tenant's portal (its email/domain allowlist; an empty
|
||||
allowlist admits admins only). Otherwise the job is charged normally.
|
||||
"""
|
||||
if not tenant_id or not user_email:
|
||||
return False
|
||||
try:
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
|
||||
config = get_tenant_service().get_tenant_config(tenant_id)
|
||||
except Exception:
|
||||
logger.exception(f"Tenant lookup failed for {tenant_id}; charging consumer credits")
|
||||
return False
|
||||
return bool(config and config.is_active and config.is_email_allowed(user_email))
|
||||
|
||||
def create_job(self, job_create: JobCreate, is_admin: bool = False) -> Job:
|
||||
"""
|
||||
Create a new job with initial state PENDING.
|
||||
@@ -57,9 +89,15 @@ class JobManager:
|
||||
Raises:
|
||||
ValueError: If theme_id is not provided (all jobs require a theme)
|
||||
"""
|
||||
# Check credits (skip for admins)
|
||||
# Check credits (skip for admins, and for tenant-portal jobs: tenants are
|
||||
# billed under a separate commercial agreement, never consumer credits)
|
||||
credits_to_charge = job_create.credits
|
||||
if job_create.user_email and not is_admin:
|
||||
charge_credits = (
|
||||
bool(job_create.user_email)
|
||||
and not is_admin
|
||||
and not self._is_tenant_billed(job_create.tenant_id, job_create.user_email)
|
||||
)
|
||||
if charge_credits:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
credits_available = user_service.check_credits(job_create.user_email)
|
||||
@@ -105,6 +143,8 @@ class JobManager:
|
||||
review_mode=job_create.review_mode,
|
||||
# Backing-vocals preference ("auto"=retain-where-safe | clean | review)
|
||||
backing_preference=job_create.backing_preference,
|
||||
# Translated lyrics beneath each line (None = off)
|
||||
translation_language=job_create.translation_language,
|
||||
# Distribution settings
|
||||
brand_prefix=job_create.brand_prefix,
|
||||
discord_webhook_url=job_create.discord_webhook_url,
|
||||
@@ -138,12 +178,12 @@ class JobManager:
|
||||
"created_from": job_create.request_metadata.get("created_from", "unknown"),
|
||||
},
|
||||
# Record how many credits were charged for this job (authoritative running total).
|
||||
# When charging is bypassed (admin / no user_email), set credits_charged=0 and
|
||||
# payment_bypassed=True so duration reconciliation short-circuits without pausing,
|
||||
# charging, or refunding.
|
||||
# When charging is bypassed (admin / no user_email / tenant portal), set
|
||||
# credits_charged=0 and payment_bypassed=True so duration reconciliation
|
||||
# short-circuits without pausing, charging, or refunding.
|
||||
state_data=(
|
||||
{"credits_charged": 0, "payment_bypassed": True}
|
||||
if (is_admin or not job_create.user_email)
|
||||
if not charge_credits
|
||||
else {"credits_charged": credits_to_charge}
|
||||
),
|
||||
)
|
||||
@@ -152,7 +192,7 @@ class JobManager:
|
||||
logger.info(f"Created new job {job_id} with status PENDING")
|
||||
|
||||
# Deduct credits atomically (after job is persisted so we have job_id for transaction record)
|
||||
if job_create.user_email and not is_admin:
|
||||
if charge_credits:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
success, _remaining, deduct_msg = user_service.deduct_credits(
|
||||
@@ -448,7 +488,18 @@ class JobManager:
|
||||
|
||||
return True
|
||||
|
||||
def transition_to_state(
|
||||
def transition_to_state(self, job_id: str, *args, **kwargs) -> bool:
|
||||
"""Validate + apply a status transition (see _transition_to_state_unlocked).
|
||||
|
||||
Serialized per job within this instance: route handlers run in the
|
||||
threadpool, so two concurrent requests (e.g. a double-clicked Complete)
|
||||
could otherwise both pass validation and both transition/trigger
|
||||
workers. (They used to be serialized by running on the event loop.)
|
||||
"""
|
||||
with job_lock(job_id):
|
||||
return self._transition_to_state_unlocked(job_id, *args, **kwargs)
|
||||
|
||||
def _transition_to_state_unlocked(
|
||||
self,
|
||||
job_id: str,
|
||||
new_status: JobStatus,
|
||||
@@ -457,6 +508,9 @@ class JobManager:
|
||||
state_data_updates: Optional[Dict[str, Any]] = None,
|
||||
raise_on_invalid: bool = True,
|
||||
timeline_metadata: Optional[Dict[str, Any]] = None,
|
||||
notify: bool = True,
|
||||
extra_updates: Optional[Dict[str, Any]] = None,
|
||||
count_completion: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
Transition job to new state with validation.
|
||||
@@ -470,6 +524,14 @@ class JobManager:
|
||||
raise_on_invalid: If True (default), raise InvalidStateTransitionError
|
||||
on invalid transitions. If False, return False silently.
|
||||
timeline_metadata: Optional structured metadata to attach to the timeline event
|
||||
notify: If False, skip the user email/push notifications for this
|
||||
transition (e.g. an admin re-render the admin didn't opt
|
||||
into announcing to the customer).
|
||||
extra_updates: Additional Firestore field updates (dot paths allowed,
|
||||
e.g. ``{"state_data.admin_rerender": DELETE_FIELD}``) written
|
||||
in the SAME update as the status change.
|
||||
count_completion: If False, don't increment the user's completed-jobs
|
||||
counter on COMPLETE (an admin re-render isn't a new job).
|
||||
|
||||
Returns:
|
||||
True if transition succeeded, False if failed (only when raise_on_invalid=False)
|
||||
@@ -477,6 +539,17 @@ class JobManager:
|
||||
Raises:
|
||||
InvalidStateTransitionError: If transition is invalid and raise_on_invalid=True
|
||||
"""
|
||||
if state_data_updates and any(
|
||||
key == "state_data" or key.startswith("state_data.") for key in (extra_updates or {})
|
||||
):
|
||||
# state_data_updates rewrites the whole state_data map; a dot-path
|
||||
# write to state_data.* in the same Firestore update is a
|
||||
# conflicting-path error (and would be ambiguous anyway).
|
||||
raise ValueError(
|
||||
"transition_to_state: pass state_data changes via state_data_updates OR "
|
||||
"extra_updates['state_data.*'], not both"
|
||||
)
|
||||
|
||||
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
|
||||
return False
|
||||
|
||||
@@ -505,6 +578,7 @@ class JobManager:
|
||||
merged_state_data = {**job.state_data, **state_data_updates}
|
||||
|
||||
# Update job status (includes timeline event), passing state_data if present
|
||||
extra = dict(extra_updates or {})
|
||||
if merged_state_data is not None:
|
||||
self.update_job_status(
|
||||
job_id=job_id,
|
||||
@@ -512,7 +586,8 @@ class JobManager:
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
state_data=merged_state_data
|
||||
state_data=merged_state_data,
|
||||
**extra,
|
||||
)
|
||||
else:
|
||||
self.update_job_status(
|
||||
@@ -521,6 +596,7 @@ class JobManager:
|
||||
progress=progress,
|
||||
message=message,
|
||||
timeline_metadata=timeline_metadata,
|
||||
**extra,
|
||||
)
|
||||
|
||||
# Apply review token update separately if generated
|
||||
@@ -533,18 +609,28 @@ class JobManager:
|
||||
logger.info(f"Job {job_id} transitioned to {new_status}")
|
||||
|
||||
# Increment user's completed jobs counter on terminal success states
|
||||
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
|
||||
if new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE) and not count_completion:
|
||||
logger.info(f"Job {job_id}: completion not counted towards the user's jobs_completed")
|
||||
elif new_status in (JobStatus.COMPLETE, JobStatus.PREP_COMPLETE):
|
||||
try:
|
||||
job = self.get_job(job_id)
|
||||
if job and job.user_email:
|
||||
from backend.services.user_service import get_user_service
|
||||
user_service = get_user_service()
|
||||
user_service.increment_jobs_completed(job.user_email)
|
||||
try:
|
||||
from backend.services.conversion_emails import on_job_completed
|
||||
on_job_completed(job, user_service)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to schedule conversion email for job {job_id}")
|
||||
except Exception:
|
||||
logger.exception(f"Failed to increment jobs_completed for job {job_id}")
|
||||
|
||||
# Trigger notifications asynchronously (fire-and-forget)
|
||||
self._trigger_state_notifications(job_id, new_status)
|
||||
if notify:
|
||||
self._trigger_state_notifications(job_id, new_status)
|
||||
else:
|
||||
logger.info(f"Job {job_id}: notifications suppressed for transition to {new_status}")
|
||||
|
||||
return True
|
||||
|
||||
@@ -778,6 +864,34 @@ class JobManager:
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send push notification for job {job.job_id}: {e}")
|
||||
|
||||
def record_review_started(
|
||||
self,
|
||||
job_id: str,
|
||||
job_user_email: Optional[str],
|
||||
reviewer_email: Optional[str],
|
||||
is_admin: bool,
|
||||
) -> str:
|
||||
"""Record who opened the lyrics review first (AWAITING_REVIEW → IN_REVIEW).
|
||||
|
||||
``state_data.review_started_by`` is "admin" when someone other than the
|
||||
owner (the KJ / support) opened it, else "owner" (incl. review-token
|
||||
links, which only the owner is sent). kjbox shows singers "the host has
|
||||
already started reviewing" from it. Best-effort; returns the value.
|
||||
"""
|
||||
is_owner = bool(
|
||||
reviewer_email and job_user_email
|
||||
and reviewer_email.lower() == job_user_email.lower()
|
||||
)
|
||||
by = "admin" if (is_admin and not is_owner) else "owner"
|
||||
try:
|
||||
self.update_job(job_id, {
|
||||
"state_data.review_started_by": by,
|
||||
"state_data.review_started_at": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: could not record review_started_by: {e}")
|
||||
return by
|
||||
|
||||
def update_state_data(self, job_id: str, key: str, value: Any) -> None:
|
||||
"""
|
||||
Update a specific key in the job's state_data field.
|
||||
@@ -937,6 +1051,18 @@ class JobManager:
|
||||
# default to 1. payment_bypassed admin/no-email jobs have
|
||||
# credits_charged=0 and must not be refunded.
|
||||
state_data = job.state_data or {}
|
||||
# A re-run of an already-delivered track (storage-retention
|
||||
# regenerate, admin/theme re-render) was paid for when it first
|
||||
# completed — cancelling the re-run must not refund that credit.
|
||||
if any(state_data.get(k) for k in ("regenerate", "admin_rerender", "theme_rerender")):
|
||||
logger.info(f"Job {job_id}: cancelled re-run of a delivered track, skipping refund")
|
||||
return False
|
||||
# Same for a customer edit: "Edit" reopens a completed (delivered) track
|
||||
# for review, so a delete/cancel/fail after it must not refund — otherwise
|
||||
# complete → edit → delete returns the credit for a video already received.
|
||||
if job.edit_count:
|
||||
logger.info(f"Job {job_id}: edited track was already delivered, skipping refund")
|
||||
return False
|
||||
credits_charged = int(state_data.get("credits_charged", 1))
|
||||
|
||||
if credits_charged == 0:
|
||||
@@ -1097,6 +1223,28 @@ class JobManager:
|
||||
message=message
|
||||
)
|
||||
|
||||
# "Edit audio first" was requested (e.g. a file upload with the audio-edit
|
||||
# option ticked): park at the audio editor instead of starting workers.
|
||||
# The editor's submit endpoint reconciles duration and triggers them —
|
||||
# same as the audio-download flow, which parks before reconciling too.
|
||||
if (job.state_data or {}).get('requires_audio_edit'):
|
||||
from backend.workers.audio_download_worker import enter_audio_edit
|
||||
|
||||
# Editor asset pre-generation (transcode + waveform) is blocking I/O —
|
||||
# keep it off the API event loop.
|
||||
try:
|
||||
await asyncio.to_thread(enter_audio_edit, self, job_id, job.input_media_gcs_path)
|
||||
except Exception as e:
|
||||
# Callers often run this as a background task — don't strand the
|
||||
# job at DOWNLOADING with nothing to retry it.
|
||||
logger.error(f"Job {job_id}: Audio edit preparation failed: {e}", exc_info=True)
|
||||
await asyncio.to_thread(
|
||||
self.fail_job, job_id, f"Audio edit preparation failed: {e}"
|
||||
)
|
||||
raise
|
||||
logger.info(f"Job {job_id}: Awaiting audio edit before processing")
|
||||
return
|
||||
|
||||
# Reconcile credit charge against actual audio duration before triggering workers.
|
||||
# Probes input_media_gcs_path (already set by the upload handler) via ffprobe.
|
||||
# Returns True when the job is paused (AWAITING_DURATION_CONFIRM) or cancelled,
|
||||
@@ -1160,7 +1308,8 @@ class JobManager:
|
||||
|
||||
Screen generation is gated on LYRICS only (audio separation is decoupled
|
||||
so reviewers can start while it finishes), so this no-ops until lyrics are
|
||||
done, and only fires while the job is still at ``downloading``.
|
||||
done, and only fires while the job is still in its prep phase
|
||||
(``downloading``, or ``audio_edit_complete`` for audio-edited jobs).
|
||||
|
||||
Returns:
|
||||
True iff a screens dispatch was issued.
|
||||
@@ -1171,13 +1320,13 @@ class JobManager:
|
||||
if not job.state_data.get('lyrics_complete', False):
|
||||
# Lyrics not finished yet — whichever worker finishes lyrics triggers.
|
||||
return False
|
||||
if job.status != JobStatus.DOWNLOADING:
|
||||
if job.status not in PREP_PHASE_STATUSES:
|
||||
# Already advanced past prep (or parked in a special state). Keeps the
|
||||
# audio-worker fallback from re-triggering a job that already reached
|
||||
# screens/review.
|
||||
logger.info(
|
||||
f"Job {job_id}: screens not (re)triggered — status={job.status} "
|
||||
"(expected downloading)"
|
||||
"(expected downloading or audio_edit_complete)"
|
||||
)
|
||||
return False
|
||||
from backend.services.worker_service import get_worker_service
|
||||
@@ -1192,8 +1341,13 @@ class JobManager:
|
||||
"""
|
||||
Cancel a job.
|
||||
|
||||
Only jobs in non-terminal states can be cancelled.
|
||||
Only jobs in non-terminal states can be cancelled. Serialized per job
|
||||
within this instance so a double-clicked Cancel can't refund twice.
|
||||
"""
|
||||
with job_lock(job_id):
|
||||
return self._cancel_job_unlocked(job_id, reason)
|
||||
|
||||
def _cancel_job_unlocked(self, job_id: str, reason: Optional[str]) -> bool:
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
return False
|
||||
|
||||
@@ -24,6 +24,10 @@ logger = logging.getLogger(__name__)
|
||||
# Environment variable to enable/disable auto emails
|
||||
ENABLE_AUTO_EMAILS = os.getenv("ENABLE_AUTO_EMAILS", "true").lower() == "true"
|
||||
|
||||
# One-click review sign-in links in kjbox jobs' review emails stay valid this long
|
||||
# (single-use; an expired/used link offers a fresh one on the verify page).
|
||||
KJBOX_REVIEW_LOGIN_LINK_EXPIRY_HOURS = 72
|
||||
|
||||
# Feedback form URL (configured per environment, empty by default to avoid placeholder in emails)
|
||||
FEEDBACK_FORM_URL = os.getenv("FEEDBACK_FORM_URL", "")
|
||||
|
||||
@@ -38,6 +42,48 @@ def _mask_email(email: str) -> str:
|
||||
return f"{local[0]}***@{domain}"
|
||||
|
||||
|
||||
def is_kjbox_job(request_metadata: Optional[Dict[str, Any]]) -> bool:
|
||||
"""Jobs created by kjbox (``X-Client-Id: kjbox…``) on behalf of a singer."""
|
||||
client_id = str((request_metadata or {}).get("client_id") or "")
|
||||
return client_id.lower().startswith("kjbox")
|
||||
|
||||
|
||||
def build_review_login_url(
|
||||
job_id: str,
|
||||
user_email: str,
|
||||
locale: str = "en",
|
||||
frontend_url: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""One-click sign-in link that lands on the job's lyrics review.
|
||||
|
||||
kjbox singers verified their email on the karaoke-night page and have never
|
||||
signed in on the gen website, so a bare review URL would dead-end at a login
|
||||
wall. The magic-link token's ``job_review:<id>`` purpose makes /auth/verify
|
||||
redirect straight to the review. Returns None on failure (callers fall back
|
||||
to the bare review URL).
|
||||
"""
|
||||
base = frontend_url or os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
|
||||
try:
|
||||
token = get_user_service().create_admin_login_token(
|
||||
email=user_email,
|
||||
expiry_hours=KJBOX_REVIEW_LOGIN_LINK_EXPIRY_HOURS,
|
||||
purpose=f"job_review:{job_id}",
|
||||
)
|
||||
return f"{base}{get_locale_prefix(locale)}/auth/verify?token={token.token}"
|
||||
except Exception:
|
||||
logger.exception(f"Failed to mint review login link for job {job_id}; using bare review URL")
|
||||
return None
|
||||
|
||||
|
||||
def review_login_url_for_job(job, locale: str = "en") -> Optional[str]:
|
||||
"""Sign-in review link for kjbox jobs; None for every other job."""
|
||||
if not job or not getattr(job, "user_email", None):
|
||||
return None
|
||||
if not is_kjbox_job(getattr(job, "request_metadata", None)):
|
||||
return None
|
||||
return build_review_login_url(job.job_id, job.user_email, locale=locale)
|
||||
|
||||
|
||||
class JobNotificationService:
|
||||
"""
|
||||
Service for sending job-related email notifications.
|
||||
@@ -69,6 +115,13 @@ class JobNotificationService:
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
return f"{self.frontend_url}{get_locale_prefix(locale)}/app/jobs#/{job_id}/review"
|
||||
|
||||
@staticmethod
|
||||
def _is_kjbox_job(request_metadata: Optional[Dict[str, Any]]) -> bool:
|
||||
return is_kjbox_job(request_metadata)
|
||||
|
||||
def _build_review_login_url(self, job_id: str, user_email: str, locale: str = "en") -> Optional[str]:
|
||||
return build_review_login_url(job_id, user_email, locale=locale, frontend_url=self.frontend_url)
|
||||
|
||||
def _build_instrumental_url(self, job_id: str, instrumental_token: Optional[str] = None, locale: str = "en") -> str:
|
||||
"""Build the instrumental selection URL for a job."""
|
||||
# Use hash-based routing for static hosting compatibility
|
||||
@@ -287,6 +340,7 @@ class JobNotificationService:
|
||||
audio_hash: Optional[str] = None,
|
||||
review_token: Optional[str] = None,
|
||||
instrumental_token: Optional[str] = None,
|
||||
request_metadata: Optional[Dict[str, Any]] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send action-needed reminder email to user.
|
||||
@@ -304,6 +358,8 @@ class JobNotificationService:
|
||||
audio_hash: Audio hash for review URL (unused, kept for compatibility)
|
||||
review_token: Review token for URL (unused, kept for compatibility)
|
||||
instrumental_token: Instrumental token for URL (unused, kept for compatibility)
|
||||
request_metadata: Job request metadata; kjbox jobs (client_id "kjbox…")
|
||||
get a one-click sign-in link to the review instead of the bare URL
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
@@ -322,7 +378,11 @@ class JobNotificationService:
|
||||
|
||||
# Render the appropriate template
|
||||
if action_type == "lyrics":
|
||||
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
|
||||
review_url = None
|
||||
if self._is_kjbox_job(request_metadata):
|
||||
review_url = self._build_review_login_url(job_id, user_email, locale=user_locale)
|
||||
if not review_url:
|
||||
review_url = self._build_review_url(job_id, audio_hash, review_token, locale=user_locale)
|
||||
message_content = self.template_service.render_action_needed_lyrics(
|
||||
name=user_name,
|
||||
artist=artist,
|
||||
|
||||
@@ -68,8 +68,14 @@ _index_lock = asyncio.Lock()
|
||||
_KEY_SEP = "\x1f"
|
||||
|
||||
|
||||
def _match_key(artist: str, title: str) -> str:
|
||||
return f"{normalize_for_match(artist)}{_KEY_SEP}{normalize_for_match(title)}"
|
||||
def _match_key(artist: str, title: str) -> str | None:
|
||||
"""Normalized (artist, title) key, or None if either side normalizes to empty
|
||||
(punctuation-only input) — an empty key must never match anything."""
|
||||
norm_artist = normalize_for_match(artist)
|
||||
norm_title = normalize_for_match(title)
|
||||
if not norm_artist or not norm_title:
|
||||
return None
|
||||
return f"{norm_artist}{_KEY_SEP}{norm_title}"
|
||||
|
||||
|
||||
def _build_index(items: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
@@ -91,6 +97,8 @@ def _build_index(items: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
youtube_url = _normalize_youtube_url(row.get("Watch"))
|
||||
|
||||
key = _match_key(artist, title)
|
||||
if key is None:
|
||||
continue
|
||||
song = index.get(key)
|
||||
if song is None:
|
||||
# Keep the first-seen display casing for artist/title.
|
||||
@@ -167,7 +175,8 @@ async def _get_index() -> dict[str, dict[str, Any]]:
|
||||
|
||||
def _lookup(index: dict[str, dict[str, Any]], artist: str, title: str) -> dict:
|
||||
"""Build a check result for one (artist, title) from the index."""
|
||||
song = index.get(_match_key(artist, title))
|
||||
key = _match_key(artist, title)
|
||||
song = index.get(key) if key else None
|
||||
if not song or not song.get("community_tracks"):
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
"""Firestore state for the kjbox partner API (``/api/kjbox/*``).
|
||||
|
||||
kjbox (the KJ device app at live karaoke nights) signs singers in to gen with a
|
||||
6-digit emailed code and tops up one "free at the show" credit per make-it job.
|
||||
This module owns the persistence + policy for that; the HTTP layer lives in
|
||||
``backend/api/routes/kjbox.py``.
|
||||
|
||||
Collections:
|
||||
- ``kjbox_login_codes`` one doc per email (id = sha256(email)); holds only an
|
||||
HMAC of the current code, its expiry + attempt counter,
|
||||
the recent send timestamps (per-email throttle) and the
|
||||
precomputed welcome-credit evaluation.
|
||||
- ``kjbox_login_code_uses`` create()-only markers keyed by code_id — makes a code
|
||||
strictly single-use even under concurrent verifies.
|
||||
- ``kjbox_signups`` one doc per NEW gen account created via kjbox — written
|
||||
only once the email is VERIFIED (the partner-wide
|
||||
rolling-24h signup cap counts these).
|
||||
- ``kjbox_show_credits`` one doc per idempotency key that actually GRANTED a
|
||||
credit (id = sha256(key)).
|
||||
- ``kjbox_show_credit_users`` per-user doc (id = sha256(email)) with recent grant
|
||||
timestamps; read+written in the grant transaction so
|
||||
the per-user rolling-24h cap can't be raced.
|
||||
|
||||
Throttle/cap/idempotency decisions run inside Firestore transactions so
|
||||
concurrent requests can't slip past them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import secrets
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter, Increment
|
||||
|
||||
from backend.models.user import CreditTransaction
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LOGIN_CODES_COLLECTION = "kjbox_login_codes"
|
||||
LOGIN_CODE_USES_COLLECTION = "kjbox_login_code_uses"
|
||||
SIGNUPS_COLLECTION = "kjbox_signups"
|
||||
SHOW_CREDITS_COLLECTION = "kjbox_show_credits"
|
||||
SHOW_CREDIT_USERS_COLLECTION = "kjbox_show_credit_users"
|
||||
|
||||
CODE_LENGTH = 6
|
||||
CODE_EXPIRY_MINUTES = 10
|
||||
MAX_VERIFY_ATTEMPTS = 5
|
||||
SHOW_CREDIT_REASON = "kjbox show credit"
|
||||
|
||||
TRANSACTION_MAX_ATTEMPTS = 10
|
||||
|
||||
_THROTTLE_WINDOW = timedelta(hours=1)
|
||||
_DAY = timedelta(hours=24)
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _aware(dt: Any) -> Optional[datetime]:
|
||||
"""Normalize Firestore/ISO timestamps to tz-aware UTC datetimes."""
|
||||
if dt is None:
|
||||
return None
|
||||
if isinstance(dt, str):
|
||||
try:
|
||||
dt = datetime.fromisoformat(dt)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(dt, datetime):
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _sha256(value: str) -> str:
|
||||
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def code_doc_id(email: str) -> str:
|
||||
return _sha256(email.strip().lower())
|
||||
|
||||
|
||||
@dataclass
|
||||
class IssuedCode:
|
||||
code: str
|
||||
doc_id: str
|
||||
needs_credit_eval: bool
|
||||
|
||||
|
||||
class TransactionContention(Exception):
|
||||
"""A Firestore transaction gave up after repeated contention (nothing written)."""
|
||||
|
||||
|
||||
class CodeThrottled(Exception):
|
||||
"""Per-email code throttle hit (raised out of the issue transaction)."""
|
||||
|
||||
|
||||
class ShowCreditCapReached(Exception):
|
||||
"""Per-user rolling-24h show-credit cap hit."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ShowCreditResult:
|
||||
granted: bool
|
||||
credits: int
|
||||
|
||||
|
||||
class VerifyOutcome:
|
||||
OK = "ok"
|
||||
EXPIRED = "expired"
|
||||
INVALID = "invalid_code"
|
||||
TOO_MANY_ATTEMPTS = "too_many_attempts"
|
||||
|
||||
|
||||
class KjboxPartnerService:
|
||||
"""Code issuance/verification, signup cap, and show-credit bookkeeping."""
|
||||
|
||||
def __init__(self, db, pepper: str, transaction_runner=None):
|
||||
self.db = db
|
||||
# The partner secret doubles as the HMAC pepper: a Firestore read alone
|
||||
# (backups, exports) can't brute-force the 10^6 code space offline.
|
||||
self._pepper = pepper.encode("utf-8")
|
||||
# Injectable for unit tests (in-memory Firestore fake); production runs
|
||||
# ``fn(transaction)`` under @firestore.transactional (retried on contention).
|
||||
self._transaction_runner = transaction_runner
|
||||
|
||||
def _run_transaction(self, fn):
|
||||
if self._transaction_runner is not None:
|
||||
return self._transaction_runner(fn)
|
||||
try:
|
||||
return firestore.transactional(fn)(self.db.transaction(max_attempts=TRANSACTION_MAX_ATTEMPTS))
|
||||
except ValueError as exc:
|
||||
# google-cloud-firestore gives up with ValueError("Failed to commit
|
||||
# transaction in N attempts.") under heavy contention. Nothing was
|
||||
# written, so callers can safely treat it as "busy, retry".
|
||||
if "Failed to commit transaction" in str(exc):
|
||||
raise TransactionContention() from exc
|
||||
raise
|
||||
|
||||
# ------------------------------------------------------------------ codes
|
||||
|
||||
def _hash_code(self, code_id: str, code: str) -> str:
|
||||
return hmac.new(self._pepper, f"{code_id}:{code}".encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
|
||||
def _code_ref(self, email: str):
|
||||
return self.db.collection(LOGIN_CODES_COLLECTION).document(code_doc_id(email))
|
||||
|
||||
def get_code_record(self, email: str) -> Optional[dict]:
|
||||
snap = self._code_ref(email).get()
|
||||
return snap.to_dict() if snap.exists else None
|
||||
|
||||
def recent_send_times(self, record: Optional[dict], now: Optional[datetime] = None) -> list:
|
||||
now = now or _now()
|
||||
times = [_aware(t) for t in (record or {}).get("send_times") or []]
|
||||
return [t for t in times if t and now - t < _THROTTLE_WINDOW]
|
||||
|
||||
def issue_code(
|
||||
self,
|
||||
email: str,
|
||||
*,
|
||||
max_per_hour: int,
|
||||
needs_credit_eval: bool,
|
||||
locale: Optional[str],
|
||||
ui_locale: Optional[str],
|
||||
venue: Optional[str],
|
||||
ip_address: Optional[str],
|
||||
user_agent: Optional[str],
|
||||
) -> IssuedCode:
|
||||
"""Mint a fresh code for ``email``, replacing (invalidating) any prior one.
|
||||
|
||||
The throttle check, the send_times append and the code write happen in ONE
|
||||
transaction, so parallel requests can't exceed ``max_per_hour`` sends
|
||||
(raises :class:`CodeThrottled`). Only an HMAC of the code is stored.
|
||||
``merge=True`` keeps any precomputed welcome-credit evaluation across
|
||||
re-sends. Venue/locale are kept for attribution when the email verifies.
|
||||
"""
|
||||
email = email.strip().lower()
|
||||
ref = self._code_ref(email)
|
||||
|
||||
def _txn(transaction):
|
||||
now = _now()
|
||||
snap = ref.get(transaction=transaction)
|
||||
record = snap.to_dict() if snap.exists else None
|
||||
recent = self.recent_send_times(record, now)
|
||||
if len(recent) >= max_per_hour:
|
||||
raise CodeThrottled()
|
||||
code = f"{secrets.randbelow(10 ** CODE_LENGTH):0{CODE_LENGTH}d}"
|
||||
code_id = secrets.token_urlsafe(16)
|
||||
transaction.set(
|
||||
ref,
|
||||
{
|
||||
"email": email,
|
||||
"code_id": code_id,
|
||||
"code_hash": self._hash_code(code_id, code),
|
||||
"created_at": now,
|
||||
"expires_at": now + timedelta(minutes=CODE_EXPIRY_MINUTES),
|
||||
"attempts": 0,
|
||||
"send_times": recent + [now],
|
||||
"locale": locale,
|
||||
"ui_locale": ui_locale,
|
||||
"venue": venue,
|
||||
"ip_address": ip_address,
|
||||
"user_agent": user_agent,
|
||||
},
|
||||
merge=True,
|
||||
)
|
||||
has_eval = bool((record or {}).get("credit_eval_decision"))
|
||||
return IssuedCode(
|
||||
code=code,
|
||||
doc_id=code_doc_id(email),
|
||||
needs_credit_eval=needs_credit_eval and not has_eval,
|
||||
)
|
||||
|
||||
return self._run_transaction(_txn)
|
||||
|
||||
def verify_code(self, email: str, code: str) -> tuple[str, Optional[dict]]:
|
||||
"""Check ``code`` for ``email``. Returns (outcome, code_record).
|
||||
|
||||
Attempts are counted with an atomic server-side increment BEFORE the
|
||||
comparison, so parallel guesses can't exceed MAX_VERIFY_ATTEMPTS. A
|
||||
success is claimed via a create()-only marker so a code works once.
|
||||
"""
|
||||
email = email.strip().lower()
|
||||
ref = self._code_ref(email)
|
||||
snap = ref.get()
|
||||
record = snap.to_dict() if snap.exists else None
|
||||
if not record or not record.get("code_hash") or not record.get("code_id"):
|
||||
return VerifyOutcome.EXPIRED, None
|
||||
|
||||
expires_at = _aware(record.get("expires_at"))
|
||||
if not expires_at or _now() > expires_at:
|
||||
ref.update({"code_hash": None})
|
||||
return VerifyOutcome.EXPIRED, None
|
||||
|
||||
ref.update({"attempts": Increment(1)})
|
||||
after = ref.get().to_dict() or {}
|
||||
if after.get("code_id") != record["code_id"] or not after.get("code_hash"):
|
||||
# Superseded or burned between our read and the increment.
|
||||
return VerifyOutcome.EXPIRED, None
|
||||
if int(after.get("attempts") or 0) > MAX_VERIFY_ATTEMPTS:
|
||||
ref.update({"code_hash": None})
|
||||
return VerifyOutcome.TOO_MANY_ATTEMPTS, None
|
||||
|
||||
candidate = (code or "").strip()
|
||||
expected = record["code_hash"]
|
||||
provided = self._hash_code(record["code_id"], candidate)
|
||||
if not (candidate.isdigit() and len(candidate) == CODE_LENGTH
|
||||
and hmac.compare_digest(provided, expected)):
|
||||
return VerifyOutcome.INVALID, None
|
||||
|
||||
try:
|
||||
self.db.collection(LOGIN_CODE_USES_COLLECTION).document(record["code_id"]).create(
|
||||
{"email": email, "used_at": _now()}
|
||||
)
|
||||
except google_exceptions.AlreadyExists:
|
||||
return VerifyOutcome.EXPIRED, None
|
||||
|
||||
ref.update({"code_hash": None, "used_at": _now()})
|
||||
return VerifyOutcome.OK, after
|
||||
|
||||
# ----------------------------------------------------------- signup cap
|
||||
|
||||
def count_recent_signups(self) -> int:
|
||||
cutoff = _now() - _DAY
|
||||
query = self.db.collection(SIGNUPS_COLLECTION).where(
|
||||
filter=FieldFilter("created_at", ">=", cutoff)
|
||||
)
|
||||
return sum(1 for _ in query.stream())
|
||||
|
||||
def record_signup(self, email: str, venue: Optional[str]) -> None:
|
||||
self.db.collection(SIGNUPS_COLLECTION).document().set(
|
||||
{"email": email.strip().lower(), "venue": venue, "created_at": _now()}
|
||||
)
|
||||
|
||||
# --------------------------------------------------------- show credits
|
||||
|
||||
def _show_credit_ref(self, idempotency_key: str):
|
||||
return self.db.collection(SHOW_CREDITS_COLLECTION).document(_sha256(idempotency_key))
|
||||
|
||||
def _show_credit_user_ref(self, email: str):
|
||||
return self.db.collection(SHOW_CREDIT_USERS_COLLECTION).document(_sha256(email.strip().lower()))
|
||||
|
||||
def grant_show_credit(
|
||||
self,
|
||||
user_ref,
|
||||
email: str,
|
||||
idempotency_key: str,
|
||||
*,
|
||||
venue: Optional[str],
|
||||
only_if_empty: bool,
|
||||
max_per_24h: int,
|
||||
reason: str = SHOW_CREDIT_REASON,
|
||||
max_transactions: int = 100,
|
||||
) -> ShowCreditResult:
|
||||
"""Atomically: idempotency check, only-if-empty check, per-user cap, key
|
||||
claim, and the +1 credit (with its transaction-history entry).
|
||||
|
||||
The key is claimed ONLY when a credit is actually granted, so kjbox can
|
||||
call with ``only_if_empty=True`` early and again with the same key and
|
||||
``only_if_empty=False`` later — the second call grants only if the first
|
||||
didn't. Raises :class:`ShowCreditCapReached` at the cap.
|
||||
"""
|
||||
email = email.strip().lower()
|
||||
key_ref = self._show_credit_ref(idempotency_key)
|
||||
counter_ref = self._show_credit_user_ref(email)
|
||||
|
||||
def _txn(transaction):
|
||||
now = _now()
|
||||
key_snap = key_ref.get(transaction=transaction)
|
||||
user_snap = user_ref.get(transaction=transaction)
|
||||
counter_snap = counter_ref.get(transaction=transaction)
|
||||
user_data = user_snap.to_dict() if user_snap.exists else None
|
||||
if user_data is None:
|
||||
raise LookupError("user not found")
|
||||
credits = int(user_data.get("credits") or 0)
|
||||
|
||||
if key_snap.exists:
|
||||
return ShowCreditResult(granted=False, credits=credits)
|
||||
if only_if_empty and credits >= 1:
|
||||
return ShowCreditResult(granted=False, credits=credits)
|
||||
|
||||
counter = counter_snap.to_dict() if counter_snap.exists else {}
|
||||
recent = [t for t in (_aware(x) for x in counter.get("grant_times") or [])
|
||||
if t and now - t < _DAY]
|
||||
if len(recent) >= max_per_24h:
|
||||
raise ShowCreditCapReached()
|
||||
|
||||
entry = CreditTransaction(
|
||||
id=str(uuid.uuid4()), amount=1, reason=reason,
|
||||
).model_dump(mode="json")
|
||||
history = list(user_data.get("credit_transactions") or [])
|
||||
history = history[-(max_transactions - 1):] + [entry]
|
||||
|
||||
transaction.create(key_ref, {
|
||||
"idempotency_key": idempotency_key,
|
||||
"email": email,
|
||||
"venue": venue,
|
||||
"created_at": now,
|
||||
})
|
||||
transaction.set(counter_ref, {"email": email, "grant_times": recent + [now]})
|
||||
transaction.update(user_ref, {
|
||||
"credits": credits + 1,
|
||||
"credit_transactions": history,
|
||||
"updated_at": datetime.utcnow(),
|
||||
})
|
||||
return ShowCreditResult(granted=True, credits=credits + 1)
|
||||
|
||||
return self._run_transaction(_txn)
|
||||
@@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)
|
||||
@dataclass
|
||||
class EncodingConfig:
|
||||
"""Configuration for video encoding."""
|
||||
title_video: str # Path to title video
|
||||
title_video: Optional[str] # Path to title video (None = theme omits the title screen)
|
||||
karaoke_video: str # Path to karaoke video (with vocals)
|
||||
instrumental_audio: str # Path to instrumental audio
|
||||
end_video: Optional[str] = None # Optional path to end credits video
|
||||
@@ -369,16 +369,16 @@ class LocalEncodingService:
|
||||
|
||||
def encode_lossless_mp4(
|
||||
self,
|
||||
title_video: str,
|
||||
title_video: Optional[str],
|
||||
karaoke_video: str,
|
||||
output_file: str,
|
||||
end_video: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Create lossless 4K MP4 by concatenating title, karaoke, and optionally end videos.
|
||||
Create lossless 4K MP4 by concatenating the title (if any), karaoke and end (if any) videos.
|
||||
|
||||
Args:
|
||||
title_video: Path to title video
|
||||
title_video: Path to title video, or None when the theme omits the title screen
|
||||
karaoke_video: Path to karaoke video
|
||||
output_file: Path for output file
|
||||
end_video: Optional path to end credits video
|
||||
@@ -386,34 +386,31 @@ class LocalEncodingService:
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
# Quote file paths
|
||||
title_quoted = shlex.quote(os.path.abspath(title_video))
|
||||
karaoke_quoted = shlex.quote(os.path.abspath(karaoke_video))
|
||||
|
||||
# Build filter and inputs for concatenation
|
||||
# (path, hardware-decode) per concat segment, in order
|
||||
segments = []
|
||||
if title_video:
|
||||
segments.append((title_video, True))
|
||||
segments.append((karaoke_video, True))
|
||||
if end_video and os.path.isfile(end_video):
|
||||
end_quoted = shlex.quote(os.path.abspath(end_video))
|
||||
extra_input = f"-i {end_quoted}"
|
||||
concat_filter = (
|
||||
'-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]'
|
||||
'concat=n=3:v=1:a=1[outv][outa]"'
|
||||
)
|
||||
else:
|
||||
extra_input = ""
|
||||
concat_filter = (
|
||||
'-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]'
|
||||
'concat=n=2:v=1:a=1[outv][outa]"'
|
||||
segments.append((end_video, False))
|
||||
|
||||
def inputs(hwaccel: bool) -> str:
|
||||
return " ".join(
|
||||
(f"{self.hwaccel_decode_flags} " if hwaccel and hw else "") + f"-i {shlex.quote(os.path.abspath(path))}"
|
||||
for path, hw in segments
|
||||
)
|
||||
|
||||
streams = "".join(f"[{i}:v:0][{i}:a:0]" for i in range(len(segments)))
|
||||
concat_filter = f'-filter_complex "{streams}concat=n={len(segments)}:v=1:a=1[outv][outa]"'
|
||||
|
||||
gpu_command = (
|
||||
f"{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i {title_quoted} "
|
||||
f"{self.hwaccel_decode_flags} -i {karaoke_quoted} {extra_input} "
|
||||
f"{self._ffmpeg_base_command} {inputs(True)} "
|
||||
f'{concat_filter} -map "[outv]" -map "[outa]" -c:v {self.video_encoder} '
|
||||
f'{self._get_nvenc_quality_settings("lossless")} -c:a pcm_s16le '
|
||||
f'{self.MP4_FLAGS} "{output_file}"'
|
||||
)
|
||||
cpu_command = (
|
||||
f"{self._ffmpeg_base_command} -i {title_quoted} -i {karaoke_quoted} {extra_input} "
|
||||
f"{self._ffmpeg_base_command} {inputs(False)} "
|
||||
f'{concat_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le '
|
||||
f'{self.MP4_FLAGS} "{output_file}"'
|
||||
)
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
"""Event-loop stall watchdog.
|
||||
|
||||
The API runs ONE uvicorn process with ONE asyncio event loop per Cloud Run
|
||||
instance. Any synchronous work executed on that loop (sync Firestore/GCS/HTTP
|
||||
calls, PIL/ffmpeg, a first ``import matplotlib.pyplot``…) freezes *every*
|
||||
request on the instance — including ``/api/health`` — which users see as the
|
||||
"Reconnecting" pill / "temporarily unavailable" banner. (Analysis 2026-10-03:
|
||||
docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md.)
|
||||
|
||||
This module makes such freezes self-diagnosing:
|
||||
|
||||
* an asyncio heartbeat task stamps ``last_tick`` every ``tick_s``;
|
||||
* a daemon thread notices when the stamp goes stale (> ``stall_threshold_s``)
|
||||
and captures the *event-loop thread's* Python stack via
|
||||
``sys._current_frames()`` — i.e. the exact line that is blocking — resampling
|
||||
at ``sample_at_s`` so a long freeze shows where it actually spent its time;
|
||||
* when the loop resumes it logs ``EVENT_LOOP_STALL ended duration_ms=…``
|
||||
(WARNING, or ERROR at ``error_threshold_s`` — the alerting log metric keys on
|
||||
that), and for stalls ≥ ``record_threshold_s`` hands a summary to
|
||||
``recorder`` (Firestore ``client_events`` type ``server_loop_stall`` in prod),
|
||||
so server-side cause and user-visible impact live in one collection.
|
||||
|
||||
The thread only reads frames and a float; it never touches the loop, so it is
|
||||
safe to run alongside it. Recording happens on the watchdog thread (sync
|
||||
Firestore is fine there).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Frames from these path fragments are "ours" — the innermost one is reported
|
||||
# as the culprit (the stdlib/library frame below it is usually just the I/O).
|
||||
_OWN_CODE_MARKERS = ("/backend/", "/karaoke_gen/")
|
||||
_MAX_STACK_FRAMES = 30
|
||||
_MAX_STACK_CHARS = 8000
|
||||
|
||||
Recorder = Callable[[dict], None]
|
||||
|
||||
|
||||
class RequestTracker:
|
||||
"""Counts HTTP requests so the watchdog can tell whether a stall hurt anyone.
|
||||
|
||||
Mutated only on the event-loop thread (by ``RequestTrackingMiddleware``) and
|
||||
read from the watchdog thread; plain ints are safe to read under the GIL.
|
||||
|
||||
Why (2026-10-12/13 flapping alert): Cloud Run autoscaling starts extra
|
||||
instances that serve one request and then sit idle, CPU-throttled, while the
|
||||
SpaCy/NLTK warmup thread trickles along for 10+ minutes. Those idle instances
|
||||
produced 10-40s "stalls" (empty culprit — the freeze consumed the sampling
|
||||
schedule) with no request on them, tripping the >=2-in-30min alert. A stall
|
||||
with no request in flight and none queued behind it affects nobody.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.in_flight = 0
|
||||
self.started = 0
|
||||
|
||||
def begin(self) -> None:
|
||||
self.in_flight += 1
|
||||
self.started += 1
|
||||
|
||||
def end(self) -> None:
|
||||
self.in_flight = max(0, self.in_flight - 1)
|
||||
|
||||
|
||||
# Process-wide tracker: the middleware is attached at import time, the watchdog
|
||||
# is created later in the lifespan — both share this instance.
|
||||
request_tracker = RequestTracker()
|
||||
|
||||
|
||||
class RequestTrackingMiddleware:
|
||||
"""Pure-ASGI middleware feeding ``request_tracker`` (no per-request allocation
|
||||
beyond the wrapper call; outermost so even rejected requests count)."""
|
||||
|
||||
def __init__(self, app, tracker: Optional[RequestTracker] = None) -> None:
|
||||
self.app = app
|
||||
self.tracker = tracker or request_tracker
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope.get("type") != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
self.tracker.begin()
|
||||
try:
|
||||
return await self.app(scope, receive, send)
|
||||
finally:
|
||||
self.tracker.end()
|
||||
|
||||
# Innermost frames that mean "the loop is idle, waiting for I/O" — not blocked.
|
||||
_IDLE_FUNCS = {"select", "poll", "epoll", "kqueue", "control", "_run_once"}
|
||||
_IDLE_FILES = ("selectors.py", "base_events.py")
|
||||
|
||||
|
||||
def _is_idle_frame(frame) -> bool:
|
||||
"""True when the loop thread is parked in the selector (idle), not running code."""
|
||||
if frame is None:
|
||||
return False
|
||||
code = frame.f_code
|
||||
return code.co_name in _IDLE_FUNCS and code.co_filename.endswith(_IDLE_FILES)
|
||||
|
||||
|
||||
def _format_stack(frame) -> tuple[str, str]:
|
||||
"""Return (stack_text, culprit) for a frame; culprit = innermost own-code frame."""
|
||||
if frame is None:
|
||||
return "", ""
|
||||
summary = traceback.extract_stack(frame)[-_MAX_STACK_FRAMES:]
|
||||
culprit = ""
|
||||
for fs in reversed(summary):
|
||||
if any(m in fs.filename for m in _OWN_CODE_MARKERS) and "loop_watchdog" not in fs.filename:
|
||||
short = fs.filename.split("/app/")[-1]
|
||||
culprit = f"{short}:{fs.lineno} in {fs.name}"
|
||||
break
|
||||
if not culprit and summary:
|
||||
fs = summary[-1]
|
||||
culprit = f"{fs.filename}:{fs.lineno} in {fs.name}"
|
||||
text = "".join(traceback.format_list(summary))[-_MAX_STACK_CHARS:]
|
||||
return text, culprit
|
||||
|
||||
|
||||
class LoopWatchdog:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
tick_s: float = 0.25,
|
||||
stall_threshold_s: float = 1.0,
|
||||
error_threshold_s: float = 10.0,
|
||||
record_threshold_s: float = 5.0,
|
||||
sample_at_s: tuple[float, ...] = (1.0, 5.0, 15.0),
|
||||
recorder: Optional[Recorder] = None,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
cpu_clock: Callable[[], float] = time.process_time,
|
||||
frozen_gap_s: float = 0.75,
|
||||
frozen_cpu_ratio: float = 0.25,
|
||||
request_tracker: Optional[RequestTracker] = None,
|
||||
request_grace_s: float = 0.5,
|
||||
) -> None:
|
||||
self.tick_s = tick_s
|
||||
self.stall_threshold_s = stall_threshold_s
|
||||
self.error_threshold_s = error_threshold_s
|
||||
self.record_threshold_s = record_threshold_s
|
||||
self.sample_at_s = tuple(sorted(sample_at_s))
|
||||
self.recorder = recorder
|
||||
self._clock = clock
|
||||
self._cpu_clock = cpu_clock
|
||||
# Cloud Run --cpu-throttling freezes the WHOLE process between requests —
|
||||
# sometimes mid-callback, where the "loop parked in select()" check can't
|
||||
# see it (2026-10-08: a 30s "stall" in asyncio's get_debug on an instance
|
||||
# with no requests in flight). Signature: this watchdog thread itself
|
||||
# oversleeps by >= frozen_gap_s while the process burns almost no CPU
|
||||
# (a blocking I/O call lets this thread wake on time; GIL-hogging CPU
|
||||
# work burns CPU). That frozen time is discounted from the stall.
|
||||
# 0.75s = 3 missed ticks: measured wake gaps stay <= 0.27s under sync I/O,
|
||||
# pure-Python CPU and C-extension CPU on the loop, while partial throttling
|
||||
# gives short 1-2.5s freezes (126 of 128 asyncio-internal "stalls" on
|
||||
# 2026-10-08 had no request waiting on them).
|
||||
self.frozen_gap_s = frozen_gap_s
|
||||
self.frozen_cpu_ratio = frozen_cpu_ratio
|
||||
self._last_check: Optional[float] = None
|
||||
self._last_cpu = 0.0
|
||||
self._stall_frozen_s = 0.0
|
||||
# A freeze can carry the stall past every sample_at_s point without a
|
||||
# sample. If the loop is STILL blocked after the thaw, that is real
|
||||
# blocking — take one sample then so the stall has a culprit (2026-10-12:
|
||||
# 10-40s ERROR stalls all had an empty culprit).
|
||||
self._sample_after_thaw = False
|
||||
# With a tracker, a stall only escalates to ERROR (the alerting level) if
|
||||
# a request was in flight when it began or arrived during it. Requests
|
||||
# queued in the socket during the freeze are accepted right after the loop
|
||||
# resumes, so the verdict waits ``request_grace_s`` after resume.
|
||||
self.request_tracker = request_tracker
|
||||
self.request_grace_s = request_grace_s
|
||||
self._stall_in_flight = 0
|
||||
self._stall_started_count = 0
|
||||
self._resumed_at: Optional[float] = None
|
||||
self._resumed_duration = 0.0
|
||||
|
||||
self._last_tick = clock()
|
||||
self._loop_thread_id: Optional[int] = None
|
||||
self._heartbeat_task: Optional[asyncio.Task] = None
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._stop = threading.Event()
|
||||
|
||||
# Current-stall state (only touched by the watchdog thread).
|
||||
self._in_stall = False
|
||||
self._stall_started_tick = 0.0
|
||||
self._samples: list[dict[str, Any]] = []
|
||||
self._next_sample_idx = 0
|
||||
|
||||
# ----- lifecycle -------------------------------------------------------
|
||||
def start(self) -> None:
|
||||
"""Start heartbeat + watchdog thread. Must be called from inside the loop."""
|
||||
if self._thread is not None:
|
||||
return
|
||||
self._loop_thread_id = threading.get_ident()
|
||||
self._last_tick = self._clock()
|
||||
self._heartbeat_task = asyncio.get_running_loop().create_task(self._heartbeat())
|
||||
self._stop.clear()
|
||||
self._thread = threading.Thread(target=self._run, name="loop-watchdog", daemon=True)
|
||||
self._thread.start()
|
||||
logger.info(
|
||||
"Event-loop watchdog started (stall>=%.1fs logged, >=%.1fs recorded, >=%.1fs error)",
|
||||
self.stall_threshold_s, self.record_threshold_s, self.error_threshold_s,
|
||||
)
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._stop.set()
|
||||
if self._heartbeat_task is not None:
|
||||
self._heartbeat_task.cancel()
|
||||
try:
|
||||
await self._heartbeat_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
self._heartbeat_task = None
|
||||
self._thread = None
|
||||
|
||||
async def _heartbeat(self) -> None:
|
||||
while True:
|
||||
self._last_tick = self._clock()
|
||||
await asyncio.sleep(self.tick_s)
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stop.wait(self.tick_s):
|
||||
try:
|
||||
self.check()
|
||||
except Exception: # pragma: no cover — must never kill the thread
|
||||
logger.exception("loop watchdog check failed")
|
||||
|
||||
# ----- detection (called from the watchdog thread; unit-testable) ------
|
||||
def _sample(self, age: float) -> None:
|
||||
frame = sys._current_frames().get(self._loop_thread_id) if self._loop_thread_id else None
|
||||
if _is_idle_frame(frame):
|
||||
# Loop is parked in select(): not blocked. This is what a CPU-throttled
|
||||
# idle Cloud Run instance looks like when CPU returns (the watchdog
|
||||
# thread can wake before the heartbeat does). Record it so _finish
|
||||
# can drop an all-idle "stall" as a false positive.
|
||||
self._samples.append({"at_s": round(age, 1), "culprit": "", "stack": "", "idle": True})
|
||||
return
|
||||
stack, culprit = _format_stack(frame)
|
||||
if self._samples and self._samples[-1]["stack"] == stack:
|
||||
return # identical to the previous sample — nothing new to learn
|
||||
self._samples.append({"at_s": round(age, 1), "culprit": culprit, "stack": stack, "idle": False})
|
||||
# Same impact rule as _finish: an idle instance's stall never logs ERROR.
|
||||
# (Requests still queued in the socket are invisible until the loop
|
||||
# resumes, so this can under-call mid-stall; the ended line decides.)
|
||||
no_impact = self.request_tracker is not None and self._requests_affected() == 0
|
||||
# Judge severity on blocked time only: frozen (throttled) time is discounted
|
||||
# from the final duration too, so a post-thaw sample mustn't claim ERROR
|
||||
# for a block that ends up below the threshold.
|
||||
blocked = max(0.0, age - self._stall_frozen_s)
|
||||
level = (
|
||||
logging.ERROR
|
||||
if blocked >= self.error_threshold_s and not no_impact
|
||||
else logging.WARNING
|
||||
)
|
||||
logger.log(
|
||||
level,
|
||||
"EVENT_LOOP_STALL in progress age_ms=%d culprit=%s\n%s",
|
||||
int(age * 1000), culprit, stack,
|
||||
extra={"loop_stall_age_ms": int(age * 1000), "loop_stall_culprit": culprit},
|
||||
)
|
||||
|
||||
def _frozen_gap(self, now: float) -> float:
|
||||
"""Seconds since the previous check during which the whole process was frozen."""
|
||||
cpu = self._cpu_clock()
|
||||
prev_check, prev_cpu = self._last_check, self._last_cpu
|
||||
self._last_check, self._last_cpu = now, cpu
|
||||
if prev_check is None:
|
||||
return 0.0
|
||||
gap = now - prev_check
|
||||
if gap >= self.frozen_gap_s and (cpu - prev_cpu) < gap * self.frozen_cpu_ratio:
|
||||
return gap
|
||||
return 0.0
|
||||
|
||||
def check(self, now: Optional[float] = None) -> None:
|
||||
now = self._clock() if now is None else now
|
||||
frozen = self._frozen_gap(now)
|
||||
last = self._last_tick
|
||||
age = now - last
|
||||
|
||||
if not self._in_stall:
|
||||
if age >= self.stall_threshold_s:
|
||||
self._in_stall = True
|
||||
self._stall_started_tick = last
|
||||
self._samples = []
|
||||
self._next_sample_idx = 0
|
||||
self._stall_frozen_s = 0.0
|
||||
self._sample_after_thaw = False
|
||||
self._resumed_at = None
|
||||
if self.request_tracker is not None:
|
||||
self._stall_in_flight = self.request_tracker.in_flight
|
||||
self._stall_started_count = self.request_tracker.started
|
||||
else:
|
||||
return
|
||||
if self._resumed_at is not None:
|
||||
# Loop already resumed; waiting out the grace window for queued requests.
|
||||
if self._requests_affected() or now - self._resumed_at >= self.request_grace_s:
|
||||
self._finish(self._resumed_duration)
|
||||
return
|
||||
# Only the part of the frozen gap after the last heartbeat belongs to this stall.
|
||||
self._stall_frozen_s += min(frozen, age)
|
||||
|
||||
# In a stall: has the heartbeat resumed?
|
||||
if last > self._stall_started_tick:
|
||||
# The heartbeat that ended the stall fired one tick_s after the
|
||||
# previous one would have, so subtract the nominal sleep.
|
||||
duration = max(0.0, last - self._stall_started_tick - self.tick_s)
|
||||
if self.request_tracker is not None and not self._requests_affected():
|
||||
self._resumed_at = now
|
||||
self._resumed_duration = duration
|
||||
return
|
||||
self._finish(duration)
|
||||
return
|
||||
|
||||
if frozen:
|
||||
# Just thawed: the loop's stack shows where the freeze caught it, not
|
||||
# what blocked it. Skip the samples due during the freeze.
|
||||
skipped = False
|
||||
while (
|
||||
self._next_sample_idx < len(self.sample_at_s)
|
||||
and age >= self.sample_at_s[self._next_sample_idx]
|
||||
):
|
||||
self._next_sample_idx += 1
|
||||
skipped = True
|
||||
if skipped:
|
||||
self._sample_after_thaw = True
|
||||
return
|
||||
|
||||
if self._sample_after_thaw:
|
||||
# First on-time check after a freeze and the loop still hasn't ticked.
|
||||
self._sample_after_thaw = False
|
||||
self._sample(age)
|
||||
|
||||
while (
|
||||
self._next_sample_idx < len(self.sample_at_s)
|
||||
and age >= self.sample_at_s[self._next_sample_idx]
|
||||
):
|
||||
self._next_sample_idx += 1
|
||||
self._sample(age)
|
||||
|
||||
def _requests_affected(self) -> int:
|
||||
"""Requests that waited on this stall: in flight at its start + started since."""
|
||||
t = self.request_tracker
|
||||
if t is None:
|
||||
return 0
|
||||
return self._stall_in_flight + max(0, t.started - self._stall_started_count)
|
||||
|
||||
def _finish(self, duration: float) -> None:
|
||||
samples = self._samples
|
||||
frozen_s = self._stall_frozen_s
|
||||
affected = self._requests_affected()
|
||||
tracked = self.request_tracker is not None
|
||||
self._resumed_at = None
|
||||
self._in_stall = False
|
||||
self._samples = []
|
||||
self._stall_frozen_s = 0.0
|
||||
if frozen_s:
|
||||
logger.debug(
|
||||
"loop watchdog: discounted %dms of process freeze (CPU throttling) from a %dms gap",
|
||||
int(frozen_s * 1000), int(duration * 1000),
|
||||
)
|
||||
duration = max(0.0, duration - frozen_s)
|
||||
if duration < self.stall_threshold_s:
|
||||
return
|
||||
if samples and all(s.get("idle") for s in samples):
|
||||
# Every sample saw the loop idle in select() — a throttled/idle gap
|
||||
# (no CPU allocated between requests), not a blocking call.
|
||||
logger.debug("loop watchdog: ignored idle gap of %dms", int(duration * 1000))
|
||||
return
|
||||
samples = [s for s in samples if not s.get("idle")]
|
||||
culprits = [s["culprit"] for s in samples if s["culprit"]]
|
||||
# The longest-lived sample is the most representative of the freeze.
|
||||
main_culprit = culprits[-1] if culprits else ""
|
||||
# No request waited on it (idle, typically CPU-throttled instance) → never
|
||||
# ERROR: the alert counts ERROR lines and nobody saw this freeze.
|
||||
no_impact = tracked and affected == 0
|
||||
level = (
|
||||
logging.ERROR
|
||||
if duration >= self.error_threshold_s and not no_impact
|
||||
else logging.WARNING
|
||||
)
|
||||
logger.log(
|
||||
level,
|
||||
"EVENT_LOOP_STALL ended duration_ms=%d culprit=%s requests_affected=%s",
|
||||
int(duration * 1000), main_culprit, affected if tracked else "unknown",
|
||||
extra={
|
||||
"loop_stall_duration_ms": int(duration * 1000),
|
||||
"loop_stall_culprit": main_culprit,
|
||||
"loop_stall_culprits": culprits,
|
||||
"loop_stall_requests_affected": affected if tracked else None,
|
||||
},
|
||||
)
|
||||
if self.recorder is not None and duration >= self.record_threshold_s:
|
||||
try:
|
||||
self.recorder({
|
||||
"duration_ms": int(duration * 1000),
|
||||
"culprit": main_culprit,
|
||||
"culprits": culprits,
|
||||
"stack": samples[-1]["stack"] if samples else "",
|
||||
"requests_affected": affected if tracked else None,
|
||||
})
|
||||
except Exception:
|
||||
logger.exception("Failed to record loop stall (non-fatal)")
|
||||
|
||||
|
||||
# ----- production recorder ---------------------------------------------------
|
||||
_instance_id: Optional[str] = None
|
||||
|
||||
|
||||
def _cloud_run_instance_id() -> str:
|
||||
"""Best-effort Cloud Run instance id from the metadata server (cached)."""
|
||||
global _instance_id
|
||||
if _instance_id is not None:
|
||||
return _instance_id
|
||||
_instance_id = ""
|
||||
try:
|
||||
import requests
|
||||
|
||||
resp = requests.get(
|
||||
"http://metadata.google.internal/computeMetadata/v1/instance/id",
|
||||
headers={"Metadata-Flavor": "Google"},
|
||||
timeout=1,
|
||||
)
|
||||
if resp.ok:
|
||||
_instance_id = resp.text.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return _instance_id
|
||||
|
||||
|
||||
def firestore_stall_recorder(stall: dict) -> None:
|
||||
"""Persist a stall as a ``client_events`` doc (type ``server_loop_stall``)."""
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
from backend.version import VERSION
|
||||
|
||||
doc = {
|
||||
"type": "server_loop_stall",
|
||||
"source": "server",
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"release": VERSION,
|
||||
"revision": os.getenv("K_REVISION", ""),
|
||||
"instance_id": _cloud_run_instance_id(),
|
||||
"detail": {
|
||||
"duration_ms": stall["duration_ms"],
|
||||
"culprit": stall["culprit"][:300],
|
||||
"requests_affected": stall.get("requests_affected"),
|
||||
},
|
||||
"culprits": [c[:300] for c in stall.get("culprits", [])][:5],
|
||||
"stack": stall.get("stack", "")[:_MAX_STACK_CHARS],
|
||||
}
|
||||
firestore.Client(project="nomadkaraoke").collection("client_events").add(doc)
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Translated lyrics: an LLM translation of each reviewed lyric line.
|
||||
|
||||
A job created with ``translation_language`` gets its final (post-review) lyrics
|
||||
translated once, just before the karaoke video renders. The result is stored at
|
||||
``jobs/{job_id}/lyrics/translations.json`` (format in
|
||||
``karaoke_gen.lyrics_transcriber.output.translations``), which the renderers draw in
|
||||
smaller text beneath each line. Translations aren't editable; they're regenerated
|
||||
from the reviewed text, and identical requests are served from a GCS cache (so a
|
||||
re-render costs no new LLM call).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Languages a user can pick: the app's UI locales (code -> English name for the prompt).
|
||||
TRANSLATION_LANGUAGES: Dict[str, str] = {
|
||||
"ar": "Arabic",
|
||||
"ca": "Catalan",
|
||||
"cs": "Czech",
|
||||
"da": "Danish",
|
||||
"de": "German",
|
||||
"el": "Greek",
|
||||
"en": "English",
|
||||
"es": "Spanish",
|
||||
"fi": "Finnish",
|
||||
"fr": "French",
|
||||
"he": "Hebrew",
|
||||
"hi": "Hindi",
|
||||
"hr": "Croatian",
|
||||
"hu": "Hungarian",
|
||||
"id": "Indonesian",
|
||||
"it": "Italian",
|
||||
"ja": "Japanese",
|
||||
"ko": "Korean",
|
||||
"ms": "Malay",
|
||||
"nb": "Norwegian (Bokmål)",
|
||||
"nl": "Dutch",
|
||||
"pl": "Polish",
|
||||
"pt": "Portuguese",
|
||||
"ro": "Romanian",
|
||||
"ru": "Russian",
|
||||
"sk": "Slovak",
|
||||
"sv": "Swedish",
|
||||
"th": "Thai",
|
||||
"tl": "Filipino (Tagalog)",
|
||||
"tr": "Turkish",
|
||||
"uk": "Ukrainian",
|
||||
"vi": "Vietnamese",
|
||||
"zh": "Simplified Chinese",
|
||||
}
|
||||
|
||||
TRANSLATIONS_GCS_NAME = "translations.json"
|
||||
CACHE_PREFIX = "lyrics-translation-cache"
|
||||
CACHE_VERSION = 1
|
||||
MAX_ATTEMPTS = 2
|
||||
BACKOFF_SECONDS = 2.0
|
||||
# More than this share of lines coming back unchanged = the song is already in the
|
||||
# target language, so a translation row would just repeat the lyrics.
|
||||
SAME_LANGUAGE_THRESHOLD = 0.8
|
||||
|
||||
SYSTEM_PROMPT = """You translate song lyrics for karaoke videos. Each translated line is shown \
|
||||
in small text directly beneath the original line while the singer sings it, so language \
|
||||
learners understand what they are singing.
|
||||
|
||||
Rules:
|
||||
- Return exactly one translation per input line, in the same order (same count).
|
||||
- Translate the meaning naturally and idiomatically; it does not need to rhyme or be singable.
|
||||
- A sentence often continues across lines: keep each translation aligned with the words of \
|
||||
its own line where the target grammar allows, so the meaning lines up with what is being sung.
|
||||
- Keep each translation about as short as its line; no explanations, notes, quotes or brackets.
|
||||
- Keep names, places and brand names. Keep pure vocables (oh, ooh, la la, yeah, na na) as they are.
|
||||
- If a line is already in the target language, return it unchanged.
|
||||
"""
|
||||
|
||||
|
||||
class LyricsTranslationError(Exception):
|
||||
"""The lyrics couldn't be translated (model error or malformed output)."""
|
||||
|
||||
|
||||
def normalize_language(code: Optional[str]) -> Optional[str]:
|
||||
"""Supported language code for ``code`` (case/region-insensitive), else None."""
|
||||
if not code:
|
||||
return None
|
||||
base = str(code).strip().lower().replace("_", "-")
|
||||
if base in TRANSLATION_LANGUAGES:
|
||||
return base
|
||||
base = base.split("-")[0]
|
||||
if base == "no":
|
||||
base = "nb"
|
||||
if base == "fil":
|
||||
base = "tl"
|
||||
return base if base in TRANSLATION_LANGUAGES else None
|
||||
|
||||
|
||||
def _norm(text: str) -> str:
|
||||
return " ".join((text or "").lower().split())
|
||||
|
||||
|
||||
def is_same_language(lines: List[str], translations: List[str]) -> bool:
|
||||
"""True when nearly every line came back unchanged (song already in that language)."""
|
||||
pairs = [(a, b) for a, b in zip(lines, translations) if _norm(a)]
|
||||
if not pairs:
|
||||
return False
|
||||
unchanged = sum(1 for a, b in pairs if _norm(a) == _norm(b))
|
||||
return unchanged / len(pairs) >= SAME_LANGUAGE_THRESHOLD
|
||||
|
||||
|
||||
def _user_prompt(lines: List[str], language: str, artist: Optional[str], title: Optional[str]) -> str:
|
||||
song = " - ".join(p for p in (artist, title) if p) or "unknown song"
|
||||
numbered = "\n".join(f"{i + 1}. {line}" for i, line in enumerate(lines))
|
||||
return (
|
||||
f"Song: {song}\n"
|
||||
f"Target language: {TRANSLATION_LANGUAGES[language]}\n"
|
||||
f"Translate these {len(lines)} lyric lines. Return JSON "
|
||||
f'{{"translations": [...]}} with exactly {len(lines)} strings, one per line, '
|
||||
f"without the line numbers.\n\n{numbered}"
|
||||
)
|
||||
|
||||
|
||||
def _is_transient(exc: BaseException) -> bool:
|
||||
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
|
||||
if isinstance(code, int) and code in {429, 500, 502, 503, 504}:
|
||||
return True
|
||||
text = str(exc).upper()
|
||||
return any(m in text for m in ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "DEADLINE", "429", "503"))
|
||||
|
||||
|
||||
class LyricsTranslationService:
|
||||
def __init__(self, storage=None, model: Optional[str] = None):
|
||||
self.settings = get_settings()
|
||||
self.model = model or self.settings.lyrics_translation_model
|
||||
self._storage = storage
|
||||
|
||||
def _get_storage(self):
|
||||
if self._storage is None:
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
self._storage = StorageService()
|
||||
return self._storage
|
||||
|
||||
# ---- cache (GCS, best-effort) ----
|
||||
|
||||
def _cache_path(self, lines: List[str], language: str, artist: Optional[str], title: Optional[str]) -> str:
|
||||
payload = {"v": CACHE_VERSION, "model": self.model, "language": language,
|
||||
"lines": lines, "artist": artist, "title": title}
|
||||
digest = hashlib.sha256(json.dumps(payload, ensure_ascii=False).encode()).hexdigest()[:32]
|
||||
return f"{CACHE_PREFIX}/{digest}.json"
|
||||
|
||||
def _cache_get(self, path: str, n: int) -> Optional[List[str]]:
|
||||
try:
|
||||
storage = self._get_storage()
|
||||
if not storage.file_exists(path):
|
||||
return None
|
||||
data = storage.download_json(path)
|
||||
translations = data.get("translations")
|
||||
if isinstance(translations, list) and len(translations) == n:
|
||||
return [str(t) for t in translations]
|
||||
except Exception:
|
||||
logger.warning("lyrics translation cache read failed for %s", path, exc_info=True)
|
||||
return None
|
||||
|
||||
def _cache_put(self, path: str, translations: List[str]) -> None:
|
||||
try:
|
||||
self._get_storage().upload_json(path, {"model": self.model, "translations": translations})
|
||||
except Exception:
|
||||
logger.warning("lyrics translation cache write failed for %s", path, exc_info=True)
|
||||
|
||||
# ---- model ----
|
||||
|
||||
def _call_gemini(self, user_prompt: str) -> Any:
|
||||
from google.genai import types
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=90_000) # 2 attempts: render waits <= ~3 min
|
||||
response = client.models.generate_content(
|
||||
model=self.model,
|
||||
contents=[user_prompt],
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=SYSTEM_PROMPT,
|
||||
temperature=0.3,
|
||||
response_mime_type="application/json",
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"properties": {"translations": {"type": "array", "items": {"type": "string"}}},
|
||||
"required": ["translations"],
|
||||
},
|
||||
),
|
||||
)
|
||||
if response.text is None:
|
||||
raise LyricsTranslationError("model returned an empty response")
|
||||
return json.loads(response.text)
|
||||
|
||||
def _translate_once(self, lines: List[str], language: str, artist, title) -> List[str]:
|
||||
data = self._call_gemini(_user_prompt(lines, language, artist, title))
|
||||
translations = data.get("translations") if isinstance(data, dict) else None
|
||||
if not isinstance(translations, list) or len(translations) != len(lines):
|
||||
got = len(translations) if isinstance(translations, list) else "no"
|
||||
raise LyricsTranslationError(f"expected {len(lines)} translations, got {got}")
|
||||
return [" ".join(str(t).split()) for t in translations]
|
||||
|
||||
def translate_lines(
|
||||
self,
|
||||
lines: List[str],
|
||||
language: str,
|
||||
*,
|
||||
artist: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> List[str]:
|
||||
"""One translation per line (same order). Raises LyricsTranslationError."""
|
||||
lang = normalize_language(language)
|
||||
if lang is None:
|
||||
raise LyricsTranslationError(f"unsupported language {language!r}")
|
||||
if not lines:
|
||||
return []
|
||||
cache_path = self._cache_path(lines, lang, artist, title)
|
||||
cached = self._cache_get(cache_path, len(lines))
|
||||
if cached is not None:
|
||||
logger.info("lyrics translation cache hit (%d lines, %s)", len(lines), lang)
|
||||
return cached
|
||||
|
||||
last_error: Optional[BaseException] = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
started = time.time()
|
||||
translations = self._translate_once(lines, lang, artist, title)
|
||||
logger.info(
|
||||
"lyrics translation: %d lines -> %s via %s in %.1fs",
|
||||
len(lines), lang, self.model, time.time() - started,
|
||||
)
|
||||
self._cache_put(cache_path, translations)
|
||||
return translations
|
||||
except (LyricsTranslationError, ValueError) as exc: # malformed output: retry
|
||||
last_error = exc
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
if note_gemini_failure("lyrics_translation", exc):
|
||||
# Quota/credit/key problem: don't retry; the render goes ahead
|
||||
# without the translation row.
|
||||
raise LyricsTranslationError(
|
||||
"translation service unavailable (Gemini quota/billing) — rendered without translation"
|
||||
) from exc
|
||||
if not _is_transient(exc):
|
||||
raise LyricsTranslationError(f"translation model error: {exc}") from exc
|
||||
last_error = exc
|
||||
if attempt < MAX_ATTEMPTS:
|
||||
backoff = BACKOFF_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
"lyrics translation attempt %d/%d failed (%s); retrying in %.1fs",
|
||||
attempt, MAX_ATTEMPTS, last_error, backoff,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
raise LyricsTranslationError(f"translation failed after {MAX_ATTEMPTS} attempts: {last_error}")
|
||||
|
||||
|
||||
def load_final_segments(storage, job_id: str):
|
||||
"""The reviewed lyric segments the video renders (corrections + review edits)."""
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
|
||||
base = CorrectionResult.from_dict(storage.download_json(f"jobs/{job_id}/lyrics/corrections.json"))
|
||||
updated_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
if storage.file_exists(updated_path):
|
||||
updated = storage.download_json(updated_path)
|
||||
if isinstance(updated, dict) and "corrections" in updated:
|
||||
return CorrectionOperations.update_correction_result_with_data(base, updated).corrected_segments
|
||||
return base.corrected_segments
|
||||
|
||||
|
||||
def prepare_job_translations(
|
||||
job_id: str, job, storage, job_manager=None, service: Optional[LyricsTranslationService] = None
|
||||
) -> Optional[str]:
|
||||
"""Translate a job's final lyrics and store ``translations.json``.
|
||||
|
||||
Returns the GCS path (relative to the bucket) when the video should show
|
||||
translations, else None: no language requested, the song is already in that
|
||||
language, or translation failed. A failure never blocks the render; it's logged as
|
||||
an error and recorded in ``state_data.lyrics_translation`` so an admin can
|
||||
re-render once fixed.
|
||||
"""
|
||||
stored_path = f"jobs/{job_id}/lyrics/{TRANSLATIONS_GCS_NAME}"
|
||||
language = normalize_language(getattr(job, "translation_language", None))
|
||||
if not language:
|
||||
_remove_stale(storage, stored_path)
|
||||
if job_manager is not None and (getattr(job, "state_data", None) or {}).get("lyrics_translation"):
|
||||
# Translation was turned off since a previous render: clear the old outcome
|
||||
# so the republished video isn't labelled "(With Translation into X)".
|
||||
try:
|
||||
job_manager.update_state_data(job_id, "lyrics_translation", {"status": "off"})
|
||||
except Exception:
|
||||
logger.warning(f"[job:{job_id}] could not clear lyrics_translation status", exc_info=True)
|
||||
return None
|
||||
status: Dict[str, Any] = {"language": language}
|
||||
path: Optional[str] = None
|
||||
try:
|
||||
segments = [s for s in load_final_segments(storage, job_id) if (s.text or "").strip()]
|
||||
lines = [s.text.strip() for s in segments]
|
||||
service = service or LyricsTranslationService(storage=storage)
|
||||
translations = service.translate_lines(lines, language, artist=job.artist, title=job.title)
|
||||
status.update(model=service.model, lines=len(lines))
|
||||
if is_same_language(lines, translations):
|
||||
logger.info(f"[job:{job_id}] Lyrics already in {language}; no translation row")
|
||||
status["status"] = "same_language"
|
||||
else:
|
||||
path = stored_path
|
||||
storage.upload_json(path, {
|
||||
"language": language,
|
||||
"language_name": TRANSLATION_LANGUAGES[language],
|
||||
"model": service.model,
|
||||
"lines": [
|
||||
{"segment_id": s.id, "text": line, "translation": tr}
|
||||
for s, line, tr in zip(segments, lines, translations)
|
||||
],
|
||||
})
|
||||
status["status"] = "translated"
|
||||
except Exception as exc:
|
||||
logger.error(f"[job:{job_id}] Lyrics translation to {language} failed; rendering without it: {exc}", exc_info=True)
|
||||
status.update(status="failed", error=str(exc)[:500])
|
||||
path = None
|
||||
if path is None:
|
||||
# The encoder also reads lyrics/translations.json for the portrait video
|
||||
_remove_stale(storage, stored_path)
|
||||
if job_manager is not None:
|
||||
try:
|
||||
job_manager.update_state_data(job_id, "lyrics_translation", status)
|
||||
except Exception:
|
||||
logger.warning(f"[job:{job_id}] could not record lyrics_translation status", exc_info=True)
|
||||
return path
|
||||
|
||||
|
||||
def _remove_stale(storage, path: str) -> None:
|
||||
"""Delete a translations file left by an earlier render (best-effort)."""
|
||||
try:
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
except Exception:
|
||||
logger.warning("could not delete stale %s", path, exc_info=True)
|
||||
@@ -70,9 +70,9 @@ RESPONSE_SCHEMA = {
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
|
||||
return getattr(settings, "match_judge_model", "gemini-3.8-flash")
|
||||
except Exception: # pragma: no cover - config import guard
|
||||
return "gemini-3.5-flash"
|
||||
return "gemini-3.8-flash"
|
||||
|
||||
|
||||
def build_prompts(
|
||||
@@ -149,18 +149,14 @@ async def _default_generate(model: str, system_prompt: str, user_prompt: str) ->
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
import copy
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user_prompt],
|
||||
@@ -169,6 +165,9 @@ def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -19,26 +19,54 @@ from backend.services.match_judge.verdict import (
|
||||
MatchVerdict,
|
||||
)
|
||||
|
||||
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
|
||||
_WS = re.compile(r"\s+")
|
||||
|
||||
# Combining marks are folded only on Latin/Greek/Cyrillic bases, where they're
|
||||
# diacritics ('é' -> 'e'). Elsewhere they carry meaning (Japanese voiced kana,
|
||||
# Indic vowel signs), so they're kept.
|
||||
_DIACRITIC_BASE_MAX = 0x052F
|
||||
|
||||
|
||||
def _fold_accents(text: str) -> str:
|
||||
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
|
||||
decomposed = unicodedata.normalize("NFKD", text)
|
||||
return "".join(c for c in decomposed if not unicodedata.combining(c))
|
||||
"""Drop diacritics so 'Beyoncé' and 'beyonce' compare equal."""
|
||||
out: list[str] = []
|
||||
base_ord = 0
|
||||
for c in unicodedata.normalize("NFKD", text):
|
||||
if unicodedata.combining(c):
|
||||
if base_ord <= _DIACRITIC_BASE_MAX:
|
||||
continue
|
||||
else:
|
||||
base_ord = ord(c)
|
||||
out.append(c)
|
||||
return unicodedata.normalize("NFC", "".join(out))
|
||||
|
||||
|
||||
def _strip_punctuation(text: str) -> str:
|
||||
"""Replace everything but letters, digits, combining marks and whitespace
|
||||
with a space.
|
||||
|
||||
Unicode-aware: an ASCII-only filter here erased all non-Latin text, so every
|
||||
non-Latin song normalized to "" and they all "matched" each other. Marks are
|
||||
kept explicitly because regex ``\\w`` drops them (Indic vowel signs).
|
||||
"""
|
||||
return "".join(
|
||||
c if c.isalnum() or c.isspace() or unicodedata.category(c).startswith("M") else " "
|
||||
for c in text
|
||||
)
|
||||
|
||||
|
||||
def normalize_for_match(text: str) -> str:
|
||||
"""Aggressive key used only for equality comparison (never displayed).
|
||||
|
||||
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
|
||||
Non-Latin letters are preserved. Can return "" (blank/punctuation-only
|
||||
input) — callers must not treat two empty keys as a match.
|
||||
"""
|
||||
s = normalize_text(text or "")
|
||||
s = s.replace("&", " and ")
|
||||
s = _fold_accents(s)
|
||||
s = s.casefold()
|
||||
s = _NON_ALNUM.sub(" ", s)
|
||||
s = _strip_punctuation(s)
|
||||
s = _WS.sub(" ", s).strip()
|
||||
return s
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Free-text song resolution for the kjbox singer search box.
|
||||
|
||||
gen's match judge takes a separate artist + title; a karaoke singer types one
|
||||
line ("the strokes max picu"). One small Gemini call splits the query into
|
||||
artist/title AND corrects typos in the same step, returning the match judge's
|
||||
verdict shape (kind cosmetic/content/ambiguous/none) plus the typed split.
|
||||
|
||||
:func:`resolve_and_tidy` then runs that split through the job flow's own
|
||||
:func:`judge_match` catalog pass, so the singer gets exactly the canonical
|
||||
artist/title gen's AudioSourceStep would "tidy" to (the catalog can't parse a
|
||||
one-line query itself — the AI only does the split + typo fix).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
from backend.services.match_judge.ai import _model
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
from backend.services.match_judge.verdict import KIND_COSMETIC, KIND_NONE, MatchVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
Generate = Callable[[str, str, str], Awaitable[dict]]
|
||||
Judge = Callable[[str, str], Awaitable[MatchVerdict]]
|
||||
|
||||
_VALID_KINDS = {"cosmetic", "content", "ambiguous"}
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You resolve a karaoke singer's free-text song search. The query is one line "
|
||||
"holding an artist and/or a song title in any order, often lazily typed or "
|
||||
"misspelled (e.g. 'the strokes max picu' = The Strokes — Machu Picchu). It may "
|
||||
"instead DESCRIBE the song — where it's from, a line of its lyrics, what it's "
|
||||
"about (e.g. 'that song from titanic' = Céline Dion — My Heart Will Go On; "
|
||||
"'is this the real life' = Queen — Bohemian Rhapsody). Then name the song meant "
|
||||
"(kind 'content'), or use 'ambiguous' with the likely songs when several fit.\n"
|
||||
"Return JSON with: kind, confident, typed_artist, typed_title, canonical_artist, "
|
||||
"canonical_title, alternatives, reason.\n"
|
||||
"typed_artist/typed_title: how the query splits as typed (either may be empty).\n"
|
||||
"kind:\n"
|
||||
" 'cosmetic' – the query already names one real song; only casing/punctuation "
|
||||
"differ.\n"
|
||||
" 'content' – the query names one real song but with typos or a wrong/variant "
|
||||
"title; canonical_* is the song meant.\n"
|
||||
" 'ambiguous' – several real songs are plausible; list them in alternatives.\n"
|
||||
" 'none' – not a recognisable song, or you are not sure.\n"
|
||||
"confident: true only when you are sure which released song is meant. Never "
|
||||
"invent songs; prefer kind='none' when unsure. canonical_artist/canonical_title "
|
||||
"must use official formatting. alternatives is a list of {artist,title} (max 4)."
|
||||
)
|
||||
|
||||
RESPONSE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
|
||||
"confident": {"type": "boolean"},
|
||||
"typed_artist": {"type": "string"},
|
||||
"typed_title": {"type": "string"},
|
||||
"canonical_artist": {"type": "string"},
|
||||
"canonical_title": {"type": "string"},
|
||||
"alternatives": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {"artist": {"type": "string"}, "title": {"type": "string"}},
|
||||
},
|
||||
},
|
||||
"reason": {"type": "string"},
|
||||
},
|
||||
"required": ["kind", "confident"],
|
||||
}
|
||||
|
||||
|
||||
def _none(query: str, reason: str = "no suggestion") -> dict:
|
||||
return {
|
||||
"kind": KIND_NONE, "confident": False, "typed_artist": "", "typed_title": query,
|
||||
"canonical_artist": "", "canonical_title": "", "alternatives": [],
|
||||
"engine": "ai", "reason": reason,
|
||||
}
|
||||
|
||||
|
||||
def verdict_from_response(data: object, query: str) -> dict:
|
||||
"""Validate/normalise the model's JSON into the resolve response shape.
|
||||
Anything malformed (wrong kinds or field types) → kind 'none'."""
|
||||
try:
|
||||
return _verdict_from_response(data, query)
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
return _none(query, "malformed response")
|
||||
|
||||
|
||||
def _verdict_from_response(data: object, query: str) -> dict:
|
||||
if isinstance(data, dict) and data.get("kind") == KIND_NONE:
|
||||
# Not a song the model recognises — keep its split so the catalog can
|
||||
# still find it (resolve_and_tidy).
|
||||
typed_artist, typed_title = data.get("typed_artist"), data.get("typed_title")
|
||||
if (isinstance(typed_artist, str) and isinstance(typed_title, str)
|
||||
and typed_artist.strip() and typed_title.strip()):
|
||||
return {**_none(query, str(data.get("reason") or "no suggestion")),
|
||||
"typed_artist": typed_artist.strip(), "typed_title": typed_title.strip()}
|
||||
return _none(query)
|
||||
if not isinstance(data, dict) or data.get("kind") not in _VALID_KINDS:
|
||||
return _none(query)
|
||||
for key in ("typed_artist", "typed_title", "canonical_artist", "canonical_title", "reason"):
|
||||
if data.get(key) is not None and not isinstance(data[key], str):
|
||||
return _none(query, "malformed response")
|
||||
if data.get("alternatives") is not None and not isinstance(data["alternatives"], list):
|
||||
return _none(query, "malformed response")
|
||||
s = lambda k: str(data.get(k) or "").strip() # noqa: E731
|
||||
alternatives = [
|
||||
{"artist": str(a["artist"]).strip(), "title": str(a["title"]).strip()}
|
||||
for a in (data.get("alternatives") or [])
|
||||
if isinstance(a, dict) and isinstance(a.get("artist"), str) and isinstance(a.get("title"), str)
|
||||
and a["artist"].strip() and a["title"].strip()
|
||||
][:4]
|
||||
canonical_artist, canonical_title = s("canonical_artist"), s("canonical_title")
|
||||
kind = data["kind"]
|
||||
if kind in ("cosmetic", "content") and not (canonical_artist and canonical_title):
|
||||
return _none(query, "incomplete suggestion")
|
||||
if kind == "ambiguous" and not alternatives:
|
||||
return _none(query, "ambiguous without alternatives")
|
||||
return {
|
||||
"kind": kind,
|
||||
"confident": bool(data.get("confident", False)),
|
||||
"typed_artist": s("typed_artist"),
|
||||
"typed_title": s("typed_title") or (query if not s("typed_artist") else ""),
|
||||
"canonical_artist": canonical_artist,
|
||||
"canonical_title": canonical_title,
|
||||
"alternatives": alternatives,
|
||||
"engine": "ai",
|
||||
"reason": s("reason"),
|
||||
}
|
||||
|
||||
|
||||
async def resolve_free_text(query: str, *, generate: Optional[Generate] = None,
|
||||
model: Optional[str] = None) -> dict:
|
||||
"""Split + correct a free-text song query. Never raises: failures → kind 'none'."""
|
||||
try:
|
||||
data = await (generate or _default_generate)(
|
||||
model or _model(), _SYSTEM_PROMPT, f'Singer typed: "{query}"')
|
||||
except Exception as e:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("match_judge_free_text", e)
|
||||
logger.warning(f"resolve_free_text failed: {e}")
|
||||
return _none(query, "unavailable")
|
||||
return verdict_from_response(data, query)
|
||||
|
||||
|
||||
async def resolve_and_tidy(query: str, *, generate: Optional[Generate] = None,
|
||||
judge: Optional[Judge] = None, model: Optional[str] = None) -> dict:
|
||||
"""Free-text split/correct, then gen's catalog tidy (the job flow's fast pass).
|
||||
|
||||
The AI verdict's song — its canonical pick when confident, else the typed
|
||||
split — is checked against the catalog with :func:`judge_match` (stage
|
||||
"fast": catalog only, no second AI call). A confident catalog match wins:
|
||||
its formatting becomes the canonical artist/title, kind "cosmetic" when the
|
||||
query already named that song (only casing/punctuation/word order differ),
|
||||
else "content". No catalog match → the AI verdict unchanged. Never raises.
|
||||
"""
|
||||
verdict = await resolve_free_text(query, generate=generate, model=model)
|
||||
kind = verdict.get("kind")
|
||||
if kind in ("cosmetic", "content") and verdict.get("confident"):
|
||||
artist, title = verdict["canonical_artist"], verdict["canonical_title"]
|
||||
elif kind == KIND_NONE and verdict.get("typed_artist") and verdict.get("typed_title"):
|
||||
artist, title = verdict["typed_artist"], verdict["typed_title"]
|
||||
else:
|
||||
return verdict
|
||||
try:
|
||||
cat = await (judge or _default_judge)(artist, title)
|
||||
except Exception as e:
|
||||
logger.warning(f"resolve_and_tidy catalog pass failed: {e}")
|
||||
# Still answer with the AI verdict, but as a transient result: the
|
||||
# resolve route doesn't cache "unavailable", so the tidy retries later.
|
||||
return {**verdict, "reason": "unavailable"}
|
||||
if not (cat.confident and cat.engine == "catalog" and cat.kind in (KIND_COSMETIC, KIND_NONE)
|
||||
and cat.canonical_artist and cat.canonical_title):
|
||||
return verdict
|
||||
ca, ct = cat.canonical_artist, cat.canonical_title
|
||||
typed = normalize_for_match(query)
|
||||
same_song = typed in (normalize_for_match(f"{ca} {ct}"), normalize_for_match(f"{ct} {ca}"))
|
||||
return {
|
||||
**verdict,
|
||||
"kind": KIND_COSMETIC if same_song else "content",
|
||||
"confident": True,
|
||||
"canonical_artist": ca,
|
||||
"canonical_title": ct,
|
||||
"alternatives": [],
|
||||
"engine": "catalog",
|
||||
"reason": "catalog match",
|
||||
}
|
||||
|
||||
|
||||
async def _default_judge(artist: str, title: str) -> MatchVerdict:
|
||||
from backend.services.match_judge.service import judge_match
|
||||
return await judge_match(artist, title, stage="fast")
|
||||
|
||||
|
||||
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
client = get_genai_client(timeout_ms=int(getattr(settings, "match_judge_timeout_ms", 12000)))
|
||||
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),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -126,7 +126,10 @@ async def judge_match(
|
||||
|
||||
try:
|
||||
return await ai(artist, title, candidates, audio_tier)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("match_judge", exc)
|
||||
# Graceful degradation: returning no-suggestion is a safe fallback (the
|
||||
# user just gets no auto-match). Log at WARNING (with traceback) so a
|
||||
# transient AI blip does not page as a red "new error pattern".
|
||||
|
||||
@@ -134,7 +134,9 @@ def _signature(error_message: str) -> str:
|
||||
return hashlib.sha256((error_message or "").encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, int, Any]:
|
||||
def _should_alert(
|
||||
db: Any, signature: str, now: datetime, throttle_minutes: Optional[int] = None
|
||||
) -> tuple[bool, bool, int, Any]:
|
||||
"""Decide whether to send, WITHOUT yet acknowledging delivery.
|
||||
|
||||
Returns ``(should_send, is_novel, suppressed_since_last, doc_ref)``:
|
||||
@@ -182,7 +184,8 @@ def _should_alert(db: Any, signature: str, now: datetime) -> tuple[bool, bool, i
|
||||
if last_alerted_raw:
|
||||
try:
|
||||
last_alerted = datetime.fromisoformat(last_alerted_raw)
|
||||
within_window = (now - last_alerted) < timedelta(minutes=_throttle_minutes())
|
||||
window = throttle_minutes if throttle_minutes is not None else _throttle_minutes()
|
||||
within_window = (now - last_alerted) < timedelta(minutes=window)
|
||||
except (TypeError, ValueError):
|
||||
within_window = False
|
||||
|
||||
@@ -225,6 +228,50 @@ def _mark_alerted(doc_ref: Any, now: datetime) -> None:
|
||||
logger.debug("ops_alerts: could not record alert delivery: %s", exc)
|
||||
|
||||
|
||||
def send_throttled_ops_alert(key: str, message: str, throttle_minutes: int) -> bool:
|
||||
"""Send an ops alert at most once per ``throttle_minutes`` for ``key``.
|
||||
|
||||
The throttle lives in Firestore (same dedup collection as job-failure
|
||||
alerts), so it holds across every Cloud Run instance and job execution.
|
||||
Fails open (sends) if Firestore is unreachable. Best-effort; never raises.
|
||||
Returns True if an alert was sent.
|
||||
"""
|
||||
try:
|
||||
if not _is_enabled():
|
||||
return False
|
||||
from backend.services.firestore_service import get_firestore_client
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
should_send, _novel, suppressed, doc_ref = _should_alert(
|
||||
get_firestore_client(), key, now, throttle_minutes=throttle_minutes
|
||||
)
|
||||
if not should_send:
|
||||
return False
|
||||
if suppressed:
|
||||
message += f"\n_(Collapsed {suppressed} earlier occurrence(s).)_"
|
||||
sent = send_ops_alert(message)
|
||||
if sent:
|
||||
_mark_alerted(doc_ref, now)
|
||||
return sent
|
||||
except Exception as exc: # noqa: BLE001 - alerting must never raise
|
||||
logger.warning("ops_alerts: throttled alert %s failed: %s", key, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _retry_pending(state_data: dict) -> bool:
|
||||
"""True if state_data.cloud_run_retry_pending is set and unexpired."""
|
||||
pending = (state_data or {}).get("cloud_run_retry_pending")
|
||||
if not isinstance(pending, dict) or not pending.get("expires_at"):
|
||||
return False
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(str(pending["expires_at"]).replace("Z", "+00:00"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
return expires_at > datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def notify_job_failed(
|
||||
db: Any,
|
||||
collection: str,
|
||||
@@ -249,6 +296,8 @@ def notify_job_failed(
|
||||
# Enrich from the job doc (best-effort). We only just wrote it, so this
|
||||
# is a single extra read on the rare FAILED path.
|
||||
artist = title = environment = brand_code = None
|
||||
retry_pending = False
|
||||
error_code = None
|
||||
error_message = (additional_fields or {}).get("error_message") or message or ""
|
||||
try:
|
||||
snap = db.collection(collection).document(job_id).get()
|
||||
@@ -260,6 +309,8 @@ def notify_job_failed(
|
||||
environment = meta.get("environment")
|
||||
state = job.get("state_data") or {}
|
||||
brand_code = state.get("brand_code")
|
||||
retry_pending = _retry_pending(state)
|
||||
error_code = (job.get("error_details") or {}).get("code")
|
||||
if not error_message:
|
||||
error_message = job.get("error_message") or ""
|
||||
except Exception as exc: # noqa: BLE001
|
||||
@@ -269,6 +320,13 @@ def notify_job_failed(
|
||||
logger.debug("ops_alerts: skipping failure alert for %s env job %s", environment, job_id)
|
||||
return False
|
||||
|
||||
# A Cloud Run auto-retry is already queued: this failure is transient
|
||||
# from the user's view (they see "Retrying automatically…"). If the final
|
||||
# attempt also fails, it clears the marker first and alerts then.
|
||||
if retry_pending:
|
||||
logger.info("ops_alerts: skipping failure alert for job %s (auto-retry pending)", job_id)
|
||||
return False
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
signature = _signature(error_message)
|
||||
should_send, is_novel, suppressed, doc_ref = _should_alert(db, signature, now)
|
||||
@@ -276,8 +334,13 @@ def notify_job_failed(
|
||||
return False
|
||||
|
||||
track = " - ".join(p for p in (artist, title) if p) or "(unknown track)"
|
||||
headline = (
|
||||
"🟠 **Audio download stalled** — waiting for the user to keep trying or pick other audio"
|
||||
if error_code == "audio_download_stalled"
|
||||
else "🔴 **Job failed** — near-real-time alert"
|
||||
)
|
||||
lines = [
|
||||
"🔴 **Job failed** — near-real-time alert",
|
||||
headline,
|
||||
f"**Job:** `{job_id}`" + (f" ({brand_code})" if brand_code else ""),
|
||||
f"**Track:** {track}",
|
||||
]
|
||||
|
||||
@@ -59,9 +59,9 @@ RESPONSE_SCHEMA = {
|
||||
def _model() -> str:
|
||||
try:
|
||||
from backend.config import settings
|
||||
return getattr(settings, "parse_titles_model", "gemini-3.5-flash")
|
||||
return getattr(settings, "parse_titles_model", "gemini-3.8-flash")
|
||||
except Exception: # pragma: no cover - config guard
|
||||
return "gemini-3.5-flash"
|
||||
return "gemini-3.8-flash"
|
||||
|
||||
|
||||
def build_prompts(items: list[dict]) -> tuple[str, str]:
|
||||
@@ -123,18 +123,14 @@ async def _default_generate(model: str, system: str, user: str) -> dict:
|
||||
|
||||
|
||||
def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
from backend.services.gemini_client import get_genai_client
|
||||
|
||||
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=settings.google_cloud_project,
|
||||
location="global",
|
||||
http_options=types.HttpOptions(timeout=timeout_ms),
|
||||
)
|
||||
client = get_genai_client(timeout_ms=timeout_ms)
|
||||
response = client.models.generate_content(
|
||||
model=model,
|
||||
contents=[user],
|
||||
@@ -143,6 +139,9 @@ def _blocking_generate(model: str, system: str, user: str) -> dict:
|
||||
response_mime_type="application/json",
|
||||
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
|
||||
temperature=0,
|
||||
# Simple extraction/classification: low thinking keeps cost and
|
||||
# latency down (Gemini 3 Flash defaults to high/dynamic thinking).
|
||||
thinking_config=types.ThinkingConfig(thinking_level="low"),
|
||||
),
|
||||
)
|
||||
return json.loads(response.text)
|
||||
@@ -56,6 +56,9 @@ async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
|
||||
try:
|
||||
results = await ai.ai_parse(chunk, model=model, generate=generate)
|
||||
except Exception as exc:
|
||||
from backend.services.gemini_client import note_gemini_failure
|
||||
|
||||
note_gemini_failure("parse_titles", exc)
|
||||
logger.warning(
|
||||
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
|
||||
return _blanks(chunk)
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
Delete a job's published (distributed) outputs: YouTube video, Dropbox folder,
|
||||
Google Drive files.
|
||||
|
||||
Shared by the track Edit flow (``POST /api/jobs/{id}/edit``) and the admin
|
||||
re-render (``POST /api/admin/jobs/{id}/rerender``). Each helper returns a small
|
||||
result dict (``{"status": "success" | "failed" | "partial" | "skipped" |
|
||||
"error", ...}``) suitable for the job timeline and API responses, and never
|
||||
raises — the caller decides which failures are fatal.
|
||||
|
||||
Brand-code recycling is deliberately NOT done here: Edit recycles the code,
|
||||
the admin re-render keeps it and re-publishes under the same code.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_YOUTUBE_ID_RE = re.compile(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)')
|
||||
|
||||
# state_data keys that point at published outputs.
|
||||
PUBLISHED_OUTPUT_KEYS = ("youtube_url", "dropbox_link", "brand_code", "gdrive_files")
|
||||
|
||||
|
||||
def snapshot_published_outputs(state_data: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""The job's current published-output references (for the timeline/audit)."""
|
||||
state_data = state_data or {}
|
||||
return {key: state_data[key] for key in PUBLISHED_OUTPUT_KEYS if state_data.get(key)}
|
||||
|
||||
|
||||
def youtube_video_id(youtube_url: Optional[str]) -> Optional[str]:
|
||||
match = _YOUTUBE_ID_RE.search(youtube_url or "")
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def delete_youtube_video(job_id: str, youtube_url: Optional[str]) -> Dict[str, Any]:
|
||||
"""Delete the job's YouTube video (via the server-side YouTube credentials)."""
|
||||
if not youtube_url:
|
||||
return {"status": "skipped", "reason": "no youtube_url"}
|
||||
video_id = None
|
||||
try:
|
||||
# Inside the try: a malformed (e.g. non-string) URL must not raise.
|
||||
video_id = youtube_video_id(youtube_url)
|
||||
if not video_id:
|
||||
return {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
|
||||
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from backend.services.youtube_service import get_youtube_service
|
||||
|
||||
youtube_service = get_youtube_service()
|
||||
if not youtube_service.is_configured:
|
||||
return {"status": "skipped", "reason": "YouTube not configured"}
|
||||
finalise = KaraokeFinalise(
|
||||
dry_run=False,
|
||||
non_interactive=True,
|
||||
user_youtube_credentials=youtube_service.get_credentials_dict(),
|
||||
)
|
||||
success = finalise.delete_youtube_video(video_id)
|
||||
return {"status": "success" if success else "failed", "video_id": video_id}
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Error deleting YouTube video {video_id}: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e), "video_id": video_id}
|
||||
|
||||
|
||||
def legacy_dropbox_folder_path(
|
||||
dropbox_path: str, brand_code: str, artist: Optional[str], title: Optional[str]
|
||||
) -> str:
|
||||
"""Raw-name folder (no sanitisation) that older Edit/delete code assumed."""
|
||||
return f"{dropbox_path}/{brand_code} - {artist or 'Unknown'} - {title or 'Unknown'}"
|
||||
|
||||
|
||||
def dropbox_folder_path(dropbox_path: str, brand_code: str, artist: Optional[str], title: Optional[str]) -> str:
|
||||
"""The Dropbox folder the distribution step uploads to (same sanitisation)."""
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
safe_artist = sanitize_filename(artist) if artist else "Unknown"
|
||||
safe_title = sanitize_filename(title) if title else "Unknown"
|
||||
return f"{dropbox_path}/{brand_code} - {safe_artist} - {safe_title}"
|
||||
|
||||
|
||||
def delete_dropbox_folder(
|
||||
job_id: str,
|
||||
dropbox_path: Optional[str],
|
||||
brand_code: Optional[str],
|
||||
artist: Optional[str],
|
||||
title: Optional[str],
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete the job's ``{dropbox_path}/{brand_code} - {Artist} - {Title}`` folder.
|
||||
|
||||
The uploader sanitises artist/title; older code paths assumed the raw names.
|
||||
When the two differ, both are checked and whichever exists is deleted.
|
||||
``success`` (which lets callers recycle the brand code) only when no folder
|
||||
remains; ``deleted`` lists what was removed.
|
||||
"""
|
||||
if not (brand_code and dropbox_path):
|
||||
return {"status": "skipped", "reason": "no brand_code or dropbox_path"}
|
||||
try:
|
||||
from backend.services.dropbox_service import get_dropbox_service
|
||||
|
||||
dropbox = get_dropbox_service()
|
||||
if not dropbox.is_configured:
|
||||
return {"status": "skipped", "reason": "Dropbox not configured"}
|
||||
full_path = dropbox_folder_path(dropbox_path, brand_code, artist, title)
|
||||
legacy_path = legacy_dropbox_folder_path(dropbox_path, brand_code, artist, title)
|
||||
candidates = [full_path] if legacy_path == full_path else [full_path, legacy_path]
|
||||
|
||||
deleted, failed = [], []
|
||||
for path in candidates:
|
||||
if len(candidates) > 1:
|
||||
try:
|
||||
if not dropbox.file_exists(path):
|
||||
continue
|
||||
except Exception as e: # unknown → attempt the delete anyway
|
||||
logger.warning(f"[job:{job_id}] Dropbox existence check failed for {path}: {e}")
|
||||
# delete_folder is True when deleted OR already absent.
|
||||
(deleted if dropbox.delete_folder(path) else failed).append(path)
|
||||
result = {"status": "failed" if failed else "success", "path": full_path, "deleted": deleted}
|
||||
if failed:
|
||||
result["failed"] = failed
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Error deleting Dropbox folder: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
|
||||
def delete_gdrive_files(
|
||||
job_id: str,
|
||||
gdrive_files: Optional[Dict[str, str]],
|
||||
brand_code: Optional[str] = None,
|
||||
cleanup_mirror: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete the job's Google Drive public-share files.
|
||||
|
||||
``cleanup_mirror`` also removes the Nomad 720p master from the GCS
|
||||
fast-sync mirror (kjbox). A re-render that re-publishes under the same brand
|
||||
code skips it: the new upload overwrites the same mirror object, so kjbox
|
||||
keeps the old master until the new one lands instead of losing the song.
|
||||
"""
|
||||
if not gdrive_files:
|
||||
return {"status": "skipped", "reason": "no gdrive_files"}
|
||||
try:
|
||||
from backend.services.gdrive_service import get_gdrive_service
|
||||
|
||||
gdrive = get_gdrive_service()
|
||||
if not gdrive.is_configured:
|
||||
return {"status": "skipped", "reason": "Google Drive not configured"}
|
||||
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
|
||||
delete_results = gdrive.delete_files(file_ids)
|
||||
all_success = all(delete_results.values())
|
||||
if cleanup_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)
|
||||
return {"status": "success" if all_success else "partial", "files": delete_results}
|
||||
except Exception as e:
|
||||
logger.error(f"[job:{job_id}] Error deleting Google Drive files: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e)}
|
||||
@@ -4,10 +4,12 @@ Push Notification Service for Web Push Notifications.
|
||||
Handles sending push notifications to users' browsers/devices using the Web Push protocol.
|
||||
Uses pywebpush library for VAPID authentication and push message encryption.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List
|
||||
|
||||
from google.cloud.firestore_v1 import ArrayRemove
|
||||
from pywebpush import webpush, WebPushException
|
||||
|
||||
from backend.config import get_settings
|
||||
@@ -88,6 +90,26 @@ class PushNotificationService:
|
||||
url: str = "/app/",
|
||||
tag: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
) -> int:
|
||||
"""Async entry point: runs ``send_push_sync`` in a worker thread.
|
||||
|
||||
The body is all blocking I/O (a Firestore read, one ``webpush`` HTTP POST
|
||||
per device, maybe a Firestore update). Running it on the API event loop
|
||||
froze every request on the instance (loop watchdog, 2026-10-13:
|
||||
``push_notification_service.py:166 in send_push`` with a request waiting).
|
||||
"""
|
||||
return await asyncio.to_thread(
|
||||
self.send_push_sync, user_email, title, body, url, tag, tenant_id
|
||||
)
|
||||
|
||||
def send_push_sync(
|
||||
self,
|
||||
user_email: str,
|
||||
title: str,
|
||||
body: str,
|
||||
url: str = "/app/",
|
||||
tag: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None
|
||||
) -> int:
|
||||
"""
|
||||
Send a push notification to a user's subscribed devices for a specific tenant.
|
||||
@@ -191,12 +213,12 @@ class PushNotificationService:
|
||||
|
||||
# Remove invalid subscriptions
|
||||
if invalid_subscriptions:
|
||||
await self._remove_invalid_subscriptions(user_email, invalid_subscriptions)
|
||||
self._remove_invalid_subscriptions(user_email, invalid_subscriptions)
|
||||
|
||||
logger.info(f"Push notifications sent to {success_count}/{len(subscriptions)} devices for {user_email}")
|
||||
return success_count
|
||||
|
||||
async def _remove_invalid_subscriptions(self, user_email: str, endpoints: List[str]) -> None:
|
||||
def _remove_invalid_subscriptions(self, user_email: str, endpoints: List[str]) -> None:
|
||||
"""Remove invalid subscriptions from user's list."""
|
||||
try:
|
||||
user_ref = self.db.collection("gen_users").document(user_email)
|
||||
@@ -207,12 +229,15 @@ class PushNotificationService:
|
||||
user_data = user_doc.to_dict()
|
||||
current_subs = user_data.get("push_subscriptions", [])
|
||||
|
||||
# Filter out invalid subscriptions
|
||||
valid_subs = [s for s in current_subs if s["endpoint"] not in endpoints]
|
||||
stale = [s for s in current_subs if s["endpoint"] in endpoints]
|
||||
|
||||
if len(valid_subs) < len(current_subs):
|
||||
user_ref.update({"push_subscriptions": valid_subs})
|
||||
logger.info(f"Removed {len(current_subs) - len(valid_subs)} invalid subscriptions for {user_email}")
|
||||
if stale:
|
||||
# ArrayRemove deletes exactly these entries server-side, so a device
|
||||
# registered concurrently (add_subscription) isn't overwritten by a
|
||||
# whole-array rewrite. send_push_sync runs in a worker thread, so the
|
||||
# two can now overlap within one instance too.
|
||||
user_ref.update({"push_subscriptions": ArrayRemove(stale)})
|
||||
logger.info(f"Removed {len(stale)} invalid subscriptions for {user_email}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to remove invalid subscriptions: {e}")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Quick (fastgen-style) draft video for kjbox make-it jobs."""
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Quick-version renderer — a scrolling-lyrics 480p karaoke video in seconds.
|
||||
|
||||
Ported from kjbox ``fastgen/fastgen.py`` (the local POC Andrew uses at shows).
|
||||
Given an instrumental (+ optional vocals guide), artist and title, it:
|
||||
|
||||
1. fetches lyrics from LRCLIB (line-synced preferred, plain as fallback);
|
||||
2. lays the lines out as one tall PIL-rendered PNG;
|
||||
3. scrolls that PNG upward with an ffmpeg ``overlay`` whose y expression is a
|
||||
piecewise-linear "sum of ramps" anchored so each synced line reaches the
|
||||
reading row at its sung time (constant crawl when there is no timing);
|
||||
4. muxes it with the instrumental (and the vocals quietly mixed back in as a
|
||||
singer guide) in a single ffmpeg pass.
|
||||
|
||||
Deliberately primitive: no word-level highlighting and no review — it exists
|
||||
so a kjbox singer can sing a song minutes after asking, while the full gen job
|
||||
keeps working toward the proper NOMAD version.
|
||||
|
||||
PIL rather than ffmpeg ``drawtext``: ffmpeg 8's always-on harfbuzz shaping
|
||||
renders a ``.notdef`` box for every newline in a multi-line textfile.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import textwrap
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LRCLIB_BASE = "https://lrclib.net/api"
|
||||
USER_AGENT = "nomadkaraoke-quick-version/1.0 (https://nomadkaraoke.com)"
|
||||
|
||||
_FONT_PATH = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))),
|
||||
"karaoke_gen", "resources", "Montserrat-Bold.ttf",
|
||||
)
|
||||
|
||||
# (text, anchor_seconds | None). Only the first visual row of a lyric line
|
||||
# carries its anchor.
|
||||
TimedLine = Tuple[str, Optional[float]]
|
||||
|
||||
_LRC_RE = re.compile(r"\[(\d+):(\d+(?:\.\d+)?)\]")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Lyrics:
|
||||
kind: str # "synced" | "plain"
|
||||
plain: str
|
||||
timed: Optional[List[Tuple[float, str]]] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class RenderSettings:
|
||||
height: int = 480
|
||||
fps: int = 24
|
||||
wrap: int = 34
|
||||
reading_frac: float = 0.42
|
||||
vocals_level: float = 0.3
|
||||
gap_threshold: float = 5.0
|
||||
gap_lines: int = 1
|
||||
font_path: str = _FONT_PATH
|
||||
|
||||
|
||||
@dataclass
|
||||
class RenderResult:
|
||||
output_path: str
|
||||
lyrics_tier: str # "synced" | "constant" | "none"
|
||||
line_count: int
|
||||
duration_seconds: float
|
||||
extra: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Lyrics
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _strip_lrc_timestamps(synced: str) -> str:
|
||||
return "\n".join(_LRC_RE.sub("", raw).strip() for raw in synced.splitlines()).strip()
|
||||
|
||||
|
||||
def parse_synced(synced: str) -> List[Tuple[float, str]]:
|
||||
"""Parse ``[mm:ss.xx] line`` LRC into sorted (start_seconds, text) pairs.
|
||||
|
||||
A line may carry several timestamps (``[00:10.00][01:10.00] chorus``); each
|
||||
becomes its own entry.
|
||||
"""
|
||||
out: List[Tuple[float, str]] = []
|
||||
for raw in synced.splitlines():
|
||||
stamps = _LRC_RE.findall(raw)
|
||||
if not stamps:
|
||||
continue
|
||||
text = _LRC_RE.sub("", raw).strip()
|
||||
for mins, secs in stamps:
|
||||
out.append((int(mins) * 60 + float(secs), text))
|
||||
out.sort(key=lambda p: p[0])
|
||||
return out
|
||||
|
||||
|
||||
def lyrics_from_lrclib_payload(data: dict) -> Optional[Lyrics]:
|
||||
synced = data.get("syncedLyrics")
|
||||
if synced and synced.strip():
|
||||
timed = parse_synced(synced)
|
||||
if timed:
|
||||
return Lyrics("synced", _strip_lrc_timestamps(synced), timed)
|
||||
plain = data.get("plainLyrics")
|
||||
if plain and plain.strip():
|
||||
return Lyrics("plain", plain)
|
||||
return None
|
||||
|
||||
|
||||
def fetch_lrclib_lyrics(
|
||||
artist: str, title: str, duration: Optional[float], timeout: float = 10.0
|
||||
) -> Optional[Lyrics]:
|
||||
"""Exact ``/get`` (with duration when known), then ``/search`` preferring synced."""
|
||||
session = requests.Session()
|
||||
session.headers["User-Agent"] = USER_AGENT
|
||||
|
||||
params = {"artist_name": artist, "track_name": title}
|
||||
if duration:
|
||||
params["duration"] = int(round(duration))
|
||||
try:
|
||||
r = session.get(f"{LRCLIB_BASE}/get", params=params, timeout=timeout)
|
||||
if r.status_code == 200:
|
||||
got = lyrics_from_lrclib_payload(r.json())
|
||||
if got and got.kind == "synced":
|
||||
return got
|
||||
exact_plain = got
|
||||
else:
|
||||
exact_plain = None
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
logger.warning(f"LRCLIB get failed: {exc}")
|
||||
exact_plain = None
|
||||
|
||||
try:
|
||||
r = session.get(f"{LRCLIB_BASE}/search", params={"q": f"{artist} {title}"}, timeout=timeout)
|
||||
if r.status_code == 200:
|
||||
hits = r.json() or []
|
||||
for hit in sorted(hits, key=lambda h: 0 if h.get("syncedLyrics") else 1):
|
||||
got = lyrics_from_lrclib_payload(hit)
|
||||
if got and got.kind == "synced":
|
||||
return got
|
||||
if got and exact_plain is None:
|
||||
exact_plain = got
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
logger.warning(f"LRCLIB search failed: {exc}")
|
||||
|
||||
return exact_plain
|
||||
|
||||
|
||||
def resolve_timed_lines(lyrics: Optional[Lyrics]) -> Tuple[List[TimedLine], str]:
|
||||
"""Lyrics → (line, anchor|None) pairs + tier label (synced / constant / none)."""
|
||||
if lyrics is None:
|
||||
return [], "none"
|
||||
if lyrics.kind == "synced" and lyrics.timed:
|
||||
return [(text, t) for t, text in lyrics.timed if text.strip()], "synced"
|
||||
return [(raw.strip(), None) for raw in lyrics.plain.splitlines()], "constant"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Layout
|
||||
# --------------------------------------------------------------------------- #
|
||||
def insert_instrumental_gaps(timed_lines: List[TimedLine], threshold: float, gap_lines: int = 1) -> List[TimedLine]:
|
||||
"""Blank spacer rows where consecutive anchored lines are > threshold apart,
|
||||
so the crawl visibly opens up during an instrumental break."""
|
||||
if threshold <= 0:
|
||||
return list(timed_lines)
|
||||
out: List[TimedLine] = []
|
||||
last_t: Optional[float] = None
|
||||
for text, anchor in timed_lines:
|
||||
if anchor is not None:
|
||||
if last_t is not None and anchor - last_t > threshold:
|
||||
out.extend([("", None)] * gap_lines)
|
||||
last_t = anchor
|
||||
out.append((text, anchor))
|
||||
return out
|
||||
|
||||
|
||||
def build_visual_lines(artist: str, title: str, timed_lines: List[TimedLine], wrap: int) -> List[TimedLine]:
|
||||
header: List[TimedLine] = [("", None), ("", None), (artist.upper(), None), (title.upper(), None),
|
||||
("", None), ("", None)]
|
||||
body: List[TimedLine] = []
|
||||
for text, anchor in timed_lines:
|
||||
text = text.strip()
|
||||
if not text:
|
||||
body.append(("", None))
|
||||
continue
|
||||
for i, row in enumerate(textwrap.wrap(text, width=wrap) or [""]):
|
||||
body.append((row, anchor if i == 0 else None))
|
||||
return header + body + [("", None)] * 3
|
||||
|
||||
|
||||
def render_crawl_png(
|
||||
lines: List[TimedLine], width: int, fontsize: int, font_path: str, workdir: str
|
||||
) -> Tuple[str, int, List[float]]:
|
||||
"""Rasterise the whole crawl to one tall PNG → (path, height, row centres)."""
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
font = ImageFont.truetype(font_path, fontsize)
|
||||
ascent, descent = font.getmetrics()
|
||||
line_advance = ascent + descent + round(fontsize * 0.35)
|
||||
stroke = max(2, fontsize // 16)
|
||||
pad = fontsize
|
||||
|
||||
height = pad * 2 + line_advance * len(lines)
|
||||
img = Image.new("RGB", (width, height), (0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
centers: List[float] = []
|
||||
y = pad
|
||||
for text, _anchor in lines:
|
||||
if text:
|
||||
line_w = draw.textlength(text, font=font)
|
||||
draw.text(((width - line_w) / 2, y), text, font=font, fill=(255, 232, 31),
|
||||
stroke_width=stroke, stroke_fill=(0, 0, 0))
|
||||
centers.append(y + line_advance / 2)
|
||||
y += line_advance
|
||||
|
||||
png_path = os.path.join(workdir, "crawl.png")
|
||||
img.save(png_path)
|
||||
return png_path, height, centers
|
||||
|
||||
|
||||
def build_scroll_y_expr(
|
||||
lines: List[TimedLine], centers: List[float], duration: float,
|
||||
frame_h: int, img_h: int, reading_frac: float,
|
||||
) -> Tuple[str, bool]:
|
||||
"""ffmpeg ``overlay`` y expression → (expr, is_time_anchored).
|
||||
|
||||
y is the PNG's top edge relative to the frame top; each anchored line's
|
||||
centre ``c_i`` should sit on the reading row ``R`` at ``t_i`` (y = R - c_i).
|
||||
Piecewise-linear between anchors, written as a flat sum of ramps
|
||||
``Y0 + M0*(t-T0) + Σ (Mk-M[k-1])*max(0,t-Tk)`` with commas escaped for the
|
||||
filtergraph parser.
|
||||
"""
|
||||
reading_row = reading_frac * frame_h
|
||||
pts = [(0.0, float(frame_h))]
|
||||
for (_text, anchor), c in zip(lines, centers):
|
||||
if anchor is not None and 0.0 < anchor < duration:
|
||||
pts.append((float(anchor), reading_row - c))
|
||||
|
||||
timed = len(pts) > 1
|
||||
if timed:
|
||||
pts.append((duration, pts[-1][1]))
|
||||
else:
|
||||
pts.append((duration, -float(img_h)))
|
||||
|
||||
clean = [pts[0]]
|
||||
for t, y in pts[1:]:
|
||||
if t > clean[-1][0] + 1e-3:
|
||||
clean.append((t, y))
|
||||
pts = clean
|
||||
if len(pts) < 2: # degenerate (zero-length audio) — park the crawl off-screen
|
||||
return f"{float(frame_h):.2f}", False
|
||||
|
||||
slopes = [(pts[i + 1][1] - pts[i][1]) / (pts[i + 1][0] - pts[i][0]) for i in range(len(pts) - 1)]
|
||||
terms = [f"{pts[0][1]:.2f}", f"({slopes[0]:.5f})*(t-{pts[0][0]:.3f})"]
|
||||
for k in range(1, len(slopes)):
|
||||
dm = slopes[k] - slopes[k - 1]
|
||||
if abs(dm) < 1e-6:
|
||||
continue
|
||||
terms.append(f"({dm:.5f})*max(0\\,t-{pts[k][0]:.3f})")
|
||||
return "+".join(terms), timed
|
||||
|
||||
|
||||
def build_ffmpeg_cmd(
|
||||
instrumental: str, vocals: Optional[str], vocals_level: float,
|
||||
crawl_png: str, y_expr: str, out_path: str, width: int, height: int, fps: int,
|
||||
duration: float,
|
||||
) -> List[str]:
|
||||
"""Every input and the output are explicitly bounded to ``duration``.
|
||||
|
||||
``-shortest`` alone is NOT enough: ffmpeg 4.4 (the GPU image's Ubuntu 22.04
|
||||
package) never ends when an ``amix`` output is paired with the infinite
|
||||
lavfi colour + looped PNG video — a 20 s song rendered 540 s+ of video until
|
||||
the timeout (prod job 405eed71, 2026-09-28). ffmpeg 8 happens to stop."""
|
||||
dur = f"{max(duration, 0.1):.3f}"
|
||||
overlay = f"[0:v][1:v]overlay=x=(W-w)/2:y={y_expr}[v]"
|
||||
inputs = [
|
||||
"-f", "lavfi", "-i", f"color=c=black:s={width}x{height}:r={fps}:d={dur}",
|
||||
"-loop", "1", "-framerate", str(fps), "-t", dur, "-i", crawl_png,
|
||||
"-i", instrumental,
|
||||
]
|
||||
if vocals and vocals_level > 0:
|
||||
# Faint lead vocal as a singer guide (there is no word highlighting).
|
||||
inputs += ["-i", vocals]
|
||||
audio = (f"[2:a]volume=1[gi];[3:a]volume={vocals_level:.3f}[gv];"
|
||||
f"[gi][gv]amix=inputs=2:normalize=0:duration=first[a]")
|
||||
filt, amap = overlay + ";" + audio, ["-map", "[a]"]
|
||||
else:
|
||||
filt, amap = overlay, ["-map", "2:a"]
|
||||
return [
|
||||
"ffmpeg", "-y", "-hide_banner", "-loglevel", "error", *inputs,
|
||||
"-filter_complex", filt,
|
||||
"-map", "[v]", *amap,
|
||||
"-c:v", "libx264", "-preset", "veryfast", "-crf", "26", "-pix_fmt", "yuv420p",
|
||||
"-c:a", "aac", "-b:a", "192k",
|
||||
"-movflags", "+faststart",
|
||||
"-t", dur,
|
||||
"-shortest",
|
||||
out_path,
|
||||
]
|
||||
|
||||
|
||||
def probe_duration(audio_path: str) -> float:
|
||||
out = subprocess.run(
|
||||
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nk=1:nw=1", audio_path],
|
||||
capture_output=True, text=True, check=True, timeout=60,
|
||||
)
|
||||
return float(out.stdout.strip())
|
||||
|
||||
|
||||
def render_quick_video(
|
||||
*,
|
||||
instrumental_path: str,
|
||||
vocals_path: Optional[str],
|
||||
artist: str,
|
||||
title: str,
|
||||
out_path: str,
|
||||
workdir: str,
|
||||
lyrics: Optional[Lyrics] = None,
|
||||
fetch_lyrics: bool = True,
|
||||
settings: Optional[RenderSettings] = None,
|
||||
ffmpeg_timeout: float = 600.0,
|
||||
) -> RenderResult:
|
||||
"""Render the quick video. ``lyrics`` overrides the LRCLIB fetch."""
|
||||
s = settings or RenderSettings()
|
||||
duration = probe_duration(instrumental_path)
|
||||
|
||||
if lyrics is None and fetch_lyrics:
|
||||
lyrics = fetch_lrclib_lyrics(artist, title, duration)
|
||||
|
||||
timed_lines, tier = resolve_timed_lines(lyrics)
|
||||
if tier == "synced":
|
||||
timed_lines = insert_instrumental_gaps(timed_lines, s.gap_threshold, s.gap_lines)
|
||||
if tier == "none":
|
||||
timed_lines = [("(lyrics unavailable)", None)]
|
||||
|
||||
width = round(s.height * 16 / 9)
|
||||
width += width % 2
|
||||
fontsize = max(18, round(s.height * 0.07))
|
||||
lines = build_visual_lines(artist, title, timed_lines, s.wrap)
|
||||
crawl_png, img_h, centers = render_crawl_png(lines, width, fontsize, s.font_path, workdir)
|
||||
y_expr, _ = build_scroll_y_expr(lines, centers, duration, s.height, img_h, s.reading_frac)
|
||||
|
||||
cmd = build_ffmpeg_cmd(instrumental_path, vocals_path, s.vocals_level, crawl_png, y_expr,
|
||||
out_path, width, s.height, s.fps, duration)
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=ffmpeg_timeout)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"ffmpeg failed ({proc.returncode}): {proc.stderr[-2000:]}")
|
||||
|
||||
return RenderResult(
|
||||
output_path=out_path,
|
||||
lyrics_tier=tier,
|
||||
line_count=sum(1 for t, _ in timed_lines if t.strip()),
|
||||
duration_seconds=duration,
|
||||
)
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Quick version for kjbox make-it jobs — orchestration inside the audio worker.
|
||||
|
||||
The kjbox singer "make it" flow creates a normal gen job, which takes ~30 min
|
||||
(ensemble separation, transcription, lyrics review, render). For those jobs we
|
||||
*also* produce a rough scrolling-lyrics video within a few minutes of the audio
|
||||
landing, so the singer can choose to sing it right away:
|
||||
|
||||
1. ``separate_quick`` — one fast single-model pass on the (already warm) L4,
|
||||
run by the audio worker BEFORE the ensemble.
|
||||
2. ``QuickVersionRender`` — a background thread renders the video (CPU: PIL +
|
||||
ffmpeg) while the GPU runs the ensemble, then uploads it and records
|
||||
``file_urls.quick.video_mp4`` + ``state_data.quick_version``.
|
||||
|
||||
kjbox's GenPoller already reads the job doc and downloads ``file_urls`` entries
|
||||
through ``/api/jobs/{id}/download/{category}/{key}``, so nothing else is needed
|
||||
to deliver it. Every failure here is non-fatal to the full job.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gc
|
||||
import glob
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Dict, Optional, Tuple
|
||||
|
||||
from backend.services.job_notification_service import is_kjbox_job
|
||||
from backend.services.quick_version.renderer import render_quick_video
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STATE_KEY = "quick_version"
|
||||
FILE_CATEGORY = "quick"
|
||||
FILE_KEY = "video_mp4"
|
||||
|
||||
# fastgen's model: a light MDX-Net ONNX (~60 MB), ~10x less compute than a
|
||||
# roformer. The baked roformer (instrumental_clean preset's first model) took
|
||||
# 14 s to load + 124 s to separate a 3:15 song on the L4 (prod, 2026-09-28).
|
||||
# If the ONNX isn't in /models yet, audio-separator downloads it on load
|
||||
# (baked by download_models.py on the next GPU base rebuild). Override with
|
||||
# QUICK_VERSION_MODEL.
|
||||
DEFAULT_QUICK_MODEL = "UVR-MDX-NET-Inst_HQ_4.onnx"
|
||||
# Always baked into the GPU image — used if the default can't be loaded
|
||||
# (e.g. the model download fails).
|
||||
FALLBACK_QUICK_MODEL = "mel_band_roformer_instrumental_fv7z_gabox.ckpt"
|
||||
# Roformer (MDXC) overlap: the library default is 8; 2 is ~4x less compute and
|
||||
# plenty for a draft.
|
||||
QUICK_MDXC_OVERLAP = 2
|
||||
|
||||
STATUS_SEPARATING = "separating"
|
||||
STATUS_RENDERING = "rendering"
|
||||
STATUS_READY = "ready"
|
||||
STATUS_FAILED = "failed"
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def quick_version_enabled() -> bool:
|
||||
return os.environ.get("KJBOX_QUICK_VERSION_ENABLED", "true").strip().lower() not in ("0", "false", "no", "off")
|
||||
|
||||
|
||||
def should_build_quick_version(job: Any) -> bool:
|
||||
"""Only for kjbox jobs, when enabled, and not already delivered (job retries)."""
|
||||
if not quick_version_enabled():
|
||||
return False
|
||||
if not is_kjbox_job(getattr(job, "request_metadata", None)):
|
||||
return False
|
||||
existing = (getattr(job, "state_data", None) or {}).get(STATE_KEY) or {}
|
||||
return existing.get("status") != STATUS_READY
|
||||
|
||||
|
||||
def _classify_output(path: str) -> Optional[str]:
|
||||
"""Map a separator output filename to 'instrumental' / 'vocals' / None."""
|
||||
base = os.path.basename(path).lower()
|
||||
if "quick_instrumental" in base:
|
||||
return "instrumental"
|
||||
if "quick_vocals" in base:
|
||||
return "vocals"
|
||||
tag_start = base.rfind("_(")
|
||||
tag_end = base.find(")", tag_start) if tag_start >= 0 else -1
|
||||
tag = base[tag_start + 2:tag_end] if tag_start >= 0 and tag_end > tag_start else ""
|
||||
if tag in ("instrumental", "no vocal", "no_vocal", "no vocals"):
|
||||
return "instrumental"
|
||||
if tag in ("vocals", "vocal"):
|
||||
return "vocals"
|
||||
return None
|
||||
|
||||
|
||||
def separate_quick(
|
||||
audio_path: str,
|
||||
workdir: str,
|
||||
model_dir: Optional[str],
|
||||
model: Optional[str] = None,
|
||||
separator_factory: Optional[Callable[..., Any]] = None,
|
||||
) -> Tuple[str, Optional[str]]:
|
||||
"""Single-model separation → (instrumental_path, vocals_path|None)."""
|
||||
model = model or os.environ.get("QUICK_VERSION_MODEL") or DEFAULT_QUICK_MODEL
|
||||
if separator_factory is None:
|
||||
from audio_separator.separator import Separator as separator_factory # heavy; lazy
|
||||
|
||||
out_dir = os.path.join(workdir, "quick_stems")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
kwargs: Dict[str, Any] = {
|
||||
"output_dir": out_dir,
|
||||
"output_format": "FLAC",
|
||||
"mdxc_params": {"segment_size": 256, "override_model_segment_size": False,
|
||||
"batch_size": 1, "overlap": QUICK_MDXC_OVERLAP, "pitch_shift": 0},
|
||||
}
|
||||
if model_dir:
|
||||
kwargs["model_file_dir"] = model_dir
|
||||
candidates = [model] + ([FALLBACK_QUICK_MODEL] if model != FALLBACK_QUICK_MODEL else [])
|
||||
sep = None
|
||||
for i, name in enumerate(candidates):
|
||||
try:
|
||||
sep = separator_factory(**kwargs)
|
||||
sep.load_model(model_filename=name)
|
||||
break
|
||||
except Exception as exc:
|
||||
if i == len(candidates) - 1:
|
||||
raise
|
||||
logger.warning(f"Quick model {name} failed to load ({exc}); falling back to {candidates[i + 1]}")
|
||||
outputs = sep.separate(audio_path, {
|
||||
"Instrumental": "quick_instrumental", "Vocals": "quick_vocals",
|
||||
"instrumental": "quick_instrumental", "vocals": "quick_vocals",
|
||||
}) or []
|
||||
|
||||
produced = [o if os.path.isabs(o) else os.path.join(out_dir, o) for o in outputs]
|
||||
produced += glob.glob(os.path.join(out_dir, "*"))
|
||||
inst = vocals = None
|
||||
for p in produced:
|
||||
if not os.path.exists(p):
|
||||
continue
|
||||
kind = _classify_output(p)
|
||||
if kind == "instrumental" and inst is None:
|
||||
inst = p
|
||||
elif kind == "vocals" and vocals is None:
|
||||
vocals = p
|
||||
|
||||
# Free GPU memory before the ensemble loads its models.
|
||||
del sep
|
||||
gc.collect()
|
||||
try:
|
||||
import torch
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.empty_cache()
|
||||
except Exception: # pragma: no cover - torch optional in tests
|
||||
pass
|
||||
|
||||
if inst is None:
|
||||
raise RuntimeError(f"Quick separation produced no instrumental (outputs: {outputs!r})")
|
||||
return inst, vocals
|
||||
|
||||
|
||||
class QuickVersionRender:
|
||||
"""Renders + uploads the quick video on a background thread."""
|
||||
|
||||
def __init__(self, job_id: str, artist: str, title: str, instrumental: str, vocals: Optional[str],
|
||||
workdir: str, job_manager: Any, storage: Any, job_log: Any = None,
|
||||
started_monotonic: Optional[float] = None, separation_seconds: Optional[float] = None):
|
||||
self.job_id = job_id
|
||||
self.artist = artist or "Unknown"
|
||||
self.title = title or "Unknown"
|
||||
self.instrumental = instrumental
|
||||
self.vocals = vocals
|
||||
self.workdir = workdir
|
||||
self.job_manager = job_manager
|
||||
self.storage = storage
|
||||
self.job_log = job_log or logger
|
||||
self.started = started_monotonic or time.monotonic()
|
||||
self.separation_seconds = separation_seconds
|
||||
self.ok: Optional[bool] = None
|
||||
self._thread = threading.Thread(target=self._run, name=f"quick-version-{job_id}", daemon=True)
|
||||
|
||||
def start(self) -> "QuickVersionRender":
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def join(self, timeout: float) -> bool:
|
||||
"""Wait for the render; True if it finished (ok or failed) in time."""
|
||||
self._thread.join(timeout)
|
||||
return not self._thread.is_alive()
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
set_quick_state(self.job_manager, self.job_id, STATUS_RENDERING)
|
||||
render_dir = os.path.join(self.workdir, "quick_render")
|
||||
os.makedirs(render_dir, exist_ok=True)
|
||||
out_path = os.path.join(render_dir, "quick.mp4")
|
||||
t0 = time.monotonic()
|
||||
result = render_quick_video(
|
||||
instrumental_path=self.instrumental, vocals_path=self.vocals,
|
||||
artist=self.artist, title=self.title, out_path=out_path, workdir=render_dir,
|
||||
)
|
||||
render_seconds = time.monotonic() - t0
|
||||
gcs_path = f"jobs/{self.job_id}/quick/quick.mp4"
|
||||
self.storage.upload_file(out_path, gcs_path)
|
||||
self.job_manager.update_file_url(self.job_id, FILE_CATEGORY, FILE_KEY, gcs_path)
|
||||
set_quick_state(
|
||||
self.job_manager, self.job_id, STATUS_READY,
|
||||
lyrics_tier=result.lyrics_tier,
|
||||
line_count=result.line_count,
|
||||
duration_seconds=round(result.duration_seconds, 1),
|
||||
size_bytes=os.path.getsize(out_path),
|
||||
separation_seconds=round(self.separation_seconds, 1) if self.separation_seconds else None,
|
||||
render_seconds=round(render_seconds, 1),
|
||||
worker_seconds=round(time.monotonic() - self.started, 1),
|
||||
ready_at=_now_iso(),
|
||||
)
|
||||
self.ok = True
|
||||
self.job_log.info(
|
||||
f"Quick version ready: tier={result.lyrics_tier} lines={result.line_count} "
|
||||
f"render={render_seconds:.1f}s total={time.monotonic() - self.started:.1f}s"
|
||||
)
|
||||
except Exception as exc:
|
||||
self.ok = False
|
||||
logger.warning(f"[job:{self.job_id}] Quick version render failed (non-fatal): {exc}", exc_info=True)
|
||||
try:
|
||||
self.job_log.warning(f"Quick version render failed (non-fatal): {exc}")
|
||||
except Exception:
|
||||
pass
|
||||
set_quick_state(self.job_manager, self.job_id, STATUS_FAILED, error=str(exc)[:500])
|
||||
|
||||
|
||||
def set_quick_state(job_manager: Any, job_id: str, status: str, **extra: Any) -> None:
|
||||
"""Write ``state_data.quick_version`` (never raises)."""
|
||||
value: Dict[str, Any] = {"status": status, "updated_at": _now_iso()}
|
||||
value.update({k: v for k, v in extra.items() if v is not None})
|
||||
try:
|
||||
job_manager.update_state_data(job_id, STATE_KEY, value)
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning(f"[job:{job_id}] Could not record quick_version state: {exc}")
|
||||
|
||||
|
||||
def start_quick_version(
|
||||
job: Any, audio_path: str, workdir: str, model_dir: Optional[str],
|
||||
job_manager: Any, storage: Any, job_log: Any = None,
|
||||
separator_factory: Optional[Callable[..., Any]] = None,
|
||||
) -> Optional[QuickVersionRender]:
|
||||
"""Run the quick separation (blocking, GPU) and start the render thread.
|
||||
|
||||
Returns the running render (join it before the worker exits) or None when
|
||||
skipped/failed. Never raises.
|
||||
"""
|
||||
job_id = job.job_id
|
||||
try:
|
||||
if not should_build_quick_version(job):
|
||||
return None
|
||||
started = time.monotonic()
|
||||
set_quick_state(job_manager, job_id, STATUS_SEPARATING, started_at=_now_iso())
|
||||
inst, vocals = separate_quick(audio_path, workdir, model_dir, separator_factory=separator_factory)
|
||||
sep_seconds = time.monotonic() - started
|
||||
if job_log:
|
||||
job_log.info(f"Quick separation done in {sep_seconds:.1f}s")
|
||||
return QuickVersionRender(
|
||||
job_id, job.artist, job.title, inst, vocals, workdir, job_manager, storage, job_log,
|
||||
started_monotonic=started, separation_seconds=sep_seconds,
|
||||
).start()
|
||||
except Exception as exc:
|
||||
logger.warning(f"[job:{job_id}] Quick version skipped after error (non-fatal): {exc}", exc_info=True)
|
||||
if job_log:
|
||||
try:
|
||||
job_log.warning(f"Quick version failed (non-fatal): {exc}")
|
||||
except Exception:
|
||||
pass
|
||||
set_quick_state(job_manager, job_id, STATUS_FAILED, error=str(exc)[:500])
|
||||
return None
|
||||
@@ -0,0 +1,367 @@
|
||||
"""
|
||||
Regenerate a completed job's GCS outputs on demand (storage retention).
|
||||
|
||||
The storage-retention job (backend/services/storage_retention.py) purges the big
|
||||
regenerable files of jobs completed >30 days ago — every final except the 720p,
|
||||
the rendered lyrics video, previews and (where the input audio is kept) the
|
||||
separated stems. This service brings them back:
|
||||
|
||||
1. claim the job atomically: COMPLETE -> LYRICS_COMPLETE with
|
||||
``state_data.regen_restore_status = "review_complete"`` (the mechanism shared
|
||||
with the admin/theme re-render and the private->public visibility flow) and
|
||||
the ``state_data.regenerate`` marker;
|
||||
2. trigger the screens worker. If the job's stems were purged
|
||||
(``stems_purged_at``), the screens worker first re-runs audio separation from
|
||||
the job's input (``input_media_gcs_path``, i.e. ``input/edited.flac`` for
|
||||
audio-edited jobs) — see ``backend/workers/screens_worker.py`` stems gate and
|
||||
the audio worker's restore mode;
|
||||
3. screens -> render -> video worker, using the job's EXISTING reviewed lyrics,
|
||||
instrumental selection (custom/uploaded instrumentals are never purged) and
|
||||
style snapshot.
|
||||
|
||||
Unlike the admin re-render this is GCS-ONLY: the video worker skips the whole
|
||||
distribution stage (no YouTube/Dropbox/Google Drive changes, no new brand code,
|
||||
no Discord post) while the marker is active, and keeps the job's published links.
|
||||
The customer is emailed/pushed on completion unless ``notify_customer`` is False.
|
||||
|
||||
``after="change_to_private"`` chains a public->private visibility change once
|
||||
the finals are back (redistribution needs the full finals set).
|
||||
|
||||
Like the admin re-render the marker records the job's ``review_token`` at claim,
|
||||
so a later trip through review retires it; a FAILED regenerate keeps it, so
|
||||
``POST /api/jobs/{id}/retry`` (or another regenerate) resumes it.
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.services.firestore_service import log_to_job
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.theme_rerender_service import (
|
||||
RerenderConflictError,
|
||||
RerenderError,
|
||||
claim_for_rerender,
|
||||
delete_regenerated_artifacts,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REGENERATE_MARKER = "regenerate"
|
||||
_LOG_SOURCE = "regenerate"
|
||||
RATE_LIMIT_COLLECTION = "regenerate_rate_limits"
|
||||
AFTER_CHANGE_TO_PRIVATE = "change_to_private"
|
||||
_ALLOWED_AFTER = {None, AFTER_CHANGE_TO_PRIVATE}
|
||||
|
||||
# Finals the UI / redistribution need; any missing => renders must be regenerated.
|
||||
_REQUIRED_FINAL_KEYS = ("lossy_4k_mp4", "lossy_720p_mp4")
|
||||
|
||||
|
||||
# --- Marker helpers ------------------------------------------------------------
|
||||
|
||||
def raw_regenerate_marker(job) -> Dict[str, Any]:
|
||||
state_data = getattr(job, "state_data", None)
|
||||
marker = state_data.get(REGENERATE_MARKER) if isinstance(state_data, dict) else None
|
||||
return marker if isinstance(marker, dict) else {}
|
||||
|
||||
|
||||
def active_regenerate(job) -> Dict[str, Any]:
|
||||
"""The marker if it belongs to the job's current run (same review_token), else ``{}``."""
|
||||
marker = raw_regenerate_marker(job)
|
||||
if marker and "review_token" in marker:
|
||||
if marker["review_token"] != getattr(job, "review_token", None):
|
||||
return {}
|
||||
return marker
|
||||
|
||||
|
||||
def clear_regenerate_update(job) -> Dict[str, Any]:
|
||||
if raw_regenerate_marker(job):
|
||||
return {f"state_data.{REGENERATE_MARKER}": DELETE_FIELD}
|
||||
return {}
|
||||
|
||||
|
||||
def regenerate_brand_code(job) -> Optional[str]:
|
||||
return active_regenerate(job).get("brand_code") or None
|
||||
|
||||
|
||||
def regenerate_suppresses_notifications(job) -> bool:
|
||||
marker = active_regenerate(job)
|
||||
return bool(marker) and not marker.get("notify_customer", True)
|
||||
|
||||
|
||||
def is_gcs_only_run(job) -> bool:
|
||||
"""True while a regenerate is rebuilding this job's GCS outputs (no distribution)."""
|
||||
return bool(active_regenerate(job))
|
||||
|
||||
|
||||
def renders_missing(job) -> bool:
|
||||
"""True if the job's big finals are gone (purged, or never recorded)."""
|
||||
if getattr(job, "renders_purged_at", None):
|
||||
return True
|
||||
finals = (getattr(job, "file_urls", None) or {}).get("finals") or {}
|
||||
if not isinstance(finals, dict):
|
||||
return True
|
||||
return not all(finals.get(key) for key in _REQUIRED_FINAL_KEYS)
|
||||
|
||||
|
||||
def stems_need_restore(job) -> bool:
|
||||
"""True if the job's separated stems were purged and must be re-separated first.
|
||||
|
||||
Bring-your-own-instrumental and finalise-only jobs never had separated
|
||||
stems to restore.
|
||||
"""
|
||||
if getattr(job, "existing_instrumental_gcs_path", None):
|
||||
return False
|
||||
if getattr(job, "finalise_only", False):
|
||||
return False
|
||||
return bool(getattr(job, "stems_purged_at", None))
|
||||
|
||||
|
||||
# --- Validation ------------------------------------------------------------------
|
||||
|
||||
def _claimable_statuses(job) -> set:
|
||||
statuses = {JobStatus.COMPLETE.value}
|
||||
if active_regenerate(job):
|
||||
statuses.update({JobStatus.FAILED.value, JobStatus.CANCELLED.value})
|
||||
return statuses
|
||||
|
||||
|
||||
def validate_regenerate(job, after: Optional[str] = None) -> Optional[str]:
|
||||
"""Return a reason the job can't be regenerated, or None if it can."""
|
||||
from backend.services.storage_retention import PURGE_IN_PROGRESS_MESSAGE, purge_in_progress
|
||||
|
||||
status = job.status.value if hasattr(job.status, "value") else job.status
|
||||
if status not in _claimable_statuses(job):
|
||||
return f"Only finished tracks can be regenerated (current status: {status})."
|
||||
if getattr(job, "outputs_deleted_at", None):
|
||||
return "This track's outputs were deleted, so it can't be regenerated."
|
||||
if getattr(job, "prep_only", False) or getattr(job, "finalise_only", False):
|
||||
return "This track type can't be regenerated."
|
||||
state_data = job.state_data or {}
|
||||
if state_data.get("visibility_change_in_progress") and after != AFTER_CHANGE_TO_PRIVATE:
|
||||
return "A visibility change is in progress for this track."
|
||||
from backend.services.admin_rerender_service import active_admin_rerender
|
||||
if active_admin_rerender(job) or state_data.get("theme_rerender"):
|
||||
return "This track is already being re-rendered."
|
||||
if purge_in_progress(job):
|
||||
return PURGE_IN_PROGRESS_MESSAGE
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "This track has no instrumental selection to regenerate with."
|
||||
if not ((job.file_urls or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "This track has no reviewed lyrics to regenerate with."
|
||||
if not getattr(job, "input_media_gcs_path", None):
|
||||
return "This track's original audio is no longer available, so it can't be regenerated."
|
||||
if not getattr(job, "theme_id", None):
|
||||
return "This track has no video style to regenerate with."
|
||||
return None
|
||||
|
||||
|
||||
# --- Rate limiting ------------------------------------------------------------------
|
||||
|
||||
def _recent(timestamps: List[str], now: datetime, window: timedelta) -> List[str]:
|
||||
out = []
|
||||
for ts in timestamps or []:
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
continue
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
if now - dt < window:
|
||||
out.append(dt.isoformat())
|
||||
return out
|
||||
|
||||
|
||||
def check_and_record_rate_limit(db, job, user_email: str, settings, now: Optional[datetime] = None) -> Optional[str]:
|
||||
"""Customer limits: N regenerations per job and M per user in a rolling 24h.
|
||||
|
||||
Returns a refusal message, or None (and records the request) if allowed.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = settings or get_settings()
|
||||
now = now or datetime.now(timezone.utc)
|
||||
window = timedelta(hours=24)
|
||||
|
||||
job_recent = _recent((job.state_data or {}).get("regenerate_requests") or [], now, window)
|
||||
if len(job_recent) >= settings.regenerate_max_per_job_per_day:
|
||||
return "This track was regenerated recently. Please try again tomorrow."
|
||||
|
||||
key = hashlib.sha256((user_email or "unknown").strip().lower().encode()).hexdigest()[:32]
|
||||
user_ref = db.collection(RATE_LIMIT_COLLECTION).document(key)
|
||||
|
||||
@firestore.transactional
|
||||
def record(transaction):
|
||||
snap = user_ref.get(transaction=transaction)
|
||||
user_recent = _recent((snap.to_dict() or {}).get("requests") if snap.exists else [], now, window)
|
||||
if len(user_recent) >= settings.regenerate_max_per_user_per_day:
|
||||
return False
|
||||
transaction.set(user_ref, {"requests": user_recent + [now.isoformat()], "updated_at": now})
|
||||
return True
|
||||
|
||||
if not record(db.transaction()):
|
||||
return "You've regenerated several tracks today. Please try again tomorrow."
|
||||
return None
|
||||
|
||||
|
||||
# --- Service ---------------------------------------------------------------------
|
||||
|
||||
class RegenerateService:
|
||||
def __init__(
|
||||
self,
|
||||
job_manager: Optional[JobManager] = None,
|
||||
storage: Optional[StorageService] = None,
|
||||
):
|
||||
self.job_manager = job_manager or JobManager()
|
||||
self.storage = storage or StorageService()
|
||||
|
||||
async def start(
|
||||
self,
|
||||
job,
|
||||
requested_by: str,
|
||||
source: str = "customer",
|
||||
notify_customer: bool = True,
|
||||
after: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Claim the job and kick off the GCS-only regenerate.
|
||||
|
||||
Raises RerenderError (400/500/503) or RerenderConflictError (409).
|
||||
Returns ``{"needs_stems": bool, "brand_code": ...}``.
|
||||
"""
|
||||
if after not in _ALLOWED_AFTER:
|
||||
raise RerenderError(f"Unknown follow-up action: {after}")
|
||||
reason = validate_regenerate(job, after=after)
|
||||
if reason:
|
||||
raise RerenderError(reason)
|
||||
|
||||
job_id = job.job_id
|
||||
input_path = getattr(job, "input_media_gcs_path", None)
|
||||
if not await asyncio.to_thread(self.storage.file_exists, input_path):
|
||||
raise RerenderError(
|
||||
"This track's original audio is no longer available, so it can't be regenerated."
|
||||
)
|
||||
update, context = self._build_claim(job, requested_by, source, notify_customer, after)
|
||||
await asyncio.to_thread(
|
||||
claim_for_rerender, self.job_manager.firestore.db, job_id, update, _claimable_statuses(job),
|
||||
)
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(self._after_claim, job, context)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
except Exception as e:
|
||||
logger.exception(f"[job:{job_id}] Regenerate failed after claim")
|
||||
await asyncio.to_thread(self._fail_run, job_id, f"Regenerate failed to start: {e}", "start_error")
|
||||
raise RerenderError(
|
||||
"The regeneration failed to start. Please try again.", status_code=500,
|
||||
) from e
|
||||
if not triggered:
|
||||
await asyncio.to_thread(
|
||||
self._fail_run, job_id, "Regenerate couldn't start the screens worker.", "screens_trigger_failed",
|
||||
)
|
||||
raise RerenderError("Couldn't start the regeneration. Please try again.", status_code=503)
|
||||
|
||||
await asyncio.to_thread(
|
||||
log_to_job, job_id, _LOG_SOURCE, "INFO",
|
||||
f"Regenerate started by {requested_by} ({source}); stems restore first: {context['needs_stems']}",
|
||||
)
|
||||
return {"needs_stems": context["needs_stems"], "brand_code": context["brand_code"]}
|
||||
|
||||
def _build_claim(self, job, requested_by, source, notify_customer, after):
|
||||
state_data = job.state_data or {}
|
||||
previous = active_regenerate(job)
|
||||
brand_code = state_data.get("brand_code") or previous.get("brand_code")
|
||||
needs_stems = stems_need_restore(job)
|
||||
now = datetime.now(timezone.utc)
|
||||
message = (
|
||||
f"Regenerate requested by {requested_by} ({source}): rebuilding GCS outputs only "
|
||||
f"(no YouTube/Dropbox/Google Drive changes){'; re-separating stems first' if needs_stems else ''}"
|
||||
)
|
||||
# Only customer-triggered runs count towards the customer's daily limit.
|
||||
requests = _recent(state_data.get("regenerate_requests") or [], now, timedelta(hours=24))
|
||||
if source == "customer":
|
||||
requests = requests + [now.isoformat()]
|
||||
update: Dict[str, Any] = {
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"progress": 50,
|
||||
"error_message": None,
|
||||
"error_details": None,
|
||||
"state_data.regen_restore_status": "review_complete",
|
||||
"state_data.audio_complete": True,
|
||||
"state_data.lyrics_complete": True,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"state_data.render_progress": DELETE_FIELD,
|
||||
"state_data.video_progress": DELETE_FIELD,
|
||||
"state_data.encoding_progress": DELETE_FIELD,
|
||||
"state_data.stems_restore": DELETE_FIELD,
|
||||
"state_data.regenerate_requests": requests,
|
||||
f"state_data.{REGENERATE_MARKER}": {
|
||||
"requested_by": requested_by,
|
||||
"requested_at": now.isoformat(),
|
||||
"source": source,
|
||||
"notify_customer": bool(notify_customer),
|
||||
"brand_code": brand_code,
|
||||
"after": after,
|
||||
"needs_stems": needs_stems,
|
||||
"review_token": getattr(job, "review_token", None),
|
||||
},
|
||||
# Stale screens/lyrics video are deleted below; drop their file_urls.
|
||||
"file_urls.screens": DELETE_FIELD,
|
||||
"file_urls.videos.with_vocals": DELETE_FIELD,
|
||||
"updated_at": now,
|
||||
"timeline": ArrayUnion([{
|
||||
"status": JobStatus.LYRICS_COMPLETE.value,
|
||||
"timestamp": now.isoformat(),
|
||||
"message": message,
|
||||
"metadata": {
|
||||
"action": "regenerate_initiated",
|
||||
"initiated_by": requested_by,
|
||||
"source": source,
|
||||
"needs_stems": needs_stems,
|
||||
"after": after,
|
||||
},
|
||||
}]),
|
||||
}
|
||||
if after == AFTER_CHANGE_TO_PRIVATE:
|
||||
update["state_data.visibility_change_in_progress"] = True
|
||||
return update, {"brand_code": brand_code, "needs_stems": needs_stems, "message": message}
|
||||
|
||||
def _after_claim(self, job, context) -> None:
|
||||
log_to_job(job.job_id, _LOG_SOURCE, "INFO", context["message"])
|
||||
delete_regenerated_artifacts(self.storage, job.job_id)
|
||||
|
||||
def _fail_run(self, job_id: str, error: str, reason: str) -> None:
|
||||
logger.error(f"[job:{job_id}] {error}")
|
||||
try:
|
||||
self.job_manager.update_job(job_id, {
|
||||
"status": JobStatus.FAILED.value,
|
||||
"error_message": error,
|
||||
"error_details": {"stage": "regenerate", "reason": reason},
|
||||
"state_data.regen_restore_status": DELETE_FIELD,
|
||||
})
|
||||
log_to_job(job_id, _LOG_SOURCE, "ERROR", error)
|
||||
except Exception:
|
||||
logger.exception(f"[job:{job_id}] Failed to mark regenerate as failed")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REGENERATE_MARKER",
|
||||
"RegenerateService",
|
||||
"RerenderConflictError",
|
||||
"RerenderError",
|
||||
"active_regenerate",
|
||||
"check_and_record_rate_limit",
|
||||
"clear_regenerate_update",
|
||||
"is_gcs_only_run",
|
||||
"regenerate_brand_code",
|
||||
"regenerate_suppresses_notifications",
|
||||
"renders_missing",
|
||||
"stems_need_restore",
|
||||
"validate_regenerate",
|
||||
]
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
First-touch signup attribution (UTM tags + referrer) for gen website signups.
|
||||
|
||||
The frontend (``frontend/lib/attribution.ts``) records the first landing that
|
||||
carried ``utm_*`` params or came from an external site, and sends it with the
|
||||
magic-link request. When that request creates the account, the cleaned values
|
||||
are stored on the user as ``signup_attribution`` and summarised into
|
||||
``signup_source`` so admins can compare channels (signups -> jobs -> paid).
|
||||
|
||||
Everything here is client-supplied, so values are whitelisted, length-capped
|
||||
and stripped of control characters; nothing is trusted beyond "a label".
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Mapping, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ATTRIBUTION_KEYS = (
|
||||
"utm_source",
|
||||
"utm_medium",
|
||||
"utm_campaign",
|
||||
"utm_content",
|
||||
"utm_term",
|
||||
"referrer",
|
||||
"landing_path",
|
||||
"captured_at",
|
||||
)
|
||||
_MAX_VALUE_LEN = 200
|
||||
_CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
|
||||
|
||||
# Gen itself: a referrer from these hosts is in-app navigation, not acquisition.
|
||||
_GEN_HOSTS = ("gen.nomadkaraoke.com", "api.nomadkaraoke.com")
|
||||
|
||||
# Referrer domains folded into one channel label each, so "m.youtube.com" and
|
||||
# "youtu.be" count as the same source as utm_source=youtube.
|
||||
_REFERRER_ALIASES = {
|
||||
"youtube.com": "youtube",
|
||||
"youtu.be": "youtube",
|
||||
"google.com": "google",
|
||||
"bing.com": "bing",
|
||||
"duckduckgo.com": "duckduckgo",
|
||||
"facebook.com": "facebook",
|
||||
"fb.com": "facebook",
|
||||
"instagram.com": "instagram",
|
||||
"reddit.com": "reddit",
|
||||
"t.co": "twitter",
|
||||
"x.com": "twitter",
|
||||
"twitter.com": "twitter",
|
||||
"tiktok.com": "tiktok",
|
||||
"chatgpt.com": "chatgpt",
|
||||
"fiverr.com": "fiverr",
|
||||
"karaokenerds.com": "karaokenerds",
|
||||
# Our sister sites count as channels (cross-product attribution)
|
||||
"decide.nomadkaraoke.com": "decide",
|
||||
"sing.nomadkaraoke.com": "kjbox",
|
||||
"kjbox.cc": "kjbox",
|
||||
"requests.nomadkaraoke.com": "requests_board",
|
||||
"nomadkaraoke.com": "website",
|
||||
}
|
||||
|
||||
|
||||
def _clean(value: object) -> Optional[str]:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
value = _CONTROL_CHARS_RE.sub("", value).strip()
|
||||
return value[:_MAX_VALUE_LEN] or None
|
||||
|
||||
|
||||
def _referrer_domain(referrer: Optional[str]) -> Optional[str]:
|
||||
"""Bare host of a referrer URL or host ("https://www.youtube.com/" -> "youtube.com")."""
|
||||
if not referrer:
|
||||
return None
|
||||
try:
|
||||
host = urlparse(referrer if "//" in referrer else f"//{referrer}").hostname or ""
|
||||
except ValueError: # e.g. a malformed bracketed IPv6 host
|
||||
return None
|
||||
host = host.lower()
|
||||
for prefix in ("www.", "m.", "l.", "lm.", "mobile."):
|
||||
if host.startswith(prefix):
|
||||
host = host[len(prefix):]
|
||||
return host or None
|
||||
|
||||
|
||||
def _is_gen_host(host: str) -> bool:
|
||||
return host in _GEN_HOSTS or host in ("localhost", "127.0.0.1")
|
||||
|
||||
|
||||
def _referrer_channel(host: str) -> str:
|
||||
for domain, label in _REFERRER_ALIASES.items():
|
||||
if host == domain or host.endswith("." + domain):
|
||||
return label
|
||||
# google.co.uk, google.de, ...
|
||||
if re.match(r"^google\.[a-z.]+$", host):
|
||||
return "google"
|
||||
return host
|
||||
|
||||
|
||||
def clean_attribution(raw: Optional[Mapping[str, object]]) -> Optional[Dict[str, str]]:
|
||||
"""Whitelist + sanitise a client-supplied attribution dict.
|
||||
|
||||
Returns None when nothing useful remains (no utm tag and no external referrer),
|
||||
so plain direct signups store nothing.
|
||||
"""
|
||||
if not raw or not isinstance(raw, Mapping):
|
||||
return None
|
||||
cleaned: Dict[str, str] = {}
|
||||
for key in ATTRIBUTION_KEYS:
|
||||
value = _clean(raw.get(key))
|
||||
if value:
|
||||
cleaned[key] = value
|
||||
|
||||
host = _referrer_domain(cleaned.get("referrer"))
|
||||
if host and not _is_gen_host(host):
|
||||
cleaned["referrer"] = host
|
||||
else:
|
||||
cleaned.pop("referrer", None)
|
||||
|
||||
for key in ("utm_source", "utm_medium", "utm_campaign"):
|
||||
if key in cleaned:
|
||||
cleaned[key] = cleaned[key].lower()
|
||||
|
||||
if not any(k in cleaned for k in ("utm_source", "utm_medium", "utm_campaign", "referrer")):
|
||||
return None
|
||||
return cleaned
|
||||
|
||||
|
||||
def derive_signup_source(attribution: Optional[Mapping[str, str]]) -> Optional[str]:
|
||||
"""One channel label for a cleaned attribution: utm_source, else the referrer's channel."""
|
||||
if not attribution:
|
||||
return None
|
||||
if attribution.get("utm_source"):
|
||||
return attribution["utm_source"][:64]
|
||||
host = attribution.get("referrer")
|
||||
if host:
|
||||
return _referrer_channel(host)[:64]
|
||||
return None
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
Restore a job's separated stems after storage retention purged them.
|
||||
|
||||
The storage-retention job deletes the separated stems of old jobs (they're
|
||||
regenerable: re-run separation on the kept input audio) and stamps
|
||||
``stems_purged_at``. Every flow that rebuilds a completed job goes through the
|
||||
screens worker — regenerate, admin re-render, theme re-render, private->public
|
||||
visibility change, Edit — so the screens worker gates on this module: if the
|
||||
job's stems were purged it starts the audio-separation Cloud Run Job in RESTORE
|
||||
mode instead of generating screens, and the audio worker re-triggers the screens
|
||||
worker once the stems are back. Review (Edit flow) and the encoder then find the
|
||||
stems exactly where they always were.
|
||||
|
||||
``state_data.stems_restore = {status: running|failed, attempts, started_at}``
|
||||
tracks the restore; ``attempts`` bounds automatic re-runs.
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STEMS_RESTORE_KEY = "stems_restore"
|
||||
MAX_AUTO_ATTEMPTS = 3
|
||||
STALE_RUNNING_SECONDS = 60 * 60
|
||||
|
||||
NOT_NEEDED = "not_needed"
|
||||
STARTED = "started"
|
||||
IN_PROGRESS = "in_progress"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
def restore_marker(job) -> dict:
|
||||
marker = (getattr(job, "state_data", None) or {}).get(STEMS_RESTORE_KEY)
|
||||
return marker if isinstance(marker, dict) else {}
|
||||
|
||||
|
||||
def _age_seconds(iso: Optional[str]) -> Optional[float]:
|
||||
if not iso:
|
||||
return None
|
||||
try:
|
||||
started = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
if started.tzinfo is None:
|
||||
started = started.replace(tzinfo=timezone.utc)
|
||||
return (datetime.now(timezone.utc) - started).total_seconds()
|
||||
|
||||
|
||||
def is_restore_run(job) -> bool:
|
||||
"""True when the audio worker was started to restore purged stems.
|
||||
|
||||
Keyed on the marker existing (any status), not just ``running``: when a
|
||||
restore attempt fails, Cloud Run retries the task after the worker already
|
||||
marked it failed — that retry must still run in restore mode.
|
||||
"""
|
||||
from backend.services.regenerate_service import stems_need_restore
|
||||
return stems_need_restore(job) and bool(restore_marker(job))
|
||||
|
||||
|
||||
async def maybe_start_stems_restore(job, job_manager, job_log=None) -> str:
|
||||
"""Screens-worker gate. Returns NOT_NEEDED, STARTED, IN_PROGRESS or FAILED."""
|
||||
from backend.services.regenerate_service import stems_need_restore
|
||||
|
||||
if not stems_need_restore(job):
|
||||
return NOT_NEEDED
|
||||
job_id = job.job_id
|
||||
marker = restore_marker(job)
|
||||
if marker.get("status") == "running":
|
||||
age = _age_seconds(marker.get("started_at"))
|
||||
if age is not None and age < STALE_RUNNING_SECONDS:
|
||||
logger.info(f"[job:{job_id}] Stems restore already running; skipping duplicate screens dispatch")
|
||||
job_manager.update_job(job_id, {"state_data.screens_progress": DELETE_FIELD})
|
||||
return IN_PROGRESS
|
||||
attempts = int(marker.get("attempts") or 0)
|
||||
if attempts >= MAX_AUTO_ATTEMPTS:
|
||||
message = (
|
||||
"Couldn't restore this track's audio stems (archived to save space) after "
|
||||
f"{attempts} attempts. Retry the job to try again."
|
||||
)
|
||||
job_manager.update_job(job_id, {"state_data.screens_progress": DELETE_FIELD})
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id, error_message=message,
|
||||
error_details={"stage": "stems_restore", "attempts": attempts},
|
||||
)
|
||||
return FAILED
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
job_manager.update_job(job_id, {
|
||||
f"state_data.{STEMS_RESTORE_KEY}": {
|
||||
"status": "running", "attempts": attempts + 1, "started_at": now,
|
||||
},
|
||||
# This screens dispatch ends here (the restore re-triggers screens), so
|
||||
# drop the "running" idempotency mark /api/internal/workers/screens set —
|
||||
# otherwise the re-trigger is skipped as "already running". Duplicate
|
||||
# dispatches meanwhile are absorbed by the stems_restore marker.
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
"message": "Restoring audio stems",
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
})
|
||||
if job_log is not None:
|
||||
job_log.info("Stems were archived by storage retention: re-running audio separation first")
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_audio_worker(job_id)
|
||||
if not triggered:
|
||||
job_manager.update_job(job_id, {f"state_data.{STEMS_RESTORE_KEY}.status": "failed",
|
||||
"state_data.screens_progress": DELETE_FIELD})
|
||||
job_manager.mark_job_failed(
|
||||
job_id=job_id,
|
||||
error_message="Couldn't start audio separation to restore this track's stems. Retry the job.",
|
||||
error_details={"stage": "stems_restore", "reason": "audio_trigger_failed"},
|
||||
)
|
||||
return FAILED
|
||||
logger.info(f"[job:{job_id}] Stems restore started (attempt {attempts + 1})")
|
||||
return STARTED
|
||||
|
||||
|
||||
async def complete_stems_restore(job_id: str, job_manager) -> bool:
|
||||
"""Audio worker (restore mode) finished: clear the markers and resume screens."""
|
||||
update = {
|
||||
"stems_purged_at": None,
|
||||
f"state_data.{STEMS_RESTORE_KEY}": DELETE_FIELD,
|
||||
"state_data.screens_progress": DELETE_FIELD,
|
||||
}
|
||||
# A Cloud Run task retry succeeded after an earlier attempt marked the job
|
||||
# FAILED: put it back where the restore started so screens can continue.
|
||||
job = job_manager.get_job(job_id)
|
||||
status = getattr(getattr(job, "status", None), "value", getattr(job, "status", None))
|
||||
if status == "failed" and ((getattr(job, "error_details", None) or {}).get("stage")
|
||||
in ("audio_separation", "download_audio", "stems_restore")):
|
||||
update.update({"status": "lyrics_complete", "error_message": None, "error_details": None})
|
||||
job_manager.update_job(job_id, update)
|
||||
from backend.services.worker_service import get_worker_service
|
||||
triggered = await get_worker_service().trigger_screens_worker(job_id)
|
||||
if not triggered:
|
||||
logger.error(f"[job:{job_id}] Stems restored but the screens worker couldn't be triggered")
|
||||
return triggered
|
||||
|
||||
|
||||
def restore_stalled(job, now: Optional[datetime] = None) -> bool:
|
||||
"""A ``running`` restore whose audio job died without reporting back."""
|
||||
marker = restore_marker(job)
|
||||
if marker.get("status") != "running":
|
||||
return False
|
||||
age = _age_seconds(marker.get("started_at"))
|
||||
return age is not None and age > STALE_RUNNING_SECONDS
|
||||
|
||||
|
||||
def mark_restore_failed(job_id: str, job_manager) -> None:
|
||||
try:
|
||||
job_manager.update_job(job_id, {f"state_data.{STEMS_RESTORE_KEY}.status": "failed"})
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception(f"[job:{job_id}] Couldn't mark stems restore failed")
|
||||
@@ -0,0 +1,992 @@
|
||||
"""
|
||||
Storage retention: purge regenerable files from old completed jobs.
|
||||
|
||||
Policy (docs/archive/2026-10-03-gen-storage-retention-plan.md, approved by
|
||||
Andrew 2026-10-03). For jobs completed more than ``min_age_days`` (30) ago:
|
||||
|
||||
KEEP forever
|
||||
- ``input/*`` (incl. ``input/edited.flac``), ``lyrics/**``, ``style/**``,
|
||||
``review_sessions/**``, ``audio_edit*/**``, ``uploads/**``
|
||||
- the 720p final (``finals/*(Final Karaoke Lossy 720p).mp4`` and the
|
||||
canonical ``finals/lossy_720p_mp4.mp4`` copy) — the one ready-made download
|
||||
- ``packages/*`` (CDG/TXT zips), ``screens/*.png|jpg``, ``analysis/*``
|
||||
- user-made instrumentals: ``stems/custom_instrumental.*`` and the staged
|
||||
copies at the job root (``custom_instrumental.*`` / ``existing_instrumental.*``)
|
||||
— they hold user mute edits / uploads, which aren't stored anywhere else
|
||||
- ``stems/vocals_derived.*`` (cheap waveform helper of bring-your-own-
|
||||
instrumental jobs; separation doesn't recreate it)
|
||||
- anything not explicitly on the purge list (unknown files are kept)
|
||||
|
||||
PURGE (regenerated on demand by backend/services/regenerate_service.py)
|
||||
- every other ``finals/*``, ``videos/*``, ``previews/*``, ``encoded/*``,
|
||||
``quick/*.mp4``, ``screens/*.mov``, ``review-audio/*``
|
||||
- separated stems (``stems/*`` apart from the kept ones above) — only when the
|
||||
input audio is still in ``jobs/{id}/`` so separation can be re-run
|
||||
|
||||
Never touched
|
||||
- finalise-only jobs (their videos/screens/stems are user-uploaded SOURCES and
|
||||
they can't be regenerated), jobs whose input audio is gone (nothing could be
|
||||
re-rendered), jobs mid-edit / re-render / visibility change, jobs with a
|
||||
pending deferred YouTube upload, excluded tenants
|
||||
- anything outside ``jobs/{job_id}/``
|
||||
|
||||
The job walks Firestore (it knows each job's type) rather than using a bucket
|
||||
lifecycle rule. It is DRY-RUN by default (settings.storage_retention_dry_run):
|
||||
it then only writes a report (GCS JSON + log summary). Real runs record
|
||||
``renders_purged_at`` / ``stems_purged_at`` + a ``storage_purge`` manifest on the
|
||||
job and drop the purged entries from ``file_urls`` so the UI offers
|
||||
"Regenerate video". Idempotent, batched (``max_jobs``) with a resumable cursor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
POLICY_VERSION = 1
|
||||
REPORT_PREFIX = "storage-retention/reports"
|
||||
# Audit trail of every object deleted (kept forever; never touched by any purge
|
||||
# or lifecycle rule — see docs/STORAGE-RETENTION.md).
|
||||
DELETION_LOG_PREFIX = "storage-retention/deletion-logs"
|
||||
MODE_JOB_PURGE = "job_purge"
|
||||
MODE_ORPHAN = "orphan"
|
||||
ORPHAN_QUIET_DAYS = 30
|
||||
# Firestore collections whose doc id == the jobs/{id}/ folder name and that mean
|
||||
# "this folder still belongs to something". encoding_worker_jobs is NOT one: it's
|
||||
# the encoder's expiring result cache, left behind by deleted jobs.
|
||||
ORPHAN_RECORD_COLLECTIONS = ("jobs", "jobs-dev", "youtube_upload_queue")
|
||||
STATE_COLLECTION = "storage_retention"
|
||||
STATE_DOC = "state"
|
||||
SCAN_PAGE_SIZE = 200
|
||||
# A purge claims the job for this long; a regenerate/edit started meanwhile waits.
|
||||
PURGE_IN_PROGRESS_KEY = "storage_purge_in_progress"
|
||||
PURGE_CLAIM_STALE_SECONDS = 30 * 60
|
||||
|
||||
# Purge categories that count as "renders" (vs stems).
|
||||
RENDER_CATEGORIES = frozenset({
|
||||
"finals", "videos", "previews", "encoded", "quick", "screens_mov", "review_audio",
|
||||
})
|
||||
STEM_CATEGORIES = frozenset({"stems"})
|
||||
|
||||
KEEP = "keep"
|
||||
PURGE = "purge"
|
||||
|
||||
_KEEP_PREFIXES = (
|
||||
"input/", "lyrics/", "style/", "review_sessions/", "audio_edit", "uploads/",
|
||||
"packages/", "analysis/",
|
||||
)
|
||||
_KEPT_STEM_STEMS = ("custom_instrumental", "vocals_derived")
|
||||
_ROOT_INSTRUMENTAL_STEMS = ("custom_instrumental", "existing_instrumental")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------
|
||||
# Policy (pure functions)
|
||||
# --------------------------------------------------------------------------------
|
||||
|
||||
def classify_file(rel_path: str, finalise_only: bool = False, stems_purgeable: bool = True) -> Tuple[str, str]:
|
||||
"""Return ``(KEEP|PURGE, category)`` for a path relative to ``jobs/{job_id}/``."""
|
||||
rel = rel_path.lstrip("/")
|
||||
name = os.path.basename(rel)
|
||||
stem = os.path.splitext(name)[0].lower()
|
||||
ext = os.path.splitext(name)[1].lower()
|
||||
|
||||
if "/" not in rel:
|
||||
if stem in _ROOT_INSTRUMENTAL_STEMS:
|
||||
return KEEP, "user_instrumental"
|
||||
return KEEP, "other"
|
||||
|
||||
top = rel.split("/", 1)[0]
|
||||
if rel.startswith(_KEEP_PREFIXES):
|
||||
return KEEP, top
|
||||
|
||||
if top == "finals":
|
||||
from backend.services.encoding_interface import classify_encoded_output
|
||||
if classify_encoded_output(name) == "mp4_720p":
|
||||
return KEEP, "final_720p"
|
||||
return PURGE, "finals"
|
||||
if top == "videos":
|
||||
# Finalise-only: the user uploaded videos/with_vocals.* (a source file).
|
||||
return (KEEP, "source_video") if finalise_only else (PURGE, "videos")
|
||||
if top == "previews":
|
||||
return PURGE, "previews"
|
||||
if top == "encoded":
|
||||
return PURGE, "encoded"
|
||||
if top == "quick":
|
||||
return (PURGE, "quick") if ext == ".mp4" else (KEEP, "quick_other")
|
||||
if top == "review-audio":
|
||||
return PURGE, "review_audio"
|
||||
if top == "screens":
|
||||
if ext == ".mov":
|
||||
return (KEEP, "source_screen") if finalise_only else (PURGE, "screens_mov")
|
||||
return KEEP, "screens_image"
|
||||
if top == "stems":
|
||||
if stem.startswith(_KEPT_STEM_STEMS):
|
||||
return KEEP, "user_instrumental" if stem.startswith("custom_instrumental") else "stems_kept"
|
||||
if finalise_only:
|
||||
return KEEP, "source_stem"
|
||||
if not stems_purgeable:
|
||||
return KEEP, "stems_unrecoverable"
|
||||
return PURGE, "stems"
|
||||
return KEEP, "other"
|
||||
|
||||
|
||||
def _parse_ts(value: Any) -> Optional[datetime]:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def completed_at(job: Dict[str, Any]) -> Optional[datetime]:
|
||||
"""When the job last completed: the newest ``complete`` timeline entry.
|
||||
|
||||
Every re-render / regenerate / edit appends a new one, so the 30-day window
|
||||
restarts whenever fresh finals are made. Falls back to ``updated_at``.
|
||||
"""
|
||||
latest = None
|
||||
for entry in job.get("timeline") or []:
|
||||
if not isinstance(entry, dict) or entry.get("status") != "complete":
|
||||
continue
|
||||
ts = _parse_ts(entry.get("timestamp"))
|
||||
if ts and (latest is None or ts > latest):
|
||||
latest = ts
|
||||
return latest or _parse_ts(job.get("updated_at"))
|
||||
|
||||
|
||||
def _input_path(job: Dict[str, Any]) -> Optional[str]:
|
||||
# Only input_media_gcs_path: it's what separation, render and regenerate read.
|
||||
path = job.get("input_media_gcs_path")
|
||||
if not isinstance(path, str) or not path:
|
||||
return None
|
||||
if path.startswith("gs://"):
|
||||
path = path.split("/", 3)[-1]
|
||||
return path
|
||||
|
||||
|
||||
def regenerable_reason(job: Dict[str, Any]) -> Optional[str]:
|
||||
"""Why a regenerate of this job couldn't run (so its renders must be kept)."""
|
||||
state_data = job.get("state_data") or {}
|
||||
if not state_data.get("instrumental_selection"):
|
||||
return "no_instrumental_selection"
|
||||
if not ((job.get("file_urls") or {}).get("lyrics") or {}).get("corrections"):
|
||||
return "no_reviewed_lyrics"
|
||||
if not job.get("theme_id"):
|
||||
return "no_theme"
|
||||
return None
|
||||
|
||||
|
||||
def job_skip_reason(
|
||||
job: Dict[str, Any],
|
||||
now: datetime,
|
||||
min_age_days: int,
|
||||
excluded_tenants: Iterable[str] = (),
|
||||
) -> Optional[str]:
|
||||
"""Why this job must not be purged (or None if it's a candidate)."""
|
||||
if job.get("status") != "complete":
|
||||
return "not_complete"
|
||||
if job.get("finalise_only"):
|
||||
return "finalise_only"
|
||||
if job.get("prep_only"):
|
||||
return "prep_only"
|
||||
if job.get("outputs_deleted_at"):
|
||||
return "outputs_deleted"
|
||||
tenant = job.get("tenant_id") or ""
|
||||
if tenant and tenant in set(excluded_tenants):
|
||||
return "excluded_tenant"
|
||||
state_data = job.get("state_data") or {}
|
||||
for marker in ("visibility_change_in_progress", "admin_rerender", "theme_rerender", "regenerate"):
|
||||
if state_data.get(marker):
|
||||
return f"active_{marker}"
|
||||
if state_data.get("youtube_upload_queued"):
|
||||
return "youtube_upload_queued"
|
||||
claim = _parse_ts(state_data.get(PURGE_IN_PROGRESS_KEY))
|
||||
if claim and (now - claim).total_seconds() < PURGE_CLAIM_STALE_SECONDS:
|
||||
return "purge_in_progress"
|
||||
done = completed_at(job)
|
||||
if done is None:
|
||||
return "no_completion_time"
|
||||
if now - done < timedelta(days=min_age_days):
|
||||
return "too_recent"
|
||||
# Only purge what a regenerate could rebuild.
|
||||
reason = regenerable_reason(job)
|
||||
if reason:
|
||||
return f"not_regenerable_{reason}"
|
||||
return None
|
||||
|
||||
|
||||
def purge_in_progress(job) -> bool:
|
||||
"""True while the retention job is deleting this job's files (Job model or dict)."""
|
||||
state_data = job.get("state_data") if isinstance(job, dict) else getattr(job, "state_data", None)
|
||||
claim = _parse_ts((state_data or {}).get(PURGE_IN_PROGRESS_KEY)) if isinstance(state_data, dict) else None
|
||||
return bool(claim) and (datetime.now(timezone.utc) - claim).total_seconds() < PURGE_CLAIM_STALE_SECONDS
|
||||
|
||||
|
||||
PURGE_IN_PROGRESS_MESSAGE = "This track's files are being archived right now. Try again in a few minutes."
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobPlan:
|
||||
job_id: str
|
||||
purge: List[Tuple[str, int, str]] = field(default_factory=list) # (blob path, bytes, category)
|
||||
kept_bytes: int = 0
|
||||
stems_purgeable: bool = True
|
||||
stems_note: Optional[str] = None
|
||||
skip_reason: Optional[str] = None
|
||||
generations: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def purge_bytes(self) -> int:
|
||||
return sum(size for _, size, _ in self.purge)
|
||||
|
||||
def bytes_by_category(self) -> Dict[str, int]:
|
||||
out: Counter = Counter()
|
||||
for _, size, category in self.purge:
|
||||
out[category] += size
|
||||
return dict(out)
|
||||
|
||||
@property
|
||||
def purges_renders(self) -> bool:
|
||||
return any(c in RENDER_CATEGORIES for _, _, c in self.purge)
|
||||
|
||||
@property
|
||||
def purges_stems(self) -> bool:
|
||||
return any(c in STEM_CATEGORIES for _, _, c in self.purge)
|
||||
|
||||
|
||||
def _listing_entries(listing) -> List[Tuple[str, int, Any]]:
|
||||
"""Normalise a listing of ``(name, size)``, ``(name, size, gen)`` or meta dicts."""
|
||||
out = []
|
||||
for item in listing:
|
||||
if isinstance(item, dict):
|
||||
out.append((item["name"], int(item.get("size") or 0), item.get("generation")))
|
||||
elif len(item) >= 3:
|
||||
out.append((item[0], int(item[1] or 0), item[2]))
|
||||
else:
|
||||
out.append((item[0], int(item[1] or 0), None))
|
||||
return out
|
||||
|
||||
|
||||
def plan_job(job: Dict[str, Any], listing) -> JobPlan:
|
||||
"""Decide what to purge for one (already eligible) job from its GCS listing."""
|
||||
job_id = job["job_id"]
|
||||
prefix = f"jobs/{job_id}/"
|
||||
plan = JobPlan(job_id=job_id)
|
||||
entries = _listing_entries(listing)
|
||||
names = {name for name, _, _ in entries}
|
||||
|
||||
# Re-rendering needs the input audio (render worker + separation). If it's
|
||||
# gone (e.g. pre-persistence jobs whose input expired from uploads/), nothing
|
||||
# could ever be regenerated: keep everything.
|
||||
input_path = _input_path(job)
|
||||
if not input_path or not input_path.startswith(prefix) or input_path not in names:
|
||||
plan.skip_reason = "input_unavailable"
|
||||
return plan
|
||||
|
||||
finalise_only = bool(job.get("finalise_only"))
|
||||
# Bring-your-own-instrumental jobs never ran separation, so "re-separate"
|
||||
# isn't part of their pipeline — leave whatever stems they have.
|
||||
if job.get("existing_instrumental_gcs_path"):
|
||||
plan.stems_purgeable = False
|
||||
plan.stems_note = "existing_instrumental"
|
||||
|
||||
for name, size, generation in entries:
|
||||
if not name.startswith(prefix): # defence in depth: never outside jobs/{id}/
|
||||
continue
|
||||
action, category = classify_file(
|
||||
name[len(prefix):], finalise_only=finalise_only, stems_purgeable=plan.stems_purgeable,
|
||||
)
|
||||
if action == PURGE:
|
||||
plan.purge.append((name, size, category))
|
||||
plan.generations[name] = generation
|
||||
else:
|
||||
plan.kept_bytes += size
|
||||
return plan
|
||||
|
||||
|
||||
def assert_deletable(path: str) -> None:
|
||||
"""Hard guard: retention code only ever deletes inside a jobs/{id}/ folder."""
|
||||
parts = path.split("/")
|
||||
if len(parts) < 3 or parts[0] != "jobs" or not parts[1] or path.startswith(DELETION_LOG_PREFIX):
|
||||
raise ValueError(f"refusing to delete outside jobs/{{id}}/: {path}")
|
||||
|
||||
|
||||
def log_category(category: str) -> str:
|
||||
"""Category label used in the deletion log (finals, review-audio, screens-mov, ...)."""
|
||||
return category.replace("_", "-")
|
||||
|
||||
|
||||
class DeletionLog:
|
||||
"""Append-only JSONL audit log of one run's deletions, flushed to GCS in batches.
|
||||
|
||||
``storage-retention/deletion-logs/<run-ts>-<mode>.jsonl`` holds one line per
|
||||
attempted delete; it is re-uploaded (whole) after every batch so a crash
|
||||
mid-run still leaves a complete record of what was deleted up to the last
|
||||
flush (the batch in flight is at most ``flush_every`` lines / one job).
|
||||
"""
|
||||
|
||||
def __init__(self, storage, run_ts: datetime, mode: str, flush_every: int = 200):
|
||||
self.storage = storage
|
||||
self.mode = mode
|
||||
self.run_id = f"{run_ts.strftime('%Y%m%dT%H%M%SZ')}-{mode}"
|
||||
self.path = f"{DELETION_LOG_PREFIX}/{self.run_id}.jsonl"
|
||||
self.summary_path = f"{DELETION_LOG_PREFIX}/{self.run_id}.summary.json"
|
||||
self.flush_every = flush_every
|
||||
self._lines: List[str] = []
|
||||
self._unflushed = 0
|
||||
self.totals: Counter = Counter()
|
||||
self.counts: Counter = Counter()
|
||||
self.failures = 0
|
||||
self.jobs: set = set()
|
||||
# Set when the audit log couldn't be written: callers stop deleting.
|
||||
self.flush_error: Optional[str] = None
|
||||
|
||||
def record(self, job_id: str, path: str, size: int, generation, category: str,
|
||||
result: str, error: Optional[str] = None) -> None:
|
||||
import json
|
||||
entry = {
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"run_id": self.run_id,
|
||||
"mode": self.mode,
|
||||
"job_id": job_id,
|
||||
"path": path,
|
||||
"size_bytes": int(size or 0),
|
||||
"generation": str(generation) if generation is not None else None,
|
||||
"category": category,
|
||||
"result": result,
|
||||
}
|
||||
if error:
|
||||
entry["error"] = error[:500]
|
||||
self._lines.append(json.dumps(entry, ensure_ascii=False))
|
||||
self._unflushed += 1
|
||||
if result == "deleted":
|
||||
self.totals[category] += int(size or 0)
|
||||
self.counts[category] += 1
|
||||
self.jobs.add(job_id)
|
||||
elif result == "failed":
|
||||
self.failures += 1
|
||||
if self._unflushed >= self.flush_every:
|
||||
self.flush()
|
||||
|
||||
def flush(self) -> None:
|
||||
if not self._lines:
|
||||
return
|
||||
try:
|
||||
self.storage.upload_text(self.path, "\n".join(self._lines) + "\n", content_type="application/x-ndjson")
|
||||
self._unflushed = 0
|
||||
self.flush_error = None
|
||||
except Exception as e: # noqa: BLE001 - recorded; the run stops deleting
|
||||
self.flush_error = str(e)
|
||||
logger.error(f"storage retention: deletion log flush failed ({self.path}): {e}")
|
||||
|
||||
def write_summary(self, extra: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
summary = {
|
||||
"run_id": self.run_id,
|
||||
"mode": self.mode,
|
||||
"deletion_log": self.path,
|
||||
"objects_deleted": sum(self.counts.values()),
|
||||
"jobs": len(self.jobs),
|
||||
"bytes_deleted": sum(self.totals.values()),
|
||||
"gib_deleted": round(sum(self.totals.values()) / 2**30, 3),
|
||||
"bytes_by_category": dict(self.totals),
|
||||
"objects_by_category": dict(self.counts),
|
||||
"failures": self.failures,
|
||||
"log_flush_error": self.flush_error,
|
||||
"written_at": datetime.now(timezone.utc).isoformat(),
|
||||
**(extra or {}),
|
||||
}
|
||||
self.flush()
|
||||
try:
|
||||
self.storage.upload_json(self.summary_path, summary)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"storage retention: summary write failed ({self.summary_path}): {e}")
|
||||
return summary
|
||||
|
||||
|
||||
def orphan_candidates(entries: Iterable[Dict[str, Any]], known_ids: set) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""Group ``jobs/{id}/...`` objects whose id has no job record."""
|
||||
folders: Dict[str, List[Dict[str, Any]]] = {}
|
||||
for meta in entries:
|
||||
parts = meta["name"].split("/")
|
||||
if len(parts) < 3 or parts[0] != "jobs" or not parts[1]:
|
||||
continue
|
||||
if parts[1] in known_ids:
|
||||
continue
|
||||
folders.setdefault(parts[1], []).append(meta)
|
||||
return folders
|
||||
|
||||
|
||||
def plan_orphan_folder(job_id: str, objects: List[Dict[str, Any]], now: datetime,
|
||||
quiet_days: int = ORPHAN_QUIET_DAYS) -> Dict[str, Any]:
|
||||
"""Keep ``input/``; everything else in an orphan folder is deleted (if quiet)."""
|
||||
prefix = f"jobs/{job_id}/"
|
||||
latest = None
|
||||
for meta in objects:
|
||||
updated = _parse_ts(meta.get("updated"))
|
||||
if updated and (latest is None or updated > latest):
|
||||
latest = updated
|
||||
keep, purge = [], []
|
||||
for meta in objects:
|
||||
if not meta["name"].startswith(prefix):
|
||||
continue
|
||||
(keep if meta["name"][len(prefix):].startswith("input/") else purge).append(meta)
|
||||
skip = None
|
||||
if latest is None or now - latest < timedelta(days=quiet_days):
|
||||
skip = "recently_modified"
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"latest_update": latest.isoformat() if latest else None,
|
||||
"skip_reason": skip,
|
||||
"purge": purge,
|
||||
"keep": keep,
|
||||
"purge_bytes": sum(int(m.get("size") or 0) for m in purge),
|
||||
"keep_bytes": sum(int(m.get("size") or 0) for m in keep),
|
||||
}
|
||||
|
||||
|
||||
def file_url_deletions(file_urls: Dict[str, Any], purged_paths: Iterable[str]) -> List[str]:
|
||||
"""Firestore field paths under ``file_urls`` that reference purged blobs."""
|
||||
purged = set(purged_paths)
|
||||
|
||||
def norm(value: str) -> str:
|
||||
return value.split("/", 3)[-1] if value.startswith("gs://") else value
|
||||
|
||||
out: List[str] = []
|
||||
for category, entries in (file_urls or {}).items():
|
||||
if isinstance(entries, dict):
|
||||
for key, value in entries.items():
|
||||
if isinstance(value, str) and norm(value) in purged and _safe_key(category) and _safe_key(key):
|
||||
out.append(f"file_urls.{category}.{key}")
|
||||
elif isinstance(entries, str) and norm(entries) in purged and _safe_key(category):
|
||||
out.append(f"file_urls.{category}")
|
||||
return out
|
||||
|
||||
|
||||
_SAFE_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
|
||||
def _safe_key(key: str) -> bool:
|
||||
return bool(_SAFE_KEY.match(str(key)))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------
|
||||
# Service
|
||||
# --------------------------------------------------------------------------------
|
||||
|
||||
def _run_in_transaction(db, fn):
|
||||
"""Run ``fn(transaction)`` in a Firestore transaction (retried on contention)."""
|
||||
from google.cloud import firestore
|
||||
return firestore.transactional(fn)(db.transaction())
|
||||
|
||||
|
||||
_PROJECTION = [
|
||||
"job_id", "status", "timeline", "updated_at", "finalise_only", "prep_only", "theme_id",
|
||||
"storage_purge.status", "state_data.instrumental_selection",
|
||||
"outputs_deleted_at", "tenant_id", "input_media_gcs_path", "file_urls",
|
||||
"existing_instrumental_gcs_path", "renders_purged_at", "stems_purged_at",
|
||||
"state_data.visibility_change_in_progress", "state_data.admin_rerender",
|
||||
"state_data.theme_rerender", "state_data.regenerate",
|
||||
"state_data.youtube_upload_queued", f"state_data.{PURGE_IN_PROGRESS_KEY}",
|
||||
]
|
||||
|
||||
|
||||
class StorageRetentionService:
|
||||
def __init__(self, db=None, storage=None, settings=None, job_manager=None):
|
||||
from backend.config import get_settings
|
||||
self.settings = settings or get_settings()
|
||||
if storage is None:
|
||||
from backend.services.storage_service import StorageService
|
||||
storage = StorageService()
|
||||
self.storage = storage
|
||||
if db is None:
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
db = FirestoreService().db
|
||||
self.db = db
|
||||
self._job_manager = job_manager
|
||||
|
||||
@property
|
||||
def jobs_collection(self):
|
||||
return self.db.collection(self.settings.firestore_collection)
|
||||
|
||||
# --- run ----------------------------------------------------------------------
|
||||
|
||||
def run(
|
||||
self,
|
||||
dry_run: Optional[bool] = None,
|
||||
job_ids: Optional[List[str]] = None,
|
||||
max_jobs: Optional[int] = None,
|
||||
min_age_days: Optional[int] = None,
|
||||
include_orphans: bool = False,
|
||||
report_path: Optional[str] = None,
|
||||
now: Optional[datetime] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Plan (and unless dry-run, execute) one retention pass. Returns the report.
|
||||
|
||||
- ``dry_run`` defaults to settings.storage_retention_dry_run (True).
|
||||
- ``job_ids`` scopes the pass to those jobs (no cursor).
|
||||
- Dry runs without ``max_jobs`` cover every completed job (full report);
|
||||
real runs purge at most ``max_jobs`` (settings default) per pass,
|
||||
resuming from the stored cursor.
|
||||
"""
|
||||
started = time.time()
|
||||
now = now or datetime.now(timezone.utc)
|
||||
dry_run = self.settings.storage_retention_dry_run if dry_run is None else bool(dry_run)
|
||||
min_age = self.settings.storage_retention_min_age_days if min_age_days is None else int(min_age_days)
|
||||
excluded = [t.strip() for t in (self.settings.storage_retention_excluded_tenants or "").split(",") if t.strip()]
|
||||
if max_jobs is None and not dry_run and not job_ids:
|
||||
max_jobs = self.settings.storage_retention_max_jobs_per_run
|
||||
use_cursor = not job_ids and not dry_run
|
||||
|
||||
report: Dict[str, Any] = {
|
||||
"policy_version": POLICY_VERSION,
|
||||
"dry_run": dry_run,
|
||||
"started_at": now.isoformat(),
|
||||
"min_age_days": min_age,
|
||||
"max_jobs": max_jobs,
|
||||
"excluded_tenants": excluded,
|
||||
"scoped_job_ids": job_ids or None,
|
||||
"jobs": [],
|
||||
"skipped": Counter(),
|
||||
"errors": [],
|
||||
}
|
||||
totals: Counter = Counter()
|
||||
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_JOB_PURGE)
|
||||
if deletion_log:
|
||||
report["deletion_log"] = deletion_log.path
|
||||
report["deletion_summary"] = deletion_log.summary_path
|
||||
processed = 0
|
||||
scanned = 0
|
||||
last_id = None
|
||||
exhausted = True
|
||||
|
||||
for job in self._iter_jobs(job_ids, use_cursor):
|
||||
if max_jobs is not None and processed >= max_jobs:
|
||||
exhausted = False
|
||||
break
|
||||
scanned += 1
|
||||
last_id = job.get("job_id")
|
||||
reason = job_skip_reason(job, now, min_age, excluded)
|
||||
if reason is None and self._already_purged(job):
|
||||
reason = "already_purged"
|
||||
if reason:
|
||||
report["skipped"][reason] += 1
|
||||
continue
|
||||
try:
|
||||
listing = self.storage.list_blob_meta(f"jobs/{job['job_id']}/")
|
||||
plan = plan_job(job, listing)
|
||||
except Exception as e: # noqa: BLE001 - one bad job never stops the pass
|
||||
logger.exception(f"[job:{job.get('job_id')}] storage retention: planning failed")
|
||||
report["errors"].append({"job_id": job.get("job_id"), "error": str(e)})
|
||||
continue
|
||||
if plan.skip_reason:
|
||||
report["skipped"][plan.skip_reason] += 1
|
||||
continue
|
||||
if not plan.purge:
|
||||
report["skipped"]["nothing_to_purge"] += 1
|
||||
continue
|
||||
|
||||
entry = {
|
||||
"job_id": plan.job_id,
|
||||
"tenant_id": job.get("tenant_id") or None,
|
||||
"completed_at": (completed_at(job) or now).isoformat(),
|
||||
"purge_bytes": plan.purge_bytes,
|
||||
"kept_bytes": plan.kept_bytes,
|
||||
"bytes_by_category": plan.bytes_by_category(),
|
||||
"stems_kept_reason": plan.stems_note,
|
||||
"files": [{"path": p, "bytes": s, "category": c} for p, s, c in plan.purge],
|
||||
}
|
||||
if not dry_run:
|
||||
try:
|
||||
entry["result"] = self._execute(job["job_id"], plan, now, min_age, excluded, deletion_log)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception(f"[job:{plan.job_id}] storage retention: purge failed")
|
||||
entry["result"] = {"status": "error", "error": str(e)}
|
||||
report["errors"].append({"job_id": plan.job_id, "error": str(e)})
|
||||
report["jobs"].append(entry)
|
||||
if deletion_log and deletion_log.flush_error:
|
||||
# The audit log is a required safety record: no more deletes.
|
||||
report["errors"].append({"job_id": plan.job_id,
|
||||
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
|
||||
exhausted = False
|
||||
break
|
||||
if not dry_run and entry["result"].get("status") != "purged":
|
||||
continue
|
||||
processed += 1
|
||||
for category, size in plan.bytes_by_category().items():
|
||||
totals[category] += size
|
||||
|
||||
if use_cursor:
|
||||
self._save_cursor(None if exhausted else last_id)
|
||||
if deletion_log:
|
||||
report["deletion_totals"] = deletion_log.write_summary(
|
||||
{"report_path": report_path or self.default_report_path(now, dry_run)})
|
||||
|
||||
report["skipped"] = dict(report["skipped"])
|
||||
report["summary"] = {
|
||||
"jobs_scanned": scanned,
|
||||
"jobs_to_purge" if dry_run else "jobs_purged": processed,
|
||||
"bytes_total": sum(totals.values()),
|
||||
"gib_total": round(sum(totals.values()) / 2**30, 2),
|
||||
"gib_by_category": {k: round(v / 2**30, 2) for k, v in sorted(totals.items())},
|
||||
"bytes_by_category": dict(totals),
|
||||
"duration_seconds": round(time.time() - started, 1),
|
||||
}
|
||||
if include_orphans:
|
||||
try:
|
||||
report["orphans"] = self.orphan_job_folders()
|
||||
except Exception as e: # noqa: BLE001
|
||||
report["orphans"] = {"error": str(e)}
|
||||
|
||||
report["report_path"] = report_path or self.default_report_path(now, dry_run)
|
||||
try:
|
||||
self.storage.upload_json(report["report_path"], report)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"storage retention: failed to write report {report['report_path']}: {e}")
|
||||
report["report_write_error"] = str(e)
|
||||
s = report["summary"]
|
||||
logger.info(
|
||||
f"STORAGE_RETENTION {'DRY-RUN' if dry_run else 'RUN'} complete: scanned={scanned} "
|
||||
f"{'would_purge' if dry_run else 'purged'}={processed} jobs, {s['gib_total']} GiB "
|
||||
f"by_category={s['gib_by_category']} skipped={report['skipped']} "
|
||||
f"errors={len(report['errors'])} report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
|
||||
)
|
||||
return report
|
||||
|
||||
@staticmethod
|
||||
def default_report_path(now: datetime, dry_run: bool) -> str:
|
||||
return f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-{'dry-run' if dry_run else 'run'}.json"
|
||||
|
||||
# --- helpers ------------------------------------------------------------------
|
||||
|
||||
def _already_purged(self, job: Dict[str, Any]) -> bool:
|
||||
"""Skip the GCS listing for jobs already purged since their last completion."""
|
||||
if ((job.get("storage_purge") or {}).get("status")) == "pending":
|
||||
return False # an interrupted purge: finish it
|
||||
renders = _parse_ts(job.get("renders_purged_at"))
|
||||
if not renders:
|
||||
return False
|
||||
done = completed_at(job)
|
||||
if done and done > renders:
|
||||
return False # regenerated since — eligible again after its own window
|
||||
stems = _parse_ts(job.get("stems_purged_at"))
|
||||
stems_done = stems is not None or bool(job.get("existing_instrumental_gcs_path"))
|
||||
return stems_done
|
||||
|
||||
def _iter_jobs(self, job_ids: Optional[List[str]], use_cursor: bool):
|
||||
if job_ids:
|
||||
for job_id in job_ids:
|
||||
snap = self.jobs_collection.document(job_id).get()
|
||||
if snap.exists:
|
||||
data = snap.to_dict() or {}
|
||||
data.setdefault("job_id", snap.id)
|
||||
yield data
|
||||
return
|
||||
|
||||
from google.cloud.firestore_v1.base_query import FieldFilter
|
||||
|
||||
cursor = self._load_cursor() if use_cursor else None
|
||||
while True:
|
||||
query = (
|
||||
self.jobs_collection
|
||||
.where(filter=FieldFilter("status", "==", "complete"))
|
||||
.order_by("__name__")
|
||||
.select(_PROJECTION)
|
||||
.limit(SCAN_PAGE_SIZE)
|
||||
)
|
||||
if cursor:
|
||||
query = query.start_after({"__name__": self.jobs_collection.document(cursor)})
|
||||
docs = list(query.stream())
|
||||
for snap in docs:
|
||||
data = snap.to_dict() or {}
|
||||
data.setdefault("job_id", snap.id)
|
||||
data["job_id"] = data.get("job_id") or snap.id
|
||||
yield data
|
||||
if len(docs) < SCAN_PAGE_SIZE:
|
||||
return
|
||||
cursor = docs[-1].id
|
||||
|
||||
def _state_ref(self):
|
||||
return self.db.collection(STATE_COLLECTION).document(STATE_DOC)
|
||||
|
||||
def _load_cursor(self) -> Optional[str]:
|
||||
try:
|
||||
snap = self._state_ref().get()
|
||||
return (snap.to_dict() or {}).get("cursor_job_id") if snap.exists else None
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"storage retention: couldn't load cursor: {e}")
|
||||
return None
|
||||
|
||||
def _save_cursor(self, job_id: Optional[str]) -> None:
|
||||
try:
|
||||
self._state_ref().set(
|
||||
{"cursor_job_id": job_id, "updated_at": datetime.now(timezone.utc)}, merge=True,
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning(f"storage retention: couldn't save cursor: {e}")
|
||||
|
||||
def _claim(self, job_id: str, plan: "JobPlan", now: datetime, min_age: int, excluded: List[str]) -> bool:
|
||||
"""Atomically re-check eligibility on the live doc and mark the purge in progress.
|
||||
|
||||
The purge markers (``renders_purged_at`` / ``stems_purged_at``) and a
|
||||
PENDING manifest are written HERE, before anything is deleted: if the
|
||||
run dies mid-way, regenerate still knows to rebuild (and re-separate),
|
||||
and the next pass finishes the job (``storage_purge.status == pending``).
|
||||
"""
|
||||
ref = self.jobs_collection.document(job_id)
|
||||
|
||||
def claim(transaction):
|
||||
snap = ref.get(transaction=transaction)
|
||||
if not snap.exists:
|
||||
return False
|
||||
data = snap.to_dict() or {}
|
||||
data.setdefault("job_id", job_id)
|
||||
if job_skip_reason(data, now, min_age, excluded):
|
||||
return False
|
||||
update: Dict[str, Any] = {
|
||||
f"state_data.{PURGE_IN_PROGRESS_KEY}": now.isoformat(),
|
||||
"storage_purge": {
|
||||
"status": "pending",
|
||||
"started_at": now.isoformat(),
|
||||
"policy_version": POLICY_VERSION,
|
||||
"planned_bytes": plan.purge_bytes,
|
||||
"planned_files": len(plan.purge),
|
||||
},
|
||||
}
|
||||
if plan.purges_renders:
|
||||
update["renders_purged_at"] = now
|
||||
if plan.purges_stems:
|
||||
update["stems_purged_at"] = now
|
||||
transaction.update(ref, update)
|
||||
return True
|
||||
|
||||
return _run_in_transaction(self.db, claim)
|
||||
|
||||
def _execute(self, job_id: str, plan: JobPlan, now: datetime, min_age: int, excluded: List[str],
|
||||
deletion_log: Optional["DeletionLog"] = None) -> Dict[str, Any]:
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD
|
||||
|
||||
if not self._claim(job_id, plan, now, min_age, excluded):
|
||||
return {"status": "skipped", "reason": "no_longer_eligible"}
|
||||
|
||||
ref = self.jobs_collection.document(job_id)
|
||||
deleted: List[Tuple[str, int, str]] = []
|
||||
failures: List[Dict[str, str]] = []
|
||||
try:
|
||||
for path, size, category in plan.purge:
|
||||
if not path.startswith(f"jobs/{job_id}/"):
|
||||
continue
|
||||
generation = plan.generations.get(path)
|
||||
try:
|
||||
assert_deletable(path)
|
||||
self.storage.delete_file(path, ignore_missing=True, if_generation_match=generation)
|
||||
deleted.append((path, size, category))
|
||||
if deletion_log:
|
||||
deletion_log.record(job_id, path, size, generation, log_category(category), "deleted")
|
||||
except Exception as e: # noqa: BLE001
|
||||
failures.append({"path": path, "error": str(e)})
|
||||
if deletion_log:
|
||||
deletion_log.record(job_id, path, size, generation, log_category(category), "failed", str(e))
|
||||
if deletion_log:
|
||||
deletion_log.flush()
|
||||
|
||||
snap = ref.get()
|
||||
file_urls = (snap.to_dict() or {}).get("file_urls") or {} if snap.exists else {}
|
||||
update: Dict[str, Any] = {f"state_data.{PURGE_IN_PROGRESS_KEY}": DELETE_FIELD}
|
||||
for field_path in file_url_deletions(file_urls, [p for p, _, _ in deleted]):
|
||||
update[field_path] = DELETE_FIELD
|
||||
by_category: Counter = Counter()
|
||||
for _, size, category in deleted:
|
||||
by_category[category] += size
|
||||
if any(c in RENDER_CATEGORIES for _, _, c in deleted):
|
||||
update["renders_purged_at"] = now
|
||||
if any(c in STEM_CATEGORIES for _, _, c in deleted):
|
||||
update["stems_purged_at"] = now
|
||||
update["storage_purge"] = {
|
||||
"status": "complete",
|
||||
"purged_at": now.isoformat(),
|
||||
"policy_version": POLICY_VERSION,
|
||||
"bytes": sum(by_category.values()),
|
||||
"bytes_by_category": dict(by_category),
|
||||
"files": [{"path": p, "bytes": s, "category": c,
|
||||
"generation": str(plan.generations.get(p)) if plan.generations.get(p) is not None else None}
|
||||
for p, s, c in deleted],
|
||||
"failures": failures,
|
||||
"deletion_log": deletion_log.path if deletion_log else None,
|
||||
}
|
||||
ref.update(update)
|
||||
except Exception:
|
||||
try:
|
||||
ref.update({f"state_data.{PURGE_IN_PROGRESS_KEY}": DELETE_FIELD})
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise
|
||||
|
||||
try:
|
||||
from backend.services.firestore_service import log_to_job
|
||||
log_to_job(
|
||||
job_id, "storage-retention", "INFO",
|
||||
f"Storage retention purged {len(deleted)} regenerable files "
|
||||
f"({sum(by_category.values()) / 2**20:.0f} MiB); regenerate on demand",
|
||||
{"bytes_by_category": dict(by_category), "failures": failures},
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return {
|
||||
"status": "purged" if deleted else "skipped",
|
||||
"deleted": len(deleted),
|
||||
"failures": failures,
|
||||
}
|
||||
|
||||
# --- orphan folders -----------------------------------------------------------
|
||||
|
||||
def _known_job_ids(self) -> set:
|
||||
return {snap.id for snap in self.jobs_collection.select(["status"]).stream()}
|
||||
|
||||
def orphan_job_folders(self) -> Dict[str, Any]:
|
||||
"""``jobs/{id}/`` folders with no Firestore job doc (report only)."""
|
||||
known = self._known_job_ids()
|
||||
sizes: Counter = Counter()
|
||||
for name, size in self.storage.list_files_with_sizes("jobs/"):
|
||||
parts = name.split("/")
|
||||
if len(parts) > 2 and parts[1] not in known:
|
||||
sizes[parts[1]] += size
|
||||
total = sum(sizes.values())
|
||||
return {
|
||||
"folders": len(sizes),
|
||||
"gib_total": round(total / 2**30, 2),
|
||||
"largest": [{"job_id": k, "gib": round(v / 2**30, 2)} for k, v in sizes.most_common(20)],
|
||||
}
|
||||
|
||||
def _record_holder(self, job_id: str) -> Optional[str]:
|
||||
"""Collection that (still) has a record for this folder id, checked live."""
|
||||
for name in ORPHAN_RECORD_COLLECTIONS:
|
||||
if self.db.collection(name).document(job_id).get().exists:
|
||||
return name
|
||||
return None
|
||||
|
||||
def purge_orphans(
|
||||
self,
|
||||
dry_run: bool = True,
|
||||
max_folders: Optional[int] = None,
|
||||
quiet_days: int = ORPHAN_QUIET_DAYS,
|
||||
report_path: Optional[str] = None,
|
||||
now: Optional[datetime] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Delete everything but ``input/`` from job folders that have no job record.
|
||||
|
||||
Candidates come from one bucket listing vs. the ``jobs`` collection; each
|
||||
folder is then re-checked LIVE before acting: no record in any of
|
||||
ORPHAN_RECORD_COLLECTIONS, re-listed fresh, and no object modified in the
|
||||
last ``quiet_days`` days. Dry-run by default.
|
||||
"""
|
||||
started = time.time()
|
||||
now = now or datetime.now(timezone.utc)
|
||||
known = self._known_job_ids()
|
||||
candidates = orphan_candidates(self.storage.list_blob_meta("jobs/"), known)
|
||||
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_ORPHAN)
|
||||
report: Dict[str, Any] = {
|
||||
"mode": MODE_ORPHAN,
|
||||
"dry_run": dry_run,
|
||||
"started_at": now.isoformat(),
|
||||
"quiet_days": quiet_days,
|
||||
"record_collections": list(ORPHAN_RECORD_COLLECTIONS),
|
||||
"candidates": len(candidates),
|
||||
"folders": [],
|
||||
"skipped": Counter(),
|
||||
"not_orphans": [],
|
||||
"errors": [],
|
||||
}
|
||||
if deletion_log:
|
||||
report["deletion_log"] = deletion_log.path
|
||||
report["deletion_summary"] = deletion_log.summary_path
|
||||
acted = 0
|
||||
purge_bytes = keep_bytes = skipped_bytes = 0
|
||||
by_ext: Counter = Counter()
|
||||
for job_id in sorted(candidates):
|
||||
if max_folders is not None and acted >= max_folders:
|
||||
report["skipped"]["batch_limit"] += 1
|
||||
continue
|
||||
try:
|
||||
holder = self._record_holder(job_id)
|
||||
if holder:
|
||||
report["skipped"]["has_record"] += 1
|
||||
report["not_orphans"].append({"job_id": job_id, "collection": holder})
|
||||
continue
|
||||
fresh = self.storage.list_blob_meta(f"jobs/{job_id}/")
|
||||
plan = plan_orphan_folder(job_id, fresh, now, quiet_days)
|
||||
except Exception as e: # noqa: BLE001
|
||||
report["errors"].append({"job_id": job_id, "error": str(e)})
|
||||
continue
|
||||
if plan["skip_reason"]:
|
||||
report["skipped"][plan["skip_reason"]] += 1
|
||||
skipped_bytes += plan["purge_bytes"] + plan["keep_bytes"]
|
||||
continue
|
||||
if not plan["purge"]:
|
||||
report["skipped"]["nothing_to_purge"] += 1
|
||||
keep_bytes += plan["keep_bytes"]
|
||||
continue
|
||||
acted += 1
|
||||
purge_bytes += plan["purge_bytes"]
|
||||
keep_bytes += plan["keep_bytes"]
|
||||
for meta in plan["purge"]:
|
||||
rel = meta["name"].split("/", 2)[2]
|
||||
by_ext[rel.split("/", 1)[0] if "/" in rel else "(root)"] += int(meta.get("size") or 0)
|
||||
folder = {
|
||||
"job_id": job_id, "latest_update": plan["latest_update"],
|
||||
"purge_bytes": plan["purge_bytes"], "keep_bytes": plan["keep_bytes"],
|
||||
"purge_objects": len(plan["purge"]), "kept_input_objects": len(plan["keep"]),
|
||||
}
|
||||
if not dry_run:
|
||||
deleted = failed = 0
|
||||
for meta in plan["purge"]:
|
||||
path, size, gen = meta["name"], int(meta.get("size") or 0), meta.get("generation")
|
||||
try:
|
||||
assert_deletable(path)
|
||||
self.storage.delete_file(path, ignore_missing=True, if_generation_match=gen)
|
||||
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "deleted")
|
||||
deleted += 1
|
||||
except Exception as e: # noqa: BLE001
|
||||
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "failed", str(e))
|
||||
failed += 1
|
||||
deletion_log.flush()
|
||||
folder.update({"deleted": deleted, "failed": failed})
|
||||
report["folders"].append(folder)
|
||||
if deletion_log and deletion_log.flush_error:
|
||||
report["errors"].append({"job_id": job_id,
|
||||
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
|
||||
break
|
||||
|
||||
report["skipped"] = dict(report["skipped"])
|
||||
report["summary"] = {
|
||||
"folders_acted" if not dry_run else "folders_to_purge": acted,
|
||||
"gib_to_delete" if dry_run else "gib_deleted": round(purge_bytes / 2**30, 2),
|
||||
"gib_input_kept": round(keep_bytes / 2**30, 2),
|
||||
"gib_skipped_recent": round(skipped_bytes / 2**30, 2),
|
||||
"gib_by_top_level_dir": {k: round(v / 2**30, 2) for k, v in by_ext.most_common()},
|
||||
"duration_seconds": round(time.time() - started, 1),
|
||||
}
|
||||
report["report_path"] = report_path or (
|
||||
f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json")
|
||||
if deletion_log:
|
||||
report["deletion_totals"] = deletion_log.write_summary({"report_path": report["report_path"]})
|
||||
try:
|
||||
self.storage.upload_json(report["report_path"], report)
|
||||
except Exception as e: # noqa: BLE001
|
||||
report["report_write_error"] = str(e)
|
||||
logger.info(
|
||||
f"STORAGE_RETENTION ORPHANS {'DRY-RUN' if dry_run else 'RUN'}: candidates={len(candidates)} "
|
||||
f"summary={report['summary']} skipped={report['skipped']} errors={len(report['errors'])} "
|
||||
f"report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
|
||||
)
|
||||
return report
|
||||
@@ -14,6 +14,13 @@ from datetime import timedelta
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
# The bucket is publicly readable, and GCS serves publicly readable objects that
|
||||
# lack an explicit Cache-Control with ``public, max-age=3600`` — reads (including
|
||||
# the backend's own authenticated API reads) can then be answered from an edge
|
||||
# cache for up to an hour after the object is overwritten. Mutable state written
|
||||
# by the backend must never be cached.
|
||||
NO_STORE_CACHE_CONTROL = "no-store"
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -70,12 +77,24 @@ class StorageService:
|
||||
logger.error(f"Error uploading file {local_path}: {e}")
|
||||
raise
|
||||
|
||||
def upload_fileobj(self, file_obj: BinaryIO, destination_path: str, content_type: Optional[str] = None) -> str:
|
||||
"""Upload a file object to GCS."""
|
||||
def upload_fileobj(
|
||||
self,
|
||||
file_obj: BinaryIO,
|
||||
destination_path: str,
|
||||
content_type: Optional[str] = None,
|
||||
cache_control: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Upload a file object to GCS.
|
||||
|
||||
Pass ``cache_control=NO_STORE_CACHE_CONTROL`` for objects that may be
|
||||
overwritten in place and must be visible immediately (e.g. theme assets).
|
||||
"""
|
||||
try:
|
||||
blob = self.bucket.blob(destination_path)
|
||||
if content_type:
|
||||
blob.content_type = content_type
|
||||
if cache_control:
|
||||
blob.cache_control = cache_control
|
||||
blob.upload_from_file(file_obj, rewind=True)
|
||||
logger.info(f"Uploaded file object to gs://{settings.gcs_bucket_name}/{destination_path}")
|
||||
return destination_path
|
||||
@@ -279,7 +298,8 @@ class StorageService:
|
||||
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
def delete_file(self, blob_path: str, ignore_missing: bool = False) -> bool:
|
||||
def delete_file(self, blob_path: str, ignore_missing: bool = False,
|
||||
if_generation_match: Optional[int] = None) -> bool:
|
||||
"""Delete a file from GCS.
|
||||
|
||||
Args:
|
||||
@@ -295,7 +315,12 @@ class StorageService:
|
||||
"""
|
||||
try:
|
||||
blob = self.bucket.blob(blob_path)
|
||||
blob.delete()
|
||||
if if_generation_match is not None:
|
||||
# Only delete the exact version that was planned/logged; a newer
|
||||
# write since then raises PreconditionFailed.
|
||||
blob.delete(if_generation_match=if_generation_match)
|
||||
else:
|
||||
blob.delete()
|
||||
logger.info(f"Deleted gs://{settings.gcs_bucket_name}/{blob_path}")
|
||||
return True
|
||||
except NotFound:
|
||||
@@ -346,6 +371,37 @@ class StorageService:
|
||||
logger.error(f"Error listing files with prefix {prefix}: {e}")
|
||||
raise
|
||||
|
||||
def list_files_with_sizes(self, prefix: str) -> list:
|
||||
"""List ``(name, size_bytes)`` for every object under ``prefix``."""
|
||||
try:
|
||||
return [(blob.name, int(blob.size or 0)) for blob in self.bucket.list_blobs(prefix=prefix)]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing files with prefix {prefix}: {e}")
|
||||
raise
|
||||
|
||||
def list_blob_meta(self, prefix: str) -> list:
|
||||
"""List ``{name, size, generation, updated}`` for every object under ``prefix``."""
|
||||
try:
|
||||
return [
|
||||
{"name": b.name, "size": int(b.size or 0), "generation": b.generation, "updated": b.updated}
|
||||
for b in self.bucket.list_blobs(prefix=prefix)
|
||||
]
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing files with prefix {prefix}: {e}")
|
||||
raise
|
||||
|
||||
def upload_text(self, destination_path: str, text: str, content_type: str = "text/plain") -> str:
|
||||
"""Upload a text object (overwrites)."""
|
||||
blob = self.bucket.blob(destination_path)
|
||||
blob.cache_control = NO_STORE_CACHE_CONTROL
|
||||
blob.upload_from_string(text, content_type=content_type)
|
||||
return destination_path
|
||||
|
||||
def get_file_size(self, blob_path: str) -> Optional[int]:
|
||||
"""Size in bytes of a GCS object, or None if it doesn't exist."""
|
||||
blob = self.bucket.get_blob(blob_path)
|
||||
return blob.size if blob is not None else None
|
||||
|
||||
def file_exists(self, blob_path: str) -> bool:
|
||||
"""Check if a file exists in GCS."""
|
||||
try:
|
||||
@@ -371,6 +427,9 @@ class StorageService:
|
||||
try:
|
||||
blob = self.bucket.blob(destination_path)
|
||||
blob.content_type = "application/json"
|
||||
# JSON objects are mutable state (configs, registries, corrections) —
|
||||
# never let GCS edge-cache them, or overwrites stay invisible for ~1h.
|
||||
blob.cache_control = NO_STORE_CACHE_CONTROL
|
||||
upload_kwargs = {"content_type": "application/json"}
|
||||
if if_generation_match is not None:
|
||||
upload_kwargs["if_generation_match"] = if_generation_match
|
||||
@@ -385,9 +444,17 @@ class StorageService:
|
||||
raise
|
||||
|
||||
def download_json(self, source_path: str) -> Dict[str, Any]:
|
||||
"""Download and parse a JSON file from GCS."""
|
||||
"""Download and parse a JSON file from GCS, always reading the latest version.
|
||||
|
||||
Objects written before ``upload_json`` set ``no-store`` carry GCS's default
|
||||
public cache policy, so a plain download can return a stale cached copy.
|
||||
Resolving the live generation first (metadata request, not cached) and
|
||||
downloading that exact generation bypasses any cached copy.
|
||||
"""
|
||||
try:
|
||||
blob = self.bucket.blob(source_path)
|
||||
blob = self.bucket.get_blob(source_path)
|
||||
if blob is None:
|
||||
raise NotFound(f"gs://{settings.gcs_bucket_name}/{source_path} not found")
|
||||
content = blob.download_as_text()
|
||||
data = json.loads(content)
|
||||
logger.info(f"Downloaded JSON from gs://{settings.gcs_bucket_name}/{source_path}")
|
||||
|
||||
@@ -19,6 +19,7 @@ import stripe
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.stripe_service import StripeService
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -152,6 +153,8 @@ class StripeAdminService:
|
||||
"is_test": is_test,
|
||||
"promotion_code": promotion_code,
|
||||
"discount_amount": discount_amount,
|
||||
# Optional checkout tip (included in amount_total)
|
||||
"tip_cents": StripeService.tip_cents_from_session(session),
|
||||
}
|
||||
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
|
||||
Loaded 100 of 668 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user