Compare commits

...
6 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 fea6ebec1a fix(tenant): make white-label B2B portals attribute jobs to the tenant (Vocal Star + Singa) (#824)
@coderabbitai ignore

## Problem

The white-label tenant portals (`vocalstar.nomadkaraoke.com`,
`singa.nomadkaraoke.com`) looked "done" but **had never worked
end-to-end**: 0 of the last 484 production jobs carried a `tenant_id`.
No tenant job had ever run.

**Root cause:** the frontend API client never sent the `X-Tenant-ID`
header. Tenant portals call the shared `api.nomadkaraoke.com`, whose
Host isn't the tenant subdomain, and the `?tenant=` query param is
disabled in prod — so the backend could never detect the tenant. Every
tenant sign-in and job submission silently fell back to consumer
behavior (default theme, no tenant Dropbox, etc.). The
`getTenantHeaders()` helper existed and was unit-tested, but was never
wired into requests.

## Changes

**Frontend** (`lib/api.ts`, `lib/tenant.ts`)
- Attach `X-Tenant-ID` on all authenticated requests **and** the
magic-link request, sourced from `window.__TENANT_CONFIG__`
(edge-injected by the Cloudflare function; mirrored from the tenant
store for dev/preview). Consumer build resolves no tenant → no header →
**behavior unchanged**.

**Backend** (`_apply_tenant_overrides` in `file_upload.py`)
- Make tenant config **authoritative** over global distribution
defaults. Prod sets `DEFAULT_DROPBOX_PATH` / `DEFAULT_GDRIVE_FOLDER_ID`
/ `DEFAULT_BRAND_PREFIX` globally; these seed `dist`, and the old "fill
only when unset" overlay let them leak — so every tenant job would have
landed in the **shared consumer Dropbox folder** and uploaded to the
**global Google Drive**. Now Dropbox/GDrive routing is gated by the
tenant feature flags and cleared when disabled.

**Tenant configs** (GCS + setup scripts, Vocal Star + Singa)
- Disable Google Drive (`gdrive_upload=false`, `gdrive_folder_id=null`),
keep YouTube off, enable Dropbox to each tenant's own folder. B2B =
locked theme, no YouTube/GDrive, Dropbox + portal download only.

## Why it's consumer-safe
- Frontend: header only attached when a tenant is resolved (never on
`gen.nomadkaraoke.com`).
- Backend: `_apply_tenant_overrides` early-returns when `tenant_config
is None` (all consumer jobs).

## Testing
- New: frontend header-attachment tests (tenant build vs consumer);
backend authoritative-override + feature-flag-gating regression guards
(incl. the global-default-leak case).
- Full suites green: **3466 backend**, **1013 frontend**.
- Verified live tenant configs via API after update.

Manual prod E2E (real track through each portal) + a daily per-tenant
E2E workflow follow in a second PR, once this deploys and is verified in
prod.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 02:40:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fd331a643f infra: GCP cost reductions (artifact cleanup, NAT egress, weekly backup) (#823)
Part of the June 2026 cost-reduction effort
(`docs/archive/2026-06-14-gcp-cost-reduction-plan.md`). Targets the
post-credit-expiry (2026-09-19) bill.

## Changes
- **Item 4 — Artifact Registry cleanup** (~$6/mo + caps growth): keep 10
most-recent versions + delete untagged digests >7d, on all 3 repos
(karaoke-repo, karaoke-backend-gpu, audio-separator; 92 GiB, previously
no policy). In-place update.
- **Item 5 — NAT egress** (~$26/mo): ephemeral GHA runners now always
get an external IP, so egress bypasses the Cloud NAT data-processing
charge (runners were the NAT's only user; us-central1 IN_USE_ADDRESSES
quota is 69, usage 1).
- **Item 6 — backup cadence** (~$15/mo): Firestore export stays nightly
to GCS (1-day local restore point) but uploads to S3 only on Sundays
(1-week off-site RPO) — Firestore is the bulk of the cross-cloud egress.
Staging keeps only the latest export so the weekly upload ships exactly
one.
- **Item 1 — encoding disks** (~$35/mo): pinned the 4 worker hyperdisks
to the free baseline (3000 IOPS / 140 MB/s) **live via `gcloud`**, not
IaC — setting it in IaC forces a capacity-risky VM replacement. A code
comment documents this.

## Deploy status
- `pulumi up` (artifact policies + runner function): **applied** locally
(prod, update 751).
- Backup function source: shipped via
`functions/backup_to_aws/deploy.sh` (pulumi doesn't manage the source
zip).
- Encoding disks: tuned live via gcloud.

## Tests
- `backup_to_aws`: 13 pass (added firestore-cleanup + s3-exclude
coverage).
- `runner_manager/ephemeral`: 32 pass (updated external-IP assertion).

Item 7 (fallback disks on-demand) intentionally deferred — reliability
tradeoff not worth ~$20/mo. See plan doc.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 17:11:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 39fb93653f fix(auto-correct): switch active model from Fable 5 to Opus 4.8 (#822)
## Summary

Claude **Fable 5** (`claude-fable-5`) is no longer available on the
Anthropic API. Verified live against `api.anthropic.com`:

```
404 not_found_error: "Claude Fable 5 is not available. Please use Opus 4.8.
Learn more: https://www.anthropic.com/news/fable-mythos-access"
```

`claude-opus-4-8` responds normally and is the API's own prescribed
replacement. Opus 4.8 was also ≈ Gemini 3.1 Pro in our 30-job offline
eval, so switching to it preserves the two-model compare quality.

## Changes

- **`.github/workflows/ci.yml`** (load-bearing):
`AUTO_CORRECT_MODEL=claude-opus-4-8` and
`AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview`.
Compare mode now runs **Opus 4.8 + Gemini 3.1 Pro** instead of Fable +
Gemini.
- **`scripts/measure_autocorrect_cost.py`**: default models + docstring
example → Opus, so the cost tool measures what prod runs.
- **`docs/API.md`**: example auto-correct response reflects Opus.
- **`pyproject.toml`**: `0.182.1` → `0.182.2`.

## Re-enable path

Fable is **disabled, not deleted** — its pricing entry in `pricing.py`
and all Fable unit tests are intentionally left intact. If access
returns, flip it back by reverting the two env-var values in `ci.yml`.

## Testing

- Auto-correct suite: 73 passed (`backend/tests/services/auto_correct/`
+ `test_proactive_auto_correct.py`).
- Live API probe confirmed Fable 404s and Opus 4.8 works.
- CodeRabbit (uncommitted): 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 10:27:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 dfdbf60dc5 docs(monitoring): document email-channel verification gap (Pulumi vs Console) (#785)
## Summary

Followup to PR #783. The PR claimed Cloud Monitoring would deliver a
verification email to `andrew@beveridge.uk` automatically after `pulumi
up`. It didn't — the channel sat in `UNVERIFIED` state silently, exactly
as if no channel had been created.

The actual GCP behaviour: the auto-send only fires when a channel is
created through the **Cloud Console**. Channels created through the
**API/Pulumi** require an explicit call to the `:sendVerificationCode`
REST endpoint to trigger the email.

I discovered this when running `getVerificationCode` against the channel
and getting `"Cannot generate a verification code from an unverified
channel."` despite `enabled: true`. The right endpoint is
`sendVerificationCode` (no admin-flow restrictions), which returned `{}`
(success) and the email arrived shortly after.

## Change

Rewrite the "Gotcha" callout in `infrastructure/monitoring/README.md` to
explain this, with a copy-paste-ready curl invocation for triggering the
email after any future `pulumi up` that adds a new email channel.

No code change.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-12 16:03:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 9f25ae4c4c feat(divebar): on-demand pipeline refresh trigger (refresh action) (#821)
## Why

A track made via gen.nomadkaraoke.com is uploaded to the Nomad Google
Drive immediately, but the Divebar/GCS community mirror only ingests it
on the nightly schedule (mirror index 2 AM, GCS file sync 3 AM, xref
rebuild 6 AM ET). Until then, kjbox's link flow can't find a mirror copy
and falls back to a YouTube download.

This adds an **on-demand "refresh now"** path so a freshly-published
track can be pulled into the catalog within minutes.

## What

New `refresh` action on the **public `divebar-lookup`** Cloud Function:

- Force-runs the three existing scheduler jobs in pipeline order —
`divebar-mirror-daily` (Drive→BigQuery index, makes the track appear) →
`divebar-sync-vm-daily` (Drive→GCS, fast URL) →
`divebar-xref-rebuild-daily` — via `CloudSchedulerClient.run_job`.
Reuses each job's own OIDC identity/target.
- **Least privilege:** the function SA gets a custom
`divebarSchedulerRunner` role (`cloudscheduler.jobs.run` + `.get`) only
— no new function-invoke or compute perms.
- **Token-gated:** the endpoint is public, so the action requires a
shared bearer token (constant-time compare). The token is read from the
`divebar-refresh-token` Secret Manager secret **at runtime** (not
injected as a secret env var) so the function deploys cleanly before the
secret has a version — it just returns a uniform `403` until one is
added, and picks up rotations without a redeploy. Fails closed.

Consumed by kjbox's new "Refresh catalog" button (kjbox#107).

## Tests

`infrastructure/functions/divebar_lookup/test_main.py` — 8 tests: token
gate (wrong/empty/unconfigured), all-jobs-triggered-in-order,
partial-failure tolerance, dispatch 200/403. All green.

## Deploy status — ✅ applied to prod

Applied locally (provider pinned to prod's 9.22.0 so the apply contained
only these 5 resources — no unrelated provider-upgrade churn): `4
created, 1 updated, 262 unchanged`. Function source rebuilt from the new
zip. Secret version set. Verified live: no/wrong token → 403; valid
token → 200 triggering all three jobs.

**Remaining (kjbox#107):** put the same token in the kjbox device
`config.json` as `divebar_refresh_token`, then deploy kjbox.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 00:53:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 cf79da79ab fix: honor "use official formatting" correction on search-created jobs (#820)
## Problem

When a user searches for a song, selects **"Use the official
formatting"** (e.g. picks `Hard-Fi — Hard to Beat` over their typed
`hard-fi - hard to beat`), and creates the job, the job was still named
with their raw lowercase query. The official-formatting selection was
silently discarded.

## Root cause

`create_job_from_search` (`backend/api/routes/jobs.py`) derived the
display name from the **original search query stored in the session**,
not from the corrected `artist`/`title` the frontend sends in the
request body:

```python
session_artist = session.get('artist', body.artist)   # always the raw query
effective_display_artist = body.display_artist or session_artist  # body.artist never used
```

Since the session always has an `artist` key, `body.artist` was only
ever an unreachable fallback. The frontend's "Use official formatting"
click correctly updates its state and sends the corrected values — they
were just ignored server-side.

## Fix

Prefer `body.artist`/`body.title` (the wizard's current,
possibly-corrected values) over the stored query, with an explicit
display override still winning above all. Whitespace-only body values
are stripped and fall back to the stored query so a stray `" "` can't
become the job name. The original query is preserved for
`audio_search_artist`/`audio_search_title` matching metadata.

## Tests

- New regression test: corrected artist/title wins over the session
query (fails on old code: `'hard-fi' == 'Hard-Fi'`).
- New test: whitespace-only body artist/title falls back to the stored
query.
- `test_standalone_search.py`: **33 passed**; broader job
route/api/regression suites: **123 passed**.
- Existing `test_display_overrides_applied_when_provided` still passes
(override precedence intact).

Version bumped `0.181.0 → 0.181.1`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 22:44:09 -04:00
31 changed files with 886 additions and 54 deletions

No files matched your search

+1 -1
View File
@@ -1658,7 +1658,7 @@ jobs:
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-fable-5,AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
+16 -10
View File
@@ -67,12 +67,20 @@ def _apply_tenant_overrides(
"""
Apply tenant-specific overrides to distribution settings and job options.
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
distribution settings, so tenant outputs never inherit the global consumer defaults
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
tenant job would land in the shared consumer Dropbox folder and upload to the global
Google Drive, regardless of the tenant's own config.
For tenant jobs:
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
(only when not already set in the request body / dist)
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
otherwise disables that channel entirely (no global-default leak)
- Forces is_private = True
- Applies locked_theme as effective theme
- Disables YouTube upload
- Disables YouTube upload (tenants never publish to YouTube)
Returns:
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
@@ -81,14 +89,12 @@ def _apply_tenant_overrides(
return dist, effective_theme_id, is_private, enable_youtube_upload
defaults = tenant_config.defaults
features = tenant_config.features
# Overlay tenant distribution defaults (request-level values take precedence)
if defaults.brand_prefix and not dist.brand_prefix:
dist.brand_prefix = defaults.brand_prefix
if defaults.dropbox_path and not dist.dropbox_path:
dist.dropbox_path = defaults.dropbox_path
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
dist.gdrive_folder_id = defaults.gdrive_folder_id
# Authoritative distribution routing (overrides any global defaults in `dist`).
dist.brand_prefix = defaults.brand_prefix
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
# Force private for all tenant jobs
is_private = True
+13 -3
View File
@@ -2434,11 +2434,21 @@ async def create_job_from_search(
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
# Determine display values
# Determine display values.
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
# body.title carry whatever is currently in the wizard's artist/title fields,
# which reflect a "Use official formatting" correction the user may have applied
# after searching. The displayed job name must honour that correction, so prefer
# the request body over the stored query. An explicit display override wins above all.
session_artist = session.get('artist', body.artist)
session_title = session.get('title', body.title)
effective_display_artist = body.display_artist or session_artist
effective_display_title = body.display_title or session_title
# body.artist/body.title are required but unvalidated for whitespace, so strip
# them and fall back to the stored query if blank (display_* is pre-stripped to
# None by its validator). This keeps a stray " " from becoming the job name.
body_artist = (body.artist or "").strip()
body_title = (body.title or "").strip()
effective_display_artist = body.display_artist or body_artist or session_artist
effective_display_title = body.display_title or body_title or session_title
tenant_id = session.get('tenant_id') or ""
+51
View File
@@ -545,6 +545,57 @@ class TestCreateJobFromSearch:
assert job_create.artist == "Abba (Display)"
assert job_create.title == "Waterloo (Karaoke)"
def test_corrected_artist_title_wins_over_session_query(self, create_from_search_client, auth_headers):
"""Regression: when the user clicks "Use official formatting", the corrected
artist/title sent in the request body must win over the original (raw) search
query stored in the session. Previously the job was named with the raw query,
so the official formatting selection was silently ignored."""
# Session was created from the raw lowercase query the user typed...
raw_session = _make_search_session(user_email="test@example.com")
raw_session["artist"] = "hard-fi"
raw_session["title"] = "hard to beat"
create_from_search_client._mock_firestore.get_search_session.return_value = raw_session
create_from_search_client._mock_firestore.consume_search_session.return_value = raw_session
# ...then the user picked the official formatting, so the frontend sends the
# corrected artist/title (no separate display override).
create_from_search_client.post(
"/api/jobs/create-from-search",
json={
"search_session_id": "sess-abc-123",
"selection_index": 0,
"artist": "Hard-Fi",
"title": "Hard to Beat",
},
headers=auth_headers,
)
call_args = create_from_search_client._mock_jm.create_job.call_args
job_create = call_args[0][0]
assert job_create.artist == "Hard-Fi"
assert job_create.title == "Hard to Beat"
# The original query is still preserved for audio-search matching metadata.
assert job_create.audio_search_artist == "hard-fi"
assert job_create.audio_search_title == "hard to beat"
def test_blank_body_artist_title_falls_back_to_session_query(self, create_from_search_client, auth_headers):
"""Whitespace-only artist/title in the body must not become the job name —
fall back to the stored search query instead."""
create_from_search_client.post(
"/api/jobs/create-from-search",
json={
"search_session_id": "sess-abc-123",
"selection_index": 0,
"artist": " ",
"title": "\t",
},
headers=auth_headers,
)
call_args = create_from_search_client._mock_jm.create_job.call_args
job_create = call_args[0][0]
# Session stores "ABBA" / "Waterloo" (see _make_search_session).
assert job_create.artist == "ABBA"
assert job_create.title == "Waterloo"
def test_session_consumed_atomically(self, create_from_search_client, auth_headers):
"""Session is consumed (atomically read+deleted) via consume_search_session."""
create_from_search_client.post(
+54 -8
View File
@@ -125,24 +125,70 @@ class TestApplyTenantOverrides:
_, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
assert yt_upload is False
def test_request_values_take_precedence(self):
"""Explicit request-level values are not overridden by tenant defaults."""
def test_tenant_config_overrides_global_defaults(self):
"""Tenant config is authoritative: it overrides any global/consumer default
distribution settings already seeded into `dist`.
Regression guard: prod sets DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID /
DEFAULT_BRAND_PREFIX globally, which get_effective_distribution_settings seeds
into `dist`. If tenant overrides only filled in *unset* fields, every tenant job
would leak into the shared consumer Dropbox folder and global Google Drive.
"""
apply_fn = self._get_apply_fn()
tenant_config = _make_tenant_config()
# `dist` arrives pre-seeded with the GLOBAL consumer defaults.
dist = EffectiveDistributionSettings(
dropbox_path="/Custom/Path",
gdrive_folder_id="custom-folder",
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized", # global default
gdrive_folder_id="global-consumer-folder", # global default
discord_webhook_url=None,
brand_prefix="CUSTOM",
brand_prefix="NOMAD", # global default
enable_youtube_upload=True,
youtube_description=None,
)
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.brand_prefix == "CUSTOM"
assert new_dist.dropbox_path == "/Custom/Path"
assert new_dist.gdrive_folder_id == "custom-folder"
# Tenant config wins on every distribution field.
assert new_dist.brand_prefix == "VSTAR"
assert new_dist.dropbox_path == "/Karaoke/Vocal-Star"
assert new_dist.gdrive_folder_id == "gdrive-folder-123"
def test_gdrive_disabled_clears_global_default(self):
"""When the tenant disables gdrive_upload, the global default GDrive folder is
cleared so the tenant job never publishes to Google Drive (the B2B requirement)."""
apply_fn = self._get_apply_fn()
# Tenant has a gdrive folder configured but the feature is OFF — the disabled
# flag must win, clearing both the configured folder and any global default.
tenant_config = _make_tenant_config()
tenant_config.features.gdrive_upload = False
dist = EffectiveDistributionSettings(
dropbox_path=None,
gdrive_folder_id="global-consumer-folder", # would otherwise leak
discord_webhook_url=None,
brand_prefix=None,
enable_youtube_upload=True,
youtube_description=None,
)
new_dist, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.gdrive_folder_id is None
assert yt_upload is False
def test_dropbox_disabled_clears_path(self):
"""When the tenant disables dropbox_upload, the Dropbox path is cleared."""
apply_fn = self._get_apply_fn()
tenant_config = _make_tenant_config()
tenant_config.features.dropbox_upload = False
dist = EffectiveDistributionSettings(
dropbox_path="/MediaUnsynced/Karaoke/Tracks-Organized",
gdrive_folder_id=None, discord_webhook_url=None,
brand_prefix=None, enable_youtube_upload=True, youtube_description=None,
)
new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True)
assert new_dist.dropbox_path is None
def test_no_tenant_config_passthrough(self):
"""When no tenant config, all values pass through unchanged."""
+2 -2
View File
@@ -606,13 +606,13 @@ Returns:
"reason": "All references read 'chlorine' here",
"category": "mishearing",
"confidence": 0.95,
"models": ["claude-fable-5", "gemini-3.1-pro-preview"],
"models": ["claude-opus-4-8", "gemini-3.1-pro-preview"],
"consensus": 2,
"total_models": 2,
"conflict_group": null
}
],
"model": "claude-fable-5, gemini-3.1-pro-preview",
"model": "claude-opus-4-8, gemini-3.1-pro-preview",
"elapsed_seconds": 27.4,
"settings_applied": { "suggest_adlib_removal": true, "allow_insertions": true, "min_confidence": 0.0 },
"warnings": [],
@@ -0,0 +1,96 @@
/**
* @jest-environment jsdom
*
* Tests that the API client attaches the X-Tenant-ID header on white-label tenant
* portals (sourced from window.__TENANT_CONFIG__) and omits it on the consumer build.
*
* Regression guard for the root-cause bug: the frontend never sent X-Tenant-ID, so the
* shared api.nomadkaraoke.com backend could not detect the tenant and every tenant-portal
* job/sign-in silently fell back to consumer behavior (0 tenant jobs ever ran in prod).
*/
import { api, getTenantId } from '@/lib/api'
function setEdgeTenant(id: string | null) {
if (id) {
;(window as any).__TENANT_CONFIG__ = {
tenant: { id, name: id, subdomain: `${id}.nomadkaraoke.com` },
is_default: false,
}
} else {
delete (window as any).__TENANT_CONFIG__
}
}
describe('getTenantId', () => {
afterEach(() => setEdgeTenant(null))
it('returns null when no tenant config is present (consumer build)', () => {
setEdgeTenant(null)
expect(getTenantId()).toBeNull()
})
it('returns the tenant id from window.__TENANT_CONFIG__', () => {
setEdgeTenant('vocalstar')
expect(getTenantId()).toBe('vocalstar')
})
it('returns null when the injected config has no tenant (default/consumer domain)', () => {
;(window as any).__TENANT_CONFIG__ = { tenant: null, is_default: true }
expect(getTenantId()).toBeNull()
})
})
describe('X-Tenant-ID header attachment', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(global as any).fetch = fetchMock
fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) })
})
afterEach(() => setEdgeTenant(null))
it('attaches X-Tenant-ID to authenticated requests (createJobWithUploadUrls) on a tenant portal', async () => {
setEdgeTenant('vocalstar')
window.localStorage.setItem('karaoke_access_token', 'tok-123')
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ job_id: 'j1', upload_urls: [] }),
})
await api.createJobWithUploadUrls('Adele', 'Hello', [], {
is_private: true,
existing_instrumental: true,
})
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['X-Tenant-ID']).toBe('vocalstar')
expect(init.headers['Authorization']).toBe('Bearer tok-123')
window.localStorage.removeItem('karaoke_access_token')
})
it('attaches X-Tenant-ID to the magic-link request on a tenant portal', async () => {
setEdgeTenant('singa')
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
await api.sendMagicLink('user@singa.com')
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/api\/users\/auth\/magic-link$/)
expect(init.headers['X-Tenant-ID']).toBe('singa')
})
it('does NOT attach X-Tenant-ID on the consumer build', async () => {
setEdgeTenant(null)
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ success: true }) })
await api.sendMagicLink('user@example.com')
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['X-Tenant-ID']).toBeUndefined()
})
})
+3
View File
@@ -76,6 +76,9 @@ function resetStore() {
error: null,
isInitialized: false,
})
// The store now mirrors resolved config onto window.__TENANT_CONFIG__ (so lib/api.ts
// can read it synchronously). Clear it between tests to keep them isolated.
delete (window as { __TENANT_CONFIG__?: unknown }).__TENANT_CONFIG__
}
describe("useTenant store", () => {
+42 -2
View File
@@ -55,10 +55,45 @@ function getLocaleFromPath(): string {
return 'en';
}
function getAuthHeaders(): HeadersInit {
const headers: HeadersInit = {
/**
* Resolve the current white-label tenant id, if any.
*
* On tenant portals the Cloudflare Pages edge function (frontend/functions/[[path]].ts)
* injects `window.__TENANT_CONFIG__` into the HTML before any app JS runs, and the
* tenant store (lib/tenant.ts) mirrors the same shape there in dev/preview. Reading it
* directly here keeps api.ts free of an import cycle with tenant.ts (which imports
* API_BASE_URL from this module).
*
* Returns null on the consumer build / consumer domain, so no tenant header is sent and
* existing consumer behavior is unchanged.
*/
export function getTenantId(): string | null {
if (typeof window === 'undefined') return null;
const injected = (window as { __TENANT_CONFIG__?: { tenant?: { id?: string } | null } }).__TENANT_CONFIG__;
const id = injected?.tenant?.id;
return typeof id === 'string' && id ? id : null;
}
/**
* Base headers attached to every API request: locale, and the X-Tenant-ID header when
* on a white-label tenant portal. The shared backend (api.nomadkaraoke.com) cannot infer
* the tenant from the Host (it's not the tenant subdomain) or from the prod-disabled
* `?tenant=` query param, so this header is the primary tenant-detection signal that lets
* the backend apply tenant config (locked theme, Dropbox path, no YouTube/GDrive).
*/
function getBaseHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Accept-Language': getLocaleFromPath(),
};
const tenantId = getTenantId();
if (tenantId) {
headers['X-Tenant-ID'] = tenantId;
}
return headers;
}
function getAuthHeaders(): HeadersInit {
const headers: Record<string, string> = getBaseHeaders();
const token = getAccessToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
@@ -1285,6 +1320,11 @@ export const api = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Carry tenant context so the backend validates the email domain against the
// tenant, embeds tenant_id in the magic-link token, and uses the tenant's
// sender email + portal URL. Without this, tenant sign-in silently falls back
// to the consumer (nomad) flow.
...getBaseHeaders(),
},
body: JSON.stringify(body),
});
+19
View File
@@ -238,6 +238,11 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
isInitialized: true,
})
// Mirror to the edge-config global so synchronous, import-cycle-free consumers
// (e.g. getTenantId() in lib/api.ts) can read the tenant in dev/preview where the
// Cloudflare edge function does not inject __TENANT_CONFIG__.
mirrorTenantConfigToWindow(data)
// Apply tenant branding to CSS variables
if (data.tenant) {
applyTenantBranding(data.tenant.branding)
@@ -256,6 +261,7 @@ const useTenantStore = create<TenantStore>()((set, get) => ({
setTenant: (tenant, isDefault) => {
set({ tenant, isDefault, isInitialized: true })
mirrorTenantConfigToWindow({ tenant, is_default: isDefault })
if (tenant) {
applyTenantBranding(tenant.branding)
}
@@ -348,6 +354,19 @@ function applyTenantBranding(branding: TenantBranding) {
}
}
/**
* Mirror the resolved tenant config onto `window.__TENANT_CONFIG__`.
*
* The Cloudflare edge function injects this global on tenant subdomains in production,
* but not in local dev or admin preview (where the tenant is resolved by fetch or
* setTenant). Mirroring it here gives lib/api.ts a single synchronous, import-cycle-free
* source of truth for attaching the X-Tenant-ID header in every environment.
*/
function mirrorTenantConfigToWindow(data: TenantConfigResponse) {
if (typeof window === "undefined") return
;(window as { __TENANT_CONFIG__?: TenantConfigResponse }).__TENANT_CONFIG__ = data
}
/**
* Hook to get tenant-aware API headers.
* Use this when making API calls that need tenant context.
@@ -50,6 +50,18 @@ def create_encoding_worker_vms(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
# NOTE: Hyperdisk provisioned IOPS/throughput are deliberately
# NOT set here. Specifying them forces a full VM *replacement*
# (the provider treats boot-disk init params as immutable), and
# recreating a primary depends on us-central1-c capacity — the
# exact shortage the fallback fleet exists to absorb. So the
# disks are pinned to the Hyperdisk Balanced free baseline
# (3000 IOPS / 140 MB/s) live via `gcloud compute disks update`
# instead — non-disruptive, and pulumi does not manage this
# attribute so there is no drift. They were over-provisioned at
# 3600 IOPS / 290 MB/s (~$8.70/disk/mo wasted). Re-apply the
# gcloud tune after any worker-image rebuild that recreates the
# disks. See docs/archive/2026-06-14-gcp-cost-reduction-plan.md.
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
@@ -127,6 +139,18 @@ def create_encoding_worker_fallback_vms(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
# NOTE: Hyperdisk provisioned IOPS/throughput are deliberately
# NOT set here. Specifying them forces a full VM *replacement*
# (the provider treats boot-disk init params as immutable), and
# recreating a primary depends on us-central1-c capacity — the
# exact shortage the fallback fleet exists to absorb. So the
# disks are pinned to the Hyperdisk Balanced free baseline
# (3000 IOPS / 140 MB/s) live via `gcloud compute disks update`
# instead — non-disruptive, and pulumi does not manage this
# attribute so there is no drift. They were over-provisioned at
# 3600 IOPS / 290 MB/s (~$8.70/disk/mo wasted). Re-apply the
# gcloud tune after any worker-image rebuild that recreates the
# disks. See docs/archive/2026-06-14-gcp-cost-reduction-plan.md.
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
@@ -1,11 +1,36 @@
"""Firestore export to GCS staging bucket."""
import logging
from google.cloud import firestore_admin_v1
from google.cloud import firestore_admin_v1, storage
logger = logging.getLogger(__name__)
def _clear_prior_exports(staging_bucket: str, keep_date: str) -> None:
"""Delete prior firestore/ exports in staging except the keep_date one.
The Firestore export runs nightly to provide a fresh daily local (GCS)
restore point, but is only uploaded to S3 weekly (to cut egress). On
non-weekly days the export is held back from S3 and left in staging, so
without this cleanup a week of exports would pile up and the weekly upload
would ship all of them at once — defeating the saving. Keeping only the
latest export means the weekly upload ships exactly one.
"""
keep_prefix = f"firestore/{keep_date}"
try:
client = storage.Client()
bucket = client.bucket(staging_bucket)
for blob in bucket.list_blobs(prefix="firestore/"):
if not blob.name.startswith(keep_prefix):
try:
blob.delete()
except Exception as e:
logger.warning(f"Failed to delete stale firestore export {blob.name}: {e}")
except Exception as e:
# Best-effort cleanup — the export already succeeded, so never fail on it.
logger.warning(f"Failed to list/clear prior firestore exports: {e}")
def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
"""Export all Firestore collections to GCS.
@@ -32,5 +57,8 @@ def export_firestore(project: str, staging_bucket: str, date_str: str) -> str:
result = operation.result(timeout=1800) # 30 min timeout
# Keep only this export in staging so the weekly S3 upload ships exactly one.
_clear_prior_exports(staging_bucket, date_str)
logger.info(f"Firestore export complete: {output_uri}")
return f"Exported to {output_uri} ({date_str})"
+16 -4
View File
@@ -2,14 +2,18 @@
Backup to AWS Cloud Function.
Nightly backup pipeline:
1. Firestore export to GCS staging
1. Firestore export to GCS staging (nightly; uploaded to S3 weekly on Sundays)
2. BigQuery export to GCS staging (weekly/monthly schedule)
3. GCS job files delta sync to staging
4. Secret Manager export (encrypted with sealed-box public key) to staging
5. Upload staging files to S3
5. Upload staging files to S3 (Firestore export held back except Sundays)
6. Discord alert
Triggered by Cloud Scheduler at 1:00 AM ET daily.
Firestore is the bulk of the cross-cloud egress. Exporting it nightly to GCS
keeps a 1-day local restore point, while uploading to S3 only weekly keeps a
1-week off-site RPO at ~1/7th the egress cost.
"""
import datetime
@@ -59,7 +63,13 @@ def backup_to_aws(request):
results = {}
errors = []
logger.info(f"Starting backup for {date_str}")
# The Firestore export runs nightly (daily local restore point in GCS) but
# is only pushed off-site to S3 weekly, on Sundays — matching the BigQuery
# weekly cadence. This is the bulk of the cross-cloud egress, so weekly
# off-site keeps a 1-week off-site RPO while a 1-day local RPO is retained.
firestore_to_s3_today = today.weekday() == 6 # Sunday
logger.info(f"Starting backup for {date_str} (firestore->S3: {firestore_to_s3_today})")
# Step 1: Firestore export (nightly)
try:
@@ -123,11 +133,13 @@ def backup_to_aws(request):
logger.error(f"Secrets export failed: {e}")
errors.append(f"Secrets: {e}")
# Step 5: Upload to S3
# Step 5: Upload to S3. On non-Sundays, hold the Firestore export back
# (it stays in GCS staging as a daily local backup); it ships to S3 weekly.
try:
results["s3_upload"] = upload_staging_to_s3(
staging_bucket=STAGING_BUCKET,
s3_bucket=S3_BUCKET,
exclude_prefixes=[] if firestore_to_s3_today else ["firestore/"],
)
except Exception as e:
logger.error(f"S3 upload failed: {e}")
@@ -21,12 +21,20 @@ def upload_staging_to_s3(
staging_bucket: str,
s3_bucket: str,
project: str = "nomadkaraoke",
exclude_prefixes: list | None = None,
) -> str:
"""Upload all objects in staging bucket to S3 using streaming.
Walks the staging bucket and uploads each object to the corresponding
S3 key path. Skips marker files (.*).
S3 key path. Skips marker files (.*) and any object whose name starts with
one of ``exclude_prefixes`` (used to hold the nightly Firestore export back
from S3 on non-weekly days — it stays in GCS staging as a daily local
restore point and is uploaded only on the weekly run).
Excluded objects are left in staging (not deleted), so they remain a local
backup until the GCS lifecycle policy or the next weekly upload removes them.
"""
exclude_prefixes = exclude_prefixes or []
aws_creds = get_aws_credentials(project)
s3_client = boto3.client(
"s3",
@@ -45,6 +53,9 @@ def upload_staging_to_s3(
if blob.name.startswith(".") or "/.last_sync" in blob.name:
continue
if any(blob.name.startswith(p) for p in exclude_prefixes):
continue
try:
with blob.open("rb") as gcs_file:
s3_client.upload_fileobj(
@@ -5,8 +5,9 @@ from unittest.mock import MagicMock, patch
class TestFirestoreExport(unittest.TestCase):
@patch("firestore_export.storage.Client")
@patch("firestore_export.firestore_admin_v1.FirestoreAdminClient")
def test_export_firestore_calls_api(self, mock_client_class):
def test_export_firestore_calls_api(self, mock_client_class, mock_storage):
from firestore_export import export_firestore
mock_client = MagicMock()
@@ -14,6 +15,7 @@ class TestFirestoreExport(unittest.TestCase):
mock_operation = MagicMock()
mock_operation.result.return_value = MagicMock()
mock_client.export_documents.return_value = mock_operation
mock_storage.return_value.bucket.return_value.list_blobs.return_value = []
result = export_firestore(
project="test-project",
@@ -27,8 +29,9 @@ class TestFirestoreExport(unittest.TestCase):
assert request["name"] == "projects/test-project/databases/(default)"
assert "gs://test-staging/firestore/2026-03-29" in request["output_uri_prefix"]
@patch("firestore_export.storage.Client")
@patch("firestore_export.firestore_admin_v1.FirestoreAdminClient")
def test_export_firestore_returns_summary(self, mock_client_class):
def test_export_firestore_returns_summary(self, mock_client_class, mock_storage):
from firestore_export import export_firestore
mock_client = MagicMock()
@@ -36,11 +39,44 @@ class TestFirestoreExport(unittest.TestCase):
mock_operation = MagicMock()
mock_operation.result.return_value = MagicMock()
mock_client.export_documents.return_value = mock_operation
mock_storage.return_value.bucket.return_value.list_blobs.return_value = []
result = export_firestore("proj", "bucket", "2026-03-29")
assert isinstance(result, str)
assert "2026-03-29" in result
class TestClearPriorExports(unittest.TestCase):
@patch("firestore_export.storage.Client")
def test_keeps_latest_deletes_others(self, mock_storage):
from firestore_export import _clear_prior_exports
def _blob(name):
b = MagicMock()
b.name = name
return b
today = _blob("firestore/2026-03-29/out.bin")
old1 = _blob("firestore/2026-03-22/out.bin")
old2 = _blob("firestore/2026-03-15/out.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [
today, old1, old2,
]
_clear_prior_exports("staging", "2026-03-29")
today.delete.assert_not_called()
old1.delete.assert_called_once()
old2.delete.assert_called_once()
@patch("firestore_export.storage.Client")
def test_cleanup_failure_is_swallowed(self, mock_storage):
from firestore_export import _clear_prior_exports
mock_storage.return_value.bucket.return_value.list_blobs.side_effect = RuntimeError("boom")
# Must not raise — cleanup is best-effort, the export already succeeded.
_clear_prior_exports("staging", "2026-03-29")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,52 @@
"""Tests for s3_upload module, focused on the exclude_prefixes behavior."""
import unittest
from unittest.mock import MagicMock, patch
def _blob(name):
b = MagicMock()
b.name = name
return b
class TestUploadStagingToS3(unittest.TestCase):
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_excluded_prefix_not_uploaded_or_deleted(self, mock_creds, mock_storage, mock_boto):
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
fs = _blob("firestore/2026-03-29/out.bin")
sec = _blob("secrets/2026-03-29.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [fs, sec]
upload_staging_to_s3("staging", "s3b", exclude_prefixes=["firestore/"])
# firestore held back: not uploaded, not deleted (stays as local backup)
fs.delete.assert_not_called()
# secrets uploaded then deleted
sec.delete.assert_called_once()
self.assertEqual(mock_boto.return_value.upload_fileobj.call_count, 1)
@patch("s3_upload.boto3.client")
@patch("s3_upload.storage.Client")
@patch("s3_upload.get_aws_credentials")
def test_no_exclude_uploads_everything(self, mock_creds, mock_storage, mock_boto):
from s3_upload import upload_staging_to_s3
mock_creds.return_value = {"access_key_id": "x", "secret_access_key": "y"}
fs = _blob("firestore/2026-03-29/out.bin")
sec = _blob("secrets/2026-03-29.bin")
mock_storage.return_value.bucket.return_value.list_blobs.return_value = [fs, sec]
upload_staging_to_s3("staging", "s3b")
self.assertEqual(mock_boto.return_value.upload_fileobj.call_count, 2)
fs.delete.assert_called_once()
sec.delete.assert_called_once()
if __name__ == "__main__":
unittest.main()
@@ -15,10 +15,22 @@ Provides search and cross-reference endpoints for the KJ Controller:
POST / {"action": "download_url", "file_id": "abc123"}
→ Generate a signed Google Drive download URL
POST / {"action": "refresh", "token": "..."}
→ On-demand "refresh now": force-run the divebar scheduler jobs
(Drive→BigQuery index, Drive→GCS file sync, xref rebuild) so a track
just published to the Nomad Drive shows up without waiting for the
nightly 2/3/6 AM runs. Token-gated (shared bearer) since the endpoint
is otherwise public.
Environment variables:
GCP_PROJECT_ID: GCP project ID
GCP_REGION: region the divebar scheduler jobs live in (for `refresh`)
DIVEBAR_REFRESH_SECRET_ID: Secret Manager secret holding the `refresh` bearer
token (read at runtime, so the function deploys before the secret has a
value — it just returns 403 until one is added)
"""
import hmac
import json
import logging
import os
@@ -32,7 +44,17 @@ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(messag
logger = logging.getLogger(__name__)
GCP_PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "nomadkaraoke")
GCP_REGION = os.environ.get("GCP_REGION", "us-central1")
DATASET = "karaoke_decide"
REFRESH_SECRET_ID = os.environ.get("DIVEBAR_REFRESH_SECRET_ID", "divebar-refresh-token")
# Cloud Scheduler jobs the `refresh` action force-runs, in pipeline order.
# Each carries its own OIDC identity/target, so we only need run permission.
REFRESH_SCHEDULER_JOBS = [
"divebar-mirror-daily", # Drive -> BigQuery index (track first appears)
"divebar-sync-vm-daily", # Drive -> GCS file sync (upgrades to fast URL)
"divebar-xref-rebuild-daily", # KN <-> Divebar cross-reference rebuild
]
def _json_response(data: dict, status: int = 200):
@@ -379,6 +401,68 @@ def _get_full_stats() -> dict:
}
def _get_expected_token() -> str:
"""Read the refresh bearer token from Secret Manager (latest version).
Read at call time rather than injected as an env var so the function can be
deployed before the secret has any version — until one is added this returns
"" and the gate below rejects every request. Returns "" on any access error
(missing secret/version, no permission) so failures fail closed.
"""
from google.cloud import secretmanager
name = f"projects/{GCP_PROJECT_ID}/secrets/{REFRESH_SECRET_ID}/versions/latest"
try:
client = secretmanager.SecretManagerServiceClient()
resp = client.access_secret_version(name=name)
return resp.payload.data.decode("utf-8").strip()
except Exception as e:
logger.warning("Could not read refresh token secret: %s", e)
return ""
def _refresh(token: str) -> dict:
"""Force-run the divebar pipeline scheduler jobs on demand.
Validates the shared bearer token (from Secret Manager), then triggers each
job in REFRESH_SCHEDULER_JOBS via the Cloud Scheduler API. Jobs run
asynchronously under their own identities; this returns as soon as they're
queued.
Returns {"triggered": [...]} on success. Raises PermissionError on a
bad/missing token.
"""
expected = _get_expected_token()
# Constant-time compare; also reject when the token isn't configured so a
# function deployed before the secret has a value can't be bypassed.
if not expected or not token or not hmac.compare_digest(str(token), expected):
raise PermissionError("invalid or missing refresh token")
from google.cloud import scheduler_v1
client = scheduler_v1.CloudSchedulerClient()
triggered, failed = [], []
for job in REFRESH_SCHEDULER_JOBS:
job_path = f"projects/{GCP_PROJECT_ID}/locations/{GCP_REGION}/jobs/{job}"
try:
client.run_job(name=job_path)
triggered.append(job)
except Exception as e:
# Best-effort: one job failing (e.g. already running) shouldn't
# block the others. Surface it so callers can see partial success.
logger.warning("Failed to run scheduler job %s: %s", job, e)
failed.append({"job": job, "error": str(e)})
return {
"triggered": triggered,
"failed": failed,
# The mirror/sync jobs run async (index ~minutes, GCS sync up to ~1h);
# the catalog reflects a newly-published track once the mirror index
# completes. xref fully reflects new tracks after the next mirror run.
"note": "Jobs queued. New tracks appear after the mirror index completes (~minutes).",
}
@functions_framework.http
def divebar_lookup(request):
"""HTTP Cloud Function entry point."""
@@ -434,6 +518,14 @@ def divebar_lookup(request):
stats = _get_full_stats()
return _json_response({"status": "ok", **stats})
elif action == "refresh":
try:
result = _refresh(body.get("token", ""))
except PermissionError:
# Don't leak whether the token exists; uniform 403.
return _json_response({"status": "error", "message": "forbidden"}, 403)
return _json_response({"status": "ok", **result})
else:
return _json_response({"status": "error", "message": f"Unknown action: {action}"}, 400)
@@ -4,5 +4,12 @@ google-cloud-bigquery>=3.13.0
# Cloud Storage (for signed download URLs)
google-cloud-storage>=2.13.0
# Cloud Scheduler (for the on-demand `refresh` action — force-runs the
# divebar mirror/sync/xref scheduler jobs)
google-cloud-scheduler>=2.13.0
# Secret Manager (reads the `refresh` action's bearer token at runtime)
google-cloud-secret-manager>=2.16.0
# Cloud Functions framework
functions-framework>=3.0.0
@@ -0,0 +1,139 @@
"""
Tests for divebar_lookup/main.py — focused on the on-demand `refresh` action.
`refresh` force-runs the divebar pipeline scheduler jobs (mirror index, GCS
file sync, xref rebuild) so a just-published track shows up without waiting for
the nightly runs. The endpoint is otherwise public, so the action is gated by a
shared bearer token (constant-time compare).
"""
import os
import sys
import json
from unittest.mock import MagicMock
import pytest
# Stub out Cloud Function deps that aren't installed in the test env. The
# scheduler/secret clients are imported lazily inside the refresh helpers, so
# stub them here too. functions_framework.http must be an identity decorator so
# the real entry point stays callable (a bare MagicMock would replace it).
_functions_framework = MagicMock()
_functions_framework.http = lambda fn: fn
_scheduler_mod = MagicMock()
for name, mod in (
("functions_framework", _functions_framework),
("google.cloud.bigquery", MagicMock()),
("google.cloud.storage", MagicMock()),
("google.cloud.scheduler_v1", _scheduler_mod),
("google.cloud.secretmanager", MagicMock()),
):
sys.modules.setdefault(name, mod)
sys.path.insert(0, os.path.dirname(__file__))
import main # noqa: E402
TOKEN = "s3cret-refresh-token"
@pytest.fixture(autouse=True)
def _reset_scheduler(monkeypatch):
"""Fresh scheduler client mock + a configured token (read from Secret
Manager at runtime, mocked here) for each test."""
monkeypatch.setattr(main, "_get_expected_token", lambda: TOKEN)
client = MagicMock()
_scheduler_mod.CloudSchedulerClient = MagicMock(return_value=client)
yield client
class MockRequest:
def __init__(self, body, method="POST"):
self.method = method
self._body = body
def get_json(self, silent=False):
return self._body
# ---------------------------------------------------------------------------
# _refresh — token gate
# ---------------------------------------------------------------------------
class TestRefreshTokenGate:
def test_wrong_token_raises(self, _reset_scheduler):
with pytest.raises(PermissionError):
main._refresh("nope")
_reset_scheduler.run_job.assert_not_called()
def test_empty_token_raises(self, _reset_scheduler):
with pytest.raises(PermissionError):
main._refresh("")
_reset_scheduler.run_job.assert_not_called()
def test_unconfigured_server_token_raises(self, monkeypatch, _reset_scheduler):
# Secret has no value yet (read returns "") — even if the caller sends a
# token, an unconfigured server rejects it (fails closed).
monkeypatch.setattr(main, "_get_expected_token", lambda: "")
with pytest.raises(PermissionError):
main._refresh("anything")
_reset_scheduler.run_job.assert_not_called()
# ---------------------------------------------------------------------------
# _refresh — job triggering
# ---------------------------------------------------------------------------
class TestRefreshTriggers:
def test_runs_all_pipeline_jobs_in_order(self, _reset_scheduler):
result = main._refresh(TOKEN)
assert result["triggered"] == main.REFRESH_SCHEDULER_JOBS
assert result["failed"] == []
# Each job referenced by its full path in the configured region.
called_paths = [c.kwargs["name"] for c in _reset_scheduler.run_job.call_args_list]
assert called_paths == [
f"projects/{main.GCP_PROJECT_ID}/locations/{main.GCP_REGION}/jobs/{j}"
for j in main.REFRESH_SCHEDULER_JOBS
]
def test_one_job_failing_does_not_block_others(self, _reset_scheduler):
# First job raises (e.g. already running); the rest still fire.
_reset_scheduler.run_job.side_effect = [
RuntimeError("already running"), None, None,
]
result = main._refresh(TOKEN)
assert result["triggered"] == main.REFRESH_SCHEDULER_JOBS[1:]
assert len(result["failed"]) == 1
assert result["failed"][0]["job"] == main.REFRESH_SCHEDULER_JOBS[0]
# ---------------------------------------------------------------------------
# divebar_lookup dispatch — refresh action
# ---------------------------------------------------------------------------
class TestRefreshDispatch:
def test_good_token_returns_200(self, _reset_scheduler):
body, status, _ = main.divebar_lookup(
MockRequest({"action": "refresh", "token": TOKEN})
)
assert status == 200
payload = json.loads(body)
assert payload["status"] == "ok"
assert payload["triggered"] == main.REFRESH_SCHEDULER_JOBS
def test_bad_token_returns_403_uniform_message(self, _reset_scheduler):
body, status, _ = main.divebar_lookup(
MockRequest({"action": "refresh", "token": "wrong"})
)
assert status == 403
payload = json.loads(body)
assert payload["status"] == "error"
# Uniform message — doesn't leak whether the token is configured.
assert payload["message"] == "forbidden"
_reset_scheduler.run_job.assert_not_called()
def test_missing_token_returns_403(self, _reset_scheduler):
body, status, _ = main.divebar_lookup(MockRequest({"action": "refresh"}))
assert status == 403
_reset_scheduler.run_job.assert_not_called()
@@ -370,9 +370,14 @@ def create_ephemeral_runner(labels: Iterable[str], pat: str) -> dict:
last_error: Exception | None = None
for zone in zones:
use_external_ip = (
family.needs_external_ip_in_fallback_zone and zone != PRIMARY_ZONE
)
# Always attach an ephemeral external IP so runner egress (Docker
# pulls, dependency downloads) leaves via the VM's own IP and bypasses
# the Cloud NAT data-processing charge (~$26/mo — runners were the
# NAT's only user). Ephemeral IPs are free while attached to a running
# VM, runners are short-lived, and us-central1 has ample IN_USE_ADDRESSES
# quota (limit 69). Supersedes the prior fallback-zone-only logic;
# `needs_external_ip_in_fallback_zone` is retained for documentation.
use_external_ip = True
instance = _build_instance(
name=runner_name,
family=family,
@@ -164,7 +164,9 @@ class TestCreateEphemeralRunner:
assert result["family"] == "general"
assert result["zone"] == "us-central1-a"
assert result["external_ip"] is False
# All runners now get an ephemeral external IP to bypass the Cloud NAT
# data-processing charge (runners were the NAT's only user).
assert result["external_ip"] is True
assert result["runner_name"].startswith("gha-general-")
compute_client.insert.assert_called_once()
@@ -24,6 +24,27 @@ def create_repository() -> artifactregistry.Repository:
location=REGION,
format="DOCKER",
description="Docker repository for karaoke backend images",
# Cost control: keep the 10 most recent versions for rollback, and
# delete untagged digests older than 7 days (orphaned layers left by
# repeated :latest pushes). Tagged images are never auto-deleted.
cleanup_policies=[
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-recent-10",
action="KEEP",
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
keep_count=10,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-untagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="UNTAGGED",
older_than="604800s", # 7 days
),
),
],
cleanup_policy_dry_run=False,
)
return artifact_repo
@@ -30,6 +30,27 @@ def create_audio_separator_artifact_repo() -> artifactregistry.Repository:
location=AUDIO_SEPARATOR_REGION,
format="DOCKER",
description="Docker repository for audio-separator GPU service",
# Cost control: audio-separator images bake ~14GB of models. Keep 10
# most recent versions for rollback; delete untagged digests older
# than 7 days.
cleanup_policies=[
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-recent-10",
action="KEEP",
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
keep_count=10,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-untagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="UNTAGGED",
older_than="604800s", # 7 days
),
),
],
cleanup_policy_dry_run=False,
)
+43
View File
@@ -115,11 +115,27 @@ def create_divebar_lookup_resources(all_secrets: dict) -> dict:
service_account_email=sa.email,
environment_variables={
"GCP_PROJECT_ID": PROJECT_ID,
# Region the divebar scheduler jobs live in — the `refresh`
# action builds job paths from it to run them on demand.
"GCP_REGION": REGION,
# Secret holding the `refresh` bearer token. Read at runtime
# (not injected as a secret env var) so the function deploys
# cleanly before the secret has a version — it just returns 403
# until one is added. Avoids a deploy-ordering gotcha.
"DIVEBAR_REFRESH_SECRET_ID": all_secrets["divebar-refresh-token"].secret_id,
},
),
)
resources["function"] = function
# Allow the function SA to read the refresh-token secret at runtime.
resources["refresh_token_accessor"] = gcp.secretmanager.SecretIamMember(
"divebar-lookup-refresh-token-accessor",
secret_id=all_secrets["divebar-refresh-token"].secret_id,
role="roles/secretmanager.secretAccessor",
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
# ==================== IAM: Allow unauthenticated access ====================
# The KJ Controller calls this from a LAN device without GCP credentials.
# The function only reads from BigQuery (no write to external resources).
@@ -189,4 +205,31 @@ def create_divebar_lookup_resources(all_secrets: dict) -> dict:
),
)
# ==================== IAM: on-demand scheduler-job runner ====================
# The `refresh` action forces the existing divebar scheduler jobs
# (mirror index, file-sync VM start, xref rebuild) to run immediately,
# reusing their own OIDC identities and targets. The function SA therefore
# only needs permission to *run* those jobs — not to invoke the mirror
# function or start the VM directly. Least-privilege custom role rather than
# the broad roles/cloudscheduler.admin.
scheduler_runner_role = gcp.projects.IAMCustomRole(
"divebar-scheduler-runner-role",
role_id="divebarSchedulerRunner",
title="Divebar Scheduler Job Runner",
description="Run (force-trigger) Divebar Cloud Scheduler jobs on demand",
permissions=[
"cloudscheduler.jobs.run",
"cloudscheduler.jobs.get",
],
)
resources["scheduler_runner_role"] = scheduler_runner_role
resources["scheduler_runner_binding"] = gcp.projects.IAMMember(
"divebar-lookup-scheduler-runner",
project=PROJECT_ID,
role=scheduler_runner_role.id,
member=sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
return resources
@@ -21,4 +21,24 @@ def create_gpu_artifact_repo() -> artifactregistry.Repository:
location=GPU_REGION,
format="DOCKER",
description="Docker repository for GPU-enabled karaoke-backend images (audio worker)",
# Cost control: GPU images are multi-GB. Keep 10 most recent versions
# for rollback; delete untagged digests older than 7 days.
cleanup_policies=[
artifactregistry.RepositoryCleanupPolicyArgs(
id="keep-recent-10",
action="KEEP",
most_recent_versions=artifactregistry.RepositoryCleanupPolicyMostRecentVersionsArgs(
keep_count=10,
),
),
artifactregistry.RepositoryCleanupPolicyArgs(
id="delete-untagged-after-7d",
action="DELETE",
condition=artifactregistry.RepositoryCleanupPolicyConditionArgs(
tag_state="UNTAGGED",
older_than="604800s", # 7 days
),
),
],
cleanup_policy_dry_run=False,
)
+6
View File
@@ -68,6 +68,12 @@ def create_secrets() -> dict[str, secretmanager.Secret]:
# Notifications (Discord)
"discord-alert-webhook",
# Divebar on-demand refresh trigger (shared bearer token: kjbox's
# "Refresh catalog" button -> divebar-lookup `refresh` action). Gates
# an otherwise-public endpoint that re-runs the mirror/sync/xref
# scheduler jobs on demand, so it's anti-abuse, not data-sensitive.
"divebar-refresh-token",
]
secrets = {}
+45 -7
View File
@@ -129,18 +129,56 @@ Notification channels are managed as Pulumi IaC in
attached to every alert policy.
**Current channel:** one email channel (`alerts-email`) delivering to the
project owner. Cloud Monitoring puts new email channels in PENDING state and
sends a one-time confirmation link to the address; the channel stays inactive
until the link is clicked.
project owner.
If alerts seem to be firing but not delivering, check:
### Gotcha: Pulumi-created email channels don't auto-send the verification email
When an email channel is created through the **Cloud Console**, Cloud Monitoring
automatically sends a verification link to the address. When it's created
through the **API or Pulumi**, that auto-send does **not** happen — the channel
lands in `verificationStatus=UNVERIFIED` and stays there silently. Alerts will
fire and resolve but no email gets delivered.
After `pulumi up` creates a new email channel, trigger the verification email
explicitly:
```bash
gcloud alpha monitoring channels list --project=nomadkaraoke \
--format='table(displayName,type,verificationStatus,enabled)'
unset GOOGLE_APPLICATION_CREDENTIALS # need admin creds, not claude-readonly
CHANNEL_ID=$(gcloud alpha monitoring channels list --project=nomadkaraoke \
--filter='type=email AND displayName="Andrew (email)"' \
--format='value(name.basename())')
curl -sS -X POST -d '{}' \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://monitoring.googleapis.com/v3/projects/nomadkaraoke/notificationChannels/${CHANNEL_ID}:sendVerificationCode"
```
`verificationStatus=VERIFIED` is the active state.
The email arrives within a minute or two. Subject is something like
"Verify your email address for Google Cloud Alerting" and the body contains
a code in the form `G-NNNNNN` plus a clickable link. Either path completes
the verification — clicking the link is simplest, or POST the code to
`:verify`:
```bash
curl -sS -X POST -d '{"code":"G-NNNNNN"}' \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://monitoring.googleapis.com/v3/projects/nomadkaraoke/notificationChannels/${CHANNEL_ID}:verify"
```
Confirm afterwards:
```bash
curl -sS -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://monitoring.googleapis.com/v3/projects/nomadkaraoke/notificationChannels/${CHANNEL_ID}" \
| python3 -c "import json,sys; print(json.load(sys.stdin).get('verificationStatus','(missing)'))"
```
Expected output: `VERIFIED`. Until that's true, `gcloud alpha monitoring
channels list --format='table(...,verificationStatus,...)'` returns an
empty `verificationStatus` column (which is itself a tell — verified
channels populate the field).
### Adding a second channel (e.g. Discord)
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.182.0"
version = "0.183.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+2 -2
View File
@@ -19,7 +19,7 @@ Usage:
python scripts/measure_autocorrect_cost.py --jobs abc123 def456
# Single-model instead of the multi-model compare config
python scripts/measure_autocorrect_cost.py --limit 3 --models claude-fable-5
python scripts/measure_autocorrect_cost.py --limit 3 --models claude-opus-4-8
Requires:
- ANTHROPIC_API_KEY in the environment (for claude-* models)
@@ -55,7 +55,7 @@ logger.setLevel(logging.INFO)
PROJECT = "nomadkaraoke"
GCS_BUCKET = "karaoke-gen-storage-nomadkaraoke"
DEFAULT_MODELS = ["claude-fable-5", "gemini-3.1-pro-preview"]
DEFAULT_MODELS = ["claude-opus-4-8", "gemini-3.1-pro-preview"]
# ---------------------------------------------------------------------------
+5 -3
View File
@@ -565,9 +565,9 @@ def create_tenant_config() -> dict:
"audio_search": False,
"file_upload": True,
"youtube_url": False,
"youtube_upload": False,
"dropbox_upload": False,
"gdrive_upload": False,
"youtube_upload": False, # B2B: never publish to YouTube
"dropbox_upload": True, # Outputs delivered to the tenant's Dropbox folder
"gdrive_upload": False, # B2B: never publish to Google Drive
"theme_selection": False,
"color_overrides": False,
"enable_cdg": True,
@@ -579,6 +579,8 @@ def create_tenant_config() -> dict:
"locked_theme": THEME_ID,
"distribution_mode": "download_only",
"brand_prefix": "SINGA",
"dropbox_path": "/MediaUnsynced/Karaoke/Tracks-Singa",
"gdrive_folder_id": None, # No Google Drive for white-label tenants
"youtube_description_template": None,
},
"auth": {
+5 -3
View File
@@ -246,9 +246,9 @@ def create_tenant_config() -> dict:
"audio_search": False, # Vocal Star provides their own audio
"file_upload": True,
"youtube_url": False,
"youtube_upload": False, # Download only
"dropbox_upload": False,
"gdrive_upload": False,
"youtube_upload": False, # B2B: never publish to YouTube
"dropbox_upload": True, # Outputs delivered to the tenant's Dropbox folder
"gdrive_upload": False, # B2B: never publish to Google Drive
"theme_selection": False, # Always use Vocal Star theme
"color_overrides": False,
"enable_cdg": True,
@@ -260,6 +260,8 @@ def create_tenant_config() -> dict:
"locked_theme": THEME_ID, # Lock to Vocal Star theme - users cannot change
"distribution_mode": "download_only",
"brand_prefix": "VSTAR",
"dropbox_path": "/MediaUnsynced/Karaoke/Tracks-VocalStar",
"gdrive_folder_id": None, # No Google Drive for white-label tenants
"youtube_description_template": None
},
"auth": {