Compare commits

...
10 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 efb4aa8351 fix: add google-cloud-compute dependency for encoding worker VM management (#598)
## Summary

- Adds `google-cloud-compute` to pyproject.toml dependencies
- The backend needs this to call the Compute API (start/stop VMs) for
the blue-green encoding worker warmup
- Without it, the warmup/heartbeat endpoints return 500 with
`ImportError: cannot import name 'compute_v1' from 'google.cloud'`

## Test plan

- [x] Verified the import error in Cloud Run logs
- [ ] After merge, warmup endpoint should return 200

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 14:12:15 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d681e26b02 fix: encoding worker deploy failure should not block Docker deploy (#597)
## Summary

- The blue-green encoding worker health check failure was blocking the
entire CI job, preventing the Docker image from being built and deployed
to Cloud Run
- This meant the new backend code (with warmup/heartbeat endpoints) was
never deployed, causing 404s on the new routes
- Fix: add `continue-on-error: true` to health check and encode test
steps so the Docker deploy always proceeds
- The rollback step now checks step outputs instead of `failure()`
condition

## Root cause

The CI job runs encoding worker deploy → Docker build → Cloud Run deploy
sequentially. When the encoding worker health check failed (missing
`packaging` module), the job stopped before reaching the Docker build
step.

## Test plan

- [x] Encoding worker deploy failure no longer blocks Docker deploy
- [ ] Next CI run on main will deploy the backend with new routes

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 13:53:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2003d4acc8 fix: add packaging to encoding worker Packer image venv (#596)
## Summary

- Adds `packaging` to the pre-installed Python dependencies in the
Packer image venv
- The encoding worker imports `packaging.version.Version` but this
wasn't in the base image
- First blue-green deploy caught this via the health check — encoding
worker crashed on startup with `ModuleNotFoundError: No module named
'packaging'`
- Manually installed on both VMs as a temporary fix; this makes it
permanent for future image builds

## Test plan

- [x] Verified encoding worker starts after manual `pip install
packaging` on both VMs
- [ ] Next Packer image build will include this dependency

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 12:00:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 19efa269a8 feat: blue-green encoding worker deployment with deep health checks (#595)
## Summary

- Replaces single encoding worker VM with a blue-green pair (a/b) for
zero-downtime deployments
- VMs auto-start on demand (JIT warmup when user opens lyrics review)
and auto-shutdown after 15 min idle
- CI deploys to secondary VM, runs a real encode test, then swaps the
Firestore pointer atomically
- Deep health check catches issues like PR #587's pip crash before they
reach users
- Cloud Function checks idle VMs every 5 minutes and stops them to
minimize cost (~$10-15/mo idle vs $800/mo always-on)

## Architecture

- **Firestore config doc** (`config/encoding-worker`) is single source
of truth for primary/secondary routing
- **Backend** reads primary IP from Firestore (30s TTL cache), starts VM
on demand via Compute API
- **CI workflow** handles blue-green swap: deploy → health check → real
encode test → atomic Firestore swap → drain & stop old
- **Cloud Function** auto-stops idle VMs based on active jobs, user
activity, and deploy status
- **Frontend** sends warmup signal on lyrics review page load +
heartbeat on interactions

## Changes

### New Files
- `backend/services/encoding_worker_manager.py` — VM lifecycle +
Firestore config management
- `backend/api/routes/encoding_worker.py` — Warmup and heartbeat API
endpoints
- `infrastructure/functions/encoding_worker_idle/` — Idle shutdown Cloud
Function
- `infrastructure/modules/encoding_worker_manager.py` — Pulumi module
for Cloud Function + Scheduler
- `scripts/seed-encoding-worker-config.py` — Firestore config seeding
script
- `infrastructure/encoding-worker/test-assets/test-preview.ass` — Test
file for deploy health check

### Modified Files
- `infrastructure/compute/encoding_worker_vm.py` — Single VM →
blue-green pair
- `infrastructure/__main__.py` — Wire up new VMs, Cloud Function, IAM
- `backend/services/encoding_service.py` — Dynamic URL from Firestore,
warmup-aware retry
- `.github/workflows/ci.yml` — Blue-green deploy flow
- `frontend/` — Warmup signal on lyrics review, heartbeat, warming-up UI
state
- `docs/` — Architecture, development, troubleshooting, lessons learned

## Test plan

- [x] 47 new backend tests pass (EncodingWorkerManager, routes, dynamic
URL resolution)
- [x] 9 Cloud Function unit tests pass
- [x] All 2808 existing backend tests pass (1 pre-existing failure
unrelated)
- [x] All 1116 existing unit tests pass (3 pre-existing failures
unrelated)
- [ ] Pulumi preview shows expected resource changes
- [ ] Pulumi up applied locally before merge
- [ ] Firestore config seeded with VM IPs
- [ ] End-to-end verification after deployment

## Migration Steps (post-merge)

1. `pulumi up` creates 2 VMs, removes old VM
2. Seed Firestore: `python scripts/seed-encoding-worker-config.py <ip-a>
<ip-b>`
3. Start VM A, verify health
4. First CI deploy exercises the blue-green flow

## Design Docs

- Spec:
`docs/superpowers/specs/2026-03-24-blue-green-encoding-worker-design.md`
- Plan:
`docs/superpowers/plans/2026-03-24-blue-green-encoding-worker.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 11:28:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4e23f07d0a Fix credit evaluation: Vertex AI credentials + enriched admin review email (#594)
## Summary
- Fix Gemini API call failing due to missing API key — switch to Vertex
AI with default GCP credentials
- Enrich admin review email with abuse signals (IP, geo, fingerprint,
matching accounts, user agent, signup counts)
- HTML-escape user-controlled values in review email

## Test plan
- [x] All 50 anti-abuse + credit evaluation tests pass
- [x] Full backend test suite passes (2549 pass, 139 skipped)
- [ ] Manual test: sign up with clean email, verify welcome credits
granted
- [ ] Manual test: verify admin review email includes signal details
when evaluation triggers

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 23:48:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7d887a11b0 Fix FLAC uploads to AudioShake by stripping metadata (#593)
## Summary
- Strip metadata from FLAC files before uploading to AudioShake to
prevent 502 errors caused by non-standard tags (MP4/M4A container fields
embedded in FLAC)
- Uses `ffmpeg -map 0:a -c copy -map_metadata -1` to remove metadata
while keeping audio unchanged
- Added unit + integration tests for the new metadata stripping path

## Context
AudioShake confirmed that non-standard metadata tags in FLAC files cause
their processing pipeline to fail during task creation. The audio itself
is valid — only the metadata is problematic. This fix proactively strips
all metadata before upload.

## Test plan
- [x] Unit test: FLAC files route through `_strip_metadata` instead of
direct upload
- [x] Integration test: metadata is actually removed from output FLAC
(verified via ffprobe)
- [x] All 30 AudioShake tests pass
- [x] Full test suite: 1117 passed (3 pre-existing failures unrelated to
this change)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 23:18:56 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 6577babfea Reduce free credits from 2 to 1 per grant (#592)
## Summary

- Welcome credits: 2 → 1 (granted on first email verification)
- Feedback credits: 2 → 1 (granted for submitting product feedback)
- Total possible free credits per account: 4 → 2

## Changes

**Backend:** `NEW_USER_FREE_CREDITS` constant, feedback credit grant, AI
evaluation prompt, model defaults
**Frontend:** Landing page, dashboard banner, feedback dialog, auth
dropdown menu text
**Tests:** Updated all assertions and mock values (115 backend + 712
frontend tests pass)
**Docs:** AI-CREDIT-GATING.md, API.md, README.md,
PRODUCT-COMMUNICATION-GUIDE.md

## Test plan

- [x] Backend tests pass (115 passed)
- [x] Frontend Jest tests pass (712 passed)
- [ ] CI pipeline passes
- [ ] Verify landing page shows "1 Free Credit" after deploy
- [ ] Verify new user signup grants 1 credit (not 2)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:30:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a7e41a09d6 Fix custom background image not applied in guided flow (#590)
@coderabbitai ignore

## Summary

- **Bug:** Custom background images uploaded during guided job creation
were silently ignored — the endpoint returned 500 due to
`AttributeError: 'StorageService' object has no attribute 'bucket_name'`
- **Fix:** `storage_service.bucket_name` → `storage_service.bucket.name`
(the correct attribute path)
- **Test fix:** Updated mock to use real attribute path
(`mock.bucket.name`) so this class of bug is caught

## Root Cause

The `complete_style_uploads` endpoint (line 2489) referenced
`storage_service.bucket_name`, but `StorageService` only exposes
`self.bucket` (a GCS Bucket object). The correct path is
`storage_service.bucket.name`.

The frontend's `uploadStyleAssets` caught the 500 error silently
(`console.error` only), so jobs continued rendering with default theme
backgrounds instead of the user's uploaded custom image.

The test passed because Mock objects auto-create attributes —
`mock.bucket_name = "test-bucket"` worked even though the real service
has no such attribute.

## Test plan

- [x] All 23 style upload tests pass
- [ ] Submit a job with custom background image and verify it renders
correctly

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:00:12 -04:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 3e8e3474b2 Fix Pulumi state drift: env var ordering, divebar VM, model bucket (#591)
@coderabbitai ignore

## Summary
- Sort Cloud Run Job env vars alphabetically to match GCP API return
order (prevents phantom diffs on every `pulumi preview`)
- Add divebar-sync VM infrastructure code that was deployed from a
feature branch but never merged to main (prevents accidental deletion of
active infrastructure)
- Remove dead `create_model_bucket()` code and empty GCS bucket (models
baked into Docker image)

## Changes
- **`infrastructure/modules/cloud_run.py`**: Reorder env vars
alphabetically in all 4 Cloud Run Jobs (video-encoding,
audio-separation, lyrics-transcription, audio-download)
- **`infrastructure/compute/divebar_sync_vm.py`** (new): GCE VM
definition for divebar file sync (Drive → GCS)
- **`infrastructure/compute/startup_scripts/divebar_sync.sh`** (new): VM
startup script with google-auth pinning and MTLS workarounds
- **`infrastructure/__main__.py`**: Wire divebar-sync VM, Cloud
Scheduler, and IAM binding
- **`infrastructure/modules/audio_separator_service.py`**: Remove unused
`create_model_bucket()` and `storage` import

## Verification
- `pulumi preview` shows **0 changes** after applying
- `pulumi up` applied successfully (4 Cloud Run Job SDK metadata updates
+ 2 empty bucket deletes)
- Divebar-sync VM continues running undisturbed

## Test plan
- [x] `pulumi preview --diff` confirms zero drift
- [x] `pulumi up` applied cleanly (update #649)
- [x] Divebar-sync VM verified RUNNING in GCP
- [x] No application code changes — infra-only

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 20:53:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4f8d2d71ed Fix pip resolution-too-deep in Docker base image build (#589)
## Summary
- Pin all 10 google-cloud-* and google-auth-* packages to exact latest
versions instead of loose lower bounds (e.g., `>=2.14.0` → `2.26.0`)
- Eliminates pip's massive backtracking that caused
`resolution-too-deep` errors during Docker base image builds
- Version bump: 0.150.2 → 0.150.3

## Context
The Docker base image build (`pip install -e .`) was failing because pip
had to search through hundreds of version combinations for
google-cloud-run, google-cloud-monitoring, grpc-google-iam-v1, and
googleapis-common-protos. Exact pins give pip zero backtracking to do.

## Test plan
- [x] `poetry lock` resolves cleanly
- [x] Backend tests pass (297 passed)
- [ ] CI Docker base image build succeeds (the actual fix)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 20:47:05 -04:00
58 changed files with 5350 additions and 528 deletions

No files matched your search

+245 -111
View File
@@ -1016,14 +1016,15 @@ jobs:
version: "latest"
# ============================================
# Deploy to GCE Encoding Worker (Immutable Deployment Pattern)
# Blue-Green Deploy to GCE Encoding Worker
#
# This pattern ensures version consistency:
# 1. Upload wheel to FIXED path (no version sorting)
# 2. Upload startup.sh (logic can change without image rebuild)
# 3. Write version manifest for verification
# 4. Restart service (triggers bootstrap.sh -> startup.sh)
# 5. STRICTLY verify deployed version (fail CI on mismatch)
# This pattern ensures zero-downtime deployments:
# 1. Upload wheel + startup.sh + version manifest to GCS
# 2. Read blue-green config from Firestore
# 3. Start secondary VM, wait for health + version match
# 4. Deep health check: submit a real encode test
# 5. Swap primary/secondary in Firestore (atomic transaction)
# 6. Drain and stop old primary
#
# See infrastructure/encoding-worker/README.md for details
# ============================================
@@ -1034,12 +1035,12 @@ jobs:
name: package-dist
path: dist/
- name: Deploy to GCE Encoding Worker
- name: Deploy to GCS
run: |
VERSION="${{ steps.version_check.outputs.version }}"
BUCKET="gs://karaoke-gen-storage-${{ env.PROJECT_ID }}"
echo "🚀 Deploying encoding worker v${VERSION}..."
echo "Deploying encoding worker v${VERSION}..."
# 1. Find the wheel file
WHEEL_FILE=$(ls dist/*.whl | head -1)
@@ -1047,11 +1048,11 @@ jobs:
echo "::error::No wheel file found in dist/"
exit 1
fi
echo "📦 Found wheel: $WHEEL_FILE"
echo "Found wheel: $WHEEL_FILE"
# 2. Upload wheel to FIXED path (atomic via temp file)
# This eliminates version sorting - always use karaoke_gen-current.whl
echo "📤 Uploading wheel to fixed path..."
echo "Uploading wheel to fixed path..."
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/karaoke_gen-current.whl.tmp"
gsutil mv "${BUCKET}/wheels/karaoke_gen-current.whl.tmp" \
"${BUCKET}/wheels/karaoke_gen-current.whl"
@@ -1060,130 +1061,263 @@ jobs:
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/"
# 3. Upload startup.sh (allows logic changes without image rebuild)
echo "📤 Uploading startup.sh..."
echo "Uploading startup.sh..."
gsutil cp infrastructure/encoding-worker/startup.sh \
"${BUCKET}/encoding-worker/startup.sh"
# 4. Write version manifest for verification
echo "📝 Writing version manifest..."
echo "Writing version manifest..."
echo "${VERSION}" | gsutil cp - "${BUCKET}/encoding-worker/version.txt"
echo "✅ GCS deployment complete"
echo "GCS deployment complete"
- name: Drain active encoding jobs before restart
- name: Install Firestore client
run: pip install google-cloud-firestore
- name: Read Firestore config
id: config
run: |
# Graceful drain: wait for any active encoding jobs to finish before
# restarting the worker. This prevents killing in-flight FFmpeg encodes.
#
# The /health endpoint returns active_jobs count. We poll until it's 0
# or until the drain timeout expires (10 minutes — well within the
# longest encoding time of ~5 min for a full 4-format encode).
python3 << 'PYEOF'
import json, os
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
doc = db.collection("config").document("encoding-worker").get()
if not doc.exists:
print("::error::Encoding worker config not found in Firestore")
raise SystemExit(1)
data = doc.to_dict()
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for key in ["primary_vm", "primary_ip", "primary_version",
"secondary_vm", "secondary_ip"]:
f.write(f"{key}={data.get(key, '')}\n")
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
PYEOF
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
DRAIN_TIMEOUT=600 # 10 minutes
POLL_INTERVAL=15
ELAPSED=0
- name: Wait for concurrent deploy
if: steps.config.outputs.deploy_in_progress == 'true'
run: |
echo "Another deploy is in progress, waiting..."
python3 << 'PYEOF'
import time
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
for i in range(20):
time.sleep(30)
doc = db.collection("config").document("encoding-worker").get()
if not doc.to_dict().get("deploy_in_progress", False):
print("Concurrent deploy finished, proceeding")
break
else:
print("::error::Timed out waiting for concurrent deploy (10 min)")
raise SystemExit(1)
PYEOF
echo "🔍 Checking for active encoding jobs before restart..."
- name: Set deploy in progress
run: |
python3 << 'PYEOF'
from datetime import datetime, timezone
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
db.collection("config").document("encoding-worker").update({
"deploy_in_progress": True,
"deploy_in_progress_since": datetime.now(timezone.utc).isoformat(),
})
print("Set deploy_in_progress=true")
PYEOF
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
HEALTH=$(curl -sf -H "X-API-Key: $WORKER_KEY" "$WORKER_URL/health" 2>/dev/null || echo '{"active_jobs": -1}')
ACTIVE=$(echo "$HEALTH" | grep -o '"active_jobs":[0-9]*' | cut -d: -f2)
- name: Start secondary VM
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
echo "Starting secondary VM: $SECONDARY_VM"
gcloud compute instances start "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
if [ -z "$ACTIVE" ] || [ "$ACTIVE" = "-1" ]; then
echo "⚠️ Could not reach health endpoint (worker may already be down). Proceeding with restart."
for i in $(seq 1 12); do
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(status)')
echo "VM status: $STATUS (attempt $i/12)"
if [ "$STATUS" = "RUNNING" ]; then
break
fi
if [ "$ACTIVE" = "0" ]; then
echo "✅ No active encoding jobs. Safe to restart."
break
fi
echo "⏳ $ACTIVE active encoding job(s) running. Waiting ${POLL_INTERVAL}s... (${ELAPSED}s/${DRAIN_TIMEOUT}s)"
sleep $POLL_INTERVAL
ELAPSED=$((ELAPSED + POLL_INTERVAL))
sleep 10
done
if [ $ELAPSED -ge $DRAIN_TIMEOUT ]; then
echo "⚠️ Drain timeout reached (${DRAIN_TIMEOUT}s) with jobs still active. Proceeding with restart."
echo " Active jobs will be recoverable via idempotent /encode endpoint (PR #413)."
- name: Wait for service health
id: health
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
echo "Waiting for service at $HEALTH_URL..."
for i in $(seq 1 18); do
RESPONSE=$(curl -sf "$HEALTH_URL" 2>/dev/null || echo "")
if [ -n "$RESPONSE" ]; then
WHEEL_VERSION=$(echo "$RESPONSE" | jq -r '.wheel_version // empty')
echo "Health: version=$WHEEL_VERSION"
if [ "$WHEEL_VERSION" = "$EXPECTED_VERSION" ]; then
echo "Version matches! Service is healthy."
echo "healthy=true" >> $GITHUB_OUTPUT
exit 0
fi
fi
echo "Attempt $i/18 - waiting 10s..."
sleep 10
done
echo "::error::Service did not become healthy within 3 minutes"
echo "healthy=false" >> $GITHUB_OUTPUT
exit 1
- name: Deep health check - real encode test
if: steps.health.outputs.healthy == 'true'
id: encode-test
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
echo "Uploading test assets to GCS..."
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
echo "Submitting test encode to $SECONDARY_IP..."
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"job_id": "deploy-health-check",
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
"duration_seconds": 10
}')
echo "Encode response: $RESPONSE"
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
echo "::error::Encode test failed with status: $STATUS"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
- name: Restart GCE Encoding Worker
run: |
VERSION="${{ steps.version_check.outputs.version }}"
echo "🔄 Restarting encoding worker..."
# Use IAP tunneling - works directly with service account credentials
gcloud compute ssh encoding-worker \
--zone=us-central1-c \
--project=nomadkaraoke \
--tunnel-through-iap \
--command="sudo systemctl restart encoding-worker"
echo "⏳ Waiting for service to start (up to 60s)..."
sleep 20
- name: Verify Encoding Worker Version
run: |
VERSION="${{ steps.version_check.outputs.version }}"
echo "🔍 Verifying encoding worker version..."
# Retry loop - service may take time to fully start
MAX_RETRIES=6
RETRY_DELAY=10
for i in $(seq 1 $MAX_RETRIES); do
echo "Attempt $i/$MAX_RETRIES..."
NEW_VERSION=$(gcloud compute ssh encoding-worker \
--zone=us-central1-c \
--project=nomadkaraoke \
--tunnel-through-iap \
--command="curl -s http://localhost:8080/health 2>/dev/null | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4" 2>/dev/null || echo "")
if [ "$NEW_VERSION" = "$VERSION" ]; then
echo "✅ Encoding worker version verified: v$NEW_VERSION"
for i in $(seq 1 12); do
sleep 5
JOB_STATUS=$(curl -sf \
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
echo "Encode status: $JOB_STATUS (attempt $i/12)"
if [ "$JOB_STATUS" = "completed" ]; then
echo "Encode test passed!"
echo "passed=true" >> $GITHUB_OUTPUT
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
exit 0
fi
if [ -n "$NEW_VERSION" ]; then
echo "⚠️ Version: $NEW_VERSION (expected: $VERSION)"
else
echo "⚠️ Health endpoint not responding yet"
fi
if [ $i -lt $MAX_RETRIES ]; then
echo " Retrying in ${RETRY_DELAY}s..."
sleep $RETRY_DELAY
elif [ "$JOB_STATUS" = "failed" ]; then
echo "::error::Encode test failed"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
done
# STRICT VERIFICATION: Fail CI on version mismatch
echo ""
echo "=============================================="
echo "❌ ENCODING WORKER DEPLOYMENT FAILED"
echo "=============================================="
echo "Expected version: $VERSION"
echo "Deployed version: $NEW_VERSION"
echo ""
echo "Possible causes:"
echo " - GCS upload failed (check 'Deploy to GCE' step)"
echo " - startup.sh download failed (check VM logs)"
echo " - Wheel installation failed (check VM logs)"
echo ""
echo "To debug, SSH to VM and check logs:"
echo " gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke --tunnel-through-iap"
echo " sudo journalctl -u encoding-worker -n 100"
echo " cat /var/log/encoding-worker-startup.log"
echo "=============================================="
echo "::error::Encode test timed out after 60s"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
- name: Rollback on failure
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
gcloud compute instances stop "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
fi
python3 -c "
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
db.collection('config').document('encoding-worker').update({
'deploy_in_progress': False,
'deploy_in_progress_since': None,
})
print('Cleared deploy_in_progress flag')
" || true
- name: Swap primary in Firestore
if: steps.encode-test.outputs.passed == 'true'
env:
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
NEW_VERSION: ${{ steps.version_check.outputs.version }}
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
run: |
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
python3 << 'PYEOF'
import os
from datetime import datetime, timezone
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
doc_ref = db.collection("config").document("encoding-worker")
now = datetime.now(timezone.utc).isoformat()
@firestore.transactional
def swap(transaction):
transaction.update(doc_ref, {
"primary_vm": os.environ["NEW_PRIMARY"],
"primary_ip": os.environ["NEW_PRIMARY_IP"],
"primary_version": os.environ["NEW_VERSION"],
"primary_deployed_at": now,
"secondary_vm": os.environ["OLD_PRIMARY"],
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
"secondary_version": os.environ["OLD_VERSION"],
"secondary_deployed_at": now,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
transaction = db.transaction()
swap(transaction)
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
PYEOF
- name: Drain and stop old primary
if: steps.encode-test.outputs.passed == 'true'
run: |
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
if [ "$ACTIVE_JOBS" -gt 0 ]; then
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
DRAIN_TIMEOUT=600
ELAPSED=0
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
if [ "$ACTIVE_JOBS" -eq 0 ]; then
break
fi
done
fi
echo "Stopping old primary: $OLD_PRIMARY"
gcloud compute instances stop "$OLD_PRIMARY" \
--zone=us-central1-c --project=nomadkaraoke || true
- name: Configure Docker for Artifact Registry
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
+65
View File
@@ -0,0 +1,65 @@
"""
Encoding worker lifecycle endpoints.
Provides warmup and heartbeat endpoints for the blue-green
encoding worker VMs. Called by the frontend to ensure the
primary VM is running before encoding requests.
"""
import logging
from fastapi import APIRouter, Depends
from backend.api.dependencies import require_admin
from backend.services.encoding_worker_manager import EncodingWorkerManager
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/internal/encoding-worker", tags=["encoding-worker"])
# Lazy-loaded singleton
_manager = None
def get_worker_manager():
global _manager
if _manager is None:
from google.cloud import compute_v1, firestore
from backend.config import get_settings
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,
)
return _manager
@router.post("/warmup")
async def warmup_encoding_worker(
_admin=Depends(require_admin),
manager=Depends(get_worker_manager),
):
"""Start the primary encoding worker VM if it's stopped."""
try:
result = manager.ensure_primary_running()
if result["started"]:
logger.info(f"Started encoding worker VM: {result['vm_name']}")
return result
except Exception as e:
logger.error(f"Failed to warm up encoding worker: {e}")
return {"started": False, "error": str(e)}
@router.post("/heartbeat")
async def heartbeat_encoding_worker(
_admin=Depends(require_admin),
manager=Depends(get_worker_manager),
):
"""Update activity timestamp to prevent idle shutdown."""
try:
manager.update_activity()
return {"status": "ok"}
except Exception as e:
logger.error(f"Failed to update encoding worker heartbeat: {e}")
return {"status": "error", "error": str(e)}
+1 -1
View File
@@ -2486,7 +2486,7 @@ async def complete_style_uploads(
# Overwrite background paths with custom uploads
for asset_key, gcs_path in new_style_assets.items():
bucket_name = storage_service.bucket_name
bucket_name = storage_service.bucket.name
gcs_uri = f"gs://{bucket_name}/{gcs_path}"
if asset_key == "intro_background" and "intro" in style_params:
style_params["intro"]["background_image"] = gcs_uri
+4 -4
View File
@@ -1126,7 +1126,7 @@ async def check_feedback_eligibility(
eligible=eligible,
has_submitted=user.has_submitted_feedback,
jobs_completed=user.total_jobs_completed,
credits_reward=2,
credits_reward=1,
)
@@ -1137,7 +1137,7 @@ async def submit_user_feedback(
user_service: UserService = Depends(get_user_service),
):
"""
Submit product feedback to earn 2 free credits.
Submit product feedback to earn 1 free credit.
Requires authentication. Users must have completed 2+ jobs and
not have already submitted feedback. At least one text field
@@ -1266,8 +1266,8 @@ async def submit_user_feedback(
credits_granted=0,
)
# Grant 2 credits (passed evaluation)
credits_granted = 2
# Grant 1 credit (passed evaluation)
credits_granted = 1
user_service.add_credits(
email=user.email,
amount=credits_granted,
+2 -1
View File
@@ -7,7 +7,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
from backend.services.spacy_preloader import preload_spacy_model
@@ -153,6 +153,7 @@ app.include_router(health.router, prefix="/api")
app.include_router(jobs.router, prefix="/api")
app.include_router(file_upload.router, prefix="/api") # File upload endpoint
app.include_router(internal.router, prefix="/api") # Internal worker endpoints
app.include_router(encoding_worker.router, prefix="/api") # Encoding worker lifecycle
app.include_router(review.router, prefix="/api") # Review UI compatibility endpoints
app.include_router(auth.router, prefix="/api") # OAuth credential management
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
+2 -2
View File
@@ -229,7 +229,7 @@ class UserFeedback(BaseModel):
Feedback from any user (not just beta testers).
Stored in Firestore 'user_feedback' collection.
Users earn 2 free credits for submitting detailed feedback.
Users earn 1 free credit for submitting detailed feedback.
"""
id: str
user_email: str
@@ -284,4 +284,4 @@ class FeedbackEligibilityResponse(BaseModel):
eligible: bool
has_submitted: bool
jobs_completed: int
credits_reward: int = 2
credits_reward: int = 1
+13 -3
View File
@@ -26,11 +26,12 @@ class CreditEvaluation:
reasoning: str
confidence: float
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
SYSTEM_PROMPT = """You are an anti-abuse evaluator for Nomad Karaoke, a web service that creates professional karaoke videos. Each job costs the service real money in API credits and cloud compute.
New users get 2 free welcome credits to try the service. Users who complete 2 jobs and submit feedback get 2 more credits. Some users abuse this by creating multiple accounts to get unlimited free karaoke generation.
New users get 1 free welcome credit to try the service. Users who complete 2 jobs and submit feedback get 1 more credit. Some users abuse this by creating multiple accounts to get unlimited free karaoke generation.
Your job: Given the signals below, decide whether to GRANT or DENY free credits to this user.
@@ -293,7 +294,11 @@ class CreditEvaluationService:
"""Call Gemini and return the response text."""
from google import genai
client = genai.Client()
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location=self.settings.gcp_region,
)
response = client.models.generate_content(
model=self.settings.credit_eval_model,
contents=prompt,
@@ -377,6 +382,7 @@ class CreditEvaluationService:
decision="grant",
reasoning="No suspicious correlations found — clean user",
confidence=1.0,
signals=signals,
)
self._log_evaluation(email, grant_type, evaluation, signals)
return evaluation
@@ -397,6 +403,7 @@ class CreditEvaluationService:
response_text = self._call_gemini(prompt)
evaluation = _parse_gemini_response(response_text)
evaluation.signals = signals
self._log_evaluation(email, grant_type, evaluation, signals)
logger.info(
@@ -407,14 +414,17 @@ class CreditEvaluationService:
except Exception as e:
logger.exception(f"Credit evaluation failed for {email} — pending manual review (fail-closed)")
# Include whatever signals were collected before the failure
collected_signals = locals().get("signals")
evaluation = CreditEvaluation(
decision="pending_review",
reasoning="Evaluation failed — pending manual review",
confidence=0.0,
error=str(e),
signals=collected_signals,
)
try:
self._log_evaluation(email, grant_type, evaluation, {})
self._log_evaluation(email, grant_type, evaluation, collected_signals or {})
except Exception:
pass
return evaluation
+72 -4
View File
@@ -1548,21 +1548,88 @@ View all feedback: {admin_url}
)
def send_credit_review_needed_email(self, user_email: str, grant_type: str, reason: str) -> bool:
def send_credit_review_needed_email(
self,
user_email: str,
grant_type: str,
reason: str,
signals: dict | None = None,
) -> bool:
"""
Notify Andrew that a credit grant needs manual review.
Sent when AI evaluation fails, is uncertain, or encounters an error.
Includes a direct link to the user's admin page for quick action.
Includes abuse signals and a direct link to the user's admin page.
"""
admin_user_url = f"{self.frontend_url}/admin/users/detail?email={user_email}"
subject = f"Credit review needed: {user_email} ({grant_type})"
# Build signals summary for the email
signals_html = ""
signals_text = ""
if signals:
user_data = signals.get("user_data", {})
ip_geo = signals.get("ip_geo")
fp_matches = signals.get("fingerprint_matches", [])
ip_matches = signals.get("ip_matches", [])
rows = []
text_rows = []
if user_data.get("signup_ip"):
rows.append(("IP Address", user_data["signup_ip"]))
text_rows.append(f"IP Address: {user_data['signup_ip']}")
if ip_geo:
geo_str = ", ".join(
str(v) for v in [
ip_geo.get("city"), ip_geo.get("region"), ip_geo.get("country"),
] if v
)
if ip_geo.get("org"):
geo_str += f" ({ip_geo['org']})"
if geo_str:
rows.append(("Location", geo_str))
text_rows.append(f"Location: {geo_str}")
if signals.get("user_agent"):
rows.append(("User Agent", signals["user_agent"]))
text_rows.append(f"User Agent: {signals['user_agent']}")
if user_data.get("device_fingerprint"):
fp = user_data["device_fingerprint"]
rows.append(("Fingerprint", f"{fp[:12]}..."))
text_rows.append(f"Fingerprint: {fp[:12]}...")
rows.append(("Recent signups (IP)", str(signals.get("recent_signups_ip", 0))))
rows.append(("Recent signups (fingerprint)", str(signals.get("recent_signups_fp", 0))))
text_rows.append(f"Recent signups from IP: {signals.get('recent_signups_ip', 0)}")
text_rows.append(f"Recent signups from fingerprint: {signals.get('recent_signups_fp', 0)}")
if fp_matches:
match_emails = ", ".join(m.get("email", "?") for m in fp_matches)
rows.append(("Fingerprint matches", match_emails))
text_rows.append(f"Fingerprint matches: {match_emails}")
if ip_matches:
match_emails = ", ".join(m.get("email", "?") for m in ip_matches)
rows.append(("IP matches", match_emails))
text_rows.append(f"IP matches: {match_emails}")
table_rows = "".join(
f'<tr><td style="padding:4px 12px 4px 0;color:#999;white-space:nowrap;">{html.escape(label)}</td>'
f'<td style="padding:4px 0;">{html.escape(value or "")}</td></tr>'
for label, value in rows
)
signals_html = f"""
<table style="margin:12px 0;font-size:14px;border-collapse:collapse;">{table_rows}</table>"""
signals_text = "\n".join(text_rows)
content = f"""
<p>A {grant_type} credit grant for <strong>{user_email}</strong> needs your review.</p>
<p><strong>Reason:</strong> {reason}</p>
{signals_html}
<p>The user has been told that their signup is being reviewed and credits will be
assigned shortly if everything checks out.</p>
@@ -1576,10 +1643,11 @@ View all feedback: {admin_url}
</p>
"""
signals_section = f"\n{signals_text}\n" if signals_text else ""
text_content = f"""Credit review needed: {user_email} ({grant_type})
Reason: {reason}
{signals_section}
Review user: {admin_user_url}
If the user looks legitimate, grant them credits from their admin page.
+49 -4
View File
@@ -17,6 +17,7 @@ Usage:
import asyncio
import logging
import time
from typing import Optional, Dict, Any
import aiohttp
@@ -52,6 +53,34 @@ class EncodingService:
self._url = None
self._api_key = None
self._initialized = False
self._worker_manager = None
self._cached_url = None
self._url_cached_at = 0
self._URL_CACHE_TTL = 30 # seconds
def set_worker_manager(self, manager):
"""Set the worker manager for dynamic URL resolution from Firestore."""
self._worker_manager = manager
def _get_worker_url(self) -> str:
"""Get the current primary worker URL from Firestore (with TTL cache).
Falls back to static URL from config if worker_manager is not set.
"""
now = time.time()
if self._cached_url and (now - self._url_cached_at) < self._URL_CACHE_TTL:
return self._cached_url
if self._worker_manager:
config = self._worker_manager.get_config()
self._cached_url = config.primary_url
self._url_cached_at = now
return self._cached_url
# Fallback to static URL
if not self._initialized:
self._load_credentials()
return self._url
def _load_credentials(self):
"""Load encoding worker URL and API key from config/secrets."""
@@ -188,7 +217,7 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._url}/encode"
url = f"{self._get_worker_url()}/encode"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {
"job_id": job_id,
@@ -249,7 +278,7 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._url}/status/{job_id}"
url = f"{self._get_worker_url()}/status/{job_id}"
headers = {"X-API-Key": self._api_key}
resp = await self._request_with_retry(
@@ -437,7 +466,7 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._url}/encode-preview"
url = f"{self._get_worker_url()}/encode-preview"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {
"job_id": job_id,
@@ -543,7 +572,7 @@ class EncodingService:
if not self.is_configured:
return {"status": "not_configured"}
url = f"{self._url}/health"
url = f"{self._get_worker_url()}/health"
headers = {"X-API-Key": self._api_key}
try:
@@ -565,4 +594,20 @@ def get_encoding_service() -> EncodingService:
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
return _encoding_service
+239
View File
@@ -0,0 +1,239 @@
"""
Blue-Green Encoding Worker Manager.
Manages the lifecycle and role assignment of two GCE encoding worker VMs
(blue/green) via a Firestore config document as the single source of truth.
The config document at `config/encoding-worker` tracks which VM is primary
(actively serving encoding requests) and which is secondary (idle or being
deployed to). This enables zero-downtime deployments by swapping roles
after deploying new code to the secondary.
Usage:
from google.cloud import firestore
from google.cloud.compute_v1 import InstancesClient
db = firestore.Client()
compute = InstancesClient()
manager = EncodingWorkerManager(db, compute)
# Get current config
config = manager.get_config()
print(f"Primary: {config.primary_vm} at {config.primary_url}")
# Ensure primary VM is running before dispatching work
result = manager.ensure_primary_running()
"""
import logging
from dataclasses import dataclass
from datetime import datetime, UTC
from typing import Optional
from google.cloud import firestore
logger = logging.getLogger(__name__)
CONFIG_COLLECTION = "config"
CONFIG_DOCUMENT = "encoding-worker"
ENCODING_WORKER_PORT = 8080
@dataclass
class EncodingWorkerConfig:
"""Represents the Firestore config/encoding-worker document."""
primary_vm: str
primary_ip: str
primary_version: str
primary_deployed_at: Optional[str]
secondary_vm: str
secondary_ip: str
secondary_version: Optional[str]
secondary_deployed_at: Optional[str]
last_swap_at: Optional[str]
last_activity_at: Optional[str]
deploy_in_progress: bool
deploy_in_progress_since: Optional[str]
@property
def primary_url(self) -> str:
return f"http://{self.primary_ip}:{ENCODING_WORKER_PORT}"
@property
def secondary_url(self) -> str:
return f"http://{self.secondary_ip}:{ENCODING_WORKER_PORT}"
class EncodingWorkerManager:
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
def __init__(self, db, compute_client=None, project_id="nomadkaraoke", zone="us-central1-c"):
self._db = db
self._compute = compute_client
self._project_id = project_id
self._zone = zone
def _doc_ref(self):
"""Return a reference to the config/encoding-worker document."""
return self._db.collection(CONFIG_COLLECTION).document(CONFIG_DOCUMENT)
# ------------------------------------------------------------------
# Firestore config operations (Task 1)
# ------------------------------------------------------------------
def get_config(self) -> EncodingWorkerConfig:
"""Read config/encoding-worker from Firestore and return as dataclass."""
snapshot = self._doc_ref().get()
if not snapshot.exists:
raise ValueError(
f"Encoding worker config document not found at "
f"{CONFIG_COLLECTION}/{CONFIG_DOCUMENT}"
)
data = snapshot.to_dict()
return EncodingWorkerConfig(
primary_vm=data["primary_vm"],
primary_ip=data["primary_ip"],
primary_version=data["primary_version"],
primary_deployed_at=data.get("primary_deployed_at"),
secondary_vm=data["secondary_vm"],
secondary_ip=data["secondary_ip"],
secondary_version=data.get("secondary_version"),
secondary_deployed_at=data.get("secondary_deployed_at"),
last_swap_at=data.get("last_swap_at"),
last_activity_at=data.get("last_activity_at"),
deploy_in_progress=data.get("deploy_in_progress", False),
deploy_in_progress_since=data.get("deploy_in_progress_since"),
)
def update_activity(self) -> None:
"""Update last_activity_at timestamp to record recent usage."""
now = datetime.now(UTC).isoformat()
self._doc_ref().update({"last_activity_at": now})
logger.info("Updated encoding worker last_activity_at to %s", now)
def swap_roles(
self,
new_primary_vm: str,
new_primary_ip: str,
new_primary_version: str,
old_primary_vm: str,
old_primary_ip: str,
old_primary_version: str,
) -> None:
"""Atomically swap primary and secondary roles using a Firestore transaction.
Args:
new_primary_vm: VM name that will become the new primary.
new_primary_ip: Internal IP of the new primary.
new_primary_version: Version deployed on the new primary.
old_primary_vm: Current primary VM name (becomes secondary).
old_primary_ip: Internal IP of the old primary.
old_primary_version: Version on the old primary.
"""
transaction = self._db.transaction()
doc_ref = self._doc_ref()
now = datetime.now(UTC).isoformat()
@firestore.transactional
def _swap_in_transaction(txn, ref):
txn.update(ref, {
"primary_vm": new_primary_vm,
"primary_ip": new_primary_ip,
"primary_version": new_primary_version,
"primary_deployed_at": now,
"secondary_vm": old_primary_vm,
"secondary_ip": old_primary_ip,
"secondary_version": old_primary_version,
"secondary_deployed_at": None,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
_swap_in_transaction(transaction, doc_ref)
logger.info(
"Swapped encoding worker roles: %s -> primary, %s -> secondary",
new_primary_vm, old_primary_vm,
)
# ------------------------------------------------------------------
# VM lifecycle operations (Task 2)
# ------------------------------------------------------------------
def get_vm_status(self, vm_name: str) -> str:
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING)."""
instance = self._compute.get(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
return instance.status
def start_vm(self, vm_name: str) -> None:
"""Start a VM if it is not already running or starting.
Fire-and-forget: returns immediately. Caller should poll get_vm_status
if they need to wait for the VM to be fully RUNNING.
"""
status = self.get_vm_status(vm_name)
if status in ("RUNNING", "STAGING"):
logger.info("VM %s is already %s, skipping start", vm_name, status)
return
logger.info("Starting VM %s (current status: %s)", vm_name, status)
self._compute.start(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
def stop_vm(self, vm_name: str) -> None:
"""Stop a VM if it is not already stopped or stopping."""
status = self.get_vm_status(vm_name)
if status in ("TERMINATED", "STOPPING"):
logger.info("VM %s is already %s, skipping stop", vm_name, status)
return
logger.info("Stopping VM %s (current status: %s)", vm_name, status)
self._compute.stop(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
def ensure_primary_running(self) -> dict:
"""Ensure the primary encoding worker VM is running.
Reads config, starts primary VM if stopped, and updates activity timestamp.
Returns:
dict with keys:
- started (bool): True if VM was started, False if already running
- vm_name (str): Name of the primary VM
- primary_url (str): URL of the primary encoding worker
"""
config = self.get_config()
vm_name = config.primary_vm
status = self.get_vm_status(vm_name)
started = False
if status not in ("RUNNING", "STAGING"):
logger.info("Primary VM %s is %s, starting it", vm_name, status)
self._compute.start(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
started = True
else:
logger.info("Primary VM %s is already %s", vm_name, status)
self.update_activity()
return {
"started": started,
"vm_name": vm_name,
"primary_url": config.primary_url,
}
+7 -3
View File
@@ -48,7 +48,7 @@ class UserService:
"""Service for user management and authentication."""
# Number of free credits granted to new users
NEW_USER_FREE_CREDITS = 2
NEW_USER_FREE_CREDITS = 1
def __init__(self):
"""Initialize user service with Firestore client."""
@@ -427,7 +427,9 @@ class UserService:
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(email, "welcome", evaluation.reasoning)
email_service.send_credit_review_needed_email(
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
return False, "pending_review"
@@ -436,7 +438,9 @@ class UserService:
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(email, "welcome", f"Evaluation error: {email}")
email_service.send_credit_review_needed_email(
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
pass
return False, "pending_review"
+2 -2
View File
@@ -299,7 +299,7 @@ class TestSubmitFeedbackEmailIntegration:
would_use_again=False,
)
assert result.credits_granted == 2
assert result.credits_granted == 1
@patch("backend.services.email_service.get_email_service")
@patch("backend.services.auth_service.get_auth_service")
@@ -344,7 +344,7 @@ class TestSubmitFeedbackEmailIntegration:
# User still gets credits even though email failed
assert result.status == "success"
assert result.credits_granted == 2
assert result.credits_granted == 1
class TestFeedbackEmailNotification:
+4 -4
View File
@@ -127,7 +127,7 @@ class TestGrantWelcomeCredits:
# Verify update was called with credits and flag
mock_db.collection.return_value.document.return_value.update.assert_called_once()
update_args = mock_db.collection.return_value.document.return_value.update.call_args[0][0]
assert update_args['credits'] == 2
assert update_args['credits'] == 1
assert update_args['welcome_credits_granted'] is True
@patch('backend.services.user_service.get_settings')
@@ -379,7 +379,7 @@ def mock_user_svc():
email="test@example.com",
expires_at=datetime.utcnow() + timedelta(minutes=15),
)
svc.NEW_USER_FREE_CREDITS = 2
svc.NEW_USER_FREE_CREDITS = 1
return svc
@@ -530,7 +530,7 @@ class TestVerifyGrantsCredits:
mock_user_svc.grant_welcome_credits_if_eligible.return_value = (credits_eligible, "granted" if credits_eligible else "already_granted")
mock_user_svc.get_user.return_value = user
mock_user_svc.create_session.return_value = MagicMock(token="session-token")
mock_user_svc.NEW_USER_FREE_CREDITS = 2
mock_user_svc.NEW_USER_FREE_CREDITS = 1
# Mock magic link doc for first-login check
mock_ml_doc = MagicMock()
@@ -559,7 +559,7 @@ class TestVerifyGrantsCredits:
assert response.status_code == 200
data = response.json()
assert data["credits_granted"] == 2
assert data["credits_granted"] == 1
mock_user_svc.grant_welcome_credits_if_eligible.assert_called_once()
finally:
from backend.main import app
@@ -276,7 +276,7 @@ class TestFindRelatedAccounts:
@pytest.fixture
def mock_user_svc():
svc = MagicMock()
svc.NEW_USER_FREE_CREDITS = 2
svc.NEW_USER_FREE_CREDITS = 1
return svc
+3 -3
View File
@@ -405,10 +405,10 @@ class TestCreditRefundOnJobDeletion:
class TestWelcomeCredits:
"""Test new user welcome credits."""
def test_new_user_gets_2_welcome_credits(self):
"""Verify NEW_USER_FREE_CREDITS is set to 2."""
def test_new_user_gets_1_welcome_credit(self):
"""Verify NEW_USER_FREE_CREDITS is set to 1."""
from backend.services.user_service import UserService
assert UserService.NEW_USER_FREE_CREDITS == 2
assert UserService.NEW_USER_FREE_CREDITS == 1
class TestInsufficientCreditsError:
+60
View File
@@ -310,3 +310,63 @@ class TestWaitForCompletionPollTolerance:
assert result["status"] == "complete"
assert call_count == 6 # 2 fail + 1 success + 2 fail + 1 success
class TestDynamicURLResolution:
"""Tests that EncodingService reads URL from Firestore, not static config."""
def test_url_from_worker_manager(self):
"""Should read primary_url from worker manager."""
mock_manager = MagicMock()
mock_manager.get_config.return_value = MagicMock(
primary_url="http://34.1.2.3:8080",
)
service = EncodingService()
service._initialized = True
service._api_key = "test-key"
service.set_worker_manager(mock_manager)
url = service._get_worker_url()
assert url == "http://34.1.2.3:8080"
mock_manager.get_config.assert_called_once()
def test_url_caches_within_ttl(self):
"""Should cache URL and not re-read within TTL."""
mock_manager = MagicMock()
mock_manager.get_config.return_value = MagicMock(
primary_url="http://34.1.2.3:8080",
)
service = EncodingService()
service._initialized = True
service.set_worker_manager(mock_manager)
service._get_worker_url()
service._get_worker_url()
assert mock_manager.get_config.call_count == 1
def test_url_refreshes_after_ttl(self):
"""Should re-read URL after TTL expires."""
mock_manager = MagicMock()
mock_manager.get_config.return_value = MagicMock(
primary_url="http://34.1.2.3:8080",
)
service = EncodingService()
service._initialized = True
service.set_worker_manager(mock_manager)
service._URL_CACHE_TTL = 0 # Expire immediately
service._get_worker_url()
service._get_worker_url()
assert mock_manager.get_config.call_count == 2
def test_fallback_to_static_url_without_manager(self):
"""Should fall back to static URL when no worker manager set."""
service = EncodingService()
service._url = "http://static:8080"
service._api_key = "test-key"
service._initialized = True
url = service._get_worker_url()
assert url == "http://static:8080"
@@ -0,0 +1,330 @@
"""
Tests for the blue-green encoding worker manager service.
Tests cover:
- Task 1: Firestore config document schema, get_config, update_activity, swap_roles
- Task 2: VM lifecycle (get_vm_status, start_vm, stop_vm, ensure_primary_running)
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, patch, call
from backend.services.encoding_worker_manager import (
EncodingWorkerConfig,
EncodingWorkerManager,
CONFIG_COLLECTION,
CONFIG_DOCUMENT,
ENCODING_WORKER_PORT,
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
def _make_firestore_data(**overrides):
"""Create a realistic Firestore document dict for encoding-worker config."""
data = {
"primary_vm": "encoding-worker-blue",
"primary_ip": "10.128.0.50",
"primary_version": "1.0.0",
"primary_deployed_at": "2026-03-20T10:00:00Z",
"secondary_vm": "encoding-worker-green",
"secondary_ip": "10.128.0.51",
"secondary_version": "0.9.0",
"secondary_deployed_at": "2026-03-19T08:00:00Z",
"last_swap_at": "2026-03-20T10:00:00Z",
"last_activity_at": "2026-03-24T12:00:00Z",
"deploy_in_progress": False,
"deploy_in_progress_since": None,
}
data.update(overrides)
return data
@pytest.fixture
def mock_db():
"""Return a mock Firestore client with a pre-configured config document."""
db = MagicMock()
snapshot = MagicMock()
snapshot.exists = True
snapshot.to_dict.return_value = _make_firestore_data()
doc_ref = MagicMock()
doc_ref.get.return_value = snapshot
collection_ref = MagicMock()
collection_ref.document.return_value = doc_ref
db.collection.return_value = collection_ref
return db
@pytest.fixture
def mock_compute():
"""Return a mock Compute Engine InstancesClient."""
return MagicMock()
@pytest.fixture
def manager(mock_db, mock_compute):
return EncodingWorkerManager(
db=mock_db,
compute_client=mock_compute,
project_id="nomadkaraoke",
zone="us-central1-c",
)
# ---------------------------------------------------------------------------
# Task 1: Config dataclass
# ---------------------------------------------------------------------------
class TestEncodingWorkerConfig:
"""Tests for the EncodingWorkerConfig dataclass."""
def test_primary_url(self):
config = EncodingWorkerConfig(
primary_vm="blue", primary_ip="10.0.0.1", primary_version="1.0",
primary_deployed_at=None,
secondary_vm="green", secondary_ip="10.0.0.2",
secondary_version=None, secondary_deployed_at=None,
last_swap_at=None, last_activity_at=None,
deploy_in_progress=False, deploy_in_progress_since=None,
)
assert config.primary_url == "http://10.0.0.1:8080"
def test_secondary_url(self):
config = EncodingWorkerConfig(
primary_vm="blue", primary_ip="10.0.0.1", primary_version="1.0",
primary_deployed_at=None,
secondary_vm="green", secondary_ip="10.0.0.2",
secondary_version=None, secondary_deployed_at=None,
last_swap_at=None, last_activity_at=None,
deploy_in_progress=False, deploy_in_progress_since=None,
)
assert config.secondary_url == "http://10.0.0.2:8080"
# ---------------------------------------------------------------------------
# Task 1: get_config / update_activity / swap_roles
# ---------------------------------------------------------------------------
class TestEncodingWorkerManager:
"""Tests for Firestore config operations."""
def test_get_config_returns_dataclass(self, manager, mock_db):
config = manager.get_config()
assert isinstance(config, EncodingWorkerConfig)
assert config.primary_vm == "encoding-worker-blue"
assert config.primary_ip == "10.128.0.50"
assert config.primary_version == "1.0.0"
assert config.secondary_vm == "encoding-worker-green"
assert config.deploy_in_progress is False
def test_get_config_document_not_found(self, manager, mock_db):
snapshot = MagicMock()
snapshot.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = snapshot
with pytest.raises(ValueError, match="not found"):
manager.get_config()
def test_get_config_reads_correct_path(self, manager, mock_db):
manager.get_config()
mock_db.collection.assert_called_with(CONFIG_COLLECTION)
mock_db.collection.return_value.document.assert_called_with(CONFIG_DOCUMENT)
def test_update_activity_sets_timestamp(self, manager, mock_db):
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.update_activity()
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_called_once_with({
"last_activity_at": "2026-03-24T15:00:00+00:00",
})
def test_swap_roles_uses_transaction(self, manager, mock_db):
"""swap_roles should use a Firestore transaction for atomicity."""
# Set up the transaction mock
mock_transaction = MagicMock()
mock_db.transaction.return_value = mock_transaction
# The transactional function is called with the transaction
manager.swap_roles(
new_primary_vm="encoding-worker-green",
new_primary_ip="10.128.0.51",
new_primary_version="2.0.0",
old_primary_vm="encoding-worker-blue",
old_primary_ip="10.128.0.50",
old_primary_version="1.0.0",
)
# Verify transaction was created and the doc was updated within it
mock_db.transaction.assert_called_once()
def test_swap_roles_writes_correct_data(self, manager, mock_db):
"""swap_roles should write the swapped primary/secondary fields."""
mock_transaction = MagicMock()
mock_db.transaction.return_value = mock_transaction
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 16, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.swap_roles(
new_primary_vm="encoding-worker-green",
new_primary_ip="10.128.0.51",
new_primary_version="2.0.0",
old_primary_vm="encoding-worker-blue",
old_primary_ip="10.128.0.50",
old_primary_version="1.0.0",
)
# The transaction.update call should contain the swapped values
doc_ref = mock_db.collection.return_value.document.return_value
update_call = mock_transaction.update.call_args
assert update_call is not None
data = update_call[0][1] # second positional arg is the data dict
assert data["primary_vm"] == "encoding-worker-green"
assert data["primary_ip"] == "10.128.0.51"
assert data["primary_version"] == "2.0.0"
assert data["secondary_vm"] == "encoding-worker-blue"
assert data["secondary_ip"] == "10.128.0.50"
assert data["secondary_version"] == "1.0.0"
assert data["last_swap_at"] == "2026-03-24T16:00:00+00:00"
# ---------------------------------------------------------------------------
# Task 2: VM lifecycle
# ---------------------------------------------------------------------------
class TestVMLifecycle:
"""Tests for Compute Engine VM operations."""
def test_get_vm_status_returns_status(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
status = manager.get_vm_status("encoding-worker-blue")
assert status == "RUNNING"
mock_compute.get.assert_called_once_with(
project="nomadkaraoke",
zone="us-central1-c",
instance="encoding-worker-blue",
)
def test_get_vm_status_terminated(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
assert manager.get_vm_status("encoding-worker-blue") == "TERMINATED"
def test_start_vm_calls_compute_start(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_called_once_with(
project="nomadkaraoke",
zone="us-central1-c",
instance="encoding-worker-blue",
)
def test_start_vm_skips_if_already_running(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_not_called()
def test_stop_vm_calls_compute_stop(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
manager.stop_vm("encoding-worker-blue")
mock_compute.stop.assert_called_once_with(
project="nomadkaraoke",
zone="us-central1-c",
instance="encoding-worker-blue",
)
def test_stop_vm_skips_if_already_terminated(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
manager.stop_vm("encoding-worker-blue")
mock_compute.stop.assert_not_called()
def test_ensure_primary_running_starts_stopped_vm(self, manager, mock_db, mock_compute):
"""When primary is stopped, ensure_primary_running should start it."""
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_primary_running()
assert result["started"] is True
assert result["vm_name"] == "encoding-worker-blue"
assert result["primary_url"] == "http://10.128.0.50:8080"
mock_compute.start.assert_called_once()
def test_ensure_primary_running_already_running(self, manager, mock_db, mock_compute):
"""When primary is already running, should not start and still update activity."""
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_primary_running()
assert result["started"] is False
assert result["vm_name"] == "encoding-worker-blue"
assert result["primary_url"] == "http://10.128.0.50:8080"
mock_compute.start.assert_not_called()
def test_ensure_primary_running_updates_activity(self, manager, mock_db, mock_compute):
"""ensure_primary_running should always update last_activity_at."""
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.ensure_primary_running()
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_called_once()
def test_start_vm_skips_if_staging(self, manager, mock_compute):
"""start_vm should also skip if VM is in STAGING state (already starting)."""
mock_instance = MagicMock()
mock_instance.status = "STAGING"
mock_compute.get.return_value = mock_instance
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_not_called()
def test_stop_vm_skips_if_stopping(self, manager, mock_compute):
"""stop_vm should skip if VM is already in STOPPING state."""
mock_instance = MagicMock()
mock_instance.status = "STOPPING"
mock_compute.get.return_value = mock_instance
manager.stop_vm("encoding-worker-blue")
mock_compute.stop.assert_not_called()
@@ -0,0 +1,81 @@
"""
Unit tests for encoding worker lifecycle endpoints.
Tests the warmup and heartbeat API endpoints.
"""
import pytest
from unittest.mock import MagicMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.encoding_worker import router, get_worker_manager
from backend.api.dependencies import require_admin
def get_mock_admin():
"""Override for require_admin dependency."""
return ("admin-token", "admin", 0)
class TestWarmupEndpoint:
def setup_method(self):
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
def test_warmup_starts_stopped_vm(self):
self.mock_manager.ensure_primary_running.return_value = {
"started": True,
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
data = response.json()
assert data["started"] is True
assert data["vm_name"] == "encoding-worker-a"
def test_warmup_already_running(self):
self.mock_manager.ensure_primary_running.return_value = {
"started": False,
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
assert response.json()["started"] is False
def test_warmup_handles_error(self):
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
"VM not found"
)
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
assert response.json()["started"] is False
assert "error" in response.json()
class TestHeartbeatEndpoint:
def setup_method(self):
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
def test_heartbeat_updates_activity(self):
response = self.client.post("/api/internal/encoding-worker/heartbeat")
assert response.status_code == 200
assert response.json()["status"] == "ok"
self.mock_manager.update_activity.assert_called_once()
def test_heartbeat_handles_error(self):
self.mock_manager.update_activity.side_effect = RuntimeError(
"Firestore error"
)
response = self.client.post("/api/internal/encoding-worker/heartbeat")
assert response.status_code == 200
assert response.json()["status"] == "error"
+1 -1
View File
@@ -36,7 +36,7 @@ def mock_job_manager():
@pytest.fixture
def mock_storage_service():
with patch('backend.api.routes.file_upload.storage_service') as mock:
mock.bucket_name = "test-bucket"
mock.bucket.name = "test-bucket"
yield mock
+2 -2
View File
@@ -34,7 +34,7 @@ Gemini decision:
| Scenario | Credits | User Experience | Admin Notification |
|----------|---------|-----------------|-------------------|
| Clean user (no correlations) | Granted | "2 free credits!" interstitial | None |
| Clean user (no correlations) | Granted | "1 free credit!" interstitial | None |
| AI approves | Granted | Same | None |
| AI denies (abuse detected) | Not granted | "Couldn't grant free credits" + buy CTA | CC on rejection email to user |
| AI error / uncertain | Not granted | "Team will review shortly" + buy CTA | Review email with admin page link |
@@ -109,7 +109,7 @@ When you receive a "Credit review needed" email:
1. Click the "Review User" link to go to their admin page
2. Check their abuse signals: fingerprint matches, IP matches, job history
3. If legitimate: Use the admin credits endpoint to grant 2 credits manually
3. If legitimate: Use the admin credits endpoint to grant 1 credit manually
4. If abusive: No action needed — they already have 0 credits
Note: For `pending_review` cases, the `welcome_credits_granted` flag is NOT set, so the system won't interfere if you grant credits manually later.
+4 -4
View File
@@ -944,7 +944,7 @@ Credits are checked and deducted at job creation time. The flow:
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
Admin users bypass credit checks entirely. New users receive 2 welcome credits. Users can earn 2 additional free credits by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
Admin users bypass credit checks entirely. New users receive 1 welcome credit. Users can earn 1 additional free credit by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
#### 402 Response
@@ -969,7 +969,7 @@ Handles `checkout.session.completed` events.
### User Feedback for Credits
Users who have completed 2+ jobs can submit feedback to earn 2 free credits.
Users who have completed 2+ jobs can submit feedback to earn 1 free credit.
#### Check Eligibility
@@ -984,7 +984,7 @@ Response:
"eligible": true,
"has_submitted": false,
"jobs_completed": 3,
"credits_reward": 2
"credits_reward": 1
}
```
@@ -1013,7 +1013,7 @@ Requirements:
- At least one text field must have >50 characters
- User can only submit once (duplicate prevention)
Grants 2 credits on success. Feedback stored in `user_feedback` Firestore collection.
Grants 1 credit on success. Feedback stored in `user_feedback` Firestore collection.
The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide feedback prompts without an extra API call.
+46
View File
@@ -214,6 +214,52 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
**Worker Logs**: Stored in subcollection (`jobs/{job_id}/logs`) instead of embedded array to avoid Firestore's 1MB document size limit. TTL policy auto-deletes logs after 30 days. Feature flag: `USE_LOG_SUBCOLLECTION` (default: true). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
## Encoding Worker Blue-Green Deployment
The GCE encoding worker uses a blue-green deployment pattern with two named VMs (`encoding-worker-a` and `encoding-worker-b`).
### Architecture
```text
Frontend → Backend (Cloud Run) → Firestore config → Primary VM (encoding-worker-a or b)
↑
Cloud Scheduler (5 min) → Cloud Function → checks idle + stops VMs
↑
CI (GitHub Actions) → deploys to secondary → health check → swap Firestore → stop old
```
### Key Components
**Two VMs (a/b)**: Both VMs are TERMINATED by default. One is designated "primary" and serves all encoding traffic. The secondary VM exists solely to receive new deployments before they go live.
**Firestore config doc** (`config/encoding-worker`): Single source of truth for routing. Fields: `primary` (a or b), `ip_a`, `ip_b`, `deploy_in_progress` flag, `activity_a`/`activity_b` timestamps.
**Backend routing** (`encoding_interface.py`): Reads the primary IP from the Firestore config doc with a 30-second TTL cache. All encoding requests route to the current primary.
**JIT startup**: When a user enters the lyrics review page, the backend starts the primary VM on demand. This gives ~60 seconds of natural warmup time before encoding is needed, avoiding both 24/7 costs and noticeable cold-start latency for the user.
**Idle auto-shutdown**: A Cloud Function (triggered every 5 minutes by Cloud Scheduler) checks the `activity_*` timestamps in Firestore and stops any VM that has been idle for more than 15 minutes. This is external to the VM — if the encoding worker code itself has a bug, the Cloud Function still shuts it down.
**Blue-green deploys**: CI builds a new wheel, deploys it to the secondary VM (not the live primary), runs a real encode test against the secondary, then atomically swaps the `primary` field in Firestore to point to the secondary. The old primary is stopped after the swap. If the health check fails, the primary is never updated.
### Seeding the Config
Initial setup or reset:
```bash
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
```
### Deploy Flow
```text
1. CI builds new karaoke-gen wheel + pushes to GCS
2. CI starts secondary VM, waits for /health to respond
3. CI runs real encode test against secondary VM
4. If test passes: CI writes secondary name to Firestore `primary` field
5. CI stops the old primary VM
6. If test fails: CI stops secondary VM, primary unchanged
```
## Video Worker Orchestrator
The Video Worker uses an orchestrator pattern to ensure all features work regardless of encoding backend (local Cloud Run or GCE VM).
+65
View File
@@ -208,6 +208,71 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
| `./scripts/setup-singa-tenant.py` | Generate Singa tenant assets and upload to GCS |
| `./scripts/setup-vocalstar-tenant.py` | Generate Vocal Star tenant assets and upload to GCS |
## Encoding Worker Operations
The encoding worker uses a blue-green deployment with two GCE VMs (`encoding-worker-a`, `encoding-worker-b`). See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-deployment) for the full design.
### Seed Firestore config (initial setup or reset)
```bash
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
```
### Check VM status
```bash
gcloud compute instances describe encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(status)'
```
### Manually start / stop a VM
```bash
# Start
gcloud compute instances start encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke
# Stop
gcloud compute instances stop encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke
```
### Check worker health
```bash
IP=$(gcloud compute instances describe encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(networkInterfaces[0].accessConfigs[0].natIP)')
curl http://$IP:8080/health
```
### Manually trigger idle shutdown
Go to Cloud Scheduler in the GCP console and click "Force run" on the `encoding-worker-idle-shutdown` job, or:
```bash
gcloud scheduler jobs run encoding-worker-idle-shutdown \
--location=us-central1 --project=nomadkaraoke
```
### Roll back a deploy
If a deploy went wrong, swap the Firestore config back to the old primary:
```bash
python3 << 'EOF'
import os
os.environ['GOOGLE_CLOUD_PROJECT'] = 'nomadkaraoke'
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
db.collection('config').document('encoding-worker').update({'primary': 'a'}) # or 'b'
print("Rolled back")
EOF
```
The backend's 30-second URL cache will pick up the change within 30 seconds.
## Project Structure
```
+10
View File
@@ -36,6 +36,16 @@ Three patterns from investigating production job failures where errors cascaded
### "Set Now and Keep" Anti-Pattern (Mar 2026)
When a metadata key is missing, don't set it to "now" and skip the action — this creates an infinite loop where the key never appears old enough to trigger the action. Instead, fall back to `creationTimestamp` (always available on GCE instances) as the baseline for idle time calculation.
### Encoding Worker Blue-Green: Named VMs Beat MIG for Small Scale (Mar 2026)
**Why not a Managed Instance Group?** MIG rolling updates don't support deep health checks — you can verify HTTP liveness but not "did a real encode actually work?". PR #587 showed that the service can respond to `/health` while failing all encode jobs (pip resolution error had broken the wheel). A real encode test catches this; a simple HTTP check does not. At two VMs, the operational complexity of a MIG (instance template management, rolling update policies, drain configuration) adds no value over two named VMs with a Firestore pointer.
**Deep health check pattern**: After deploying to the secondary VM, CI runs a real encode job end-to-end before swapping traffic. This has caught broken deploys that passed all unit tests and liveness probes.
**JIT startup**: Tying VM startup to a user workflow event (entering the lyrics review page) gives ~60 seconds of natural warmup time before encoding is actually needed. Users are reading and editing lyrics while the VM starts — they never experience a cold-start stall. This avoids both 24/7 costs (~$400/mo) and noticeable latency.
**Idle shutdown must be external**: A Cloud Function watcher is more reliable than self-shutdown. If the encoding worker code has a bug that prevents it from shutting itself down, the Cloud Function still stops it based on Firestore activity timestamps. Self-shutdown approaches that rely on the worker's own health are circular — a sick worker may not be able to stop itself.
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
+1 -1
View File
@@ -61,7 +61,7 @@ Guidelines for how to communicate about Nomad Karaoke to users, in marketing mat
## Free Credits
- All new accounts receive 2 free credits to try the service
- All new accounts receive 1 free credit to try the service
- No payment required to get started
- Credits never expire
- Additional credits available for purchase ($5/credit, bulk discounts available)
+3 -3
View File
@@ -24,7 +24,7 @@
| Token-based auth | Working |
| Magic link auth | Working |
| Payment flow (Stripe) | Working |
| Feedback-for-credits | Working (2+ jobs → 2 free credits) |
| Feedback-for-credits | Working (2+ jobs → 1 free credit) |
| Admin dashboard | Working |
| Abuse prevention & YouTube quota | Working (blocklists, IP/fingerprint rate limiting, credits on verification, quota-aware YouTube uploads) |
| CI/CD self-hosted runner | Working (GCP) |
@@ -74,9 +74,9 @@
- **Song Lookup Autocomplete & Community Version Detection** (2026-03-03): Added song catalog integration to the job creation flow. Two features: (1) **Track autocomplete** on the title field provides canonical artist/title names from MusicBrainz + Spotify data via the karaoke-decide catalog API, improving text consistency for YouTube releases. Autocomplete activates when the artist field has a value; selecting a suggestion overwrites both artist and title with canonical names. (2) **Community version detection** checks karaokenerds.com for existing high-quality karaoke versions — if found, a dismissible green banner suggests the user check those versions first before spending credits. New backend: 3 endpoints (`/api/catalog/artists`, `/api/catalog/tracks`, `/api/catalog/community-check`) with per-user rate limiting (20 req/min) and in-memory TTL caching. New services: `catalog_proxy_service.py` (proxies to karaoke-decide), `karaokenerds_service.py` (scrapes karaokenerds.com). New frontend components: `AutocompleteInput` (reusable), `CommunityVersionBanner`. See [API.md](API.md#catalog-song-lookup).
- **Feedback-for-Credits** (2026-03-01): Added a feedback-for-credits mechanism available to all users (replaces the old beta-only feedback flow). Users who complete 2+ karaoke videos can submit product feedback (star ratings + text) to earn 2 free credits (total possible free credits: 4 — 2 welcome + 2 feedback). New endpoints: `GET /api/users/feedback/eligibility`, `POST /api/users/feedback`. The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide prompts without an extra API call. Frontend shows a dismissible banner on the dashboard and a "Earn 2 Free Credits" menu item in the user dropdown when eligible. Feedback stored in `user_feedback` Firestore collection with duplicate prevention via `has_submitted_feedback` flag on user model. Welcome email updated with credit-focused messaging and feedback teaser. See [API.md](API.md#user-feedback-for-credits).
- **Feedback-for-Credits** (2026-03-01): Added a feedback-for-credits mechanism available to all users (replaces the old beta-only feedback flow). Users who complete 2+ karaoke videos can submit product feedback (star ratings + text) to earn 1 free credit (total possible free credits: 2 — 1 welcome + 1 feedback). New endpoints: `GET /api/users/feedback/eligibility`, `POST /api/users/feedback`. The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide prompts without an extra API call. Frontend shows a dismissible banner on the dashboard and a "Earn 1 Free Credit" menu item in the user dropdown when eligible. Feedback stored in `user_feedback` Firestore collection with duplicate prevention via `has_submitted_feedback` flag on user model. Welcome email updated with credit-focused messaging and feedback teaser. See [API.md](API.md#user-feedback-for-credits).
- **Remove Beta Program from Homepage** (2026-03-01): Removed beta enrollment from landing page and replaced with prominent "2 Free Credits" messaging. Beta enrollment endpoint preserved for backward compatibility but no longer actively promoted. See PR #430.
- **Remove Beta Program from Homepage** (2026-03-01): Removed beta enrollment from landing page and replaced with prominent "1 Free Credit" messaging. Beta enrollment endpoint preserved for backward compatibility but no longer actively promoted. See PR #430.
- **Fix Event Loop Blocking in Audio Search Endpoints** (2026-02-28): Fixed `/api/audio-search/{job_id}/select` taking 20-36s to respond (should be <1s) and `/api/audio-search/search` sometimes taking 25-47s. **Root cause**: Async endpoints called sync methods that create new event loops via `loop.run_until_complete()`, blocking the FastAPI event loop — response body was queued but never flushed. **Fix**: RED/OPS and Spotify download paths now call `FlacfetchClient` async methods directly (matching `YouTubeDownloadService` pattern), generic downloads use `asyncio.to_thread()`, search endpoint uses `search_async()`. Also fixed `InsufficientCreditsError` occasionally returning 500 instead of 402 by using `isinstance()` check. Added 14 new tests. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#never-call-sync-over-async-from-fastapi-async-routes-feb-2026).
+86
View File
@@ -166,3 +166,89 @@ python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
**Fix (v0.135+):** AudioShake API calls now retry up to 5 times with exponential backoff (60s base, 3x multiplier, ~40 minutes total spread). Retries on 5xx, 429, connection errors, and timeouts.
**For older jobs:** Simply retry the job via admin dashboard.
---
## Encoding worker not starting
**Symptoms:** Encoding jobs time out waiting for the VM to respond. The `/api/internal/encoding-worker/start` call returns success but the VM never accepts connections.
**Check Firestore config exists:**
```bash
python3 -c "
import os; os.environ['GOOGLE_CLOUD_PROJECT']='nomadkaraoke'
from google.cloud import firestore
doc = firestore.Client(project='nomadkaraoke').collection('config').document('encoding-worker').get()
print(doc.to_dict() if doc.exists else 'MISSING - run seed script')
"
```
**Check VM status:**
```bash
gcloud compute instances describe encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke --format='value(status)'
```
**Check backend service account permissions:** The backend Cloud Run SA needs `compute.instances.start` on the encoding worker VMs. Verify in IAM or check Cloud Run logs for permission denied errors when the start call is made.
---
## Deploy stuck in progress (`deploy_in_progress: true`)
**Symptoms:** CI deploys fail immediately with "deploy already in progress". The flag in Firestore was never cleared after a previous failed deploy.
**Auto-clear:** The Cloud Function that manages idle shutdown also clears stale `deploy_in_progress` flags after 20 minutes. Wait for the next Cloud Scheduler tick (every 5 minutes) and the function will clear it.
**Manual clear:**
```bash
python3 << 'EOF'
import os; os.environ['GOOGLE_CLOUD_PROJECT']='nomadkaraoke'
from google.cloud import firestore
firestore.Client(project='nomadkaraoke').collection('config').document('encoding-worker').update({
'deploy_in_progress': False
})
print("Cleared")
EOF
```
---
## Both VMs running unexpectedly
**Symptoms:** GCP billing alert, or you notice both `encoding-worker-a` and `encoding-worker-b` are RUNNING.
**Check Cloud Function logs:**
```bash
gcloud logging read 'resource.type="cloud_function" resource.labels.function_name="encoding-worker-idle-shutdown"' \
--project=nomadkaraoke --limit=20 --format="table(timestamp,textPayload)"
```
**Verify scheduler is firing:** Go to Cloud Scheduler console and check the `encoding-worker-idle-shutdown` job's last execution time and status.
**Check activity timestamps in Firestore:** Look at `config/encoding-worker` — the `activity_a` and `activity_b` fields show when each VM last reported activity. If a timestamp is very recent, that VM is actively being used (or the heartbeat is stuck).
**Force idle check:**
```bash
gcloud scheduler jobs run encoding-worker-idle-shutdown \
--location=us-central1 --project=nomadkaraoke
```
---
## Encoding requests failing after deploy
**Symptoms:** Jobs fail at encoding immediately after a blue-green deploy swap. Logs show connection refused or 404 to the old primary IP.
**Cause:** The backend caches the encoding worker URL for 30 seconds. Requests in-flight during the swap may hit the old (now stopped) primary.
**Fix:** Wait 30 seconds after the swap for the cache to expire. In-flight jobs can be retried via the admin dashboard — re-triggering the video worker will pick up the new primary URL.
**Verify the swap happened:**
```bash
python3 -c "
import os; os.environ['GOOGLE_CLOUD_PROJECT']='nomadkaraoke'
from google.cloud import firestore
doc = firestore.Client(project='nomadkaraoke').collection('config').document('encoding-worker').get()
print('primary:', doc.to_dict().get('primary'))
"
```
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,360 @@
# Blue-Green Encoding Worker Deployment
**Created:** 2026-03-24
**Branch:** feat/sess-20260324-1603-blue-green-encoding-deploy
**Status:** Approved
## Problem Statement
The karaoke-gen encoding worker runs as a single GCE VM (c4d-highcpu-32). Any deployment that breaks this instance causes a full encoding outage with no automatic recovery. PR #587 demonstrated this risk: a pip resolution bug crashed the worker for 17 hours because there was no fallback.
Additionally, the single VM runs 24/7 (~$800/mo) despite sporadic, unpredictable usage patterns.
## Goals
1. **Zero-downtime deployments** — broken code never reaches users
2. **Cost efficiency** — VMs shut down when not in use (both idle most of the time)
3. **Deep health verification** — real encode test before traffic switch, not just a `/health` ping
4. **Just-in-time startup** — primary VM starts when a user enters lyrics review, ready by the time they need encoding
## Architecture Overview
**Approach: Backend-Orchestrated Lifecycle + CI-Driven Blue-Green Swap**
```
┌──────────────────┐
│ Cloud Scheduler │
│ (every 5 min) │
└────────┬─────────┘
│ triggers
▼
┌──────────┐ ┌──────────────┐ ┌──────────────────┐
│ Frontend │────▶│ Backend │ │ Idle Shutdown │
│ (Next.js)│ │ (Cloud Run) │ │ Cloud Function │
└──────────┘ └──────┬───────┘ └────────┬─────────┘
│ │
reads/writes checks & stops
│ │
▼ ▼
┌───────────────┐ ┌────────────────┐
│ Firestore │ │ Compute API │
│ config/ │ │ (start/stop) │
│ encoding- │ └───────┬────────┘
│ worker │ │
└───────────────┘ ┌──────┴──────┐
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│ VM A │ │ VM B │
│ (primary │ │(secondary│
│ or off) │ │ or off) │
└──────────┘ └──────────┘
▲
│
┌──────┴──────┐
│ CI Workflow │
│ (GitHub │
│ Actions) │
└─────────────┘
```
Six components, each with one clear responsibility:
| Component | Responsibility |
|-----------|---------------|
| **Pulumi (IaC)** | Two named VMs (a/b), two static IPs, firewall, IAM |
| **Backend (Cloud Run)** | Warmup trigger, activity heartbeat, encoding with retry, reads primary from Firestore |
| **CI workflow (GitHub Actions)** | Blue-green deploy: start secondary, deploy, deep health check, swap Firestore, drain & stop old |
| **Cloud Function** | Idle auto-shutdown every 5 min based on activity + active jobs |
| **Firestore doc** | Single source of truth for primary/secondary routing + metadata |
| **Frontend (Next.js)** | Warmup signal on lyrics review, heartbeat on activity, "warming up" UI state |
---
## Section 1: Infrastructure — Two Named VMs
Two permanent GCE VMs with identical specs, differentiated only by name:
| Property | VM A | VM B |
|----------|------|------|
| Name | `encoding-worker-a` | `encoding-worker-b` |
| Machine type | c4d-highcpu-32 | c4d-highcpu-32 |
| Zone | us-central1-c | us-central1-c |
| Static IP | `encoding-worker-ip-a` | `encoding-worker-ip-b` |
| Image | `encoding-worker` family | `encoding-worker` family |
| Disk | 100 GB hyperdisk-balanced | 100 GB hyperdisk-balanced |
| Default state | **Stopped** | **Stopped** |
Both use the same Packer image, same startup script, same service account. The existing single `encoding-worker` VM and its static IP are replaced by these two. Pulumi handles the transition.
### Cost
- **Idle (both stopped):** ~$10-15/mo (disk storage only; static IPs are free while attached to a VM, even if stopped)
- **One VM running:** ~$800/mo (same as today, but only while active)
- **Both running (during deploy):** ~$1,600/mo prorated for the few minutes of overlap
### Firestore Config Document
`config/encoding-worker` stores the active routing state:
```json
{
"primary_vm": "encoding-worker-a",
"primary_ip": "34.x.x.x",
"primary_version": "0.152.0",
"primary_deployed_at": "2026-03-24T16:00:00Z",
"secondary_vm": "encoding-worker-b",
"secondary_ip": "35.x.x.x",
"secondary_version": "0.151.0",
"secondary_deployed_at": "2026-03-23T12:00:00Z",
"last_swap_at": "2026-03-24T16:00:00Z",
"last_activity_at": "2026-03-24T15:45:00Z",
"deploy_in_progress": false,
"deploy_in_progress_since": null
}
```
The backend reads `primary_ip` to route encoding requests. CI updates this document atomically (Firestore transaction) to swap roles after a successful deploy.
---
## Section 2: Backend VM Lifecycle Management
Three new responsibilities for the backend:
### 2a. Warmup Trigger
When a user opens the lyrics review page, the frontend calls:
```
POST /api/internal/encoding-worker/warmup
```
The backend:
1. Reads `config/encoding-worker` from Firestore to get the primary VM name
2. Checks VM status via Compute API (`instances.get`)
3. If stopped, calls `instances.start`
4. Updates `last_activity_at` in the Firestore doc
5. Returns immediately (fire-and-forget, doesn't wait for boot)
### 2b. Activity Heartbeat
The frontend sends a heartbeat to keep the VM alive during active sessions:
```
POST /api/internal/encoding-worker/heartbeat
```
Called on:
- Lyrics review page load (same as warmup)
- Each lyrics edit autosave
- Preview button click
- While encoding is in progress (periodic)
Updates `last_activity_at` in Firestore. The idle shutdown Cloud Function (Section 4) checks this timestamp.
### 2c. Encoding Request with Warmup Fallback
The existing `EncodingService.submit_encoding_job()` gains warmup-aware retry logic:
1. Try to submit to primary VM
2. If connection refused / VM unreachable:
- Start the VM via Compute API
- Poll `/health` with backoff until healthy (up to ~90 seconds)
- Retry the encoding submission
3. If VM is starting, return a structured response so the frontend can show a "warming up" indicator
**Important: URL resolution must be dynamic.** The current `EncodingService` loads the worker URL once at init time and caches it for the Cloud Run instance lifetime. This must change to read `primary_ip` from Firestore on each encoding request (or with a short TTL cache of ~30 seconds). Without this, the backend would never pick up a blue-green swap until the Cloud Run instance cold-starts.
**Authentication:** The warmup and heartbeat endpoints (`/api/internal/encoding-worker/*`) use the same `X-Admin-Token` header as other internal endpoints. The frontend includes this token in requests.
**IAM permissions needed:** The backend Cloud Run service account needs `compute.instances.get` and `compute.instances.start` on the two encoding worker VMs. This is a narrow IAM binding scoped to specific resources, not broad compute admin.
---
## Section 3: CI Blue-Green Deployment Flow
**Trigger:** A merge to `main` that changes files affecting the encoding worker (backend code, pyproject.toml, etc.).
### Deployment Sequence
```
1. Build wheel (existing step)
2. Upload wheel + startup.sh + version.txt to GCS (existing step)
3. Read Firestore config. If deploy_in_progress=true, wait (poll every 30s,
timeout after 10 min) or fail — this serializes concurrent deploys.
4. Set deploy_in_progress=true and deploy_in_progress_since=now in Firestore
5. Identify secondary VM name and IP from Firestore config
6. Start secondary VM (compute.instances.start)
7. Wait for VM to boot + service to come online (poll /health, up to 3 min)
8. Verify wheel_version in /health response matches expected version
9. Run deep health check: submit a real 10-second preview encode test
10. Wait for encode to complete, verify output file exists and is valid size
11. If health check FAILS:
- Stop secondary VM
- Set deploy_in_progress=false, deploy_in_progress_since=null
- Fail CI with detailed error (logs, health response, etc.)
12. If health check PASSES → swap roles in Firestore (atomic transaction):
- secondary_vm becomes primary_vm (and vice versa)
- Update IPs, versions, timestamps
- Set deploy_in_progress=false, deploy_in_progress_since=null
13. Check if old primary (now secondary) has active_jobs > 0
- If yes → wait for drain (up to 10 min)
- If no → stop it immediately
14. Stop old primary (now secondary) VM
```
### Key Properties
- **Zero-downtime:** Old primary keeps serving throughout steps 3-10. Traffic only switches at step 11.
- **Broken deploys never reach users:** If the encode test fails at step 9, the secondary is stopped and CI fails. Primary is untouched.
- **Atomic swap:** Firestore transaction in step 11 means the backend sees either old state or new state, never partial.
- **Rollback is trivial:** Swap the Firestore doc back. The old primary still has the previous version installed.
### Deep Health Check Details
The encode test validates that the full encoding pipeline works, not just that the HTTP server responds:
1. CI uploads a small test ASS subtitle file + short audio clip to a known GCS test path
2. Submits an encode request directly to the secondary VM's IP (bypasses Firestore routing)
3. Waits for the job to complete (~10-15 seconds for a minimal preview)
4. Verifies the output video file exists and has a valid size (> 0 bytes)
5. Cleans up test artifacts from GCS
This catches issues like:
- pip install failures (PR #587)
- Missing system dependencies (FFmpeg, fonts)
- Python import errors
- GCS permission issues
- Broken encoding logic
### CI Authentication
The GitHub Actions service account needs:
- `compute.instances.start`, `compute.instances.stop`, `compute.instances.get` on the two VMs
- Firestore read/write access to `config/encoding-worker`
- GCS read/write for test artifacts (already has this)
---
## Section 4: Idle Auto-Shutdown
A Cloud Function triggered by Cloud Scheduler every 5 minutes.
### Logic
```python
for each VM in [primary, secondary]:
if VM is not running:
continue
# Check all "keep alive" signals
health = GET VM:8080/health
if health.active_jobs > 0:
continue # Job in flight, don't stop
config = read Firestore config/encoding-worker
if config.last_activity_at > (now - 15 minutes):
continue # User in active session
if config.deploy_in_progress:
# Check for stale flag (CI might have crashed)
if config.deploy_in_progress_since < (now - 20 minutes):
# Stale flag (deploy started over 20 min ago), clear it
update config: deploy_in_progress = false, deploy_in_progress_since = null
else:
continue # Deploy is actively running, leave it alone
# No active jobs, no recent activity, no deploy in progress
compute.instances.stop(VM)
```
### Why a Cloud Function (Not Self-Shutdown on the VM)
- The VM process might crash or hang — an external watcher is more reliable
- If encoding worker code has a bug preventing self-shutdown, you pay ~$800/mo until someone notices
- Cloud Function cost: effectively $0/mo (free tier covers this volume)
### Idle Timeout Summary
| Signal | Keeps VM alive? |
|--------|----------------|
| `active_jobs > 0` (from /health) | Yes |
| `last_activity_at` < 15 min ago (from Firestore) | Yes |
| `deploy_in_progress == true` (from Firestore) | Yes |
| None of the above | Stop the VM |
---
## Section 5: Frontend Changes
Two small changes to the frontend:
### 5a. Warmup Signal on Lyrics Review
When the user navigates to the lyrics review page (`/app/jobs#/{jobId}/review`), the frontend fires a warmup request:
```typescript
// Fire-and-forget on page load, no loading state needed
fetch('/api/internal/encoding-worker/warmup', { method: 'POST' })
```
And sends a debounced heartbeat on interaction:
```typescript
// At most once per 60 seconds, on autosave or user interaction
fetch('/api/internal/encoding-worker/heartbeat', { method: 'POST' })
```
### 5b. "Warming Up" State in Preview UI
When the user clicks the preview button and the encoding worker is still booting, the backend returns a response indicating the worker is starting. The frontend shows a message in the preview area:
> "Starting encoding worker... This usually takes about a minute."
Once the backend confirms the worker is ready and the encode job is submitted, this transitions to the normal encoding progress UI.
The existing encoding submission endpoint returns a new status value `worker_starting` (alongside the existing `pending`, `running`, etc.). The frontend preview component handles this state with the warmup message.
---
## Rollback Plan
### Immediate Rollback (Bad Deploy)
If a deployment passes the health check but causes issues in production:
1. Swap the Firestore config doc back (old primary becomes primary again)
2. Start the old primary VM if it's stopped
3. Can be done via a manual script, admin endpoint, or `gcloud` + Firestore console
### Full Rollback (Infrastructure)
If the two-VM architecture itself has issues:
1. Revert the backend code to read `encoding-worker-url` from Secret Manager (code revert, not automatic fallback)
2. Pulumi can recreate the original single-VM setup
3. CI reverts to the current deploy flow
### Versioned Wheels
Previous versioned wheels remain in GCS (`karaoke_gen-{version}.whl`) for manual rollback to any prior version.
---
## Migration Plan
The transition from one VM to two requires careful ordering:
1. **Seed Firestore config doc** — initial state with VM A's IP set to the current encoding worker's static IP, so there's no gap where the backend reads from Firestore but no VM exists yet
2. **Deploy backend changes** (read primary from Firestore, warmup/heartbeat endpoints)
3. **Deploy Pulumi changes** (create VMs A and B, remove old VM)
4. **Deploy CI workflow changes** (blue-green deploy flow)
5. **Deploy Cloud Function** (idle auto-shutdown)
6. **Deploy frontend changes** (warmup signal, warming up UI)
Steps 1-3 must happen in order. Steps 4-6 can happen in parallel after step 3.
---
## Open Questions
None — design is complete and approved.
+1 -1
View File
@@ -335,7 +335,7 @@ function AppPageContent() {
<div className="flex items-center gap-3 min-w-0">
<Gift className="w-5 h-5 text-green-500 shrink-0" />
<p className="text-sm" style={{ color: 'var(--text)' }}>
<strong>Earn 2 free credits!</strong>{' '}
<strong>Earn 1 free credit!</strong>{' '}
<span style={{ color: 'var(--text-muted)' }}>
Share your feedback on the karaoke creation experience.
</span>
+3 -3
View File
@@ -262,7 +262,7 @@ function ConsumerLandingPage() {
Create It Yourself
<span className="ml-1 px-2 py-0.5 bg-white/20 rounded-full text-sm">$5</span>
</button>
<span className="text-green-400 text-sm">2 free credits included - no payment required</span>
<span className="text-green-400 text-sm">1 free credit included - no payment required</span>
</div>
<div className="flex flex-col items-center gap-2">
<a
@@ -451,12 +451,12 @@ function ConsumerLandingPage() {
<div className="max-w-4xl mx-auto">
<h2 className="text-3xl font-bold text-center mb-4">Simple Pricing</h2>
<p className="text-dark-400 text-center mb-4 max-w-xl mx-auto">
Start with 2 free credits, then buy more to save more.
Start with 1 free credit, then buy more to save more.
</p>
<div className="bg-green-500/10 border border-green-500/30 rounded-2xl p-6 text-center mb-10 max-w-sm mx-auto">
<div className="text-sm text-green-400 font-medium mb-1">Every new account includes</div>
<div className="text-4xl font-bold text-green-400 mb-1">2 Free Credits</div>
<div className="text-4xl font-bold text-green-400 mb-1">1 Free Credit</div>
<div className="text-sm text-dark-400 mb-4">No payment required</div>
<button
onClick={() => setShowAuthDialog(true)}
+1 -1
View File
@@ -114,7 +114,7 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
className="text-green-500 focus:text-green-400 focus:bg-secondary"
>
<Gift className="w-4 h-4 mr-2" />
<span>Earn 2 Free Credits</span>
<span>Earn 1 Free Credit</span>
</DropdownMenuItem>
)}
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
@@ -156,7 +156,7 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<Gift className="w-5 h-5 text-green-500" />
Share Your Feedback — Earn 2 Free Credits
Share Your Feedback — Earn 1 Free Credit
</DialogTitle>
<DialogDescription className="text-muted-foreground">
Tell us about your experience creating karaoke videos. Your feedback directly shapes what we build next.
@@ -268,7 +268,7 @@ export function FeedbackDialog({ open, onClose }: FeedbackDialogProps) {
Submitting...
</>
) : (
'Submit Feedback & Earn 2 Credits'
'Submit Feedback & Earn 1 Credit'
)}
</Button>
</div>
@@ -21,7 +21,7 @@ import {
} from '@/lib/lyrics-review/types'
import type { EditLog, EditLogEntry, EditFeedbackReason } from '@/lib/lyrics-review/types'
import type { InstrumentalSelectionType, LyricsReviewApiClient } from '@/lib/api'
import { lyricsReviewApi } from '@/lib/api'
import { lyricsReviewApi, warmupEncodingWorker, heartbeatEncodingWorker } from '@/lib/api'
import { cn } from '@/lib/utils'
import ReferenceView from './ReferenceView'
import TranscriptionView from './TranscriptionView'
@@ -272,12 +272,30 @@ export default function LyricsAnalyzer({
setSessionRestoreOpen(true)
}, [apiClient])
// Save data (localStorage - instant crash recovery)
// Warm up encoding worker VM when lyrics review page loads
useEffect(() => {
if (!isReadOnly) {
warmupEncodingWorker()
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Debounced heartbeat — keeps VM alive during active editing
const lastHeartbeat = useRef(0)
const sendHeartbeat = useCallback(() => {
const now = Date.now()
if (now - lastHeartbeat.current > 60_000) {
lastHeartbeat.current = now
heartbeatEncodingWorker()
}
}, [])
// Save data (localStorage - instant crash recovery) + heartbeat encoding worker
useEffect(() => {
if (!isReadOnly) {
saveData(data, initialData)
sendHeartbeat()
}
}, [data, isReadOnly, initialData])
}, [data, isReadOnly, initialData, sendHeartbeat])
// Server-side session auto-save (periodic backup)
const { saveSession } = useReviewSessionAutoSave({
@@ -32,7 +32,7 @@ export default function PreviewVideoSection({
timingOffsetMs = 0,
}: PreviewVideoSectionProps) {
const [previewState, setPreviewState] = useState<{
status: 'loading' | 'ready' | 'error'
status: 'loading' | 'warming_up' | 'ready' | 'error'
videoUrl?: string
error?: string
}>({ status: 'loading' })
@@ -51,6 +51,14 @@ export default function PreviewVideoSection({
const response = await apiClient.generatePreviewVideo(dataToPreview)
if (response.status === 'worker_starting') {
setPreviewState({
status: 'warming_up',
error: response.message,
})
return
}
if (response.status === 'error') {
setPreviewState({
status: 'error',
@@ -95,6 +103,15 @@ export default function PreviewVideoSection({
</div>
)}
{previewState.status === 'warming_up' && (
<div className="flex flex-col items-center justify-center p-8 text-center">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-200 border-t-blue-500 mb-4" />
<p className="text-sm text-gray-600">
Starting encoding worker... This usually takes about a minute.
</p>
</div>
)}
{previewState.status === 'error' && (
<Alert variant="destructive" className="mb-4">
<AlertDescription className="flex items-center justify-between">
+1 -1
View File
@@ -115,7 +115,7 @@ test.describe('Landing Page', () => {
await page.goto('/');
await page.waitForLoadState('networkidle');
await expect(page.getByText('2 Free Credits', { exact: true })).toBeVisible();
await expect(page.getByText('1 Free Credit', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: /sign up free/i })).toBeVisible();
});
+1 -1
View File
@@ -49,7 +49,7 @@ test.describe('Smoke Tests', () => {
await page.goto('/');
await page.waitForLoadState('networkidle');
await expect(page.getByText('2 Free Credits', { exact: true })).toBeVisible();
await expect(page.getByText('1 Free Credit', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: /sign up free/i })).toBeVisible();
});
});
+29
View File
@@ -3007,6 +3007,35 @@ export const lyricsReviewApi = {
},
}
/**
* Signal the backend to start the encoding worker VM.
* Fire-and-forget — doesn't wait for the VM to boot.
*/
export async function warmupEncodingWorker(): Promise<void> {
try {
await fetch(`${API_BASE_URL}/api/internal/encoding-worker/warmup`, {
method: 'POST',
headers: getAuthHeaders(),
})
} catch {
// Fire-and-forget, don't throw on failure
}
}
/**
* Send heartbeat to keep encoding worker alive during active session.
*/
export async function heartbeatEncodingWorker(): Promise<void> {
try {
await fetch(`${API_BASE_URL}/api/internal/encoding-worker/heartbeat`, {
method: 'POST',
headers: getAuthHeaders(),
})
} catch {
// Fire-and-forget
}
}
export interface DeleteOutputsResponse {
status: string;
job_id: string;
+67 -9
View File
@@ -40,8 +40,9 @@ from modules import database, storage as storage_module, artifact_registry, secr
from modules import cloud_tasks, cloud_run, monitoring, networking, runner_manager
from modules import divebar_mirror, kn_data_sync, divebar_lookup
from modules import audio_separator_service
from modules import encoding_worker_manager
from modules.iam import backend_sa, github_actions_sa, claude_automation_sa, worker_sas
from compute import encoding_worker_vm, github_runners
from compute import encoding_worker_vm, github_runners, divebar_sync_vm
# ==================== Core Infrastructure ====================
@@ -392,19 +393,65 @@ kn_data_sync_resources = kn_data_sync.create_kn_data_sync_resources(all_secrets)
divebar_lookup_resources = divebar_lookup.create_divebar_lookup_resources(all_secrets)
# ==================== Divebar File Sync VM ====================
# Divebar File Sync VM (downloads karaoke files from Drive to GCS)
divebar_sync_instance = divebar_sync_vm.create_divebar_sync_vm(
divebar_mirror_resources["service_account"]
)
# Cloud Scheduler to start the sync VM daily (uses compute.instances.start API)
divebar_sync_scheduler = cloudscheduler.Job(
"divebar-sync-vm-scheduler", # Must match Pulumi state
name="divebar-sync-vm-daily",
description="Start Divebar file sync VM daily to download new files from Drive to GCS",
region=REGION,
schedule="0 3 * * *", # 3:00 AM ET (after index refresh at 2 AM)
time_zone="America/New_York",
http_target=cloudscheduler.JobHttpTargetArgs(
uri=divebar_sync_instance.self_link.apply(
lambda link: f"https://compute.googleapis.com/compute/v1/{link}/start"
),
http_method="POST",
oidc_token=cloudscheduler.JobHttpTargetOidcTokenArgs(
service_account_email=divebar_mirror_resources["service_account"].email,
),
),
retry_config=cloudscheduler.JobRetryConfigArgs(
retry_count=1,
min_backoff_duration="60s",
max_backoff_duration="300s",
),
)
# Grant the SA permission to start/stop its own VM
divebar_sync_compute_admin = gcp.projects.IAMMember(
"divebar-mirror-compute-instance-admin", # Must match Pulumi state
project=PROJECT_ID,
role="roles/compute.instanceAdmin.v1",
member=divebar_mirror_resources["service_account"].email.apply(
lambda email: f"serviceAccount:{email}"
),
)
# ==================== Audio Separator GPU Service ====================
# Cloud Run GPU (L4) service for audio stem separation — replaces Modal
audio_separator_resources = audio_separator_service.create_all_resources()
# ==================== Compute VMs ====================
# Encoding Worker VM (video encoding service)
encoding_worker_ip = encoding_worker_vm.create_encoding_worker_ip()
encoding_worker_instance = encoding_worker_vm.create_encoding_worker_vm(
encoding_worker_ip, encoding_worker_sa
# Encoding Worker VMs (blue-green pair for zero-downtime deployments)
encoding_worker_ips = encoding_worker_vm.create_encoding_worker_ips()
encoding_worker_instances = encoding_worker_vm.create_encoding_worker_vms(
encoding_worker_ips, encoding_worker_sa
)
encoding_worker_firewall = encoding_worker_vm.create_encoding_worker_firewall()
# Grant backend SA permission to start encoding worker VMs
backend_compute_perms = worker_sas.grant_backend_compute_permissions(backend_service_account)
# Encoding Worker Idle Shutdown (auto-stop after 15 min idle)
encoding_worker_idle_resources = encoding_worker_manager.create_idle_shutdown_resources()
# GitHub Runners (CI/CD self-hosted runners)
# Create Cloud NAT for outbound internet access (no external IPs needed)
github_runners_router, github_runners_nat = github_runners.create_cloud_nat()
@@ -524,11 +571,14 @@ pulumi.export("gdrive_validator_service_account", gdrive_validator_sa.email)
pulumi.export("vpc_connector_name", vpc_connector.name)
pulumi.export("vpc_connector_self_link", vpc_connector.self_link)
# Encoding worker
pulumi.export("encoding_worker_external_ip", encoding_worker_ip.address)
pulumi.export("encoding_worker_service_url", encoding_worker_ip.address.apply(lambda ip: f"http://{ip}:8080"))
# Encoding workers (blue-green pair)
pulumi.export("encoding_worker_a_ip", encoding_worker_ips[0].address)
pulumi.export("encoding_worker_b_ip", encoding_worker_ips[1].address)
pulumi.export("encoding_worker_a_url", encoding_worker_ips[0].address.apply(lambda ip: f"http://{ip}:8080"))
pulumi.export("encoding_worker_b_url", encoding_worker_ips[1].address.apply(lambda ip: f"http://{ip}:8080"))
pulumi.export("encoding_worker_service_account", encoding_worker_sa.email)
pulumi.export("encoding_worker_vm_name", encoding_worker_instance.name)
pulumi.export("encoding_worker_a_name", encoding_worker_instances[0].name)
pulumi.export("encoding_worker_b_name", encoding_worker_instances[1].name)
# GitHub runners
pulumi.export("github_runner_vm_names", [vm.name for vm in github_runner_vms])
@@ -553,6 +603,14 @@ pulumi.export("kn_data_bucket", kn_data_sync_resources["data_bucket"].name)
# Divebar lookup API (Phase 3)
pulumi.export("divebar_lookup_function_url", divebar_lookup_resources["function"].url)
# Divebar file sync VM
pulumi.export("divebar_sync_vm_name", divebar_sync_instance.name)
pulumi.export("divebar_sync_scheduler_name", divebar_sync_scheduler.name)
# Audio separator GPU service
pulumi.export("audio_separator_service_url", audio_separator_resources["service"].uri)
pulumi.export("audio_separator_service_account", audio_separator_resources["service_account"].email)
# Encoding worker idle shutdown
pulumi.export("encoding_worker_idle_function_url", encoding_worker_idle_resources["function"].url)
pulumi.export("encoding_worker_idle_scheduler", encoding_worker_idle_resources["scheduler"].name)
+4 -4
View File
@@ -7,15 +7,15 @@ Contains VM definitions for:
"""
from .encoding_worker_vm import (
create_encoding_worker_vm,
create_encoding_worker_ip,
create_encoding_worker_vms,
create_encoding_worker_ips,
create_encoding_worker_firewall,
)
from .github_runners import create_github_runners, create_build_runner, create_cloud_nat
__all__ = [
"create_encoding_worker_vm",
"create_encoding_worker_ip",
"create_encoding_worker_vms",
"create_encoding_worker_ips",
"create_encoding_worker_firewall",
"create_github_runners",
"create_build_runner",
+63
View File
@@ -0,0 +1,63 @@
"""
Divebar File Sync VM resources.
Creates a small GCE VM that downloads karaoke files from Google Drive
to GCS. The VM starts, runs the sync, and shuts itself down.
Design:
- e2-medium (2 vCPU, 4 GB) — enough for 4 concurrent downloads
- 10 GB boot disk (minimal — files go to GCS, not local disk)
- Preemptible/Spot for cost savings (~$10/mo if running 24/7, but
it only runs for ~1-2 hours daily for incremental sync)
- Auto-shutdown after sync completes
- Cloud Scheduler starts the VM daily at 3 AM ET (after index refresh at 2 AM)
"""
import pulumi
from pulumi_gcp import compute, serviceaccount
from config import REGION, ZONE, PROJECT_ID
from .startup_scripts import read_script
def create_divebar_sync_vm(
service_account: serviceaccount.Account,
) -> compute.Instance:
"""Create the Divebar file sync VM instance."""
startup_script = read_script("divebar_sync.sh")
return compute.Instance(
"divebar-sync-vm",
name="divebar-sync",
machine_type="e2-medium",
zone=ZONE,
boot_disk=compute.InstanceBootDiskArgs(
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
image="debian-cloud/debian-12",
size=10,
type="pd-standard",
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
network="default",
# Needs internet access for Drive API and GCS
access_configs=[compute.InstanceNetworkInterfaceAccessConfigArgs()],
)],
service_account=compute.InstanceServiceAccountArgs(
email=service_account.email,
# drive.readonly for downloading files, cloud-platform for GCS + BigQuery
scopes=[
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/cloud-platform",
],
),
metadata_startup_script=startup_script,
tags=["divebar-sync"],
allow_stopping_for_update=True,
scheduling=compute.InstanceSchedulingArgs(
automatic_restart=False, # Don't restart after self-shutdown
),
# VM is started daily by Cloud Scheduler; may be RUNNING or TERMINATED
# depending on sync status. Use RUNNING to avoid Pulumi trying to stop it.
desired_status="RUNNING",
)
+59 -77
View File
@@ -1,101 +1,83 @@
"""
Encoding Worker VM resources.
Encoding Worker VM resources — blue-green deployment pair.
Manages the high-performance VM instance for video encoding,
including static IP and firewall rules.
Manages two identical VMs (a/b) for zero-downtime deployments.
Only one is active (primary) at a time; the other is stopped (secondary).
Both auto-shutdown when idle to minimize cost.
See docs/superpowers/specs/2026-03-24-blue-green-encoding-worker-design.md
"""
import pulumi
from pulumi_gcp import compute, serviceaccount
from config import REGION, ENCODING_WORKER_ZONE, PROJECT_ID, MachineTypes, DiskSizes
from config import REGION, ENCODING_WORKER_ZONE, PROJECT_ID, MachineTypes, DiskSizes, EncodingWorkerConfig
from .startup_scripts import read_script
def create_encoding_worker_ip() -> compute.Address:
"""
Create static IP for the encoding worker.
Returns:
compute.Address: The static IP resource.
"""
return compute.Address(
"encoding-worker-ip",
name="encoding-worker-static-ip",
region=REGION,
address_type="EXTERNAL",
description="Static external IP for encoding worker service",
)
def create_encoding_worker_ips() -> list[compute.Address]:
"""Create static IPs for both encoding worker VMs."""
ips = []
for name in EncodingWorkerConfig.IP_NAMES:
ip = compute.Address(
name,
name=name,
region=REGION,
address_type="EXTERNAL",
description=f"Static external IP for {name}",
)
ips.append(ip)
return ips
def create_encoding_worker_vm(
ip: compute.Address,
def create_encoding_worker_vms(
ips: list[compute.Address],
service_account: serviceaccount.Account,
) -> compute.Instance:
"""
Create the encoding worker VM instance.
This VM runs video encoding jobs with high CPU/memory resources.
Uses c4d-highcpu-32 (AMD EPYC 9B45 Turin, 32 vCPU) for 4.92x faster
encoding vs c4-standard-8. Uses hyperdisk-balanced for fast I/O.
Uses a custom Packer-built image with Python 3.13, FFmpeg, and fonts
pre-installed to reduce startup time from ~10 minutes to ~30 seconds.
See infrastructure/packer/README.md for image build instructions.
Args:
ip: The static IP address for the VM.
service_account: The encoding worker service account.
Returns:
compute.Instance: The VM instance resource.
"""
) -> list[compute.Instance]:
"""Create the blue-green encoding worker VM pair."""
startup_script = read_script("encoding_worker.sh")
# Use custom Packer image with dependencies pre-installed
# Image family returns latest image in the family
# Fallback: "debian-cloud/debian-12" if image doesn't exist yet
custom_image = f"projects/{PROJECT_ID}/global/images/family/encoding-worker"
return compute.Instance(
"encoding-worker",
name="encoding-worker",
machine_type=MachineTypes.ENCODING_WORKER,
zone=ENCODING_WORKER_ZONE,
boot_disk=compute.InstanceBootDiskArgs(
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
vms = []
for vm_name, ip in zip(EncodingWorkerConfig.VM_NAMES, ips):
vm = compute.Instance(
vm_name,
name=vm_name,
machine_type=MachineTypes.ENCODING_WORKER,
zone=ENCODING_WORKER_ZONE,
boot_disk=compute.InstanceBootDiskArgs(
initialize_params=compute.InstanceBootDiskInitializeParamsArgs(
image=custom_image,
size=DiskSizes.ENCODING_WORKER,
type="hyperdisk-balanced",
),
),
),
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
network="default",
access_configs=[compute.InstanceNetworkInterfaceAccessConfigArgs(
nat_ip=ip.address,
network_interfaces=[compute.InstanceNetworkInterfaceArgs(
network="default",
access_configs=[compute.InstanceNetworkInterfaceAccessConfigArgs(
nat_ip=ip.address,
)],
)],
)],
service_account=compute.InstanceServiceAccountArgs(
email=service_account.email,
scopes=["cloud-platform"],
),
metadata_startup_script=startup_script,
tags=["encoding-worker"],
allow_stopping_for_update=True,
advanced_machine_features=compute.InstanceAdvancedMachineFeaturesArgs(
threads_per_core=2,
),
)
service_account=compute.InstanceServiceAccountArgs(
email=service_account.email,
scopes=["cloud-platform"],
),
metadata_startup_script=startup_script,
tags=["encoding-worker"],
allow_stopping_for_update=True,
advanced_machine_features=compute.InstanceAdvancedMachineFeaturesArgs(
threads_per_core=2,
),
)
vms.append(vm)
return vms
def create_encoding_worker_firewall() -> compute.Firewall:
"""
Create firewall rules for the encoding worker.
"""Create firewall rules for encoding worker VMs.
Opens port 8080 for the HTTP API (authentication required).
Returns:
compute.Firewall: The firewall resource.
Opens port 8080 for the HTTP API. Both VMs share the same
firewall rule via the 'encoding-worker' network tag.
"""
return compute.Firewall(
"encoding-worker-firewall",
@@ -106,5 +88,5 @@ def create_encoding_worker_firewall() -> compute.Firewall:
],
source_ranges=["0.0.0.0/0"],
target_tags=["encoding-worker"],
description="Allow HTTP access to encoding worker (auth required)",
description="Allow HTTP access to encoding workers (auth required)",
)
@@ -0,0 +1,56 @@
#!/bin/bash
# Divebar File Sync VM startup script
#
# Downloads karaoke files from Google Drive to GCS using the BigQuery index.
# Auto-shuts down after sync completes. Designed to be started daily by
# Cloud Scheduler or manually for initial bulk sync.
#
# Logs: journalctl -u divebar-sync -f
# OR: /var/log/divebar-sync.log
set -euo pipefail
LOG_FILE="/var/log/divebar-sync.log"
REPO_DIR="/opt/nomad/divebar-sync"
SCRIPT="infrastructure/scripts/divebar_file_sync.py"
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') $*" | tee -a "$LOG_FILE"
}
log "=== Divebar file sync starting ==="
# Install dependencies (idempotent)
if ! command -v pip3 &>/dev/null; then
log "Installing Python3 and pip..."
apt-get update -qq && apt-get install -y -qq python3-pip python3-venv git
fi
# Clone or update the repo
if [ -d "$REPO_DIR" ]; then
log "Updating repo..."
cd "$REPO_DIR" && git pull origin main --quiet
else
log "Cloning repo..."
git clone --depth 1 https://github.com/nomadkaraoke/karaoke-gen.git "$REPO_DIR"
fi
cd "$REPO_DIR"
log "Installing Python dependencies..."
# Pin google-auth<2.28 to avoid MTLS metadata server issue on GCE
# See: https://github.com/googleapis/google-auth-library-python/issues/1474
# Use --break-system-packages since Debian 12 enforces PEP 668
pip3 install -q --break-system-packages 'google-auth<2.28' google-api-python-client google-cloud-storage google-cloud-bigquery requests
# Force metadata server to use HTTP (not HTTPS) — required for GCE VMs
# See: https://github.com/googleapis/google-auth-library-python/issues/1474
export GCE_METADATA_HOST="169.254.169.254"
export GOOGLE_CLOUD_PROJECT="nomadkaraoke"
# Run the sync
log "Starting file sync (workers=4)..."
python3 "$SCRIPT" --workers 4 2>&1 | tee -a "$LOG_FILE"
# The script handles shutdown itself after completion
log "=== Divebar file sync script exited ==="
+11
View File
@@ -122,3 +122,14 @@ class SecretNames:
# GitHub repository for runner registration
GITHUB_REPO_OWNER = "nomadkaraoke"
GITHUB_REPO_NAME = "karaoke-gen"
class EncodingWorkerConfig:
"""Configuration for blue-green encoding worker VMs."""
VM_NAMES = ["encoding-worker-a", "encoding-worker-b"]
IP_NAMES = ["encoding-worker-ip-a", "encoding-worker-ip-b"]
IDLE_CHECK_SCHEDULE = "*/5 * * * *" # Every 5 minutes
IDLE_TIMEOUT_MINUTES = 15
FUNCTION_NAME = "encoding-worker-idle-shutdown"
FUNCTION_MEMORY = "256M"
FUNCTION_TIMEOUT = 120 # 2 minutes
@@ -0,0 +1,15 @@
[Script Info]
Title: Deploy Health Check
ScriptType: v4.00+
WrapStyle: 0
PlayResX: 1920
PlayResY: 1080
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Noto Sans,60,&H00FFFFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,3,0,2,20,20,40,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Health check test
Dialogue: 0,0:00:05.00,0:00:10.00,Default,,0,0,0,,Deploy verification
@@ -0,0 +1,162 @@
"""
Encoding Worker Idle Shutdown Cloud Function.
Triggered by Cloud Scheduler every 5 minutes. Checks both encoding worker
VMs (a/b) and stops any that are idle.
Idle criteria (all must be true to stop a VM):
- No active encoding jobs (from /health endpoint active_jobs)
- No recent user activity (from Firestore last_activity_at > 15 min)
- Only applies to primary VM; secondary always stops if no active jobs
- No deploy in progress (from Firestore deploy_in_progress flag)
Environment variables:
- GCP_PROJECT: GCP project ID (default: nomadkaraoke)
- GCP_ZONE: Zone where VMs are located (default: us-central1-c)
- IDLE_TIMEOUT_MINUTES: Minutes of inactivity before shutdown (default: 15)
"""
import json
import logging
import os
from datetime import datetime, timezone, timedelta
import functions_framework
import requests
from google.cloud import compute_v1, firestore
logger = logging.getLogger(__name__)
PROJECT_ID = os.environ.get("GCP_PROJECT", "nomadkaraoke")
ZONE = os.environ.get("GCP_ZONE", "us-central1-c")
IDLE_TIMEOUT_MINUTES = int(os.environ.get("IDLE_TIMEOUT_MINUTES", "15"))
DEPLOY_STALE_TIMEOUT_MINUTES = 20
ENCODING_WORKER_PORT = 8080
_compute_client = None
_firestore_client = None
def get_compute_client():
global _compute_client
if _compute_client is None:
_compute_client = compute_v1.InstancesClient()
return _compute_client
def get_firestore_client():
global _firestore_client
if _firestore_client is None:
_firestore_client = firestore.Client(project=PROJECT_ID)
return _firestore_client
def get_vm_status(vm_name):
client = get_compute_client()
try:
instance = client.get(project=PROJECT_ID, zone=ZONE, instance=vm_name)
return instance.status
except Exception as e:
logger.error(f"Failed to get status for {vm_name}: {e}")
return "UNKNOWN"
def get_vm_ip(vm_name):
client = get_compute_client()
try:
instance = client.get(project=PROJECT_ID, zone=ZONE, instance=vm_name)
for iface in instance.network_interfaces:
for access in iface.access_configs:
if access.nat_i_p:
return access.nat_i_p
except Exception:
pass
return None
def check_active_jobs(vm_ip):
try:
resp = requests.get(f"http://{vm_ip}:{ENCODING_WORKER_PORT}/health", timeout=5)
if resp.status_code == 200:
return resp.json().get("active_jobs", 0)
except Exception:
pass
return 0
def stop_vm(vm_name):
client = get_compute_client()
logger.info(f"Stopping idle VM: {vm_name}")
client.stop(project=PROJECT_ID, zone=ZONE, instance=vm_name)
@functions_framework.http
def idle_shutdown(request):
now = datetime.now(timezone.utc)
idle_cutoff = now - timedelta(minutes=IDLE_TIMEOUT_MINUTES)
stale_cutoff = now - timedelta(minutes=DEPLOY_STALE_TIMEOUT_MINUTES)
db = get_firestore_client()
doc = db.collection("config").document("encoding-worker").get()
if not doc.exists:
logger.warning("Encoding worker config not found in Firestore")
return json.dumps({"status": "no_config"}), 200
config = doc.to_dict()
# Check deploy_in_progress
deploy_in_progress = config.get("deploy_in_progress", False)
if deploy_in_progress:
deploy_since = config.get("deploy_in_progress_since")
if deploy_since:
deploy_time = datetime.fromisoformat(deploy_since)
if deploy_time < stale_cutoff:
logger.warning(
f"Clearing stale deploy_in_progress flag (started {deploy_since})"
)
db.collection("config").document("encoding-worker").update({
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
deploy_in_progress = False
else:
logger.info("Deploy in progress, skipping idle check")
return json.dumps({"status": "deploy_in_progress"}), 200
# Parse last_activity_at
last_activity = config.get("last_activity_at")
has_recent_activity = False
if last_activity:
activity_time = datetime.fromisoformat(last_activity)
has_recent_activity = activity_time > idle_cutoff
# Check each VM individually
primary_vm = config.get("primary_vm")
results = {}
for vm_name in [primary_vm, config.get("secondary_vm")]:
if not vm_name:
continue
status = get_vm_status(vm_name)
if status != "RUNNING":
results[vm_name] = f"already_{status.lower()}"
continue
vm_ip = get_vm_ip(vm_name)
if vm_ip:
active_jobs = check_active_jobs(vm_ip)
if active_jobs > 0:
results[vm_name] = f"active_jobs={active_jobs}"
logger.info(f"{vm_name} has {active_jobs} active jobs, keeping alive")
continue
# Recent activity keeps PRIMARY alive only (not secondary)
if vm_name == primary_vm and has_recent_activity:
results[vm_name] = "active_session"
logger.info(f"{vm_name} (primary) kept alive due to recent activity")
continue
stop_vm(vm_name)
results[vm_name] = "stopped"
return json.dumps({"status": "checked", "results": results}), 200
@@ -0,0 +1,4 @@
functions-framework==3.*
google-cloud-compute==1.*
google-cloud-firestore==2.*
requests>=2.28.0
@@ -0,0 +1,239 @@
"""Unit tests for encoding worker idle shutdown Cloud Function."""
import json
import sys
from datetime import datetime, timezone, timedelta
from unittest.mock import MagicMock, patch
import pytest
# Mock external dependencies before importing main
_mock_ff = MagicMock()
# Make the @functions_framework.http decorator pass through the function
_mock_ff.http = lambda f: f
sys.modules["functions_framework"] = _mock_ff
sys.modules["google.cloud"] = MagicMock()
sys.modules["google.cloud.compute_v1"] = MagicMock()
sys.modules["google.cloud.firestore"] = MagicMock()
import main # noqa: E402
@pytest.fixture(autouse=True)
def reset_clients():
"""Reset cached clients between tests."""
main._compute_client = None
main._firestore_client = None
@pytest.fixture
def mock_compute():
with patch.object(main, "get_compute_client") as mock:
client = MagicMock()
mock.return_value = client
yield client
@pytest.fixture
def mock_firestore():
with patch.object(main, "get_firestore_client") as mock:
client = MagicMock()
mock.return_value = client
yield client
def _make_config(
primary_vm="encoding-worker-a",
secondary_vm="encoding-worker-b",
deploy_in_progress=False,
deploy_in_progress_since=None,
last_activity_at=None,
):
return {
"primary_vm": primary_vm,
"secondary_vm": secondary_vm,
"deploy_in_progress": deploy_in_progress,
"deploy_in_progress_since": deploy_in_progress_since,
"last_activity_at": last_activity_at,
}
def _make_instance(status="RUNNING", ip="1.2.3.4"):
instance = MagicMock()
instance.status = status
access_config = MagicMock()
access_config.nat_i_p = ip
iface = MagicMock()
iface.access_configs = [access_config]
instance.network_interfaces = [iface]
return instance
def _setup_firestore(mock_firestore, config_dict):
doc = MagicMock()
doc.exists = True
doc.to_dict.return_value = config_dict
mock_firestore.collection.return_value.document.return_value.get.return_value = doc
return doc
def _setup_firestore_missing(mock_firestore):
doc = MagicMock()
doc.exists = False
mock_firestore.collection.return_value.document.return_value.get.return_value = doc
class TestIdleShutdown:
"""Tests for the idle_shutdown Cloud Function."""
def test_stops_idle_running_vms(self, mock_compute, mock_firestore):
"""VMs with no active jobs and no recent activity should be stopped."""
old_activity = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
config = _make_config(last_activity_at=old_activity)
_setup_firestore(mock_firestore, config)
instance = _make_instance(status="RUNNING", ip="1.2.3.4")
mock_compute.get.return_value = instance
with patch("main.check_active_jobs", return_value=0):
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert status_code == 200
assert result["status"] == "checked"
assert result["results"]["encoding-worker-a"] == "stopped"
assert result["results"]["encoding-worker-b"] == "stopped"
assert mock_compute.stop.call_count == 2
def test_skips_deploy_in_progress(self, mock_compute, mock_firestore):
"""Should skip idle check when a deploy is in progress."""
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
config = _make_config(
deploy_in_progress=True,
deploy_in_progress_since=recent,
)
_setup_firestore(mock_firestore, config)
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["status"] == "deploy_in_progress"
mock_compute.stop.assert_not_called()
def test_clears_stale_deploy_flag(self, mock_compute, mock_firestore):
"""Deploy flags older than 20 min should be cleared and idle check should proceed."""
stale = (datetime.now(timezone.utc) - timedelta(minutes=25)).isoformat()
old_activity = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
config = _make_config(
deploy_in_progress=True,
deploy_in_progress_since=stale,
last_activity_at=old_activity,
)
_setup_firestore(mock_firestore, config)
instance = _make_instance(status="RUNNING", ip="1.2.3.4")
mock_compute.get.return_value = instance
with patch("main.check_active_jobs", return_value=0):
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["status"] == "checked"
# Verify deploy flag was cleared
mock_firestore.collection.return_value.document.return_value.update.assert_called_once_with({
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
def test_recent_activity_keeps_primary_alive(self, mock_compute, mock_firestore):
"""Recent activity should keep the primary VM alive but stop the secondary."""
recent = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
config = _make_config(last_activity_at=recent)
_setup_firestore(mock_firestore, config)
instance = _make_instance(status="RUNNING", ip="1.2.3.4")
mock_compute.get.return_value = instance
with patch("main.check_active_jobs", return_value=0):
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["results"]["encoding-worker-a"] == "active_session"
assert result["results"]["encoding-worker-b"] == "stopped"
# Only secondary should be stopped
assert mock_compute.stop.call_count == 1
def test_skips_terminated_vms(self, mock_compute, mock_firestore):
"""VMs that are already TERMINATED should be skipped."""
config = _make_config()
_setup_firestore(mock_firestore, config)
instance = _make_instance(status="TERMINATED")
mock_compute.get.return_value = instance
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["results"]["encoding-worker-a"] == "already_terminated"
assert result["results"]["encoding-worker-b"] == "already_terminated"
mock_compute.stop.assert_not_called()
def test_active_jobs_keep_vm_alive(self, mock_compute, mock_firestore):
"""VMs with active encoding jobs should not be stopped."""
old_activity = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
config = _make_config(last_activity_at=old_activity)
_setup_firestore(mock_firestore, config)
instance = _make_instance(status="RUNNING", ip="1.2.3.4")
mock_compute.get.return_value = instance
with patch("main.check_active_jobs", return_value=2):
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["results"]["encoding-worker-a"] == "active_jobs=2"
assert result["results"]["encoding-worker-b"] == "active_jobs=2"
mock_compute.stop.assert_not_called()
def test_no_config_returns_no_config(self, mock_compute, mock_firestore):
"""Should return no_config status when Firestore doc doesn't exist."""
_setup_firestore_missing(mock_firestore)
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["status"] == "no_config"
def test_vm_without_ip_still_gets_stopped(self, mock_compute, mock_firestore):
"""VMs without an IP (no access config) should still be stopped if idle."""
old_activity = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
config = _make_config(last_activity_at=old_activity)
_setup_firestore(mock_firestore, config)
instance = MagicMock()
instance.status = "RUNNING"
instance.network_interfaces = []
mock_compute.get.return_value = instance
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
assert result["results"]["encoding-worker-a"] == "stopped"
assert result["results"]["encoding-worker-b"] == "stopped"
assert mock_compute.stop.call_count == 2
def test_no_last_activity_treats_as_idle(self, mock_compute, mock_firestore):
"""If last_activity_at is not set, treat as no recent activity."""
config = _make_config(last_activity_at=None)
_setup_firestore(mock_firestore, config)
instance = _make_instance(status="RUNNING", ip="1.2.3.4")
mock_compute.get.return_value = instance
with patch("main.check_active_jobs", return_value=0):
response, status_code = main.idle_shutdown(MagicMock())
result = json.loads(response)
# Both should be stopped since no activity recorded
assert result["results"]["encoding-worker-a"] == "stopped"
assert result["results"]["encoding-worker-b"] == "stopped"
@@ -6,14 +6,13 @@ Replaces the Modal deployment for audio stem separation.
Resources created:
- Artifact Registry repository for audio-separator Docker images
- GCS bucket for pre-downloaded separation models
- Cloud Run GPU service (L4, scale-to-zero)
- Service account with minimal permissions
"""
import pulumi
import pulumi_gcp as gcp
from pulumi_gcp import artifactregistry, cloudrunv2, serviceaccount, storage
from pulumi_gcp import artifactregistry, cloudrunv2, serviceaccount
from pulumi_gcp.cloudrunv2 import ServiceTemplateNodeSelectorArgs, ServiceTemplateContainerPortsArgs
from config import PROJECT_ID, REGION
@@ -34,18 +33,6 @@ def create_audio_separator_artifact_repo() -> artifactregistry.Repository:
)
def create_model_bucket() -> storage.Bucket:
"""Create GCS bucket for audio separation model files (~1-1.5 GB total)."""
return storage.Bucket(
"audio-separator-models-bucket",
name=f"nomadkaraoke-audio-separator-models",
location=AUDIO_SEPARATOR_REGION,
storage_class="STANDARD",
uniform_bucket_level_access=True,
force_destroy=False,
)
def create_service_account() -> serviceaccount.Account:
"""Create service account for the audio separator Cloud Run service."""
return serviceaccount.Account(
+179 -179
View File
@@ -70,22 +70,15 @@ def create_lyrics_transcription_job(
},
),
envs=[
# Basic configuration
# Admin token for Cloud Tasks auth header
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
),
# AudioShake API token (required for transcription)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
@@ -97,36 +90,6 @@ def create_lyrics_transcription_job(
),
),
),
# Genius API token (for lyrics fetching)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GENIUS_API_TOKEN",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/genius-api-key",
version="latest",
),
),
),
# Spotify cookie (for Spotify lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SPOTIFY_COOKIE_SP_DC",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/spotify-cookie",
version="latest",
),
),
),
# RapidAPI key (for Musixmatch lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="RAPIDAPI_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/rapidapi-key",
version="latest",
),
),
),
# Cloud Run service URL for Cloud Tasks targeting
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="CLOUD_RUN_SERVICE_URL",
@@ -137,12 +100,49 @@ def create_lyrics_transcription_job(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# Admin token for Cloud Tasks auth header
# Basic configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
# Genius API token (for lyrics fetching)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GENIUS_API_TOKEN",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
secret=f"projects/{PROJECT_ID}/secrets/genius-api-key",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
# RapidAPI key (for Musixmatch lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="RAPIDAPI_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/rapidapi-key",
version="latest",
),
),
),
# Spotify cookie (for Spotify lyrics)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SPOTIFY_COOKIE_SP_DC",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/spotify-cookie",
version="latest",
),
),
@@ -197,22 +197,15 @@ def create_audio_separation_job(
},
),
envs=[
# Basic configuration
# Admin token for Cloud Tasks auth header
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
),
# Audio separator API (Cloud Run GPU service in us-east4)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
@@ -229,15 +222,22 @@ def create_audio_separation_job(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# Admin token for Cloud Tasks auth header
# Basic configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
],
)
@@ -300,39 +300,12 @@ def create_audio_download_job(
},
),
envs=[
# Basic configuration
# Admin token for worker auth
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
# Flacfetch API URL (internal VPC address)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_URL",
name="ADMIN_TOKENS",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-url",
version="latest",
),
),
),
# Flacfetch API key
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-key",
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
version="latest",
),
),
@@ -347,16 +320,43 @@ def create_audio_download_job(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# Admin token for worker auth
# Basic configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
name="ENVIRONMENT",
value="production",
),
# Flacfetch API key
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/admin-tokens",
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-key",
version="latest",
),
),
),
# Flacfetch API URL (internal VPC address)
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="FLACFETCH_API_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/flacfetch-api-url",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
],
)
],
@@ -410,81 +410,6 @@ def create_video_encoding_job(
},
),
envs=[
# Core configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
# GCE encoding worker
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="USE_GCE_ENCODING",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-url",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-api-key",
version="latest",
),
),
),
# Distribution defaults
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_ENABLE_YOUTUBE_UPLOAD",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_BRAND_PREFIX",
value="NOMAD",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_BRAND_PREFIX",
value="NOMADNP",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-Organized",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-NonPublished",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_GDRIVE_FOLDER_ID",
value="1laRKAyxo0v817SstfM5XkpbWiNKNAMSX",
),
# Discord webhook for release notifications
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DISCORD_WEBHOOK_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/discord-releases-webhook",
version="latest",
),
),
),
# Admin token for worker-to-service auth
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ADMIN_TOKENS",
@@ -500,10 +425,81 @@ def create_video_encoding_job(
name="CLOUD_RUN_SERVICE_URL",
value="https://api.nomadkaraoke.com",
),
# Distribution defaults
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_BRAND_PREFIX",
value="NOMAD",
),
# Discord webhook for release notifications
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DISCORD_WEBHOOK_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/discord-releases-webhook",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-Organized",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_ENABLE_YOUTUBE_UPLOAD",
value="true",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_GDRIVE_FOLDER_ID",
value="1laRKAyxo0v817SstfM5XkpbWiNKNAMSX",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_BRAND_PREFIX",
value="NOMADNP",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="DEFAULT_PRIVATE_DROPBOX_PATH",
value="/MediaUnsynced/Karaoke/Tracks-NonPublished",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENABLE_CLOUD_TASKS",
value="true",
),
# GCE encoding worker
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_API_KEY",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-api-key",
version="latest",
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENCODING_WORKER_URL",
value_source=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceArgs(
secret_key_ref=cloudrunv2.JobTemplateTemplateContainerEnvValueSourceSecretKeyRefArgs(
secret=f"projects/{PROJECT_ID}/secrets/encoding-worker-url",
version="latest",
),
),
),
# Core configuration
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="ENVIRONMENT",
value="production",
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCP_REGION",
value=REGION,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GCS_BUCKET_NAME",
value=bucket.name,
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="GOOGLE_CLOUD_PROJECT",
value=PROJECT_ID,
),
# SendGrid for completion emails
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="SENDGRID_API_KEY",
@@ -514,6 +510,10 @@ def create_video_encoding_job(
),
),
),
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
name="USE_GCE_ENCODING",
value="true",
),
],
)
],
@@ -0,0 +1,154 @@
"""
Encoding Worker Idle Shutdown — Cloud Function + Cloud Scheduler.
Automatically stops encoding worker VMs after 15 minutes of inactivity.
Checks every 5 minutes via Cloud Scheduler trigger.
"""
import pulumi
import pulumi_gcp as gcp
from config import PROJECT_ID, REGION, ENCODING_WORKER_ZONE, EncodingWorkerConfig
def create_idle_shutdown_service_account():
"""Create service account for the idle shutdown Cloud Function."""
return gcp.serviceaccount.Account(
"encoding-worker-idle-sa",
account_id="encoding-worker-idle",
display_name="Encoding Worker Idle Shutdown",
description="Service account for the encoding worker idle auto-shutdown Cloud Function",
)
def grant_idle_shutdown_permissions(service_account):
"""Grant permissions to the idle shutdown service account."""
bindings = {}
bindings["compute_viewer"] = gcp.projects.IAMMember(
"idle-shutdown-compute-viewer",
project=PROJECT_ID,
role="roles/compute.viewer",
member=service_account.email.apply(lambda e: f"serviceAccount:{e}"),
)
stop_role = gcp.projects.IAMCustomRole(
"encoding-worker-stop-role",
role_id="encodingWorkerStop",
title="Encoding Worker Stop",
description="Stop encoding worker VMs (for idle shutdown)",
permissions=["compute.instances.stop"],
project=PROJECT_ID,
)
bindings["compute_stop"] = gcp.projects.IAMMember(
"idle-shutdown-compute-stop",
project=PROJECT_ID,
role=stop_role.name,
member=service_account.email.apply(lambda e: f"serviceAccount:{e}"),
)
bindings["firestore"] = gcp.projects.IAMMember(
"idle-shutdown-firestore",
project=PROJECT_ID,
role="roles/datastore.user",
member=service_account.email.apply(lambda e: f"serviceAccount:{e}"),
)
return bindings
def create_idle_shutdown_resources():
"""
Create all resources for the encoding worker idle shutdown system.
Returns:
dict: Dictionary of all created resources.
"""
sa = create_idle_shutdown_service_account()
perms = grant_idle_shutdown_permissions(sa)
source_bucket = gcp.storage.Bucket(
"encoding-worker-idle-source",
name=f"encoding-worker-idle-source-{PROJECT_ID}",
location="US-CENTRAL1",
force_destroy=True,
uniform_bucket_level_access=True,
)
function = gcp.cloudfunctionsv2.Function(
"encoding-worker-idle-function",
name=EncodingWorkerConfig.FUNCTION_NAME,
location=REGION,
description="Auto-stop idle encoding worker VMs",
build_config=gcp.cloudfunctionsv2.FunctionBuildConfigArgs(
runtime="python312",
entry_point="idle_shutdown",
source=gcp.cloudfunctionsv2.FunctionBuildConfigSourceArgs(
storage_source=gcp.cloudfunctionsv2.FunctionBuildConfigSourceStorageSourceArgs(
bucket=source_bucket.name,
object="encoding-worker-idle-source.zip",
),
),
),
service_config=gcp.cloudfunctionsv2.FunctionServiceConfigArgs(
available_memory=EncodingWorkerConfig.FUNCTION_MEMORY,
timeout_seconds=EncodingWorkerConfig.FUNCTION_TIMEOUT,
min_instance_count=0,
max_instance_count=1,
service_account_email=sa.email,
environment_variables={
"GCP_PROJECT": PROJECT_ID,
"GCP_ZONE": ENCODING_WORKER_ZONE,
"IDLE_TIMEOUT_MINUTES": str(EncodingWorkerConfig.IDLE_TIMEOUT_MINUTES),
},
),
opts=pulumi.ResourceOptions(
depends_on=list(perms.values()),
),
)
scheduler_invoker = gcp.cloudfunctionsv2.FunctionIamMember(
"idle-shutdown-scheduler-invoker",
project=PROJECT_ID,
location=REGION,
cloud_function=function.name,
role="roles/cloudfunctions.invoker",
member=sa.email.apply(lambda e: f"serviceAccount:{e}"),
)
run_invoker = gcp.cloudrunv2.ServiceIamMember(
"idle-shutdown-run-invoker",
project=PROJECT_ID,
location=REGION,
name=function.name,
role="roles/run.invoker",
member=sa.email.apply(lambda e: f"serviceAccount:{e}"),
)
scheduler = gcp.cloudscheduler.Job(
"encoding-worker-idle-scheduler",
name="encoding-worker-idle-check",
description="Check and stop idle encoding worker VMs",
region=REGION,
schedule=EncodingWorkerConfig.IDLE_CHECK_SCHEDULE,
time_zone="UTC",
http_target=gcp.cloudscheduler.JobHttpTargetArgs(
uri=function.url,
http_method="POST",
oidc_token=gcp.cloudscheduler.JobHttpTargetOidcTokenArgs(
service_account_email=sa.email,
),
),
retry_config=gcp.cloudscheduler.JobRetryConfigArgs(
retry_count=1,
min_backoff_duration="60s",
max_backoff_duration="300s",
),
)
return {
"service_account": sa,
"function": function,
"scheduler": scheduler,
"source_bucket": source_bucket,
}
+29
View File
@@ -68,6 +68,35 @@ def grant_encoding_worker_permissions(
return bindings
def grant_backend_compute_permissions(
backend_sa: serviceaccount.Account,
) -> dict:
"""Grant the backend SA permission to start/get encoding worker VMs.
Needed for on-demand VM warmup when users open lyrics review.
"""
custom_role = gcp.projects.IAMCustomRole(
"encoding-worker-lifecycle-role",
role_id="encodingWorkerLifecycle",
title="Encoding Worker Lifecycle",
description="Start and check status of encoding worker VMs",
permissions=[
"compute.instances.get",
"compute.instances.start",
],
project=PROJECT_ID,
)
binding = gcp.projects.IAMMember(
"backend-encoding-worker-lifecycle",
project=PROJECT_ID,
role=custom_role.name,
member=backend_sa.email.apply(lambda email: f"serviceAccount:{email}"),
)
return {"custom_role": custom_role, "binding": binding}
# ==================== GDrive Validator Service Account ====================
def create_gdrive_validator_service_account() -> serviceaccount.Account:
+1 -1
View File
@@ -96,7 +96,7 @@ echo "Creating Python virtual environment..."
# Install base Python dependencies (wheel will add more at runtime)
source venv/bin/activate
pip install --upgrade pip
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp packaging
# Create bootstrap script (runs via ExecStartPre before service starts)
# This minimal script downloads the REAL startup script from GCS.
@@ -1,6 +1,7 @@
from dataclasses import dataclass
import logging
import requests
import subprocess
import time
import os
import tempfile
@@ -51,7 +52,12 @@ class AudioUploadOptimizer:
self.logger.info(f"Converting uncompressed format ({ext}) to FLAC for efficient upload")
return self._convert_to_flac(filepath)
# AudioShake-supported formats: upload directly
# FLAC files: strip metadata to avoid non-standard tags breaking AudioShake
if ext == '.flac':
self.logger.info("Stripping metadata from FLAC before upload (audio unchanged)")
return self._strip_metadata(filepath)
# Other AudioShake-supported formats: upload directly
if ext in AUDIOSHAKE_SUPPORTED:
self.logger.info(f"Uploading AudioShake-supported format ({ext}) directly")
return filepath, None
@@ -60,6 +66,31 @@ class AudioUploadOptimizer:
self.logger.info(f"Converting unsupported format ({ext}) to FLAC for AudioShake compatibility")
return self._convert_to_flac(filepath)
def _strip_metadata(self, filepath: str) -> Tuple[str, str]:
"""Strip all metadata from an audio file using ffmpeg, keeping audio unchanged.
This prevents non-standard metadata tags (e.g. MP4/M4A container fields
embedded in FLAC) from breaking AudioShake's processing pipeline.
"""
with tempfile.NamedTemporaryFile(suffix=".flac", delete=False) as temp_file:
clean_path = temp_file.name
try:
subprocess.run(
["ffmpeg", "-i", filepath, "-map", "0:a", "-c", "copy", "-map_metadata", "-1", clean_path, "-y"],
check=True,
capture_output=True,
)
except subprocess.CalledProcessError as e:
# Clean up on failure
if os.path.exists(clean_path):
os.unlink(clean_path)
self.logger.error(f"ffmpeg metadata strip failed: {e.stderr.decode()}")
raise
self.logger.info(f"Stripped metadata from {os.path.basename(filepath)}")
return clean_path, clean_path
def _convert_to_flac(self, filepath: str) -> Tuple[str, str]:
"""Convert audio file to FLAC format."""
ext = os.path.splitext(filepath)[1].lower()
Generated
+60 -64
View File
@@ -702,18 +702,6 @@ dev = ["cachecontrol[filecache,redis]", "cheroot (>=11.1.2)", "cherrypy", "codes
filecache = ["filelock (>=3.8.0)"]
redis = ["redis (>=2.10.5)"]
[[package]]
name = "cachetools"
version = "6.2.4"
description = "Extensible memoizing collections and decorators"
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "cachetools-6.2.4-py3-none-any.whl", hash = "sha256:69a7a52634fed8b8bf6e24a050fb60bff1c9bd8f6d24572b99c32d4e71e62a51"},
{file = "cachetools-6.2.4.tar.gz", hash = "sha256:82c5c05585e70b6ba2d3ae09ea60b79548872185d2f24ae1f2709d37299fd607"},
]
[[package]]
name = "catalogue"
version = "2.0.10"
@@ -2477,14 +2465,14 @@ grpcio-gcp = ["grpcio-gcp (>=0.2.2,<1.0.0)"]
[[package]]
name = "google-api-python-client"
version = "2.187.0"
version = "2.193.0"
description = "Google API Client Library for Python"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_api_python_client-2.187.0-py3-none-any.whl", hash = "sha256:d8d0f6d85d7d1d10bdab32e642312ed572bdc98919f72f831b44b9a9cebba32f"},
{file = "google_api_python_client-2.187.0.tar.gz", hash = "sha256:e98e8e8f49e1b5048c2f8276473d6485febc76c9c47892a8b4d1afa2c9ec8278"},
{file = "google_api_python_client-2.193.0-py3-none-any.whl", hash = "sha256:c42aa324b822109901cfecab5dc4fc3915d35a7b376835233c916c70610322db"},
{file = "google_api_python_client-2.193.0.tar.gz", hash = "sha256:8f88d16e89d11341e0a8b199cafde0fb7e6b44260dffb88d451577cbd1bb5d33"},
]
[package.dependencies]
@@ -2496,31 +2484,31 @@ uritemplate = ">=3.0.1,<5"
[[package]]
name = "google-auth"
version = "2.46.0"
version = "2.49.1"
description = "Google Authentication Library"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "google_auth-2.46.0-py3-none-any.whl", hash = "sha256:fa51659c3745cb7024dd073f4ab766222767ea5f7dee2472110eaa03c9dbd2cb"},
{file = "google_auth-2.46.0.tar.gz", hash = "sha256:cb04c071a73394a6e3b9e48c1a7f48506001175b33e9679587a0f5320a21a34d"},
{file = "google_auth-2.49.1-py3-none-any.whl", hash = "sha256:195ebe3dca18eddd1b3db5edc5189b76c13e96f29e73043b923ebcf3f1a860f7"},
{file = "google_auth-2.49.1.tar.gz", hash = "sha256:16d40da1c3c5a0533f57d268fe72e0ebb0ae1cc3b567024122651c045d879b64"},
]
[package.dependencies]
cachetools = ">=2.0.0,<7.0"
cryptography = ">=38.0.3"
pyasn1-modules = ">=0.2.1"
requests = {version = ">=2.20.0,<3.0.0", optional = true, markers = "extra == \"requests\""}
rsa = ">=3.1.4,<5"
[package.extras]
aiohttp = ["aiohttp (>=3.6.2,<4.0.0)", "requests (>=2.20.0,<3.0.0)"]
cryptography = ["cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)"]
enterprise-cert = ["cryptography", "pyopenssl"]
pyjwt = ["cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)", "pyjwt (>=2.0)"]
pyopenssl = ["cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)", "pyopenssl (>=20.0.0)"]
cryptography = ["cryptography (>=38.0.3)"]
enterprise-cert = ["pyopenssl"]
pyjwt = ["pyjwt (>=2.0)"]
pyopenssl = ["pyopenssl (>=20.0.0)"]
reauth = ["pyu2f (>=0.1.5)"]
requests = ["requests (>=2.20.0,<3.0.0)"]
testing = ["aiohttp (<3.10.0)", "aiohttp (>=3.6.2,<4.0.0)", "aioresponses", "cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (<39.0.0) ; python_version < \"3.8\"", "cryptography (>=38.0.3)", "cryptography (>=38.0.3)", "flask", "freezegun", "grpcio", "oauth2client", "packaging", "pyjwt (>=2.0)", "pyopenssl (<24.3.0)", "pyopenssl (>=20.0.0)", "pytest", "pytest-asyncio", "pytest-cov", "pytest-localserver", "pyu2f (>=0.1.5)", "requests (>=2.20.0,<3.0.0)", "responses", "urllib3"]
rsa = ["rsa (>=3.1.4,<5)"]
testing = ["aiohttp (<3.10.0)", "aiohttp (>=3.6.2,<4.0.0)", "aioresponses", "flask", "freezegun", "grpcio", "packaging", "pyjwt (>=2.0)", "pyopenssl (<24.3.0)", "pyopenssl (>=20.0.0)", "pytest", "pytest-asyncio", "pytest-cov", "pytest-localserver", "pyu2f (>=0.1.5)", "requests (>=2.20.0,<3.0.0)", "responses", "urllib3"]
urllib3 = ["packaging", "urllib3"]
[[package]]
@@ -2541,23 +2529,45 @@ httplib2 = ">=0.19.0,<1.0.0"
[[package]]
name = "google-auth-oauthlib"
version = "1.2.2"
version = "1.3.0"
description = "Google Authentication Library"
optional = false
python-versions = ">=3.6"
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_auth_oauthlib-1.2.2-py3-none-any.whl", hash = "sha256:fd619506f4b3908b5df17b65f39ca8d66ea56986e5472eb5978fd8f3786f00a2"},
{file = "google_auth_oauthlib-1.2.2.tar.gz", hash = "sha256:11046fb8d3348b296302dd939ace8af0a724042e8029c1b872d87fabc9f41684"},
{file = "google_auth_oauthlib-1.3.0-py3-none-any.whl", hash = "sha256:386b3fb85cf4a5b819c6ad23e3128d975216b4cac76324de1d90b128aaf38f29"},
{file = "google_auth_oauthlib-1.3.0.tar.gz", hash = "sha256:cd39e807ac7229d6b8b9c1e297321d36fcc8a9e4857dff4301870985df51a528"},
]
[package.dependencies]
google-auth = ">=2.15.0"
google-auth = ">=2.15.0,<2.43.0 || >2.43.0,<2.44.0 || >2.44.0,<2.45.0 || >2.45.0,<3.0.0"
requests-oauthlib = ">=0.7.0"
[package.extras]
tool = ["click (>=6.0.0)"]
[[package]]
name = "google-cloud-compute"
version = "1.46.0"
description = "Google Cloud Compute API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_compute-1.46.0-py3-none-any.whl", hash = "sha256:f92d9a7c32454b8a719ff937bfd46e794ee35d65e141ec5d20797aad6988dfb0"},
{file = "google_cloud_compute-1.46.0.tar.gz", hash = "sha256:8b0f8d5a1115e8beae5fafdc7050f1ad15e922a5cdf6c634e5a745e47cb49281"},
]
[package.dependencies]
google-api-core = {version = ">=1.34.1,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
grpcio = ">=1.33.2,<2.0.0"
proto-plus = [
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
{version = ">=1.22.3,<2.0.0"},
]
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0"
[[package]]
name = "google-cloud-core"
version = "2.5.0"
@@ -2579,26 +2589,26 @@ grpc = ["grpcio (>=1.38.0,<2.0.0) ; python_version < \"3.14\"", "grpcio (>=1.75.
[[package]]
name = "google-cloud-firestore"
version = "2.22.0"
version = "2.26.0"
description = "Google Cloud Firestore API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_firestore-2.22.0-py3-none-any.whl", hash = "sha256:47652ca74a77903c192fe194f646871ca2f881e56c30e7f573a9782d3bdbb610"},
{file = "google_cloud_firestore-2.22.0.tar.gz", hash = "sha256:9d6a5bdefb30ed5ca94a7cb3560873352a3dbf868957ef789e6e74d086d52d82"},
{file = "google_cloud_firestore-2.26.0-py3-none-any.whl", hash = "sha256:307e6d3aed1a15e7083d9bac1871cb439be17620e035de960225bb00acc771de"},
{file = "google_cloud_firestore-2.26.0.tar.gz", hash = "sha256:103fc2bdedcb801a31590fef9a0d50754ee63b803946f9afc904817c85bd935d"},
]
[package.dependencies]
google-api-core = {version = ">=1.34.0,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
google-api-core = {version = ">=1.34.1,<2.0.dev0 || >=2.11.dev0,<3.0.0", extras = ["grpc"]}
google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0"
google-cloud-core = ">=1.4.1,<3.0.0"
grpcio = ">=1.33.2,<2.0.0"
proto-plus = [
{version = ">=1.25.0,<2.0.0", markers = "python_version >= \"3.13\""},
{version = ">=1.22.2,<2.0.0", markers = "python_version >= \"3.11\""},
{version = ">=1.22.0,<2.0.0"},
{version = ">=1.22.3,<2.0.0"},
]
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0dev"
protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<7.0.0"
[[package]]
name = "google-cloud-monitoring"
@@ -2627,14 +2637,14 @@ pandas = ["pandas (>=0.23.2)"]
[[package]]
name = "google-cloud-run"
version = "0.13.0"
version = "0.15.0"
description = "Google Cloud Run API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_run-0.13.0-py3-none-any.whl", hash = "sha256:ec61a8ec2e38e04d482643ef8a6f371630c8a7d6173ab6c69c1d80ad9754220f"},
{file = "google_cloud_run-0.13.0.tar.gz", hash = "sha256:97534ad76d3a2c2047d124c0a0a294a4822fcc24331eba0f294cadfb193c49ad"},
{file = "google_cloud_run-0.15.0-py3-none-any.whl", hash = "sha256:e457ecb1f7ff9ec2a64aed99611383adbf89fe9e02f3dd268874122b23d22601"},
{file = "google_cloud_run-0.15.0.tar.gz", hash = "sha256:158f264643f982bfa4f4f18f9e28c56ea00ea95c248bc8a746e159b538afab57"},
]
[package.dependencies]
@@ -2673,14 +2683,14 @@ protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4
[[package]]
name = "google-cloud-storage"
version = "3.7.0"
version = "3.10.1"
description = "Google Cloud Storage API client library"
optional = false
python-versions = ">=3.7"
python-versions = ">=3.10"
groups = ["main"]
files = [
{file = "google_cloud_storage-3.7.0-py3-none-any.whl", hash = "sha256:469bc9540936e02f8a4bfd1619e9dca1e42dec48f95e4204d783b36476a15093"},
{file = "google_cloud_storage-3.7.0.tar.gz", hash = "sha256:9ce59c65f4d6e372effcecc0456680a8d73cef4f2dc9212a0704799cb3d69237"},
{file = "google_cloud_storage-3.10.1-py3-none-any.whl", hash = "sha256:a72f656759b7b99bda700f901adcb3425a828d4a29f911bc26b3ea79c5b1217f"},
{file = "google_cloud_storage-3.10.1.tar.gz", hash = "sha256:97db9aa4460727982040edd2bd13ff3d5e2260b5331ad22895802da1fc2a5286"},
]
[package.dependencies]
@@ -2694,18 +2704,19 @@ requests = ">=2.22.0,<3.0.0"
[package.extras]
grpc = ["google-api-core[grpc] (>=2.27.0,<3.0.0)", "grpc-google-iam-v1 (>=0.14.0,<1.0.0)", "grpcio (>=1.33.2,<2.0.0) ; python_version < \"3.14\"", "grpcio (>=1.75.1,<2.0.0) ; python_version >= \"3.14\"", "grpcio-status (>=1.76.0,<2.0.0)", "proto-plus (>=1.22.3,<2.0.0) ; python_version < \"3.13\"", "proto-plus (>=1.25.0,<2.0.0) ; python_version >= \"3.13\"", "protobuf (>=3.20.2,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<7.0.0)"]
protobuf = ["protobuf (>=3.20.2,<7.0.0)"]
testing = ["PyYAML", "black", "brotli", "coverage", "flake8", "google-cloud-iam", "google-cloud-kms", "google-cloud-pubsub", "google-cloud-testutils", "google-cloud-testutils", "mock", "numpy", "opentelemetry-sdk", "psutil", "py-cpuinfo", "pyopenssl", "pytest", "pytest-asyncio", "pytest-benchmark", "pytest-cov", "pytest-rerunfailures", "pytest-xdist"]
tracing = ["opentelemetry-api (>=1.1.0,<2.0.0)"]
[[package]]
name = "google-cloud-tasks"
version = "2.20.0"
version = "2.21.0"
description = "Google Cloud Tasks API client library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "google_cloud_tasks-2.20.0-py3-none-any.whl", hash = "sha256:3d261a8d1f3ab90454b3e2780f484373031b0b6061506571190dc5c300768422"},
{file = "google_cloud_tasks-2.20.0.tar.gz", hash = "sha256:733cf440a25d34fe1cdb4e6c946d173bd83a2c22c3d7b2c76a24591f3c160412"},
{file = "google_cloud_tasks-2.21.0-py3-none-any.whl", hash = "sha256:4bf288876892a0afac30658fc42925ccb732d3c4433a8ea568de1d67fde738f2"},
{file = "google_cloud_tasks-2.21.0.tar.gz", hash = "sha256:d28f33248553faf0ff029e1981aab56cd13bd933635c3bc33aa187675e7e14d1"},
]
[package.dependencies]
@@ -7873,21 +7884,6 @@ files = [
einops = ">=0.7"
torch = ">=2.0"
[[package]]
name = "rsa"
version = "4.9.1"
description = "Pure-Python RSA implementation"
optional = false
python-versions = "<4,>=3.6"
groups = ["main"]
files = [
{file = "rsa-4.9.1-py3-none-any.whl", hash = "sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762"},
{file = "rsa-4.9.1.tar.gz", hash = "sha256:e7bdbfdb5497da4c07dfd35530e1a902659db6ff241e39d9953cad06ebd0ae75"},
]
[package.dependencies]
pyasn1 = ">=0.1.3"
[[package]]
name = "rtfde"
version = "0.1.2.2"
@@ -10706,4 +10702,4 @@ local-whisper = ["whisper-timestamped"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.14"
content-hash = "6f4c1aa73c0b4adecdc901fdec83dea48a9c431056c4b8fd04da5461469d3095"
content-hash = "fd26762a0d3f754ddc150bb24dc6d1ee1a15cb8154584950b213029751315ed2"
+12 -11
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.150.2"
version = "0.151.1"
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"
@@ -30,10 +30,10 @@ lyricsgenius = ">=3"
fetch-lyrics-from-genius = ">=0.1"
pillow = ">=10.1"
pyinstaller = ">=6.3"
google-api-python-client = "*"
google-auth = "*"
google-auth-oauthlib = "*"
google-auth-httplib2 = "*"
google-api-python-client = "2.193.0"
google-auth = "2.49.1"
google-auth-oauthlib = "1.3.0"
google-auth-httplib2 = "0.3.0"
thefuzz = ">=0.22"
numpy = ">=2"
audio-separator = { version = ">=0.43.0", extras = ["cpu"] }
@@ -87,12 +87,13 @@ pydantic = ">=2.5.0"
pydantic-settings = ">=2.1.0"
httpx = ">=0.25.0"
tenacity = "^8.2.0" # Retry logic for external service calls
google-cloud-firestore = ">=2.14.0"
google-cloud-storage = ">=2.14.0"
google-cloud-secret-manager = ">=2.18.0"
google-cloud-monitoring = ">=2.19.0" # Cloud Monitoring for YouTube API quota metrics
google-cloud-tasks = ">=2.16.0" # Cloud Tasks for worker coordination (Phase 1 scalability)
google-cloud-run = ">=0.10.0" # Cloud Run Jobs for long-running video encoding (Phase 2 scalability)
google-cloud-firestore = "2.26.0"
google-cloud-compute = "^1.0.0"
google-cloud-storage = "3.10.1"
google-cloud-secret-manager = "2.26.0"
google-cloud-monitoring = "2.29.1" # Cloud Monitoring for YouTube API quota metrics
google-cloud-tasks = "2.21.0" # Cloud Tasks for worker coordination (Phase 1 scalability)
google-cloud-run = "0.15.0" # Cloud Run Jobs for long-running video encoding (Phase 2 scalability)
python-dotenv = ">=1.0.0"
pydub = ">=0.25.1"
# Payment and email services
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""
Seed the Firestore config/encoding-worker document.
Run once during migration to initialize the blue-green config.
Uses the Pulumi-assigned IPs for VMs A and B.
Usage:
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
Requires:
- GOOGLE_CLOUD_PROJECT=nomadkaraoke (or gcloud default project)
- Firestore write access
"""
import sys
from datetime import datetime, timezone
from google.cloud import firestore
PROJECT_ID = "nomadkaraoke"
def main():
if len(sys.argv) != 3:
print("Usage: python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>")
print(" ip-a: Static IP assigned to encoding-worker-a")
print(" ip-b: Static IP assigned to encoding-worker-b")
sys.exit(1)
ip_a, ip_b = sys.argv[1], sys.argv[2]
db = firestore.Client(project=PROJECT_ID)
now = datetime.now(timezone.utc).isoformat()
config = {
"primary_vm": "encoding-worker-a",
"primary_ip": ip_a,
"primary_version": "unknown",
"primary_deployed_at": now,
"secondary_vm": "encoding-worker-b",
"secondary_ip": ip_b,
"secondary_version": None,
"secondary_deployed_at": None,
"last_swap_at": None,
"last_activity_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
}
doc_ref = db.collection("config").document("encoding-worker")
# Check if already exists
if doc_ref.get().exists:
print("WARNING: config/encoding-worker already exists!")
print("Current value:", doc_ref.get().to_dict())
response = input("Overwrite? (y/N): ")
if response.lower() != "y":
print("Aborted.")
sys.exit(0)
doc_ref.set(config)
print(f"Seeded config/encoding-worker:")
print(f" Primary: encoding-worker-a ({ip_a})")
print(f" Secondary: encoding-worker-b ({ip_b})")
print(f" Timestamp: {now}")
if __name__ == "__main__":
main()
+50 -1
View File
@@ -2,6 +2,7 @@
import os
import pytest
import subprocess
import tempfile
from unittest.mock import MagicMock, patch
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import (
@@ -24,7 +25,7 @@ class TestAudioUploadOptimizer:
# ===== Test AudioShake-supported formats are uploaded directly =====
@pytest.mark.parametrize("ext", [".mp3", ".flac", ".aac", ".mp4a"])
@pytest.mark.parametrize("ext", [".mp3", ".aac", ".mp4a"])
def test_supported_audio_formats_uploaded_directly(self, optimizer, ext):
"""AudioShake-supported audio formats should be uploaded directly."""
filepath = f"/path/to/audio{ext}"
@@ -36,6 +37,21 @@ class TestAudioUploadOptimizer:
optimizer.logger.info.assert_called_once()
assert "directly" in optimizer.logger.info.call_args[0][0]
def test_flac_files_have_metadata_stripped(self, optimizer):
"""FLAC files should have metadata stripped before upload."""
filepath = "/path/to/audio.flac"
with patch.object(optimizer, "_strip_metadata") as mock_strip:
mock_strip.return_value = ("/tmp/clean.flac", "/tmp/clean.flac")
result_path, temp_path = optimizer.prepare_for_upload(filepath)
mock_strip.assert_called_once_with(filepath)
assert result_path == "/tmp/clean.flac"
assert temp_path == "/tmp/clean.flac"
optimizer.logger.info.assert_called_once()
assert "metadata" in optimizer.logger.info.call_args[0][0].lower()
@pytest.mark.parametrize("ext", [".mp4", ".mov"])
def test_supported_video_formats_uploaded_directly(self, optimizer, ext):
"""AudioShake-supported video formats (mp4, mov) should be uploaded directly."""
@@ -199,3 +215,36 @@ class TestAudioUploadOptimizerConversion:
assert os.path.exists(flac_path)
finally:
optimizer.cleanup(cleanup_path)
def test_strip_metadata_produces_clean_flac(self, optimizer, tmp_path):
"""Test that _strip_metadata creates a clean FLAC file without metadata."""
pytest.importorskip("pydub")
from pydub import AudioSegment
from pydub.generators import Sine
# Generate a FLAC file with metadata
sine_wave = Sine(440).to_audio_segment(duration=1000)
flac_path = tmp_path / "test_with_metadata.flac"
sine_wave.export(str(flac_path), format="flac", tags={"title": "Test", "artist": "Bot"})
# Strip metadata
clean_path, cleanup_path = optimizer._strip_metadata(str(flac_path))
try:
assert clean_path.endswith(".flac")
assert os.path.exists(clean_path)
assert os.path.getsize(clean_path) > 0
# Verify metadata was stripped using ffprobe
result = subprocess.run(
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", clean_path],
capture_output=True, text=True,
)
import json
probe = json.loads(result.stdout)
tags = probe.get("format", {}).get("tags", {})
assert "title" not in tags
assert "artist" not in tags
finally:
optimizer.cleanup(cleanup_path)